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 #if ENABLE_FEATURE_DC_LIBM
57 static void power(void)
59 double topower = pop();
61 push(pow(pop(), topower));
65 static void divide(void)
67 double divisor = pop();
69 push(pop() / divisor);
76 push((unsigned) pop() % d);
81 push((unsigned) pop() & (unsigned) pop());
86 push((unsigned) pop() | (unsigned) pop());
91 push((unsigned) pop() ^ (unsigned) pop());
96 push(~(unsigned) pop());
99 static void set_output_base(void)
101 base = (unsigned)pop();
102 if ((base != 10) && (base != 16)) {
103 bb_error_msg("error, base %d is not supported", base);
108 static void print_base(double print)
111 printf("%x\n", (unsigned)print);
113 printf("%g\n", print);
116 static void print_stack_no_pop(void)
118 unsigned i = pointer;
120 print_base(stack[--i]);
123 static void print_no_pop(void)
125 print_base(stack[pointer-1]);
130 void (*function) (void);
133 static const struct op operators[] = {
142 #if ENABLE_FEATURE_DC_LIBM
155 {"f", print_stack_no_pop},
156 {"o", set_output_base},
157 { /* zero filled */ }
160 static void stack_machine(const char *argument)
164 const struct op *o = operators;
169 d = strtod(argument, &endPointer);
171 if (endPointer != argument) {
177 if (strcmp(o->name, argument) == 0) {
183 bb_error_msg_and_die("%s: syntax error", argument);
186 /* return pointer to next token in buffer and set *buffer to one char
187 * past the end of the above mentioned token
189 static char *get_token(char **buffer)
191 char *current = skip_whitespace(*buffer);
192 if (*current != '\0') {
193 *buffer = skip_non_whitespace(current);
199 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
200 int dc_main(int argc UNUSED_PARAM, char **argv)
206 /* take stuff from stdin if no args are given */
210 while ((line = xmalloc_fgetline(stdin)) != NULL) {
213 token = get_token(&cursor);
216 stack_machine(token);
221 if (argv[0][0] == '-')
224 stack_machine(*argv);