1 /* vi: set sw=4 ts=4: */
10 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
12 static double stack[100];
13 static unsigned int pointer;
15 static void push(double a)
17 if (pointer >= (sizeof(stack) / sizeof(*stack)))
18 error_msg_and_die("stack overflow");
25 error_msg_and_die("stack underflow");
26 return stack[--pointer];
36 double subtrahend = pop();
38 push(pop() - subtrahend);
48 double divisor = pop();
50 push(pop() / divisor);
55 push((unsigned int) pop() & (unsigned int) pop());
60 push((unsigned int) pop() | (unsigned int) pop());
65 push((unsigned int) pop() ^ (unsigned int) pop());
70 push(~(unsigned int) pop());
75 printf("%g\n", pop());
83 static const struct op operators[] = {
99 static void stack_machine(const char *argument)
101 char *endPointer = 0;
103 const struct op *o = operators;
110 d = strtod(argument, &endPointer);
112 if (endPointer != argument) {
117 while (o->name != 0) {
118 if (strcmp(o->name, argument) == 0) {
124 error_msg_and_die("%s: syntax error.", argument);
127 /* return pointer to next token in buffer and set *buffer to one char
128 * past the end of the above mentioned token
130 static char *get_token(char **buffer)
133 char *current = *buffer;
135 while (isspace(*current)) { current++; }
138 while (!isspace(*current) && current != 0) { current++; }
144 /* In Perl one might say, scalar m|\s*(\S+)\s*|g */
145 static int number_of_tokens(char *buffer)
149 while (get_token(&b)) { i++; }
153 int dc_main(int argc, char **argv)
155 /* take stuff from stdin if no args are given */
161 while ((line = get_line_from_file(stdin))) {
163 len = number_of_tokens(line);
164 for (i = 0; i < len; i++) {
165 token = get_token(&cursor);
167 stack_machine(token);
175 stack_machine(argv[1]);