2b77cd6148c8afa42bfa076a38685ba3509ce6bc
[oweals/busybox.git] / miscutils / dc.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4  */
5 //config:config DC
6 //config:       bool "dc"
7 //config:       default y
8 //config:       help
9 //config:         Dc is a reverse-polish desk calculator which supports unlimited
10 //config:         precision arithmetic.
11 //config:
12 //config:config FEATURE_DC_LIBM
13 //config:       bool "Enable power and exp functions (requires libm)"
14 //config:       default y
15 //config:       depends on DC
16 //config:       help
17 //config:         Enable power and exp functions.
18 //config:         NOTE: This will require libm to be present for linking.
19
20 //usage:#define dc_trivial_usage
21 //usage:       "EXPRESSION..."
22 //usage:
23 //usage:#define dc_full_usage "\n\n"
24 //usage:       "Tiny RPN calculator. Operations:\n"
25 //usage:       "+, add, -, sub, *, mul, /, div, %, mod, "IF_FEATURE_DC_LIBM("**, exp, ")"and, or, not, xor,\n"
26 //usage:       "p - print top of the stack (without popping),\n"
27 //usage:       "f - print entire stack,\n"
28 //usage:       "o - pop the value and set output radix (must be 10, 16, 8 or 2).\n"
29 //usage:       "Examples: 'dc 2 2 add p' -> 4, 'dc 8 8 mul 2 2 + / p' -> 16"
30 //usage:
31 //usage:#define dc_example_usage
32 //usage:       "$ dc 2 2 + p\n"
33 //usage:       "4\n"
34 //usage:       "$ dc 8 8 \\* 2 2 + / p\n"
35 //usage:       "16\n"
36 //usage:       "$ dc 0 1 and p\n"
37 //usage:       "0\n"
38 //usage:       "$ dc 0 1 or p\n"
39 //usage:       "1\n"
40 //usage:       "$ echo 72 9 div 8 mul p | dc\n"
41 //usage:       "64\n"
42
43 #include "libbb.h"
44 #include "common_bufsiz.h"
45 #include <math.h>
46
47 #if 0
48 typedef unsigned data_t;
49 #define DATA_FMT ""
50 #elif 0
51 typedef unsigned long data_t;
52 #define DATA_FMT "l"
53 #else
54 typedef unsigned long long data_t;
55 #define DATA_FMT "ll"
56 #endif
57
58
59 struct globals {
60         unsigned pointer;
61         unsigned base;
62         double stack[1];
63 } FIX_ALIASING;
64 enum { STACK_SIZE = (COMMON_BUFSIZE - offsetof(struct globals, stack)) / sizeof(double) };
65 #define G (*(struct globals*)bb_common_bufsiz1)
66 #define pointer   (G.pointer   )
67 #define base      (G.base      )
68 #define stack     (G.stack     )
69 #define INIT_G() do { \
70         setup_common_bufsiz(); \
71         base = 10; \
72 } while (0)
73
74
75 static void check_under(void)
76 {
77         if (pointer == 0)
78                 bb_error_msg_and_die("stack underflow");
79 }
80
81 static void push(double a)
82 {
83         if (pointer >= STACK_SIZE)
84                 bb_error_msg_and_die("stack overflow");
85         stack[pointer++] = a;
86 }
87
88 static double pop(void)
89 {
90         check_under();
91         return stack[--pointer];
92 }
93
94 static void add(void)
95 {
96         push(pop() + pop());
97 }
98
99 static void sub(void)
100 {
101         double subtrahend = pop();
102
103         push(pop() - subtrahend);
104 }
105
106 static void mul(void)
107 {
108         push(pop() * pop());
109 }
110
111 #if ENABLE_FEATURE_DC_LIBM
112 static void power(void)
113 {
114         double topower = pop();
115
116         push(pow(pop(), topower));
117 }
118 #endif
119
120 static void divide(void)
121 {
122         double divisor = pop();
123
124         push(pop() / divisor);
125 }
126
127 static void mod(void)
128 {
129         data_t d = pop();
130
131         push((data_t) pop() % d);
132 }
133
134 static void and(void)
135 {
136         push((data_t) pop() & (data_t) pop());
137 }
138
139 static void or(void)
140 {
141         push((data_t) pop() | (data_t) pop());
142 }
143
144 static void eor(void)
145 {
146         push((data_t) pop() ^ (data_t) pop());
147 }
148
149 static void not(void)
150 {
151         push(~(data_t) pop());
152 }
153
154 static void set_output_base(void)
155 {
156         static const char bases[] ALIGN1 = { 2, 8, 10, 16, 0 };
157         unsigned b = (unsigned)pop();
158
159         base = *strchrnul(bases, b);
160         if (base == 0) {
161                 bb_error_msg("error, base %u is not supported", b);
162                 base = 10;
163         }
164 }
165
166 static void print_base(double print)
167 {
168         data_t x, i;
169
170         x = (data_t) print;
171         if (base == 10) {
172                 if (x == print) /* exactly representable as unsigned integer */
173                         printf("%"DATA_FMT"u\n", x);
174                 else
175                         printf("%g\n", print);
176                 return;
177         }
178
179         switch (base) {
180         case 16:
181                 printf("%"DATA_FMT"x\n", x);
182                 break;
183         case 8:
184                 printf("%"DATA_FMT"o\n", x);
185                 break;
186         default: /* base 2 */
187                 i = MAXINT(data_t) - (MAXINT(data_t) >> 1);
188                 /* i is 100000...00000 */
189                 do {
190                         if (x & i)
191                                 break;
192                         i >>= 1;
193                 } while (i > 1);
194                 do {
195                         bb_putchar('1' - !(x & i));
196                         i >>= 1;
197                 } while (i);
198                 bb_putchar('\n');
199         }
200 }
201
202 static void print_stack_no_pop(void)
203 {
204         unsigned i = pointer;
205         while (i)
206                 print_base(stack[--i]);
207 }
208
209 static void print_no_pop(void)
210 {
211         check_under();
212         print_base(stack[pointer-1]);
213 }
214
215 struct op {
216         const char name[4];
217         void (*function) (void);
218 };
219
220 static const struct op operators[] = {
221 #if ENABLE_FEATURE_DC_LIBM
222         {"**",  power},
223         {"exp", power},
224         {"pow", power},
225 #endif
226         {"%",   mod},
227         {"mod", mod},
228         {"and", and},
229         {"or",  or},
230         {"not", not},
231         {"eor", eor},
232         {"xor", eor},
233         {"+",   add},
234         {"add", add},
235         {"-",   sub},
236         {"sub", sub},
237         {"*",   mul},
238         {"mul", mul},
239         {"/",   divide},
240         {"div", divide},
241         {"p", print_no_pop},
242         {"f", print_stack_no_pop},
243         {"o", set_output_base},
244 };
245
246 /* Feed the stack machine */
247 static void stack_machine(const char *argument)
248 {
249         char *end;
250         double number;
251         const struct op *o;
252
253  next:
254         number = strtod(argument, &end);
255         if (end != argument) {
256                 argument = end;
257                 push(number);
258                 goto next;
259         }
260
261         /* We might have matched a digit, eventually advance the argument */
262         argument = skip_whitespace(argument);
263
264         if (*argument == '\0')
265                 return;
266
267         o = operators;
268         do {
269                 char *after_name = is_prefixed_with(argument, o->name);
270                 if (after_name) {
271                         argument = after_name;
272                         o->function();
273                         goto next;
274                 }
275                 o++;
276         } while (o != operators + ARRAY_SIZE(operators));
277
278         bb_error_msg_and_die("syntax error at '%s'", argument);
279 }
280
281 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
282 int dc_main(int argc UNUSED_PARAM, char **argv)
283 {
284         INIT_G();
285
286         argv++;
287         if (!argv[0]) {
288                 /* take stuff from stdin if no args are given */
289                 char *line;
290                 while ((line = xmalloc_fgetline(stdin)) != NULL) {
291                         stack_machine(line);
292                         free(line);
293                 }
294         } else {
295                 do {
296                         stack_machine(*argv);
297                 } while (*++argv);
298         }
299         return EXIT_SUCCESS;
300 }