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 )
24 static void push(double a)
26 if (pointer >= STACK_SIZE)
27 bb_error_msg_and_die("stack overflow");
31 static double pop(void)
34 bb_error_msg_and_die("stack underflow");
35 return stack[--pointer];
45 double subtrahend = pop();
47 push(pop() - subtrahend);
55 static void power(void)
57 double topower = pop();
59 push(pow(pop(), topower));
62 static void divide(void)
64 double divisor = pop();
66 push(pop() / divisor);
73 push((unsigned) pop() % d);
78 push((unsigned) pop() & (unsigned) pop());
83 push((unsigned) pop() | (unsigned) pop());
88 push((unsigned) pop() ^ (unsigned) pop());
93 push(~(unsigned) pop());
96 static void set_output_base(void)
98 base = (unsigned)pop();
99 if ((base != 10) && (base != 16)) {
100 bb_error_msg("error, base %d is not supported", base);
105 static void print_base(double print)
108 printf("%x\n", (unsigned)print);
110 printf("%g\n", print);
113 static void print_stack_no_pop(void)
115 unsigned i = pointer;
117 print_base(stack[--i]);
120 static void print_no_pop(void)
122 print_base(stack[pointer-1]);
127 void (*function) (void);
130 static const struct op operators[] = {
150 {"f", print_stack_no_pop},
151 {"o", set_output_base},
152 { /* zero filled */ }
155 static void stack_machine(const char *argument)
159 const struct op *o = operators;
164 d = strtod(argument, &endPointer);
166 if (endPointer != argument) {
172 if (strcmp(o->name, argument) == 0) {
178 bb_error_msg_and_die("%s: syntax error", argument);
181 /* return pointer to next token in buffer and set *buffer to one char
182 * past the end of the above mentioned token
184 static char *get_token(char **buffer)
186 char *current = skip_whitespace(*buffer);
187 if (*current != '\0') {
188 *buffer = skip_non_whitespace(current);
194 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
195 int dc_main(int argc ATTRIBUTE_UNUSED, char **argv)
199 /* take stuff from stdin if no args are given */
203 while ((line = xmalloc_getline(stdin)) != NULL) {
206 token = get_token(&cursor);
209 stack_machine(token);
214 if (argv[0][0] == '-')
217 stack_machine(*argv);