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. */
11 enum { STACK_SIZE = COMMON_BUFSIZE / sizeof(double) };
13 #define stack ((double*)&bb_common_bufsiz1)
14 static unsigned int pointer;
15 static unsigned char base;
17 static void push(double a)
19 if (pointer >= STACK_SIZE)
20 bb_error_msg_and_die("stack overflow");
24 static double pop(void)
27 bb_error_msg_and_die("stack underflow");
28 return stack[--pointer];
38 double subtrahend = pop();
40 push(pop() - subtrahend);
48 static void power(void)
50 double topower = pop();
52 push(pow(pop(), topower));
55 static void divide(void)
57 double divisor = pop();
59 push(pop() / divisor);
64 unsigned int d = pop();
66 push((unsigned int) pop() % d);
71 push((unsigned int) pop() & (unsigned int) pop());
76 push((unsigned int) pop() | (unsigned int) pop());
81 push((unsigned int) pop() ^ (unsigned int) pop());
86 push(~(unsigned int) pop());
89 static void set_output_base(void)
91 base = (unsigned char)pop();
92 if ((base != 10) && (base != 16)) {
93 bb_error_msg("error, base %d is not supported", base);
98 static void print_base(double print)
101 printf("%x\n", (unsigned int)print);
103 printf("%g\n", print);
106 static void print_stack_no_pop(void)
108 unsigned int i = pointer;
110 print_base(stack[--i]);
113 static void print_no_pop(void)
115 print_base(stack[pointer-1]);
120 void (*function) (void);
123 static const struct op operators[] = {
143 {"f", print_stack_no_pop},
144 {"o", set_output_base},
148 static void stack_machine(const char *argument)
150 char *endPointer = 0;
152 const struct op *o = operators;
157 d = strtod(argument, &endPointer);
159 if (endPointer != argument) {
165 if (strcmp(o->name, argument) == 0) {
171 bb_error_msg_and_die("%s: syntax error", argument);
174 /* return pointer to next token in buffer and set *buffer to one char
175 * past the end of the above mentioned token
177 static char *get_token(char **buffer)
182 current = skip_whitespace(*buffer);
185 current = skip_non_whitespace(current);
191 /* In Perl one might say, scalar m|\s*(\S+)\s*|g */
192 static int number_of_tokens(char *buffer)
196 while (get_token(&b)) { i++; }
200 int dc_main(int argc, char **argv);
201 int dc_main(int argc, char **argv)
203 /* take stuff from stdin if no args are given */
209 while ((line = xmalloc_getline(stdin))) {
211 len = number_of_tokens(line);
212 for (i = 0; i < len; i++) {
213 token = get_token(&cursor);
215 stack_machine(token);
223 stack_machine(argv[1]);