1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
9 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
17 enum { STACK_SIZE = (COMMON_BUFSIZE - offsetof(struct globals, stack)) / sizeof(double) };
18 #define G (*(struct globals*)&bb_common_bufsiz1)
19 #define pointer (G.pointer )
20 #define base (G.base )
21 #define stack (G.stack )
22 #define INIT_G() do { } while (0)
25 static void push(double a)
27 if (pointer >= STACK_SIZE)
28 bb_error_msg_and_die("stack overflow");
32 static double pop(void)
35 bb_error_msg_and_die("stack underflow");
36 return stack[--pointer];
46 double subtrahend = pop();
48 push(pop() - subtrahend);
56 static void power(void)
58 double topower = pop();
60 push(pow(pop(), topower));
63 static void divide(void)
65 double divisor = pop();
67 push(pop() / divisor);
74 push((unsigned) pop() % d);
79 push((unsigned) pop() & (unsigned) pop());
84 push((unsigned) pop() | (unsigned) pop());
89 push((unsigned) pop() ^ (unsigned) pop());
94 push(~(unsigned) pop());
97 static void set_output_base(void)
99 base = (unsigned)pop();
100 if ((base != 10) && (base != 16)) {
101 bb_error_msg("error, base %d is not supported", base);
106 static void print_base(double print)
109 printf("%x\n", (unsigned)print);
111 printf("%g\n", print);
114 static void print_stack_no_pop(void)
116 unsigned i = pointer;
118 print_base(stack[--i]);
121 static void print_no_pop(void)
123 print_base(stack[pointer-1]);
128 void (*function) (void);
131 static const struct op operators[] = {
151 {"f", print_stack_no_pop},
152 {"o", set_output_base},
153 { /* zero filled */ }
156 static void stack_machine(const char *argument)
160 const struct op *o = operators;
165 d = strtod(argument, &endPointer);
167 if (endPointer != argument) {
173 if (strcmp(o->name, argument) == 0) {
179 bb_error_msg_and_die("%s: syntax error", argument);
182 /* return pointer to next token in buffer and set *buffer to one char
183 * past the end of the above mentioned token
185 static char *get_token(char **buffer)
187 char *current = skip_whitespace(*buffer);
188 if (*current != '\0') {
189 *buffer = skip_non_whitespace(current);
195 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
196 int dc_main(int argc UNUSED_PARAM, char **argv)
202 /* take stuff from stdin if no args are given */
206 while ((line = xmalloc_fgetline(stdin)) != NULL) {
209 token = get_token(&cursor);
212 stack_machine(token);
217 if (argv[0][0] == '-')
220 stack_machine(*argv);