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 { \
26 static void push(double a)
28 if (pointer >= STACK_SIZE)
29 bb_error_msg_and_die("stack overflow");
33 static double pop(void)
36 bb_error_msg_and_die("stack underflow");
37 return stack[--pointer];
47 double subtrahend = pop();
49 push(pop() - subtrahend);
57 static void power(void)
59 double topower = pop();
61 push(pow(pop(), topower));
64 static void divide(void)
66 double divisor = pop();
68 push(pop() / divisor);
75 push((unsigned) pop() % d);
80 push((unsigned) pop() & (unsigned) pop());
85 push((unsigned) pop() | (unsigned) pop());
90 push((unsigned) pop() ^ (unsigned) pop());
95 push(~(unsigned) pop());
98 static void set_output_base(void)
100 base = (unsigned)pop();
101 if ((base != 10) && (base != 16)) {
102 bb_error_msg("error, base %d is not supported", base);
107 static void print_base(double print)
110 printf("%x\n", (unsigned)print);
112 printf("%g\n", print);
115 static void print_stack_no_pop(void)
117 unsigned i = pointer;
119 print_base(stack[--i]);
122 static void print_no_pop(void)
124 print_base(stack[pointer-1]);
129 void (*function) (void);
132 static const struct op operators[] = {
152 {"f", print_stack_no_pop},
153 {"o", set_output_base},
154 { /* zero filled */ }
157 static void stack_machine(const char *argument)
161 const struct op *o = operators;
166 d = strtod(argument, &endPointer);
168 if (endPointer != argument) {
174 if (strcmp(o->name, argument) == 0) {
180 bb_error_msg_and_die("%s: syntax error", argument);
183 /* return pointer to next token in buffer and set *buffer to one char
184 * past the end of the above mentioned token
186 static char *get_token(char **buffer)
188 char *current = skip_whitespace(*buffer);
189 if (*current != '\0') {
190 *buffer = skip_non_whitespace(current);
196 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
197 int dc_main(int argc ATTRIBUTE_UNUSED, char **argv)
203 /* take stuff from stdin if no args are given */
207 while ((line = xmalloc_getline(stdin)) != NULL) {
210 token = get_token(&cursor);
213 stack_machine(token);
218 if (argv[0][0] == '-')
221 stack_machine(*argv);