1 /* vi: set sw=4 ts=4: */
9 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
11 static double stack[100];
12 static unsigned int pointer;
14 static void push(double a)
16 if (pointer >= (sizeof(stack) / sizeof(*stack)))
17 error_msg_and_die("stack overflow\n");
24 error_msg_and_die("stack underflow\n");
25 return stack[--pointer];
35 double subtrahend = pop();
37 push(pop() - subtrahend);
47 double divisor = pop();
49 push(pop() / divisor);
54 push((unsigned int) pop() & (unsigned int) pop());
59 push((unsigned int) pop() | (unsigned int) pop());
64 push((unsigned int) pop() ^ (unsigned int) pop());
69 push(~(unsigned int) pop());
74 printf("%g\n", pop());
82 static const struct op operators[] = {
98 static void stack_machine(const char *argument)
100 char *endPointer = 0;
102 const struct op *o = operators;
109 d = strtod(argument, &endPointer);
111 if (endPointer != argument) {
116 while (o->name != 0) {
117 if (strcmp(o->name, argument) == 0) {
123 error_msg_and_die("%s: syntax error.\n", argument);
126 /* return pointer to next token in buffer and set *buffer to one char
127 * past the end of the above mentioned token
129 static char *get_token(char **buffer)
132 char *current = *buffer;
134 while (isspace(*current)) { current++; }
137 while (!isspace(*current) && current != 0) { current++; }
143 /* In Perl one might say, scalar m|\s*(\S+)\s*|g */
144 static int number_of_tokens(char *buffer)
148 while (get_token(&b)) { i++; }
152 int dc_main(int argc, char **argv)
154 /* take stuff from stdin if no args are given */
160 while ((line = get_line_from_file(stdin))) {
162 len = number_of_tokens(line);
163 for (i = 0; i < len; i++) {
164 token = get_token(&cursor);
166 stack_machine(token);
174 stack_machine(argv[1]);