1 /* vi: set sw=4 ts=4: */
8 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
10 static const char math_usage[] = "math expression ...\n\n"
11 "This is a Tiny RPN calculator that understands the\n"
12 "following operations: +, -, /, *, and, or, not, eor.\n"
13 "i.e. 'math 2 2 add' -> 4, and 'math 8 8 \\* 2 2 + /' -> 16\n";
15 static double stack[100];
16 static unsigned int pointer;
18 static void push(double a)
20 if (pointer >= (sizeof(stack) / sizeof(*stack))) {
21 fprintf(stderr, "math: stack overflow\n");
30 fprintf(stderr, "math: stack underflow\n");
33 return stack[--pointer];
43 double subtrahend = pop();
45 push(pop() - subtrahend);
55 double divisor = pop();
57 push(pop() / divisor);
62 push((unsigned int) pop() & (unsigned int) pop());
67 push((unsigned int) pop() | (unsigned int) pop());
72 push((unsigned int) pop() ^ (unsigned int) pop());
77 push(~(unsigned int) pop());
82 printf("%g\n", pop());
90 static const struct op operators[] = {
102 static void stack_machine(const char *argument)
104 char *endPointer = 0;
106 const struct op *o = operators;
113 d = strtod(argument, &endPointer);
115 if (endPointer != argument) {
120 while (o->name != 0) {
121 if (strcmp(o->name, argument) == 0) {
127 fprintf(stderr, "math: %s: syntax error.\n", argument);
131 int math_main(int argc, char **argv)
133 if (argc <= 1 || *argv[1]=='-')
136 stack_machine(argv[1]);