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;
14 static unsigned char base;
16 static void push(double a)
18 if (pointer >= (sizeof(stack) / sizeof(*stack)))
19 bb_error_msg_and_die("stack overflow");
23 static double pop(void)
26 bb_error_msg_and_die("stack underflow");
27 return stack[--pointer];
37 double subtrahend = pop();
39 push(pop() - subtrahend);
47 static void divide(void)
49 double divisor = pop();
51 push(pop() / divisor);
56 push((unsigned int) pop() & (unsigned int) pop());
61 push((unsigned int) pop() | (unsigned int) pop());
66 push((unsigned int) pop() ^ (unsigned int) pop());
71 push(~(unsigned int) pop());
74 static void set_output_base(void)
76 base=(unsigned char)pop();
77 if ((base != 10) && (base != 16)) {
78 fprintf(stderr, "Error: base = %d is not supported.\n", base);
83 static void print_base(double print)
86 printf("%x\n", (unsigned int)print);
88 printf("%g\n", print);
91 static void print_stack_no_pop(void)
93 unsigned int i=pointer;
95 print_base(stack[--i]);
98 static void print_no_pop(void)
100 print_base(stack[pointer-1]);
103 static void print(void)
110 void (*function) (void);
113 static const struct op operators[] = {
127 {"f", print_stack_no_pop},
128 {"o", set_output_base},
132 static void stack_machine(const char *argument)
134 char *endPointer = 0;
136 const struct op *o = operators;
143 d = strtod(argument, &endPointer);
145 if (endPointer != argument) {
150 while (o->name != 0) {
151 if (strcmp(o->name, argument) == 0) {
157 bb_error_msg_and_die("%s: syntax error.", argument);
160 /* return pointer to next token in buffer and set *buffer to one char
161 * past the end of the above mentioned token
163 static char *get_token(char **buffer)
166 char *current = *buffer;
168 while (isspace(*current)) { current++; }
171 while (!isspace(*current) && *current != 0) { current++; }
177 /* In Perl one might say, scalar m|\s*(\S+)\s*|g */
178 static int number_of_tokens(char *buffer)
182 while (get_token(&b)) { i++; }
186 int dc_main(int argc, char **argv)
188 /* take stuff from stdin if no args are given */
194 while ((line = bb_get_chomped_line_from_file(stdin))) {
196 len = number_of_tokens(line);
197 for (i = 0; i < len; i++) {
198 token = get_token(&cursor);
200 stack_machine(token);
208 stack_machine(argv[1]);