260 lines
7.3 KiB
C
260 lines
7.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <math.h>
|
|
|
|
/* --------- ERROR MESSAGES */
|
|
#define printerr(format, ...) printf("error: " format "\n", ##__VA_ARGS__)
|
|
#define ZERODIV_ERR "zero divisor"
|
|
#define DOMAIN_ERR "operand not in domain [%d, %d]"
|
|
#define NEG_ERR "negative operand %g"
|
|
#define FULL_STACK_ERR "stack full, can't push %g"
|
|
#define EMPTY_STACK_ERR "stack empty"
|
|
#define SHORT_STACK_ERR "not enough elements on stack"
|
|
#define UNKNOWN_TOKEN_ERR "unknown token %s"
|
|
|
|
/* --------- PROMPT FORMATS */
|
|
#define PROMPT_F ">> "
|
|
#define POP_PRINT_F "pop -> %.8g\n"
|
|
#define PEEK_PRINT_F "peek -> %.8g\n"
|
|
#define INITIAL_PROMPT_F \
|
|
"A simple calculator using polish notation.\n" \
|
|
"Type 'help' for a list of available commands\n" \
|
|
PROMPT_F
|
|
|
|
/* ------ GLOBAL VALUE STACK */
|
|
#define MAXVAL 100 /* maximum depth of val stack */
|
|
|
|
int sp = 0;
|
|
double val[MAXVAL];
|
|
|
|
#define length() sp
|
|
/* push: push f onto value stack */
|
|
#define push(x) ((sp < MAXVAL) ? val[sp++] = (x) : printerr(FULL_STACK_ERR, ((double) (x))))
|
|
/* pop: pop and return top value from stack */
|
|
#define pop() (sp ? val[--sp] : (printerr(EMPTY_STACK_ERR), 0))
|
|
/* peek: return top value from stack, leave stack unchanged */
|
|
#define peek() (sp ? val[sp-1] : (printerr(EMPTY_STACK_ERR), 0))
|
|
/* clear: clear stack */
|
|
#define clear() (sp = 0)
|
|
/* print_peek: print top element, leave stack unchanged */
|
|
#define print_peek() printf(PEEK_PRINT_F, peek())
|
|
/* dup: duplicate top element */
|
|
#define dup() push(peek())
|
|
/* swap: swap top two elements */
|
|
#define swap() \
|
|
do { if (sp < 2) printerr(SHORT_STACK_ERR); else { \
|
|
double tmp = peek(); \
|
|
val[sp-1] = val[sp-2], val[sp-2] = tmp; \
|
|
} \
|
|
} while (0)
|
|
|
|
/* --------- CALCULATOR FUNCTION TYPES */
|
|
|
|
/* the following macros allow us to call native c constructs in a declarative style */
|
|
/* value */
|
|
#define VALUE(ID) push(ID)
|
|
/* command */
|
|
#define COMMAND(CMD) CMD()
|
|
/* commutative operator */
|
|
#define COMM_OP(OP) push(pop() OP pop())
|
|
/* non-commutative operator */
|
|
#define NONC_OP(OP, T, ...) \
|
|
do { T op = pop(); __VA_ARGS__ push(((T) pop()) OP op); } while (0)
|
|
/* unary function */
|
|
#define UNARY_FUN(F) push(F(pop()))
|
|
/* unary function with tests */
|
|
#define UNARY_T_FUN(F, T, ...) \
|
|
do { double op = pop(); __VA_ARGS__ push(F(op)); } while (0)
|
|
/* commutative function */
|
|
#define COMM_FUN(F) push(F(pop(), pop()))
|
|
/* non-commutative function */
|
|
#define NONC_FUN(F, T, ...) \
|
|
do { T op = pop(); __VA_ARGS__ push(F(pop(), op)); } while (0)
|
|
|
|
/* nonzero operand */
|
|
#define NONZ_SND_OP if (!op) printerr(ZERODIV_ERR); else
|
|
/* operator in range */
|
|
#define IN_RANGE(A, B) if (op < A || op > B) printerr(DOMAIN_ERR, A, B); else
|
|
/* non-negative operand */
|
|
#define NON_NEG if (op < 0) printerr(NEG_ERR, op); else
|
|
|
|
|
|
/* --------- CALCULATOR FUNCTIONS */
|
|
|
|
/* renaming macro */
|
|
#define CALL(TOKEN, F, APPLY, ...) APPLY(F, ##__VA_ARGS__)
|
|
|
|
void help(void);
|
|
|
|
#define COMMANDS \
|
|
X(print, "print top of stack", CALL, print_peek, COMMAND) \
|
|
X(dup, "duplicate top of stack", COMMAND) \
|
|
X(swap, "swap top two elements of stack", COMMAND) \
|
|
X(clear, "clear stack", COMMAND) \
|
|
X(help, "print all available commands", COMMAND)
|
|
|
|
#define OPERATORS \
|
|
X(+, "add operands", COMM_OP) \
|
|
X(*, "multiply operands", COMM_OP) \
|
|
X(-, "substact operands", NONC_OP, double) \
|
|
X(/, "divide operands", NONC_OP, double, NONZ_SND_OP) \
|
|
X(%, "modulo operands", NONC_OP, int, NONZ_SND_OP) \
|
|
X(>, "greater than", NONC_OP, double) \
|
|
X(<, "less than", NONC_OP, double) \
|
|
X(<=, "less than or equal", NONC_OP, double) \
|
|
X(>=, "greater than or equal", NONC_OP, double)
|
|
|
|
#define MATH_H_BINDINGS \
|
|
X(sin, "sine", UNARY_FUN) \
|
|
X(cos, "cosine", UNARY_FUN) \
|
|
X(tan, "tangent", UNARY_FUN) \
|
|
X(acos, "arc cosine", UNARY_T_FUN, double, IN_RANGE(-1, 1)) \
|
|
X(asin, "arc sine", UNARY_T_FUN, double, IN_RANGE(-1, 1)) \
|
|
X(atan, "arc tangent", UNARY_FUN) \
|
|
X(exp, "exponentional function", UNARY_FUN) \
|
|
X(log, "natural logarithm", UNARY_T_FUN, double, NON_NEG) \
|
|
X(log10, "logarithm of base 10", UNARY_T_FUN, double, NON_NEG) \
|
|
X(log2, "logarithm of base 2", UNARY_T_FUN, double, NON_NEG) \
|
|
X(pow, "power function", NONC_FUN, double) \
|
|
X(sqrt, "square root", UNARY_T_FUN, double, NON_NEG) \
|
|
X(ceil, "round up value", UNARY_FUN) \
|
|
X(floor, "round down value", UNARY_FUN) \
|
|
X(round, "round to nearest", UNARY_FUN) \
|
|
X(abs, "absolute value", CALL, fabs, UNARY_FUN) \
|
|
X(max, "maximum value", CALL, fmax, COMM_FUN) \
|
|
X(min, "minimum value", CALL, fmin, COMM_FUN) \
|
|
X(pi, "value of pi", CALL, M_PI, VALUE)
|
|
|
|
|
|
#define TOKENS \
|
|
COMMANDS \
|
|
OPERATORS \
|
|
MATH_H_BINDINGS
|
|
|
|
/* --------- MAIN PROGRAM */
|
|
|
|
#define MAXTOKEN 100
|
|
int gettoken(char *token, int max_t);
|
|
char * parsef(char *s, double *x);
|
|
|
|
/* reverse Polish calculator */
|
|
int main()
|
|
{
|
|
char token[MAXTOKEN + 1];
|
|
double x;
|
|
int t_len;
|
|
|
|
printf(INITIAL_PROMPT_F);
|
|
while (t_len = gettoken(token, MAXTOKEN)) {
|
|
if (t_len < 0) { /* newline token */
|
|
if (length())
|
|
printf(POP_PRINT_F, pop());
|
|
printf(PROMPT_F);
|
|
} else
|
|
#define X(F, DESC, APPLY, ...) \
|
|
if (t_len == sizeof(#F) / sizeof(char) - 1 && !strcmp(#F, token)) \
|
|
APPLY(F, ##__VA_ARGS__); \
|
|
else
|
|
TOKENS
|
|
#undef X
|
|
if (*parsef(token, &x) == '\0')
|
|
push(x);
|
|
else
|
|
printerr(UNKNOWN_TOKEN_ERR, token);
|
|
}
|
|
if (!length())
|
|
putchar('\n');
|
|
while (length())
|
|
printf(POP_PRINT_F, pop());
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
#define COMMAND_W "10"
|
|
#define NEWLINE_DESC "pop top of stack and print it"
|
|
/* help: prints all available calculator functions */
|
|
void help(void)
|
|
{
|
|
printf("%-" COMMAND_W "s" NEWLINE_DESC "\n", "ENTER");
|
|
#define X(F, DESC, ...) printf("%-" COMMAND_W "s" DESC "\n", #F);
|
|
TOKENS
|
|
#undef X
|
|
}
|
|
|
|
/* -------- PARSING FUNCTIONS */
|
|
#include <ctype.h>
|
|
|
|
#define BLANK ' '
|
|
|
|
/* gettoken: get next space delimited token from input
|
|
* return token length, -1 on newline and 0 on EOF */
|
|
int gettoken(char *token, int t_max)
|
|
{
|
|
|
|
static int c = BLANK;
|
|
|
|
while (isspace(c) && c != '\n') /* remove leading whitespace */
|
|
c = getchar();
|
|
|
|
if (c == '\n') { /* newline is a token */
|
|
c = BLANK;
|
|
return -1;
|
|
}
|
|
|
|
/* fetch token */
|
|
int i;
|
|
for (i = 0; i < t_max && c != EOF && !isspace(c); c = getchar(), i++)
|
|
token[i] = c;
|
|
|
|
token[i] = '\0';
|
|
return i;
|
|
}
|
|
|
|
/* ---------- CUSTOM ATOF */
|
|
#define DEC_SEP X('.') X(',')
|
|
#define EXP_SEP X('e') X('E')
|
|
|
|
|
|
/* macros for parsef*/
|
|
#define SIGN(s) \
|
|
((*s == '-') ? (s++, -1) : ((*s == '+') ? (s++, 1) : 1))
|
|
#define ATOI(s, x, ...) \
|
|
for (; isdigit(*s); s++, ##__VA_ARGS__) \
|
|
(x) = 10 * (x) + (*s - '0')
|
|
|
|
/* parsef: convert string s to double, write it to *x
|
|
* return pointer of last read char in s */
|
|
char * parsef(char s[], double *x)
|
|
{
|
|
*x = 0;
|
|
/* integer part */
|
|
int sign = SIGN(s);
|
|
ATOI(s, *x);
|
|
|
|
#define X(sep) *s != sep &&
|
|
if (DEC_SEP 1) {
|
|
*x *= sign;
|
|
return s;
|
|
}
|
|
#undef X
|
|
s++;
|
|
/* fractional part */
|
|
int exp = 0;
|
|
ATOI(s, *x, exp--);
|
|
*x *= sign * pow(10, exp);
|
|
|
|
#define X(sep) *s != sep &&
|
|
if (EXP_SEP 1)
|
|
return s;
|
|
#undef X
|
|
s++;
|
|
/* exponent */
|
|
sign = SIGN(s);
|
|
exp = 0;
|
|
ATOI(s, exp);
|
|
*x *= pow(10, sign * exp);
|
|
return s;
|
|
}
|