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 static const char bases[] ALIGN1 = { 2, 8, 10, 16, 0 };
102 unsigned b = (unsigned)pop();
104 base = *strchrnul(bases, b);
106 bb_error_msg("error, base %u is not supported", b);
111 static void print_base(double print)
116 printf("%g\n", print);
128 default: /* base 2 */
129 i = (unsigned)INT_MAX + 1;
135 bb_putchar('1' - !(x & i));
142 static void print_stack_no_pop(void)
144 unsigned i = pointer;
146 print_base(stack[--i]);
149 static void print_no_pop(void)
151 print_base(stack[pointer-1]);
156 void (*function) (void);
159 static const struct op operators[] = {
168 #if ENABLE_FEATURE_DC_LIBM
181 {"f", print_stack_no_pop},
182 {"o", set_output_base},
183 { /* zero filled */ }
186 static void stack_machine(const char *argument)
190 const struct op *o = operators;
195 d = strtod(argument, &endPointer);
197 if (endPointer != argument) {
203 if (strcmp(o->name, argument) == 0) {
209 bb_error_msg_and_die("%s: syntax error", argument);
212 /* return pointer to next token in buffer and set *buffer to one char
213 * past the end of the above mentioned token
215 static char *get_token(char **buffer)
217 char *current = skip_whitespace(*buffer);
218 if (*current != '\0') {
219 *buffer = skip_non_whitespace(current);
225 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
226 int dc_main(int argc UNUSED_PARAM, char **argv)
232 /* take stuff from stdin if no args are given */
236 while ((line = xmalloc_fgetline(stdin)) != NULL) {
239 token = get_token(&cursor);
242 stack_machine(token);
247 if (argv[0][0] == '-')
250 stack_machine(*argv);