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