dc: unbreak interactive mode - was trying to get next tokens instead of executing
[oweals/busybox.git] / miscutils / bc.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4  * Copyright (c) 2018 Gavin D. Howard and contributors.
5  */
6 //config:config BC
7 //config:       bool "bc (45 kb; 49 kb when combined with dc)"
8 //config:       default y
9 //config:       help
10 //config:       bc is a command-line, arbitrary-precision calculator with a
11 //config:       Turing-complete language. See the GNU bc manual
12 //config:       (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
13 //config:       (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
14 //config:
15 //config:       This bc has five differences to the GNU bc:
16 //config:         1) The period (.) is a shortcut for "last", as in the BSD bc.
17 //config:         2) Arrays are copied before being passed as arguments to
18 //config:            functions. This behavior is required by the bc spec.
19 //config:         3) Arrays can be passed to the builtin "length" function to get
20 //config:            the number of elements in the array. This prints "1":
21 //config:               a[0] = 0; length(a[])
22 //config:         4) The precedence of the boolean "not" operator (!) is equal to
23 //config:            that of the unary minus (-) negation operator. This still
24 //config:            allows POSIX-compliant scripts to work while somewhat
25 //config:            preserving expected behavior (versus C) and making parsing
26 //config:            easier.
27 //config:         5) "read()" accepts expressions, not only numeric literals.
28 //config:
29 //config:       Options:
30 //config:         -i  --interactive  force interactive mode
31 //config:         -q  --quiet        don't print version and copyright
32 //config:         -s  --standard     error if any non-POSIX extensions are used
33 //config:         -w  --warn         warn if any non-POSIX extensions are used
34 //config:         -l  --mathlib      use predefined math routines:
35 //config:               s(expr) sine in radians
36 //config:               c(expr) cosine in radians
37 //config:               a(expr) arctangent, returning radians
38 //config:               l(expr) natural log
39 //config:               e(expr) raises e to the power of expr
40 //config:               j(n, x) Bessel function of integer order n of x
41 //config:
42 //config:config DC
43 //config:       bool "dc (38 kb; 49 kb when combined with bc)"
44 //config:       default y
45 //config:       help
46 //config:       dc is a reverse-polish notation command-line calculator which
47 //config:       supports unlimited precision arithmetic. See the FreeBSD man page
48 //config:       (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
49 //config:       (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
50 //config:
51 //config:       This dc has a few differences from the two above:
52 //config:         1) When printing a byte stream (command "P"), this dc follows what
53 //config:            the FreeBSD dc does.
54 //config:         2) Implements the GNU extensions for divmod ("~") and
55 //config:            modular exponentiation ("|").
56 //config:         3) Implements all FreeBSD extensions, except for "J" and "M".
57 //config:         4) Like the FreeBSD dc, this dc supports extended registers.
58 //config:            However, they are implemented differently. When it encounters
59 //config:            whitespace where a register should be, it skips the whitespace.
60 //config:            If the character following is not a lowercase letter, an error
61 //config:            is issued. Otherwise, the register name is parsed by the
62 //config:            following regex:
63 //config:               [a-z][a-z0-9_]*
64 //config:            This generally means that register names will be surrounded by
65 //config:            whitespace. Examples:
66 //config:               l idx s temp L index S temp2 < do_thing
67 //config:            Also note that, like the FreeBSD dc, extended registers are not
68 //config:            allowed unless the "-x" option is given.
69 //config:
70 //config:config FEATURE_DC_SMALL
71 //config:       bool "Minimal dc implementation (4.2 kb), not using bc code base"
72 //config:       depends on DC && !BC
73 //config:       default n
74 //config:
75 //config:config FEATURE_DC_LIBM
76 //config:       bool "Enable power and exp functions (requires libm)"
77 //config:       default y
78 //config:       depends on FEATURE_DC_SMALL
79 //config:       help
80 //config:       Enable power and exp functions.
81 //config:       NOTE: This will require libm to be present for linking.
82 //config:
83 //config:config FEATURE_BC_SIGNALS
84 //config:       bool "Interactive mode (+4kb)"
85 //config:       default y
86 //config:       depends on (BC || DC) && !FEATURE_DC_SMALL
87 //config:       help
88 //config:       Enable interactive mode: when started on a tty,
89 //config:       ^C interrupts execution and returns to command line,
90 //config:       errors also return to command line instead of exiting,
91 //config:       line editing with history is available.
92 //config:
93 //config:       With this option off, input can still be taken from tty,
94 //config:       but all errors are fatal, ^C is fatal,
95 //config:       tty is treated exactly the same as any other
96 //config:       standard input (IOW: no line editing).
97 //config:
98 //config:config FEATURE_BC_LONG_OPTIONS
99 //config:       bool "Enable bc/dc long options"
100 //config:       default y
101 //config:       depends on (BC || DC) && !FEATURE_DC_SMALL
102 //config:       help
103 //config:       Enable long options for bc and dc.
104
105 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
106 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
107
108 //kbuild:lib-$(CONFIG_BC) += bc.o
109 //kbuild:lib-$(CONFIG_DC) += bc.o
110
111 //See www.gnu.org/software/bc/manual/bc.html
112 //usage:#define bc_trivial_usage
113 //usage:       "[-sqlw] FILE..."
114 //usage:
115 //usage:#define bc_full_usage "\n"
116 //usage:     "\nArbitrary precision calculator"
117 //usage:     "\n"
118 ///////:     "\n        -i      Interactive" - has no effect for now
119 //usage:     "\n        -q      Quiet"
120 //usage:     "\n        -l      Load standard math library"
121 //usage:     "\n        -s      Be POSIX compatible"
122 //usage:     "\n        -w      Warn if extensions are used"
123 ///////:     "\n        -v      Version"
124 //usage:     "\n"
125 //usage:     "\n$BC_LINE_LENGTH changes output width"
126 //usage:
127 //usage:#define bc_example_usage
128 //usage:       "3 + 4.129\n"
129 //usage:       "1903 - 2893\n"
130 //usage:       "-129 * 213.28935\n"
131 //usage:       "12 / -1932\n"
132 //usage:       "12 % 12\n"
133 //usage:       "34 ^ 189\n"
134 //usage:       "scale = 13\n"
135 //usage:       "ibase = 2\n"
136 //usage:       "obase = A\n"
137 //usage:
138 //usage:#define dc_trivial_usage
139 //usage:       IF_NOT_FEATURE_DC_SMALL("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
140 //usage:
141 //usage:#define dc_full_usage "\n"
142 //usage:     "\nTiny RPN calculator. Operations:"
143 //usage:     "\n+, -, *, /, %, ~, ^," IF_NOT_FEATURE_DC_SMALL(" |,")
144 //usage:     "\np - print top of the stack (without popping)"
145 //usage:     "\nf - print entire stack"
146 //usage:     "\nk - pop the value and set the precision"
147 //usage:     "\ni - pop the value and set input radix"
148 //usage:     "\no - pop the value and set output radix"
149 //usage:     "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
150 //usage:
151 //usage:#define dc_example_usage
152 //usage:       "$ dc -e'2 2 + p'\n"
153 //usage:       "4\n"
154 //usage:       "$ dc -e'8 8 \\* 2 2 + / p'\n"
155 //usage:       "16\n"
156 //usage:       "$ dc -e'0 1 & p'\n"
157 //usage:       "0\n"
158 //usage:       "$ dc -e'0 1 | p'\n"
159 //usage:       "1\n"
160 //usage:       "$ echo '72 9 / 8 * p' | dc\n"
161 //usage:       "64\n"
162
163 #include "libbb.h"
164 #include "common_bufsiz.h"
165
166 #if ENABLE_FEATURE_DC_SMALL
167 # include "dc.c"
168 #else
169
170 #define DEBUG_LEXER   0
171 #define DEBUG_COMPILE 0
172 #define DEBUG_EXEC    0
173 // This can be left enabled for production as well:
174 #define SANITY_CHECKS 1
175
176 #if DEBUG_LEXER
177 static uint8_t lex_indent;
178 #define dbg_lex(...) \
179         do { \
180                 fprintf(stderr, "%*s", lex_indent, ""); \
181                 bb_error_msg(__VA_ARGS__); \
182         } while (0)
183 #define dbg_lex_enter(...) \
184         do { \
185                 dbg_lex(__VA_ARGS__); \
186                 lex_indent++; \
187         } while (0)
188 #define dbg_lex_done(...) \
189         do { \
190                 lex_indent--; \
191                 dbg_lex(__VA_ARGS__); \
192         } while (0)
193 #else
194 # define dbg_lex(...)       ((void)0)
195 # define dbg_lex_enter(...) ((void)0)
196 # define dbg_lex_done(...)  ((void)0)
197 #endif
198
199 #if DEBUG_COMPILE
200 # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
201 #else
202 # define dbg_compile(...) ((void)0)
203 #endif
204
205 #if DEBUG_EXEC
206 # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
207 #else
208 # define dbg_exec(...) ((void)0)
209 #endif
210
211 typedef enum BcStatus {
212         BC_STATUS_SUCCESS = 0,
213         BC_STATUS_FAILURE = 1,
214         BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr_empty_ok() uses this
215 } BcStatus;
216
217 #define BC_VEC_INVALID_IDX ((size_t) -1)
218 #define BC_VEC_START_CAP (1 << 5)
219
220 typedef void (*BcVecFree)(void *) FAST_FUNC;
221
222 typedef struct BcVec {
223         char *v;
224         size_t len;
225         size_t cap;
226         size_t size;
227         BcVecFree dtor;
228 } BcVec;
229
230 typedef signed char BcDig;
231
232 typedef struct BcNum {
233         BcDig *restrict num;
234         size_t rdx;
235         size_t len;
236         size_t cap;
237         bool neg;
238 } BcNum;
239
240 #define BC_NUM_MAX_IBASE        ((unsigned long) 16)
241 // larger value might speed up BIGNUM calculations a bit:
242 #define BC_NUM_DEF_SIZE         (16)
243 #define BC_NUM_PRINT_WIDTH      (69)
244
245 #define BC_NUM_KARATSUBA_LEN    (32)
246
247 typedef enum BcInst {
248 #if ENABLE_BC
249         BC_INST_INC_PRE,
250         BC_INST_DEC_PRE,
251         BC_INST_INC_POST,
252         BC_INST_DEC_POST,
253 #endif
254
255         BC_INST_NEG,
256
257         BC_INST_POWER,
258         BC_INST_MULTIPLY,
259         BC_INST_DIVIDE,
260         BC_INST_MODULUS,
261         BC_INST_PLUS,
262         BC_INST_MINUS,
263
264         BC_INST_REL_EQ,
265         BC_INST_REL_LE,
266         BC_INST_REL_GE,
267         BC_INST_REL_NE,
268         BC_INST_REL_LT,
269         BC_INST_REL_GT,
270
271         BC_INST_BOOL_NOT,
272         BC_INST_BOOL_OR,
273         BC_INST_BOOL_AND,
274
275 #if ENABLE_BC
276         BC_INST_ASSIGN_POWER,
277         BC_INST_ASSIGN_MULTIPLY,
278         BC_INST_ASSIGN_DIVIDE,
279         BC_INST_ASSIGN_MODULUS,
280         BC_INST_ASSIGN_PLUS,
281         BC_INST_ASSIGN_MINUS,
282 #endif
283         BC_INST_ASSIGN,
284
285         BC_INST_NUM,
286         BC_INST_VAR,
287         BC_INST_ARRAY_ELEM,
288         BC_INST_ARRAY,
289
290         BC_INST_SCALE_FUNC,
291         BC_INST_IBASE,
292         BC_INST_SCALE,
293         BC_INST_LAST,
294         BC_INST_LENGTH,
295         BC_INST_READ,
296         BC_INST_OBASE,
297         BC_INST_SQRT,
298
299         BC_INST_PRINT,
300         BC_INST_PRINT_POP,
301         BC_INST_STR,
302         BC_INST_PRINT_STR,
303
304 #if ENABLE_BC
305         BC_INST_HALT,
306         BC_INST_JUMP,
307         BC_INST_JUMP_ZERO,
308
309         BC_INST_CALL,
310         BC_INST_RET0,
311 #endif
312         BC_INST_RET,
313
314         BC_INST_POP,
315 #if ENABLE_DC
316         BC_INST_POP_EXEC,
317
318         BC_INST_MODEXP,
319         BC_INST_DIVMOD,
320
321         BC_INST_EXECUTE,
322         BC_INST_EXEC_COND,
323
324         BC_INST_ASCIIFY,
325         BC_INST_PRINT_STREAM,
326
327         BC_INST_PRINT_STACK,
328         BC_INST_CLEAR_STACK,
329         BC_INST_STACK_LEN,
330         BC_INST_DUPLICATE,
331         BC_INST_SWAP,
332
333         BC_INST_LOAD,
334         BC_INST_PUSH_VAR,
335         BC_INST_PUSH_TO_VAR,
336
337         BC_INST_QUIT,
338         BC_INST_NQUIT,
339
340         BC_INST_INVALID = -1,
341 #endif
342 } BcInst;
343
344 typedef struct BcId {
345         char *name;
346         size_t idx;
347 } BcId;
348
349 typedef struct BcFunc {
350         BcVec code;
351         IF_BC(BcVec labels;)
352         IF_BC(BcVec autos;)
353         IF_BC(BcVec strs;)
354         IF_BC(BcVec consts;)
355         IF_BC(size_t nparams;)
356 } BcFunc;
357
358 typedef enum BcResultType {
359         BC_RESULT_TEMP,
360
361         BC_RESULT_VAR,
362         BC_RESULT_ARRAY_ELEM,
363         BC_RESULT_ARRAY,
364
365         BC_RESULT_STR,
366
367         //code uses "inst - BC_INST_IBASE + BC_RESULT_IBASE" construct,
368         BC_RESULT_IBASE,  // relative order should match for: BC_INST_IBASE
369         BC_RESULT_SCALE,  // relative order should match for: BC_INST_SCALE
370         BC_RESULT_LAST,   // relative order should match for: BC_INST_LAST
371         BC_RESULT_CONSTANT,
372         BC_RESULT_ONE,
373         BC_RESULT_OBASE,  // relative order should match for: BC_INST_OBASE
374 } BcResultType;
375
376 typedef union BcResultData {
377         BcNum n;
378         BcVec v;
379         BcId id;
380 } BcResultData;
381
382 typedef struct BcResult {
383         BcResultType t;
384         BcResultData d;
385 } BcResult;
386
387 typedef struct BcInstPtr {
388         size_t func;
389         size_t inst_idx;
390         IF_BC(size_t results_len_before_call;)
391 } BcInstPtr;
392
393 // BC_LEX_NEG is not used in lexing; it is only for parsing.
394 typedef enum BcLexType {
395         BC_LEX_EOF,
396         BC_LEX_INVALID,
397
398         BC_LEX_OP_INC,
399         BC_LEX_OP_DEC,
400
401         BC_LEX_NEG,
402
403         BC_LEX_OP_POWER,
404         BC_LEX_OP_MULTIPLY,
405         BC_LEX_OP_DIVIDE,
406         BC_LEX_OP_MODULUS,
407         BC_LEX_OP_PLUS,
408         BC_LEX_OP_MINUS,
409
410         BC_LEX_OP_REL_EQ,
411         BC_LEX_OP_REL_LE,
412         BC_LEX_OP_REL_GE,
413         BC_LEX_OP_REL_NE,
414         BC_LEX_OP_REL_LT,
415         BC_LEX_OP_REL_GT,
416
417         BC_LEX_OP_BOOL_NOT,
418         BC_LEX_OP_BOOL_OR,
419         BC_LEX_OP_BOOL_AND,
420
421         BC_LEX_OP_ASSIGN_POWER,
422         BC_LEX_OP_ASSIGN_MULTIPLY,
423         BC_LEX_OP_ASSIGN_DIVIDE,
424         BC_LEX_OP_ASSIGN_MODULUS,
425         BC_LEX_OP_ASSIGN_PLUS,
426         BC_LEX_OP_ASSIGN_MINUS,
427         BC_LEX_OP_ASSIGN,
428
429         BC_LEX_NLINE,
430         BC_LEX_WHITESPACE,
431
432         BC_LEX_LPAREN,
433         BC_LEX_RPAREN,
434
435         BC_LEX_LBRACKET,
436         BC_LEX_COMMA,
437         BC_LEX_RBRACKET,
438
439         BC_LEX_LBRACE, // '{' is 0x7B, '}' is 0x7D,
440         BC_LEX_SCOLON,
441         BC_LEX_RBRACE, // should be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
442
443         BC_LEX_STR,
444         BC_LEX_NAME,
445         BC_LEX_NUMBER,
446
447         BC_LEX_KEY_1st_keyword,
448         BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
449         BC_LEX_KEY_BREAK,
450         BC_LEX_KEY_CONTINUE,
451         BC_LEX_KEY_DEFINE,
452         BC_LEX_KEY_ELSE,
453         BC_LEX_KEY_FOR,
454         BC_LEX_KEY_HALT,
455         // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
456         BC_LEX_KEY_IBASE,  // relative order should match for: BC_INST_IBASE
457         BC_LEX_KEY_IF,
458         BC_LEX_KEY_LAST,   // relative order should match for: BC_INST_LAST
459         BC_LEX_KEY_LENGTH,
460         BC_LEX_KEY_LIMITS,
461         BC_LEX_KEY_OBASE,  // relative order should match for: BC_INST_OBASE
462         BC_LEX_KEY_PRINT,
463         BC_LEX_KEY_QUIT,
464         BC_LEX_KEY_READ,
465         BC_LEX_KEY_RETURN,
466         BC_LEX_KEY_SCALE,
467         BC_LEX_KEY_SQRT,
468         BC_LEX_KEY_WHILE,
469
470 #if ENABLE_DC
471         BC_LEX_EQ_NO_REG,
472         BC_LEX_OP_MODEXP,
473         BC_LEX_OP_DIVMOD,
474
475         BC_LEX_COLON,
476         BC_LEX_ELSE,
477         BC_LEX_EXECUTE,
478         BC_LEX_PRINT_STACK,
479         BC_LEX_CLEAR_STACK,
480         BC_LEX_STACK_LEVEL,
481         BC_LEX_DUPLICATE,
482         BC_LEX_SWAP,
483         BC_LEX_POP,
484
485         BC_LEX_ASCIIFY,
486         BC_LEX_PRINT_STREAM,
487
488         // code uses "t - BC_LEX_STORE_IBASE + BC_INST_IBASE" construct,
489         BC_LEX_STORE_IBASE,  // relative order should match for: BC_INST_IBASE
490         BC_LEX_STORE_SCALE,  // relative order should match for: BC_INST_SCALE
491         BC_LEX_LOAD,
492         BC_LEX_LOAD_POP,
493         BC_LEX_STORE_PUSH,
494         BC_LEX_STORE_OBASE,  // relative order should match for: BC_INST_OBASE
495         BC_LEX_PRINT_POP,
496         BC_LEX_NQUIT,
497         BC_LEX_SCALE_FACTOR,
498 #endif
499 } BcLexType;
500 // must match order of BC_LEX_KEY_foo etc above
501 #if ENABLE_BC
502 struct BcLexKeyword {
503         char name8[8];
504 };
505 #define BC_LEX_KW_ENTRY(a, b) \
506         { .name8 = a /*, .posix = b */ }
507 static const struct BcLexKeyword bc_lex_kws[20] = {
508         BC_LEX_KW_ENTRY("auto"    , 1), // 0
509         BC_LEX_KW_ENTRY("break"   , 1), // 1
510         BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
511         BC_LEX_KW_ENTRY("define"  , 1), // 3
512         BC_LEX_KW_ENTRY("else"    , 0), // 4
513         BC_LEX_KW_ENTRY("for"     , 1), // 5
514         BC_LEX_KW_ENTRY("halt"    , 0), // 6
515         BC_LEX_KW_ENTRY("ibase"   , 1), // 7
516         BC_LEX_KW_ENTRY("if"      , 1), // 8
517         BC_LEX_KW_ENTRY("last"    , 0), // 9
518         BC_LEX_KW_ENTRY("length"  , 1), // 10
519         BC_LEX_KW_ENTRY("limits"  , 0), // 11
520         BC_LEX_KW_ENTRY("obase"   , 1), // 12
521         BC_LEX_KW_ENTRY("print"   , 0), // 13
522         BC_LEX_KW_ENTRY("quit"    , 1), // 14
523         BC_LEX_KW_ENTRY("read"    , 0), // 15
524         BC_LEX_KW_ENTRY("return"  , 1), // 16
525         BC_LEX_KW_ENTRY("scale"   , 1), // 17
526         BC_LEX_KW_ENTRY("sqrt"    , 1), // 18
527         BC_LEX_KW_ENTRY("while"   , 1), // 19
528 };
529 #undef BC_LEX_KW_ENTRY
530 #define STRING_if    (bc_lex_kws[8].name8)
531 #define STRING_else  (bc_lex_kws[4].name8)
532 #define STRING_while (bc_lex_kws[19].name8)
533 #define STRING_for   (bc_lex_kws[5].name8)
534 enum {
535         POSIX_KWORD_MASK = 0
536                 | (1 << 0)  // 0
537                 | (1 << 1)  // 1
538                 | (0 << 2)  // 2
539                 | (1 << 3)  // 3
540                 | (0 << 4)  // 4
541                 | (1 << 5)  // 5
542                 | (0 << 6)  // 6
543                 | (1 << 7)  // 7
544                 | (1 << 8)  // 8
545                 | (0 << 9)  // 9
546                 | (1 << 10) // 10
547                 | (0 << 11) // 11
548                 | (1 << 12) // 12
549                 | (0 << 13) // 13
550                 | (1 << 14) // 14
551                 | (0 << 15) // 15
552                 | (1 << 16) // 16
553                 | (1 << 17) // 17
554                 | (1 << 18) // 18
555                 | (1 << 19) // 19
556 };
557 #define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
558
559 // This is a bit array that corresponds to token types. An entry is
560 // true if the token is valid in an expression, false otherwise.
561 // Used to figure out when expr parsing should stop *without error message*
562 // - 0 element indicates this condition. 1 means "this token is to be eaten
563 // as part of the expression", token can them still be determined to be invalid
564 // by later processing.
565 enum {
566 #define EXBITS(a,b,c,d,e,f,g,h) \
567         ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
568         BC_PARSE_EXPRS_BITS = 0
569         + (EXBITS(0,0,1,1,1,1,1,1) << (0*8)) //  0: eof    inval ++    --     -     ^     *    /
570         + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) //  8: %      +     -     ==     <=    >=    !=   <
571         + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: >      !     ||    &&     ^=    *=    /=   %=
572         + (EXBITS(1,1,1,0,0,1,1,0) << (3*8)) // 24: +=     -=    =     NL     WS    (     )    [
573         + (EXBITS(0,0,0,0,0,0,1,1) << (4*8)) // 32: ,      ]     {     ;      }     STR   NAME NUM
574         + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto   break cont  define else  for   halt ibase
575         + (EXBITS(0,1,1,1,1,0,0,1) << (6*8)) // 48: if     last  len   limits obase print quit read - bug, why "limits" is allowed?
576         + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt  while
577 #undef EXBITS
578 };
579 static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
580 {
581 #if ULONG_MAX > 0xffffffff
582         // 64-bit version (will not work correctly for 32-bit longs!)
583         return BC_PARSE_EXPRS_BITS & (1UL << i);
584 #else
585         // 32-bit version
586         unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
587         if (i >= 32) {
588                 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
589                 i &= 31;
590         }
591         return m & (1UL << i);
592 #endif
593 }
594
595 // This is an array of data for operators that correspond to
596 // [BC_LEX_OP_INC...BC_LEX_OP_ASSIGN] token types.
597 static const uint8_t bc_parse_ops[] = {
598 #define OP(p,l) ((int)(l) * 0x10 + (p))
599         OP(0, false), OP( 0, false ), // inc dec
600         OP(1, false), // neg
601         OP(2, false), // pow
602         OP(3, true ), OP( 3, true  ), OP( 3, true  ), // mul div mod
603         OP(4, true ), OP( 4, true  ), // + -
604         OP(6, true ), OP( 6, true  ), OP( 6, true  ), OP( 6, true  ), OP( 6, true  ), OP( 6, true ), // == <= >= != < >
605         OP(1, false), // not
606         OP(7, true ), OP( 7, true  ), // or and
607         OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
608         OP(5, false), OP( 5, false ), // -= =
609 #undef OP
610 };
611 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
612 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
613 #endif // ENABLE_BC
614
615 #if ENABLE_DC
616 static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
617 int8_t
618 dc_parse_insts[] = {
619         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
620         BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
621         BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
622         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
623         BC_INST_INVALID, BC_INST_INVALID,
624         BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
625         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
626         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
627         BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
628         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
629         BC_INST_INVALID, BC_INST_INVALID,
630         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
631         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
632         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
633         BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
634         BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
635         BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
636         BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
637         BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
638         BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
639         BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
640         BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
641         BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
642 };
643 #endif // ENABLE_DC
644
645 typedef struct BcLex {
646         const char *buf;
647         size_t i;
648         size_t line;
649         size_t len;
650         bool newline;
651         struct {
652                 BcLexType t;
653                 BcLexType last;
654                 BcVec v;
655         } t;
656 } BcLex;
657
658 #define BC_PARSE_STREND         (0xff)
659
660 #if ENABLE_BC
661 # define BC_PARSE_REL           (1 << 0)
662 # define BC_PARSE_PRINT         (1 << 1)
663 # define BC_PARSE_ARRAY         (1 << 2)
664 # define BC_PARSE_NOCALL        (1 << 3)
665 #endif
666
667 typedef struct BcParse {
668         BcLex l;
669
670         IF_BC(BcVec exits;)
671         IF_BC(BcVec conds;)
672         IF_BC(BcVec ops;)
673
674         BcFunc *func;
675         size_t fidx;
676
677         IF_BC(size_t in_funcdef;)
678 } BcParse;
679
680 typedef struct BcProgram {
681         size_t len;
682         size_t nchars;
683
684         size_t scale;
685         size_t ib_t;
686         size_t ob_t;
687
688         BcVec results;
689         BcVec exestack;
690
691         BcVec fns;
692         IF_BC(BcVec fn_map;)
693
694         BcVec vars;
695         BcVec var_map;
696
697         BcVec arrs;
698         BcVec arr_map;
699
700         IF_DC(BcVec strs;)
701         IF_DC(BcVec consts;)
702
703         const char *file;
704
705         BcNum zero;
706         IF_BC(BcNum one;)
707         IF_BC(BcNum last;)
708 } BcProgram;
709
710 #define BC_PROG_MAIN (0)
711 #define BC_PROG_READ (1)
712 #if ENABLE_DC
713 #define BC_PROG_REQ_FUNCS (2)
714 #endif
715
716 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
717 #define BC_PROG_NUM(r, n) \
718         ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
719
720 #define BC_FLAG_W (1 << 0)
721 #define BC_FLAG_V (1 << 1)
722 #define BC_FLAG_S (1 << 2)
723 #define BC_FLAG_Q (1 << 3)
724 #define BC_FLAG_L (1 << 4)
725 #define BC_FLAG_I (1 << 5)
726 #define DC_FLAG_X (1 << 6)
727
728 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
729 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
730
731 #define BC_MAX_OBASE    ((unsigned) 999)
732 #define BC_MAX_DIM      ((unsigned) INT_MAX)
733 #define BC_MAX_SCALE    ((unsigned) UINT_MAX)
734 #define BC_MAX_STRING   ((unsigned) UINT_MAX - 1)
735 #define BC_MAX_NUM      BC_MAX_STRING
736 // Unused apart from "limits" message. Just show a "biggish number" there.
737 //#define BC_MAX_NAME     BC_MAX_STRING
738 //#define BC_MAX_EXP      ((unsigned long) LONG_MAX)
739 //#define BC_MAX_VARS     ((unsigned long) SIZE_MAX - 1)
740 #define BC_MAX_NAME_STR "999999999"
741 #define BC_MAX_EXP_STR  "999999999"
742 #define BC_MAX_VARS_STR "999999999"
743
744 #define BC_MAX_OBASE_STR "999"
745
746 #if INT_MAX == 2147483647
747 # define BC_MAX_DIM_STR "2147483647"
748 #elif INT_MAX == 9223372036854775807
749 # define BC_MAX_DIM_STR "9223372036854775807"
750 #else
751 # error Strange INT_MAX
752 #endif
753
754 #if UINT_MAX == 4294967295
755 # define BC_MAX_SCALE_STR  "4294967295"
756 # define BC_MAX_STRING_STR "4294967294"
757 #elif UINT_MAX == 18446744073709551615
758 # define BC_MAX_SCALE_STR  "18446744073709551615"
759 # define BC_MAX_STRING_STR "18446744073709551614"
760 #else
761 # error Strange UINT_MAX
762 #endif
763 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
764
765 struct globals {
766         IF_FEATURE_BC_SIGNALS(smallint ttyin;)
767         IF_FEATURE_CLEAN_UP(smallint exiting;)
768
769         BcParse prs;
770         BcProgram prog;
771
772         // For error messages. Can be set to current parsed line,
773         // or [TODO] to current executing line (can be before last parsed one)
774         unsigned err_line;
775
776         BcVec files;
777         BcVec input_buffer;
778         FILE *input_fp;
779
780         char *env_args;
781
782 #if ENABLE_FEATURE_EDITING
783         line_input_t *line_input_state;
784 #endif
785 } FIX_ALIASING;
786 #define G (*ptr_to_globals)
787 #define INIT_G() do { \
788         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
789 } while (0)
790 #define FREE_G() do { \
791         FREE_PTR_TO_GLOBALS(); \
792 } while (0)
793 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
794 #define G_warn  (ENABLE_BC && (option_mask32 & BC_FLAG_W))
795 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
796 #if ENABLE_FEATURE_BC_SIGNALS
797 # define G_interrupt bb_got_signal
798 # define G_ttyin     G.ttyin
799 #else
800 # define G_interrupt 0
801 # define G_ttyin     0
802 #endif
803 #if ENABLE_FEATURE_CLEAN_UP
804 # define G_exiting G.exiting
805 #else
806 # define G_exiting 0
807 #endif
808 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
809 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
810
811 // In configurations where errors abort instead of propagating error
812 // return code up the call chain, functions returning BC_STATUS
813 // actually don't return anything, they always succeed and return "void".
814 // A macro wrapper is provided, which makes this statement work:
815 //  s = zbc_func(...)
816 // and makes it visible to the compiler that s is always zero,
817 // allowing compiler to optimize dead code after the statement.
818 //
819 // To make code more readable, each such function has a "z"
820 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
821 //
822 #if ENABLE_FEATURE_BC_SIGNALS || ENABLE_FEATURE_CLEAN_UP
823 # define ERRORS_ARE_FATAL 0
824 # define ERRORFUNC        /*nothing*/
825 # define IF_ERROR_RETURN_POSSIBLE(a)  a
826 # define BC_STATUS        BcStatus
827 # define RETURN_STATUS(v) return (v)
828 # define COMMA_SUCCESS    /*nothing*/
829 #else
830 # define ERRORS_ARE_FATAL 1
831 # define ERRORFUNC        NORETURN
832 # define IF_ERROR_RETURN_POSSIBLE(a)  /*nothing*/
833 # define BC_STATUS        void
834 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
835 # define COMMA_SUCCESS    ,BC_STATUS_SUCCESS
836 #endif
837
838 #define STACK_HAS_MORE_THAN(s, n)          ((s)->len > ((size_t)(n)))
839 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
840
841 #define BC_NUM_NEG(n, neg)      ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
842 #define BC_NUM_ONE(n)           ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
843 #define BC_NUM_INT(n)           ((n)->len - (n)->rdx)
844 //#define BC_NUM_AREQ(a, b)       (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
845 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
846 {
847         return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
848 }
849 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
850 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
851 {
852         return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
853 }
854
855 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
856
857 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
858
859 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
860                         BcNumBinaryOp op, size_t req);
861 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
862 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
863 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
864 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
865 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
866 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
867
868 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
869 {
870         BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
871         (void) scale;
872         RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
873 }
874
875 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
876 {
877         BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
878         (void) scale;
879         RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
880 }
881
882 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
883 {
884         size_t req = BC_NUM_MREQ(a, b, scale);
885         RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
886 }
887
888 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
889 {
890         size_t req = BC_NUM_MREQ(a, b, scale);
891         RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
892 }
893
894 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
895 {
896         size_t req = BC_NUM_MREQ(a, b, scale);
897         RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
898 }
899
900 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
901 {
902         RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
903 }
904
905 static const BcNumBinaryOp zbc_program_ops[] = {
906         zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
907 };
908 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
909 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
910 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
911 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
912 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
913 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
914
915 static void fflush_and_check(void)
916 {
917         fflush_all();
918         if (ferror(stdout) || ferror(stderr))
919                 bb_perror_msg_and_die("output error");
920 }
921
922 #if ENABLE_FEATURE_CLEAN_UP
923 #define QUIT_OR_RETURN_TO_MAIN \
924 do { \
925         IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
926         G_exiting = 1; \
927         return BC_STATUS_FAILURE; \
928 } while (0)
929 #else
930 #define QUIT_OR_RETURN_TO_MAIN quit()
931 #endif
932
933 static void quit(void) NORETURN;
934 static void quit(void)
935 {
936         if (ferror(stdin))
937                 bb_perror_msg_and_die("input error");
938         fflush_and_check();
939         dbg_exec("quit(): exiting with exitcode SUCCESS");
940         exit(0);
941 }
942
943 static void bc_verror_msg(const char *fmt, va_list p)
944 {
945         const char *sv = sv; // for compiler
946         if (G.prog.file) {
947                 sv = applet_name;
948                 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
949         }
950         bb_verror_msg(fmt, p, NULL);
951         if (G.prog.file) {
952                 free((char*)applet_name);
953                 applet_name = sv;
954         }
955 }
956
957 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
958 {
959         va_list p;
960
961         va_start(p, fmt);
962         bc_verror_msg(fmt, p);
963         va_end(p);
964
965         if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
966                 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
967         exit(1);
968 }
969
970 #if ENABLE_BC
971 static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
972 {
973         va_list p;
974
975         // Are non-POSIX constructs totally ok?
976         if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
977                 return BC_STATUS_SUCCESS; // yes
978
979         va_start(p, fmt);
980         bc_verror_msg(fmt, p);
981         va_end(p);
982
983         // Do we treat non-POSIX constructs as errors?
984         if (!(option_mask32 & BC_FLAG_S))
985                 return BC_STATUS_SUCCESS; // no, it's a warning
986         if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
987                 return BC_STATUS_FAILURE;
988         exit(1);
989 }
990 #endif
991
992 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
993 // This idiom begs for tail-call optimization, but for it to work,
994 // function must not have caller-cleaned parameters on stack.
995 // Unfortunately, vararg function API does exactly that on most arches.
996 // Thus, use these shims for the cases when we have no vararg PARAMS:
997 static ERRORFUNC int bc_error(const char *msg)
998 {
999         IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
1000 }
1001 static ERRORFUNC int bc_error_bad_character(char c)
1002 {
1003         if (!c)
1004                 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
1005         IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
1006 }
1007 static ERRORFUNC int bc_error_bad_expression(void)
1008 {
1009         IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
1010 }
1011 static ERRORFUNC int bc_error_bad_token(void)
1012 {
1013         IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
1014 }
1015 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1016 {
1017         IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1018 }
1019 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1020 {
1021         IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1022 }
1023 #if ENABLE_BC
1024 static int bc_POSIX_requires(const char *msg)
1025 {
1026         return bc_posix_error_fmt("POSIX requires %s", msg);
1027 }
1028 static int bc_POSIX_does_not_allow(const char *msg)
1029 {
1030         return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1031 }
1032 static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1033 {
1034         return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1035 }
1036 static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1037 {
1038         return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1039 }
1040 #endif
1041
1042 static void bc_vec_grow(BcVec *v, size_t n)
1043 {
1044         size_t cap = v->cap * 2;
1045         while (cap < v->len + n) cap *= 2;
1046         v->v = xrealloc(v->v, v->size * cap);
1047         v->cap = cap;
1048 }
1049
1050 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1051 {
1052         v->size = esize;
1053         v->cap = BC_VEC_START_CAP;
1054         v->len = 0;
1055         v->dtor = dtor;
1056         v->v = xmalloc(esize * BC_VEC_START_CAP);
1057 }
1058
1059 static void bc_char_vec_init(BcVec *v)
1060 {
1061         bc_vec_init(v, sizeof(char), NULL);
1062 }
1063
1064 static void bc_vec_expand(BcVec *v, size_t req)
1065 {
1066         if (v->cap < req) {
1067                 v->v = xrealloc(v->v, v->size * req);
1068                 v->cap = req;
1069         }
1070 }
1071
1072 static void bc_vec_pop(BcVec *v)
1073 {
1074         v->len--;
1075         if (v->dtor)
1076                 v->dtor(v->v + (v->size * v->len));
1077 }
1078
1079 static void bc_vec_npop(BcVec *v, size_t n)
1080 {
1081         if (!v->dtor)
1082                 v->len -= n;
1083         else {
1084                 size_t len = v->len - n;
1085                 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1086         }
1087 }
1088
1089 static void bc_vec_pop_all(BcVec *v)
1090 {
1091         bc_vec_npop(v, v->len);
1092 }
1093
1094 static size_t bc_vec_push(BcVec *v, const void *data)
1095 {
1096         size_t len = v->len;
1097         if (len >= v->cap) bc_vec_grow(v, 1);
1098         memmove(v->v + (v->size * len), data, v->size);
1099         v->len++;
1100         return len;
1101 }
1102
1103 // G.prog.results often needs "pop old operand, push result" idiom.
1104 // Can do this without a few extra ops
1105 static size_t bc_result_pop_and_push(const void *data)
1106 {
1107         BcVec *v = &G.prog.results;
1108         char *last;
1109         size_t len = v->len - 1;
1110
1111         last = v->v + (v->size * len);
1112         if (v->dtor)
1113                 v->dtor(last);
1114         memmove(last, data, v->size);
1115         return len;
1116 }
1117
1118 static size_t bc_vec_pushByte(BcVec *v, char data)
1119 {
1120         return bc_vec_push(v, &data);
1121 }
1122
1123 static size_t bc_vec_pushZeroByte(BcVec *v)
1124 {
1125         //return bc_vec_pushByte(v, '\0');
1126         // better:
1127         return bc_vec_push(v, &const_int_0);
1128 }
1129
1130 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1131 {
1132         if (idx == v->len)
1133                 bc_vec_push(v, data);
1134         else {
1135                 char *ptr;
1136
1137                 if (v->len == v->cap) bc_vec_grow(v, 1);
1138
1139                 ptr = v->v + v->size * idx;
1140
1141                 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1142                 memmove(ptr, data, v->size);
1143         }
1144 }
1145
1146 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1147 {
1148         bc_vec_pop_all(v);
1149         bc_vec_expand(v, len + 1);
1150         memcpy(v->v, str, len);
1151         v->len = len;
1152
1153         bc_vec_pushZeroByte(v);
1154 }
1155
1156 #if ENABLE_FEATURE_BC_SIGNALS && ENABLE_FEATURE_EDITING
1157 static void bc_vec_concat(BcVec *v, const char *str)
1158 {
1159         size_t len, slen;
1160
1161         if (v->len == 0) bc_vec_pushZeroByte(v);
1162
1163         slen = strlen(str);
1164         len = v->len + slen;
1165
1166         if (v->cap < len) bc_vec_grow(v, slen);
1167         strcpy(v->v + v->len - 1, str);
1168
1169         v->len = len;
1170 }
1171 #endif
1172
1173 static void *bc_vec_item(const BcVec *v, size_t idx)
1174 {
1175         return v->v + v->size * idx;
1176 }
1177
1178 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1179 {
1180         return v->v + v->size * (v->len - idx - 1);
1181 }
1182
1183 static void *bc_vec_top(const BcVec *v)
1184 {
1185         return v->v + v->size * (v->len - 1);
1186 }
1187
1188 static FAST_FUNC void bc_vec_free(void *vec)
1189 {
1190         BcVec *v = (BcVec *) vec;
1191         bc_vec_pop_all(v);
1192         free(v->v);
1193 }
1194
1195 static BcFunc* bc_program_func(size_t idx)
1196 {
1197         return bc_vec_item(&G.prog.fns, idx);
1198 }
1199 // BC_PROG_MAIN is zeroth element, so:
1200 #define bc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1201
1202 #if ENABLE_BC
1203 static BcFunc* bc_program_current_func(void)
1204 {
1205         BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1206         BcFunc *func = bc_program_func(ip->func);
1207         return func;
1208 }
1209 #endif
1210
1211 static char** bc_program_str(size_t idx)
1212 {
1213 #if ENABLE_BC
1214         if (IS_BC) {
1215                 BcFunc *func = bc_program_current_func();
1216                 return bc_vec_item(&func->strs, idx);
1217         }
1218 #endif
1219         IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1220 }
1221
1222 static char** bc_program_const(size_t idx)
1223 {
1224 #if ENABLE_BC
1225         if (IS_BC) {
1226                 BcFunc *func = bc_program_current_func();
1227                 return bc_vec_item(&func->consts, idx);
1228         }
1229 #endif
1230         IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1231 }
1232
1233 static int bc_id_cmp(const void *e1, const void *e2)
1234 {
1235         return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1236 }
1237
1238 static FAST_FUNC void bc_id_free(void *id)
1239 {
1240         free(((BcId *) id)->name);
1241 }
1242
1243 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1244 {
1245         size_t low = 0, high = v->len;
1246
1247         while (low < high) {
1248                 size_t mid = (low + high) / 2;
1249                 BcId *id = bc_vec_item(v, mid);
1250                 int result = bc_id_cmp(ptr, id);
1251
1252                 if (result == 0)
1253                         return mid;
1254                 if (result < 0)
1255                         high = mid;
1256                 else
1257                         low = mid + 1;
1258         }
1259
1260         return low;
1261 }
1262
1263 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1264 {
1265         size_t n = *i = bc_map_find_ge(v, ptr);
1266
1267         if (n == v->len)
1268                 bc_vec_push(v, ptr);
1269         else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1270                 return 0; // "was not inserted"
1271         else
1272                 bc_vec_pushAt(v, ptr, n);
1273         return 1; // "was inserted"
1274 }
1275
1276 #if ENABLE_BC
1277 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1278 {
1279         size_t i = bc_map_find_ge(v, ptr);
1280         if (i >= v->len) return BC_VEC_INVALID_IDX;
1281         return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1282 }
1283 #endif
1284
1285 static int bad_input_byte(char c)
1286 {
1287         if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1288          || c > 0x7e
1289         ) {
1290                 bc_error_fmt("illegal character 0x%02x", c);
1291                 return 1;
1292         }
1293         return 0;
1294 }
1295
1296 // Note: it _appends_ data from fp to vec.
1297 static void bc_read_line(BcVec *vec, FILE *fp)
1298 {
1299  again:
1300         fflush_and_check();
1301
1302 #if ENABLE_FEATURE_BC_SIGNALS
1303         if (G_interrupt) { // ^C was pressed
1304  intr:
1305                 if (fp != stdin) {
1306                         // ^C while running a script (bc SCRIPT): die.
1307                         // We do not return to interactive prompt:
1308                         // user might be running us from a shell,
1309                         // and SCRIPT might be intended to terminate
1310                         // (e.g. contain a "halt" stmt).
1311                         // ^C dropping user into a bc prompt instead of
1312                         // the shell would be unexpected.
1313                         xfunc_die();
1314                 }
1315                 // ^C while interactive input
1316                 G_interrupt = 0;
1317                 // GNU bc says "interrupted execution."
1318                 // GNU dc says "Interrupt!"
1319                 fputs("\ninterrupted execution\n", stderr);
1320         }
1321
1322 # if ENABLE_FEATURE_EDITING
1323         if (G_ttyin && fp == stdin) {
1324                 int n, i;
1325 #  define line_buf bb_common_bufsiz1
1326                 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
1327                 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1328                         if (n == 0) // ^C
1329                                 goto intr;
1330                         bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
1331                         return;
1332                 }
1333                 i = 0;
1334                 for (;;) {
1335                         char c = line_buf[i++];
1336                         if (!c) break;
1337                         if (bad_input_byte(c)) goto again;
1338                 }
1339                 bc_vec_concat(vec, line_buf);
1340 #  undef line_buf
1341         } else
1342 # endif
1343 #endif
1344         {
1345                 int c;
1346                 bool bad_chars = 0;
1347                 size_t len = vec->len;
1348
1349                 do {
1350 #if ENABLE_FEATURE_BC_SIGNALS
1351                         if (G_interrupt) {
1352                                 // ^C was pressed: ignore entire line, get another one
1353                                 vec->len = len;
1354                                 goto intr;
1355                         }
1356 #endif
1357                         do c = fgetc(fp); while (c == '\0');
1358                         if (c == EOF) {
1359                                 if (ferror(fp))
1360                                         bb_perror_msg_and_die("input error");
1361                                 // Note: EOF does not append '\n'
1362                                 break;
1363                         }
1364                         bad_chars |= bad_input_byte(c);
1365                         bc_vec_pushByte(vec, (char)c);
1366                 } while (c != '\n');
1367
1368                 if (bad_chars) {
1369                         // Bad chars on this line
1370                         if (!G.prog.file) { // stdin
1371                                 // ignore entire line, get another one
1372                                 vec->len = len;
1373                                 goto again;
1374                         }
1375                         bb_perror_msg_and_die("file '%s' is not text", G.prog.file);
1376                 }
1377                 bc_vec_pushZeroByte(vec);
1378         }
1379 }
1380
1381 static void bc_num_setToZero(BcNum *n, size_t scale)
1382 {
1383         n->len = 0;
1384         n->neg = false;
1385         n->rdx = scale;
1386 }
1387
1388 static void bc_num_zero(BcNum *n)
1389 {
1390         bc_num_setToZero(n, 0);
1391 }
1392
1393 static void bc_num_one(BcNum *n)
1394 {
1395         bc_num_setToZero(n, 0);
1396         n->len = 1;
1397         n->num[0] = 1;
1398 }
1399
1400 // Note: this also sets BcNum to zero
1401 static void bc_num_init(BcNum *n, size_t req)
1402 {
1403         req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1404         //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1405         n->num = xmalloc(req);
1406         n->cap = req;
1407         n->rdx = 0;
1408         n->len = 0;
1409         n->neg = false;
1410 }
1411
1412 static void bc_num_init_DEF_SIZE(BcNum *n)
1413 {
1414         bc_num_init(n, BC_NUM_DEF_SIZE);
1415 }
1416
1417 static void bc_num_expand(BcNum *n, size_t req)
1418 {
1419         req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1420         if (req > n->cap) {
1421                 n->num = xrealloc(n->num, req);
1422                 n->cap = req;
1423         }
1424 }
1425
1426 static FAST_FUNC void bc_num_free(void *num)
1427 {
1428         free(((BcNum *) num)->num);
1429 }
1430
1431 static void bc_num_copy(BcNum *d, BcNum *s)
1432 {
1433         if (d != s) {
1434                 bc_num_expand(d, s->cap);
1435                 d->len = s->len;
1436                 d->neg = s->neg;
1437                 d->rdx = s->rdx;
1438                 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1439         }
1440 }
1441
1442 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1443 {
1444         size_t i;
1445         unsigned long pow, result;
1446
1447         if (n->neg) RETURN_STATUS(bc_error("negative number"));
1448
1449         for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1450                 unsigned long prev = result, powprev = pow;
1451
1452                 result += ((unsigned long) n->num[i]) * pow;
1453                 pow *= 10;
1454
1455                 if (result < prev || pow < powprev)
1456                         RETURN_STATUS(bc_error("overflow"));
1457                 prev = result;
1458                 powprev = pow;
1459         }
1460         *result_p = result;
1461
1462         RETURN_STATUS(BC_STATUS_SUCCESS);
1463 }
1464 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1465
1466 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1467 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1468 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1469 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1470 #endif
1471 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1472 // would not hit realloc() code path - not good if num[] is not malloced
1473
1474 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1475 {
1476         BcDig *ptr;
1477
1478         bc_num_zero(n);
1479
1480         if (val == 0) return;
1481
1482         bc_num_expand(n, ULONG_NUM_BUFSIZE);
1483
1484         ptr = n->num;
1485         for (;;) {
1486                 n->len++;
1487                 *ptr++ = val % 10;
1488                 val /= 10;
1489                 if (val == 0) break;
1490         }
1491 }
1492
1493 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1494 {
1495         size_t i, j;
1496         for (i = 0; i < len; ++i) {
1497                 a[i] -= b[i];
1498                 for (j = i; a[j] < 0;) {
1499                         a[j++] += 10;
1500                         a[j] -= 1;
1501                 }
1502         }
1503 }
1504
1505 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1506 {
1507         size_t i = len;
1508         for (;;) {
1509                 int c;
1510                 if (i == 0)
1511                         return 0;
1512                 i--;
1513                 c = a[i] - b[i];
1514                 if (c != 0) {
1515                         i++;
1516                         if (c < 0)
1517                                 return -i;
1518                         return i;
1519                 }
1520         }
1521 }
1522
1523 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1524 {
1525         size_t i, min, a_int, b_int, diff;
1526         BcDig *max_num, *min_num;
1527         bool a_max, neg;
1528         ssize_t cmp;
1529
1530         if (a == b) return 0;
1531         if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1532         if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1533
1534         if (a->neg != b->neg) // signs of a and b differ
1535                 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1536                 return (int)b->neg - (int)a->neg;
1537         neg = a->neg; // 1 if both negative, 0 if both positive
1538
1539         a_int = BC_NUM_INT(a);
1540         b_int = BC_NUM_INT(b);
1541         a_int -= b_int;
1542
1543         if (a_int != 0) return (ssize_t) a_int;
1544
1545         a_max = (a->rdx > b->rdx);
1546         if (a_max) {
1547                 min = b->rdx;
1548                 diff = a->rdx - b->rdx;
1549                 max_num = a->num + diff;
1550                 min_num = b->num;
1551                 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1552         } else {
1553                 min = a->rdx;
1554                 diff = b->rdx - a->rdx;
1555                 max_num = b->num + diff;
1556                 min_num = a->num;
1557                 neg = !neg; // same as "neg = (a_max == neg)"
1558         }
1559
1560         cmp = bc_num_compare(max_num, min_num, b_int + min);
1561         if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1562
1563         for (max_num -= diff, i = diff - 1; i < diff; --i) {
1564                 if (max_num[i]) return BC_NUM_NEG(1, neg);
1565         }
1566
1567         return 0;
1568 }
1569
1570 static void bc_num_truncate(BcNum *n, size_t places)
1571 {
1572         if (places == 0) return;
1573
1574         n->rdx -= places;
1575
1576         if (n->len != 0) {
1577                 n->len -= places;
1578                 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1579         }
1580 }
1581
1582 static void bc_num_extend(BcNum *n, size_t places)
1583 {
1584         size_t len = n->len + places;
1585
1586         if (places != 0) {
1587                 if (n->cap < len) bc_num_expand(n, len);
1588
1589                 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1590                 memset(n->num, 0, sizeof(BcDig) * places);
1591
1592                 n->len += places;
1593                 n->rdx += places;
1594         }
1595 }
1596
1597 static void bc_num_clean(BcNum *n)
1598 {
1599         while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1600         if (n->len == 0)
1601                 n->neg = false;
1602         else if (n->len < n->rdx)
1603                 n->len = n->rdx;
1604 }
1605
1606 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1607 {
1608         if (n->rdx < scale)
1609                 bc_num_extend(n, scale - n->rdx);
1610         else
1611                 bc_num_truncate(n, n->rdx - scale);
1612
1613         bc_num_clean(n);
1614         if (n->len != 0) n->neg = !neg1 != !neg2;
1615 }
1616
1617 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1618                          BcNum *restrict b)
1619 {
1620         if (idx < n->len) {
1621                 b->len = n->len - idx;
1622                 a->len = idx;
1623                 a->rdx = b->rdx = 0;
1624
1625                 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1626                 memcpy(a->num, n->num, idx * sizeof(BcDig));
1627         } else {
1628                 bc_num_zero(b);
1629                 bc_num_copy(a, n);
1630         }
1631
1632         bc_num_clean(a);
1633         bc_num_clean(b);
1634 }
1635
1636 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1637 {
1638         if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1639
1640         // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1641         if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1642                 if (places + n->len > BC_MAX_NUM)
1643                         RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1644         }
1645
1646         if (n->rdx >= places)
1647                 n->rdx -= places;
1648         else {
1649                 bc_num_extend(n, places - n->rdx);
1650                 n->rdx = 0;
1651         }
1652
1653         bc_num_clean(n);
1654
1655         RETURN_STATUS(BC_STATUS_SUCCESS);
1656 }
1657 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1658
1659 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1660 {
1661         BcNum one;
1662         BcDig num[2];
1663
1664         one.cap = 2;
1665         one.num = num;
1666         bc_num_one(&one);
1667
1668         RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1669 }
1670 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1671
1672 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1673 {
1674         BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1675         size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1676         unsigned carry;
1677
1678         // Because this function doesn't need to use scale (per the bc spec),
1679         // I am hijacking it to say whether it's doing an add or a subtract.
1680
1681         if (a->len == 0) {
1682                 bc_num_copy(c, b);
1683                 if (sub && c->len) c->neg = !c->neg;
1684                 RETURN_STATUS(BC_STATUS_SUCCESS);
1685         }
1686         if (b->len == 0) {
1687                 bc_num_copy(c, a);
1688                 RETURN_STATUS(BC_STATUS_SUCCESS);
1689         }
1690
1691         c->neg = a->neg;
1692         c->rdx = BC_MAX(a->rdx, b->rdx);
1693         min_rdx = BC_MIN(a->rdx, b->rdx);
1694         c->len = 0;
1695
1696         if (a->rdx > b->rdx) {
1697                 diff = a->rdx - b->rdx;
1698                 ptr = a->num;
1699                 ptr_a = a->num + diff;
1700                 ptr_b = b->num;
1701         } else {
1702                 diff = b->rdx - a->rdx;
1703                 ptr = b->num;
1704                 ptr_a = a->num;
1705                 ptr_b = b->num + diff;
1706         }
1707
1708         ptr_c = c->num;
1709         for (i = 0; i < diff; ++i, ++c->len)
1710                 ptr_c[i] = ptr[i];
1711
1712         ptr_c += diff;
1713         a_int = BC_NUM_INT(a);
1714         b_int = BC_NUM_INT(b);
1715
1716         if (a_int > b_int) {
1717                 min_int = b_int;
1718                 max = a_int;
1719                 ptr = ptr_a;
1720         } else {
1721                 min_int = a_int;
1722                 max = b_int;
1723                 ptr = ptr_b;
1724         }
1725
1726         carry = 0;
1727         for (i = 0; i < min_rdx + min_int; ++i) {
1728                 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1729                 carry = in / 10;
1730                 ptr_c[i] = (BcDig)(in % 10);
1731         }
1732         for (; i < max + min_rdx; ++i) {
1733                 unsigned in = (unsigned)ptr[i] + carry;
1734                 carry = in / 10;
1735                 ptr_c[i] = (BcDig)(in % 10);
1736         }
1737         c->len += i;
1738
1739         if (carry != 0) c->num[c->len++] = (BcDig) carry;
1740
1741         RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1742 }
1743
1744 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1745 {
1746         ssize_t cmp;
1747         BcNum *minuend, *subtrahend;
1748         size_t start;
1749         bool aneg, bneg, neg;
1750
1751         // Because this function doesn't need to use scale (per the bc spec),
1752         // I am hijacking it to say whether it's doing an add or a subtract.
1753
1754         if (a->len == 0) {
1755                 bc_num_copy(c, b);
1756                 if (sub && c->len) c->neg = !c->neg;
1757                 RETURN_STATUS(BC_STATUS_SUCCESS);
1758         }
1759         if (b->len == 0) {
1760                 bc_num_copy(c, a);
1761                 RETURN_STATUS(BC_STATUS_SUCCESS);
1762         }
1763
1764         aneg = a->neg;
1765         bneg = b->neg;
1766         a->neg = b->neg = false;
1767
1768         cmp = bc_num_cmp(a, b);
1769
1770         a->neg = aneg;
1771         b->neg = bneg;
1772
1773         if (cmp == 0) {
1774                 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1775                 RETURN_STATUS(BC_STATUS_SUCCESS);
1776         }
1777         if (cmp > 0) {
1778                 neg = a->neg;
1779                 minuend = a;
1780                 subtrahend = b;
1781         } else {
1782                 neg = b->neg;
1783                 if (sub) neg = !neg;
1784                 minuend = b;
1785                 subtrahend = a;
1786         }
1787
1788         bc_num_copy(c, minuend);
1789         c->neg = neg;
1790
1791         if (c->rdx < subtrahend->rdx) {
1792                 bc_num_extend(c, subtrahend->rdx - c->rdx);
1793                 start = 0;
1794         } else
1795                 start = c->rdx - subtrahend->rdx;
1796
1797         bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1798
1799         bc_num_clean(c);
1800
1801         RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1802 }
1803
1804 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1805                          BcNum *restrict c)
1806 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1807 {
1808         BcStatus s;
1809         size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1810         BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1811         bool aone;
1812
1813         if (a->len == 0 || b->len == 0) {
1814                 bc_num_zero(c);
1815                 RETURN_STATUS(BC_STATUS_SUCCESS);
1816         }
1817         aone = BC_NUM_ONE(a);
1818         if (aone || BC_NUM_ONE(b)) {
1819                 bc_num_copy(c, aone ? b : a);
1820                 RETURN_STATUS(BC_STATUS_SUCCESS);
1821         }
1822
1823         if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1824          || a->len < BC_NUM_KARATSUBA_LEN
1825          || b->len < BC_NUM_KARATSUBA_LEN
1826         ) {
1827                 size_t i, j, len;
1828
1829                 bc_num_expand(c, a->len + b->len + 1);
1830
1831                 memset(c->num, 0, sizeof(BcDig) * c->cap);
1832                 c->len = len = 0;
1833
1834                 for (i = 0; i < b->len; ++i) {
1835                         unsigned carry = 0;
1836                         for (j = 0; j < a->len; ++j) {
1837                                 unsigned in = c->num[i + j];
1838                                 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1839                                 // note: compilers prefer _unsigned_ div/const
1840                                 carry = in / 10;
1841                                 c->num[i + j] = (BcDig)(in % 10);
1842                         }
1843
1844                         c->num[i + j] += (BcDig) carry;
1845                         len = BC_MAX(len, i + j + !!carry);
1846
1847 #if ENABLE_FEATURE_BC_SIGNALS
1848                         // a=2^1000000
1849                         // a*a <- without check below, this will not be interruptible
1850                         if (G_interrupt) return BC_STATUS_FAILURE;
1851 #endif
1852                 }
1853
1854                 c->len = len;
1855
1856                 RETURN_STATUS(BC_STATUS_SUCCESS);
1857         }
1858
1859         bc_num_init(&l1, max);
1860         bc_num_init(&h1, max);
1861         bc_num_init(&l2, max);
1862         bc_num_init(&h2, max);
1863         bc_num_init(&m1, max);
1864         bc_num_init(&m2, max);
1865         bc_num_init(&z0, max);
1866         bc_num_init(&z1, max);
1867         bc_num_init(&z2, max);
1868         bc_num_init(&temp, max + max);
1869
1870         bc_num_split(a, max2, &l1, &h1);
1871         bc_num_split(b, max2, &l2, &h2);
1872
1873         s = zbc_num_add(&h1, &l1, &m1, 0);
1874         if (s) goto err;
1875         s = zbc_num_add(&h2, &l2, &m2, 0);
1876         if (s) goto err;
1877
1878         s = zbc_num_k(&h1, &h2, &z0);
1879         if (s) goto err;
1880         s = zbc_num_k(&m1, &m2, &z1);
1881         if (s) goto err;
1882         s = zbc_num_k(&l1, &l2, &z2);
1883         if (s) goto err;
1884
1885         s = zbc_num_sub(&z1, &z0, &temp, 0);
1886         if (s) goto err;
1887         s = zbc_num_sub(&temp, &z2, &z1, 0);
1888         if (s) goto err;
1889
1890         s = zbc_num_shift(&z0, max2 * 2);
1891         if (s) goto err;
1892         s = zbc_num_shift(&z1, max2);
1893         if (s) goto err;
1894         s = zbc_num_add(&z0, &z1, &temp, 0);
1895         if (s) goto err;
1896         s = zbc_num_add(&temp, &z2, c, 0);
1897  err:
1898         bc_num_free(&temp);
1899         bc_num_free(&z2);
1900         bc_num_free(&z1);
1901         bc_num_free(&z0);
1902         bc_num_free(&m2);
1903         bc_num_free(&m1);
1904         bc_num_free(&h2);
1905         bc_num_free(&l2);
1906         bc_num_free(&h1);
1907         bc_num_free(&l1);
1908         RETURN_STATUS(s);
1909 }
1910
1911 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1912 {
1913         BcStatus s;
1914         BcNum cpa, cpb;
1915         size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1916
1917         scale = BC_MAX(scale, a->rdx);
1918         scale = BC_MAX(scale, b->rdx);
1919         scale = BC_MIN(a->rdx + b->rdx, scale);
1920         maxrdx = BC_MAX(maxrdx, scale);
1921
1922         bc_num_init(&cpa, a->len);
1923         bc_num_init(&cpb, b->len);
1924
1925         bc_num_copy(&cpa, a);
1926         bc_num_copy(&cpb, b);
1927         cpa.neg = cpb.neg = false;
1928
1929         s = zbc_num_shift(&cpa, maxrdx);
1930         if (s) goto err;
1931         s = zbc_num_shift(&cpb, maxrdx);
1932         if (s) goto err;
1933         s = zbc_num_k(&cpa, &cpb, c);
1934         if (s) goto err;
1935
1936         maxrdx += scale;
1937         bc_num_expand(c, c->len + maxrdx);
1938
1939         if (c->len < maxrdx) {
1940                 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1941                 c->len += maxrdx;
1942         }
1943
1944         c->rdx = maxrdx;
1945         bc_num_retireMul(c, scale, a->neg, b->neg);
1946  err:
1947         bc_num_free(&cpb);
1948         bc_num_free(&cpa);
1949         RETURN_STATUS(s);
1950 }
1951 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1952
1953 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1954 {
1955         BcStatus s;
1956         size_t len, end, i;
1957         BcNum cp;
1958
1959         if (b->len == 0)
1960                 RETURN_STATUS(bc_error("divide by zero"));
1961         if (a->len == 0) {
1962                 bc_num_setToZero(c, scale);
1963                 RETURN_STATUS(BC_STATUS_SUCCESS);
1964         }
1965         if (BC_NUM_ONE(b)) {
1966                 bc_num_copy(c, a);
1967                 bc_num_retireMul(c, scale, a->neg, b->neg);
1968                 RETURN_STATUS(BC_STATUS_SUCCESS);
1969         }
1970
1971         bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1972         bc_num_copy(&cp, a);
1973         len = b->len;
1974
1975         if (len > cp.len) {
1976                 bc_num_expand(&cp, len + 2);
1977                 bc_num_extend(&cp, len - cp.len);
1978         }
1979
1980         if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1981         cp.rdx -= b->rdx;
1982         if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1983
1984         if (b->rdx == b->len) {
1985                 for (;;) {
1986                         if (len == 0) break;
1987                         len--;
1988                         if (b->num[len] != 0)
1989                                 break;
1990                 }
1991                 len++;
1992         }
1993
1994         if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1995
1996         // We want an extra zero in front to make things simpler.
1997         cp.num[cp.len++] = 0;
1998         end = cp.len - len;
1999
2000         bc_num_expand(c, cp.len);
2001
2002         bc_num_zero(c);
2003         memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2004         c->rdx = cp.rdx;
2005         c->len = cp.len;
2006
2007         s = BC_STATUS_SUCCESS;
2008         for (i = end - 1; i < end; --i) {
2009                 BcDig *n, q;
2010                 n = cp.num + i;
2011                 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2012                         bc_num_subArrays(n, b->num, len);
2013                 c->num[i] = q;
2014 #if ENABLE_FEATURE_BC_SIGNALS
2015                 // a=2^100000
2016                 // scale=40000
2017                 // 1/a <- without check below, this will not be interruptible
2018                 if (G_interrupt) {
2019                         s = BC_STATUS_FAILURE;
2020                         break;
2021                 }
2022 #endif
2023         }
2024
2025         bc_num_retireMul(c, scale, a->neg, b->neg);
2026         bc_num_free(&cp);
2027
2028         RETURN_STATUS(s);
2029 }
2030 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2031
2032 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2033                          BcNum *restrict d, size_t scale, size_t ts)
2034 {
2035         BcStatus s;
2036         BcNum temp;
2037         bool neg;
2038
2039         if (b->len == 0)
2040                 RETURN_STATUS(bc_error("divide by zero"));
2041
2042         if (a->len == 0) {
2043                 bc_num_setToZero(d, ts);
2044                 RETURN_STATUS(BC_STATUS_SUCCESS);
2045         }
2046
2047         bc_num_init(&temp, d->cap);
2048         s = zbc_num_d(a, b, c, scale);
2049         if (s) goto err;
2050
2051         if (scale != 0) scale = ts;
2052
2053         s = zbc_num_m(c, b, &temp, scale);
2054         if (s) goto err;
2055         s = zbc_num_sub(a, &temp, d, scale);
2056         if (s) goto err;
2057
2058         if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2059
2060         neg = d->neg;
2061         bc_num_retireMul(d, ts, a->neg, b->neg);
2062         d->neg = neg;
2063  err:
2064         bc_num_free(&temp);
2065         RETURN_STATUS(s);
2066 }
2067 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2068
2069 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2070 {
2071         BcStatus s;
2072         BcNum c1;
2073         size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2074
2075         bc_num_init(&c1, len);
2076         s = zbc_num_r(a, b, &c1, c, scale, ts);
2077         bc_num_free(&c1);
2078
2079         RETURN_STATUS(s);
2080 }
2081 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2082
2083 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2084 {
2085         BcStatus s = BC_STATUS_SUCCESS;
2086         BcNum copy;
2087         unsigned long pow;
2088         size_t i, powrdx, resrdx;
2089         bool neg;
2090
2091         if (b->rdx) RETURN_STATUS(bc_error("non integer number"));
2092
2093         if (b->len == 0) {
2094                 bc_num_one(c);
2095                 RETURN_STATUS(BC_STATUS_SUCCESS);
2096         }
2097         if (a->len == 0) {
2098                 bc_num_setToZero(c, scale);
2099                 RETURN_STATUS(BC_STATUS_SUCCESS);
2100         }
2101         if (BC_NUM_ONE(b)) {
2102                 if (!b->neg)
2103                         bc_num_copy(c, a);
2104                 else
2105                         s = zbc_num_inv(a, c, scale);
2106                 RETURN_STATUS(s);
2107         }
2108
2109         neg = b->neg;
2110         b->neg = false;
2111
2112         s = zbc_num_ulong(b, &pow);
2113         if (s) RETURN_STATUS(s);
2114
2115         bc_num_init(&copy, a->len);
2116         bc_num_copy(&copy, a);
2117
2118         if (!neg) {
2119                 if (a->rdx > scale)
2120                         scale = a->rdx;
2121                 if (a->rdx * pow < scale)
2122                         scale = a->rdx * pow;
2123         }
2124
2125         b->neg = neg;
2126
2127         for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2128                 powrdx <<= 1;
2129                 s = zbc_num_mul(&copy, &copy, &copy, powrdx);
2130                 if (s) goto err;
2131                 // Not needed: zbc_num_mul() has a check for ^C:
2132                 //if (G_interrupt) {
2133                 //      s = BC_STATUS_FAILURE;
2134                 //      goto err;
2135                 //}
2136         }
2137
2138         bc_num_copy(c, &copy);
2139
2140         for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2141                 powrdx <<= 1;
2142                 s = zbc_num_mul(&copy, &copy, &copy, powrdx);
2143                 if (s) goto err;
2144
2145                 if (pow & 1) {
2146                         resrdx += powrdx;
2147                         s = zbc_num_mul(c, &copy, c, resrdx);
2148                         if (s) goto err;
2149                 }
2150                 // Not needed: zbc_num_mul() has a check for ^C:
2151                 //if (G_interrupt) {
2152                 //      s = BC_STATUS_FAILURE;
2153                 //      goto err;
2154                 //}
2155         }
2156
2157         if (neg) {
2158                 s = zbc_num_inv(c, c, scale);
2159                 if (s) goto err;
2160         }
2161
2162         if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2163
2164         // We can't use bc_num_clean() here.
2165         for (i = 0; i < c->len; ++i)
2166                 if (c->num[i] != 0)
2167                         goto skip;
2168         bc_num_setToZero(c, scale);
2169  skip:
2170
2171  err:
2172         bc_num_free(&copy);
2173         RETURN_STATUS(s);
2174 }
2175 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2176
2177 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2178                               BcNumBinaryOp op, size_t req)
2179 {
2180         BcStatus s;
2181         BcNum num2, *ptr_a, *ptr_b;
2182         bool init = false;
2183
2184         if (c == a) {
2185                 ptr_a = &num2;
2186                 memcpy(ptr_a, c, sizeof(BcNum));
2187                 init = true;
2188         } else
2189                 ptr_a = a;
2190
2191         if (c == b) {
2192                 ptr_b = &num2;
2193                 if (c != a) {
2194                         memcpy(ptr_b, c, sizeof(BcNum));
2195                         init = true;
2196                 }
2197         } else
2198                 ptr_b = b;
2199
2200         if (init)
2201                 bc_num_init(c, req);
2202         else
2203                 bc_num_expand(c, req);
2204
2205         s = BC_STATUS_SUCCESS;
2206         IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
2207
2208         if (init) bc_num_free(&num2);
2209
2210         RETURN_STATUS(s);
2211 }
2212 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
2213
2214 static bool bc_num_strValid(const char *val, size_t base)
2215 {
2216         BcDig b;
2217         bool radix;
2218
2219         b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2220         radix = false;
2221         for (;;) {
2222                 BcDig c = *val++;
2223                 if (c == '\0')
2224                         break;
2225                 if (c == '.') {
2226                         if (radix) return false;
2227                         radix = true;
2228                         continue;
2229                 }
2230                 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2231                         return false;
2232         }
2233         return true;
2234 }
2235
2236 // Note: n is already "bc_num_zero()"ed,
2237 // leading zeroes in "val" are removed
2238 static void bc_num_parseDecimal(BcNum *n, const char *val)
2239 {
2240         size_t len, i;
2241         const char *ptr;
2242
2243         len = strlen(val);
2244         if (len == 0)
2245                 return;
2246
2247         bc_num_expand(n, len);
2248
2249         ptr = strchr(val, '.');
2250
2251         n->rdx = 0;
2252         if (ptr != NULL)
2253                 n->rdx = (size_t)((val + len) - (ptr + 1));
2254
2255         for (i = 0; val[i]; ++i) {
2256                 if (val[i] != '0' && val[i] != '.') {
2257                         // Not entirely zero value - convert it, and exit
2258                         i = len - 1;
2259                         for (;;) {
2260                                 n->num[n->len] = val[i] - '0';
2261                                 ++n->len;
2262  skip_dot:
2263                                 if (i == 0) break;
2264                                 if (val[--i] == '.') goto skip_dot;
2265                         }
2266                         break;
2267                 }
2268         }
2269         // if for() exits without hitting if(), the value is entirely zero
2270 }
2271
2272 // Note: n is already "bc_num_zero()"ed,
2273 // leading zeroes in "val" are removed
2274 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2275 {
2276         BcStatus s;
2277         BcNum temp, mult, result;
2278         BcNum base;
2279         BcDig base_digs[ULONG_NUM_BUFSIZE];
2280         BcDig c = '\0';
2281         unsigned long v;
2282         size_t i, digits;
2283
2284         for (i = 0; ; ++i) {
2285                 if (val[i] == '\0')
2286                         return;
2287                 if (val[i] != '.' && val[i] != '0')
2288                         break;
2289         }
2290
2291         bc_num_init_DEF_SIZE(&temp);
2292         bc_num_init_DEF_SIZE(&mult);
2293         base.cap = ARRAY_SIZE(base_digs);
2294         base.num = base_digs;
2295         bc_num_ulong2num(&base, base_t);
2296
2297         for (;;) {
2298                 c = *val++;
2299                 if (c == '\0') goto int_err;
2300                 if (c == '.') break;
2301
2302                 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2303
2304                 s = zbc_num_mul(n, &base, &mult, 0);
2305                 if (s) goto int_err;
2306                 bc_num_ulong2num(&temp, v);
2307                 s = zbc_num_add(&mult, &temp, n, 0);
2308                 if (s) goto int_err;
2309         }
2310
2311         bc_num_init(&result, base.len);
2312         //bc_num_zero(&result); - already is
2313         bc_num_one(&mult);
2314
2315         digits = 0;
2316         for (;;) {
2317                 c = *val++;
2318                 if (c == '\0') break;
2319                 digits++;
2320
2321                 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2322
2323                 s = zbc_num_mul(&result, &base, &result, 0);
2324                 if (s) goto err;
2325                 bc_num_ulong2num(&temp, v);
2326                 s = zbc_num_add(&result, &temp, &result, 0);
2327                 if (s) goto err;
2328                 s = zbc_num_mul(&mult, &base, &mult, 0);
2329                 if (s) goto err;
2330         }
2331
2332         s = zbc_num_div(&result, &mult, &result, digits);
2333         if (s) goto err;
2334         s = zbc_num_add(n, &result, n, digits);
2335         if (s) goto err;
2336
2337         if (n->len != 0) {
2338                 if (n->rdx < digits)
2339                         bc_num_extend(n, digits - n->rdx);
2340         } else
2341                 bc_num_zero(n);
2342  err:
2343         bc_num_free(&result);
2344  int_err:
2345         bc_num_free(&mult);
2346         bc_num_free(&temp);
2347 }
2348
2349 static BC_STATUS zbc_num_parse(BcNum *n, const char *val, unsigned base_t)
2350 {
2351         if (!bc_num_strValid(val, base_t))
2352                 RETURN_STATUS(bc_error("bad number string"));
2353
2354         bc_num_zero(n);
2355         while (*val == '0') val++;
2356
2357         if (base_t == 10)
2358                 bc_num_parseDecimal(n, val);
2359         else
2360                 bc_num_parseBase(n, val, base_t);
2361
2362         RETURN_STATUS(BC_STATUS_SUCCESS);
2363 }
2364 #define zbc_num_parse(...) (zbc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2365
2366 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2367 {
2368         BcStatus s;
2369         BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2370         size_t pow, len, digs, digs1, resrdx, req, times = 0;
2371         ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2372
2373         req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2374         bc_num_expand(b, req);
2375
2376         if (a->len == 0) {
2377                 bc_num_setToZero(b, scale);
2378                 RETURN_STATUS(BC_STATUS_SUCCESS);
2379         }
2380         if (a->neg) {
2381                 RETURN_STATUS(bc_error("negative number"));
2382         }
2383         if (BC_NUM_ONE(a)) {
2384                 bc_num_one(b);
2385                 bc_num_extend(b, scale);
2386                 RETURN_STATUS(BC_STATUS_SUCCESS);
2387         }
2388
2389         scale = BC_MAX(scale, a->rdx) + 1;
2390         len = a->len + scale;
2391
2392         bc_num_init(&num1, len);
2393         bc_num_init(&num2, len);
2394         bc_num_init_DEF_SIZE(&half);
2395
2396         bc_num_one(&half);
2397         half.num[0] = 5;
2398         half.rdx = 1;
2399
2400         bc_num_init(&f, len);
2401         bc_num_init(&fprime, len);
2402
2403         x0 = &num1;
2404         x1 = &num2;
2405
2406         bc_num_one(x0);
2407         pow = BC_NUM_INT(a);
2408
2409         if (pow) {
2410                 if (pow & 1)
2411                         x0->num[0] = 2;
2412                 else
2413                         x0->num[0] = 6;
2414
2415                 pow -= 2 - (pow & 1);
2416
2417                 bc_num_extend(x0, pow);
2418
2419                 // Make sure to move the radix back.
2420                 x0->rdx -= pow;
2421         }
2422
2423         x0->rdx = digs = digs1 = 0;
2424         resrdx = scale + 2;
2425         len = BC_NUM_INT(x0) + resrdx - 1;
2426
2427         while (cmp != 0 || digs < len) {
2428                 s = zbc_num_div(a, x0, &f, resrdx);
2429                 if (s) goto err;
2430                 s = zbc_num_add(x0, &f, &fprime, resrdx);
2431                 if (s) goto err;
2432                 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2433                 if (s) goto err;
2434
2435                 cmp = bc_num_cmp(x1, x0);
2436                 digs = x1->len - (unsigned long long) llabs(cmp);
2437
2438                 if (cmp == cmp2 && digs == digs1)
2439                         times += 1;
2440                 else
2441                         times = 0;
2442
2443                 resrdx += times > 4;
2444
2445                 cmp2 = cmp1;
2446                 cmp1 = cmp;
2447                 digs1 = digs;
2448
2449                 temp = x0;
2450                 x0 = x1;
2451                 x1 = temp;
2452         }
2453
2454         bc_num_copy(b, x0);
2455         scale -= 1;
2456         if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2457  err:
2458         bc_num_free(&fprime);
2459         bc_num_free(&f);
2460         bc_num_free(&half);
2461         bc_num_free(&num2);
2462         bc_num_free(&num1);
2463         RETURN_STATUS(s);
2464 }
2465 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2466
2467 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2468                               size_t scale)
2469 {
2470         BcStatus s;
2471         BcNum num2, *ptr_a;
2472         bool init = false;
2473         size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2474
2475         if (c == a) {
2476                 memcpy(&num2, c, sizeof(BcNum));
2477                 ptr_a = &num2;
2478                 bc_num_init(c, len);
2479                 init = true;
2480         } else {
2481                 ptr_a = a;
2482                 bc_num_expand(c, len);
2483         }
2484
2485         s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2486
2487         if (init) bc_num_free(&num2);
2488
2489         RETURN_STATUS(s);
2490 }
2491 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2492
2493 #if ENABLE_DC
2494 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2495 {
2496         BcStatus s;
2497         BcNum base, exp, two, temp;
2498
2499         if (c->len == 0)
2500                 RETURN_STATUS(bc_error("divide by zero"));
2501         if (a->rdx || b->rdx || c->rdx)
2502                 RETURN_STATUS(bc_error("non integer number"));
2503         if (b->neg)
2504                 RETURN_STATUS(bc_error("negative number"));
2505
2506         bc_num_expand(d, c->len);
2507         bc_num_init(&base, c->len);
2508         bc_num_init(&exp, b->len);
2509         bc_num_init_DEF_SIZE(&two);
2510         bc_num_init(&temp, b->len);
2511
2512         bc_num_one(&two);
2513         two.num[0] = 2;
2514         bc_num_one(d);
2515
2516         s = zbc_num_rem(a, c, &base, 0);
2517         if (s) goto err;
2518         bc_num_copy(&exp, b);
2519
2520         while (exp.len != 0) {
2521                 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2522                 if (s) goto err;
2523
2524                 if (BC_NUM_ONE(&temp)) {
2525                         s = zbc_num_mul(d, &base, &temp, 0);
2526                         if (s) goto err;
2527                         s = zbc_num_rem(&temp, c, d, 0);
2528                         if (s) goto err;
2529                 }
2530
2531                 s = zbc_num_mul(&base, &base, &temp, 0);
2532                 if (s) goto err;
2533                 s = zbc_num_rem(&temp, c, &base, 0);
2534                 if (s) goto err;
2535         }
2536  err:
2537         bc_num_free(&temp);
2538         bc_num_free(&two);
2539         bc_num_free(&exp);
2540         bc_num_free(&base);
2541         RETURN_STATUS(s);
2542 }
2543 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2544 #endif // ENABLE_DC
2545
2546 #if ENABLE_BC
2547 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
2548 {
2549         BcId *autoid;
2550         BcId a;
2551         size_t i;
2552
2553         autoid = (void*)f->autos.v;
2554         for (i = 0; i < f->autos.len; i++, autoid++) {
2555                 if (strcmp(name, autoid->name) == 0)
2556                         RETURN_STATUS(bc_error("function parameter or auto var has the same name as another"));
2557         }
2558
2559         a.idx = var;
2560         a.name = name;
2561
2562         bc_vec_push(&f->autos, &a);
2563
2564         RETURN_STATUS(BC_STATUS_SUCCESS);
2565 }
2566 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
2567 #endif
2568
2569 static FAST_FUNC void bc_string_free(void *string)
2570 {
2571         free(*(char**)string);
2572 }
2573
2574 static void bc_func_init(BcFunc *f)
2575 {
2576         bc_char_vec_init(&f->code);
2577         IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2578         IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2579         IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2580         IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2581         IF_BC(f->nparams = 0;)
2582 }
2583
2584 static FAST_FUNC void bc_func_free(void *func)
2585 {
2586         BcFunc *f = (BcFunc *) func;
2587         bc_vec_free(&f->code);
2588         IF_BC(bc_vec_free(&f->labels);)
2589         IF_BC(bc_vec_free(&f->autos);)
2590         IF_BC(bc_vec_free(&f->strs);)
2591         IF_BC(bc_vec_free(&f->consts);)
2592 }
2593
2594 static void bc_array_expand(BcVec *a, size_t len);
2595
2596 static void bc_array_init(BcVec *a, bool nums)
2597 {
2598         if (nums)
2599                 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2600         else
2601                 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2602         bc_array_expand(a, 1);
2603 }
2604
2605 static void bc_array_expand(BcVec *a, size_t len)
2606 {
2607         if (a->dtor == bc_num_free
2608          // && a->size == sizeof(BcNum) - always true
2609         ) {
2610                 BcNum n;
2611                 while (len > a->len) {
2612                         bc_num_init_DEF_SIZE(&n);
2613                         bc_vec_push(a, &n);
2614                 }
2615         } else {
2616                 BcVec v;
2617                 while (len > a->len) {
2618                         bc_array_init(&v, true);
2619                         bc_vec_push(a, &v);
2620                 }
2621         }
2622 }
2623
2624 static void bc_array_copy(BcVec *d, const BcVec *s)
2625 {
2626         BcNum *dnum, *snum;
2627         size_t i;
2628
2629         bc_vec_pop_all(d);
2630         bc_vec_expand(d, s->cap);
2631         d->len = s->len;
2632
2633         dnum = (void*)d->v;
2634         snum = (void*)s->v;
2635         for (i = 0; i < s->len; i++, dnum++, snum++) {
2636                 bc_num_init(dnum, snum->len);
2637                 bc_num_copy(dnum, snum);
2638         }
2639 }
2640
2641 #if ENABLE_DC
2642 static void dc_result_copy(BcResult *d, BcResult *src)
2643 {
2644         d->t = src->t;
2645
2646         switch (d->t) {
2647                 case BC_RESULT_TEMP:
2648                 case BC_RESULT_IBASE:
2649                 case BC_RESULT_SCALE:
2650                 case BC_RESULT_OBASE:
2651                         bc_num_init(&d->d.n, src->d.n.len);
2652                         bc_num_copy(&d->d.n, &src->d.n);
2653                         break;
2654                 case BC_RESULT_VAR:
2655                 case BC_RESULT_ARRAY:
2656                 case BC_RESULT_ARRAY_ELEM:
2657                         d->d.id.name = xstrdup(src->d.id.name);
2658                         break;
2659                 case BC_RESULT_CONSTANT:
2660                 case BC_RESULT_LAST:
2661                 case BC_RESULT_ONE:
2662                 case BC_RESULT_STR:
2663                         memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2664                         break;
2665         }
2666 }
2667 #endif // ENABLE_DC
2668
2669 static FAST_FUNC void bc_result_free(void *result)
2670 {
2671         BcResult *r = (BcResult *) result;
2672
2673         switch (r->t) {
2674                 case BC_RESULT_TEMP:
2675                 case BC_RESULT_IBASE:
2676                 case BC_RESULT_SCALE:
2677                 case BC_RESULT_OBASE:
2678                         bc_num_free(&r->d.n);
2679                         break;
2680                 case BC_RESULT_VAR:
2681                 case BC_RESULT_ARRAY:
2682                 case BC_RESULT_ARRAY_ELEM:
2683                         free(r->d.id.name);
2684                         break;
2685                 default:
2686                         // Do nothing.
2687                         break;
2688         }
2689 }
2690
2691 static void bc_lex_lineComment(BcLex *l)
2692 {
2693         // Try: echo -n '#foo' | bc
2694         size_t i;
2695         l->t.t = BC_LEX_WHITESPACE;
2696         i = l->i;
2697         while (i < l->len && l->buf[i] != '\n')
2698                 i++;
2699         l->i = i;
2700 }
2701
2702 static void bc_lex_whitespace(BcLex *l)
2703 {
2704         l->t.t = BC_LEX_WHITESPACE;
2705         for (;;) {
2706                 char c = l->buf[l->i];
2707                 if (c == '\n') // this is BC_LEX_NLINE, not BC_LEX_WHITESPACE
2708                         break;
2709                 if (!isspace(c))
2710                         break;
2711                 l->i++;
2712         }
2713 }
2714
2715 static BC_STATUS zbc_lex_number(BcLex *l, char start)
2716 {
2717         const char *buf = l->buf + l->i;
2718         size_t len, i, ccnt;
2719         bool pt;
2720
2721         pt = (start == '.');
2722         l->t.t = BC_LEX_NUMBER;
2723         ccnt = i = 0;
2724         for (;;) {
2725                 char c = buf[i];
2726                 if (c == '\0')
2727                         break;
2728                 if (c == '\\' && buf[i + 1] == '\n') {
2729                         i += 2;
2730                         //number_of_backslashes++ - see comment below
2731                         continue;
2732                 }
2733                 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2734                         if (c != '.') break;
2735                         // if '.' was already seen, stop on second one:
2736                         if (pt) break;
2737                         pt = true;
2738                 }
2739                 // buf[i] is one of "0-9A-F."
2740                 i++;
2741                 if (c != '.')
2742                         ccnt = i;
2743         }
2744         //ccnt is the number of chars in the number string, excluding possible
2745         //trailing "[\<newline>].[\<newline>]" (with any number of \<NL> repetitions).
2746         //i is buf[i] index of the first not-yet-parsed char after that.
2747         l->i += i;
2748
2749         // This might overestimate the size, if there are "\<NL>"'s
2750         // in the number. Subtracting number_of_backslashes*2 correctly
2751         // is not that easy: consider that in the case of "NNN.\<NL>"
2752         // loop above will count "\<NL>" before it realizes it is not
2753         // in fact *inside* the number:
2754         len = ccnt + 1; // +1 byte for NUL termination
2755
2756         // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2757         if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2758                 if (len > BC_MAX_NUM)
2759                         RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
2760         }
2761
2762         bc_vec_pop_all(&l->t.v);
2763         bc_vec_expand(&l->t.v, 1 + len);
2764         bc_vec_push(&l->t.v, &start);
2765
2766         while (ccnt != 0) {
2767                 // If we have hit a backslash, skip it. We don't have
2768                 // to check for a newline because it's guaranteed.
2769                 if (*buf == '\\') {
2770                         buf += 2;
2771                         ccnt -= 2;
2772                         continue;
2773                 }
2774                 bc_vec_push(&l->t.v, buf);
2775                 buf++;
2776                 ccnt--;
2777         }
2778
2779         bc_vec_pushZeroByte(&l->t.v);
2780
2781         RETURN_STATUS(BC_STATUS_SUCCESS);
2782 }
2783 #define zbc_lex_number(...) (zbc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2784
2785 static void bc_lex_name(BcLex *l)
2786 {
2787         size_t i;
2788         const char *buf;
2789
2790         l->t.t = BC_LEX_NAME;
2791
2792         i = 0;
2793         buf = l->buf + l->i - 1;
2794         for (;;) {
2795                 char c = buf[i];
2796                 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2797                 i++;
2798         }
2799
2800 #if 0 // We do not protect against people with gigabyte-long names
2801         // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2802         if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2803                 if (i > BC_MAX_STRING)
2804                         return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2805         }
2806 #endif
2807         bc_vec_string(&l->t.v, i, buf);
2808
2809         // Increment the index. We minus 1 because it has already been incremented.
2810         l->i += i - 1;
2811
2812         //return BC_STATUS_SUCCESS;
2813 }
2814
2815 static void bc_lex_init(BcLex *l)
2816 {
2817         bc_char_vec_init(&l->t.v);
2818 }
2819
2820 static void bc_lex_free(BcLex *l)
2821 {
2822         bc_vec_free(&l->t.v);
2823 }
2824
2825 static void bc_lex_file(BcLex *l)
2826 {
2827         G.err_line = l->line = 1;
2828         l->newline = false;
2829 }
2830
2831 static bool bc_lex_more_input(BcLex *l)
2832 {
2833         size_t str;
2834         bool comment;
2835
2836         bc_vec_pop_all(&G.input_buffer);
2837
2838         // This loop is complex because the vm tries not to send any lines that end
2839         // with a backslash to the parser. The reason for that is because the parser
2840         // treats a backslash+newline combo as whitespace, per the bc spec. In that
2841         // case, and for strings and comments, the parser will expect more stuff.
2842         comment = false;
2843         str = 0;
2844         for (;;) {
2845                 size_t prevlen = G.input_buffer.len;
2846                 char *string;
2847
2848                 bc_read_line(&G.input_buffer, G.input_fp);
2849                 // No more input means EOF
2850                 if (G.input_buffer.len <= prevlen + 1) // (we expect +1 for NUL byte)
2851                         break;
2852
2853                 string = G.input_buffer.v + prevlen;
2854                 while (*string) {
2855                         char c = *string;
2856                         if (string == G.input_buffer.v || string[-1] != '\\') {
2857                                 if (IS_BC)
2858                                         str ^= (c == '"');
2859                                 else {
2860                                         if (c == ']')
2861                                                 str -= 1;
2862                                         else if (c == '[')
2863                                                 str += 1;
2864                                 }
2865                         }
2866                         string++;
2867                         if (c == '/' && *string == '*') {
2868                                 comment = true;
2869                                 string++;
2870                                 continue;
2871                         }
2872                         if (c == '*' && *string == '/') {
2873                                 comment = false;
2874                                 string++;
2875                         }
2876                 }
2877                 if (str != 0 || comment) {
2878                         G.input_buffer.len--; // backstep over the trailing NUL byte
2879                         continue;
2880                 }
2881
2882                 // Check for backslash+newline.
2883                 // we do not check that last char is '\n' -
2884                 // if it is not, then it's EOF, and looping back
2885                 // to bc_read_line() will detect it:
2886                 string -= 2;
2887                 if (string >= G.input_buffer.v && *string == '\\') {
2888                         G.input_buffer.len--;
2889                         continue;
2890                 }
2891
2892                 break;
2893         }
2894
2895         l->buf = G.input_buffer.v;
2896         l->i = 0;
2897 //      bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2898         l->len = G.input_buffer.len - 1; // do not include NUL
2899
2900         return l->len != 0;
2901 }
2902
2903 IF_BC(static BC_STATUS zbc_lex_token(BcLex *l);)
2904 IF_DC(static BC_STATUS zdc_lex_token(BcLex *l);)
2905
2906 static BC_STATUS zbc_lex_next(BcLex *l)
2907 {
2908         BcStatus s;
2909
2910         l->t.last = l->t.t;
2911         if (l->t.last == BC_LEX_EOF) RETURN_STATUS(bc_error("end of file"));
2912
2913         l->line += l->newline;
2914         G.err_line = l->line;
2915         l->newline = false;
2916
2917         // Loop until failure or we don't have whitespace. This
2918         // is so the parser doesn't get inundated with whitespace.
2919         // Comments are also BC_LEX_WHITESPACE tokens and eaten here.
2920         s = BC_STATUS_SUCCESS;
2921         do {
2922                 if (l->i == l->len) {
2923                         l->t.t = BC_LEX_EOF;
2924                         if (!G.input_fp)
2925                                 RETURN_STATUS(BC_STATUS_SUCCESS);
2926                         if (!bc_lex_more_input(l)) {
2927                                 G.input_fp = NULL;
2928                                 RETURN_STATUS(BC_STATUS_SUCCESS);
2929                         }
2930                         // here it's guaranteed that l->i is below l->len
2931                 }
2932                 dbg_lex("next string to parse:'%.*s'",
2933                         (int)(strchrnul(l->buf + l->i, '\n') - (l->buf + l->i)),
2934                         l->buf + l->i);
2935                 if (IS_BC) {
2936                         IF_BC(s = zbc_lex_token(l));
2937                 } else {
2938                         IF_DC(s = zdc_lex_token(l));
2939                 }
2940         } while (!s && l->t.t == BC_LEX_WHITESPACE);
2941         dbg_lex("l->t.t from string:%d", l->t.t);
2942
2943         RETURN_STATUS(s);
2944 }
2945 #define zbc_lex_next(...) (zbc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
2946
2947 #if ENABLE_BC
2948 static BC_STATUS zbc_lex_skip_if_at_NLINE(BcLex *l)
2949 {
2950         if (l->t.t == BC_LEX_NLINE)
2951                 RETURN_STATUS(zbc_lex_next(l));
2952         RETURN_STATUS(BC_STATUS_SUCCESS);
2953 }
2954 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2955
2956 static BC_STATUS zbc_lex_next_and_skip_NLINE(BcLex *l)
2957 {
2958         BcStatus s;
2959         s = zbc_lex_next(l);
2960         if (s) RETURN_STATUS(s);
2961         // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
2962         s = zbc_lex_skip_if_at_NLINE(l);
2963         RETURN_STATUS(s);
2964 }
2965 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2966 #endif
2967
2968 static BC_STATUS zbc_lex_text_init(BcLex *l, const char *text)
2969 {
2970         l->buf = text;
2971         l->i = 0;
2972         l->len = strlen(text);
2973         l->t.t = l->t.last = BC_LEX_INVALID;
2974         RETURN_STATUS(zbc_lex_next(l));
2975 }
2976 #define zbc_lex_text_init(...) (zbc_lex_text_init(__VA_ARGS__) COMMA_SUCCESS)
2977
2978 #if ENABLE_BC
2979 static BC_STATUS zbc_lex_identifier(BcLex *l)
2980 {
2981         BcStatus s;
2982         unsigned i;
2983         const char *buf = l->buf + l->i - 1;
2984
2985         for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2986                 const char *keyword8 = bc_lex_kws[i].name8;
2987                 unsigned j = 0;
2988                 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2989                         j++;
2990                         if (j == 8) goto match;
2991                 }
2992                 if (keyword8[j] != '\0')
2993                         continue;
2994  match:
2995                 // buf starts with keyword bc_lex_kws[i]
2996                 if (isalnum(buf[j]) || buf[j]=='_')
2997                         continue; // "ifz" does not match "if" keyword, "if." does
2998                 l->t.t = BC_LEX_KEY_1st_keyword + i;
2999                 if (!bc_lex_kws_POSIX(i)) {
3000                         s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3001                         IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3002                 }
3003
3004                 // We minus 1 because the index has already been incremented.
3005                 l->i += j - 1;
3006                 RETURN_STATUS(BC_STATUS_SUCCESS);
3007         }
3008
3009         bc_lex_name(l);
3010         s = BC_STATUS_SUCCESS;
3011
3012         if (l->t.v.len > 2) {
3013                 // Prevent this:
3014                 // >>> qwe=1
3015                 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3016                 // '
3017                 unsigned len = strchrnul(buf, '\n') - buf;
3018                 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3019         }
3020
3021         RETURN_STATUS(s);
3022 }
3023 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3024
3025 static BC_STATUS zbc_lex_string(BcLex *l)
3026 {
3027         size_t len, nls, i;
3028
3029         l->t.t = BC_LEX_STR;
3030
3031         nls = 0;
3032         i = l->i;
3033         for (;;) {
3034                 char c = l->buf[i];
3035                 if (c == '\0') {
3036                         l->i = i;
3037                         RETURN_STATUS(bc_error("string end could not be found"));
3038                 }
3039                 if (c == '"')
3040                         break;
3041                 nls += (c == '\n');
3042                 i++;
3043         }
3044
3045         len = i - l->i;
3046         // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3047         if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3048                 if (len > BC_MAX_STRING)
3049                         RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3050         }
3051         bc_vec_string(&l->t.v, len, l->buf + l->i);
3052
3053         l->i = i + 1;
3054         l->line += nls;
3055         G.err_line = l->line;
3056
3057         RETURN_STATUS(BC_STATUS_SUCCESS);
3058 }
3059 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3060
3061 static void bc_lex_assign(BcLex *l, unsigned with_and_without)
3062 {
3063         if (l->buf[l->i] == '=') {
3064                 ++l->i;
3065                 with_and_without >>= 8; // store "with" value
3066         } // else store "without" value
3067         l->t.t = (with_and_without & 0xff);
3068 }
3069 #define bc_lex_assign(l, with, without) \
3070         bc_lex_assign(l, ((with)<<8)|(without))
3071
3072 static BC_STATUS zbc_lex_comment(BcLex *l)
3073 {
3074         size_t i, nls = 0;
3075         const char *buf = l->buf;
3076
3077         l->t.t = BC_LEX_WHITESPACE;
3078         i = l->i; /* here buf[l->i] is the '*' of opening comment delimiter */
3079         for (;;) {
3080                 char c = buf[++i];
3081  check_star:
3082                 if (c == '*') {
3083                         c = buf[++i];
3084                         if (c == '/')
3085                                 break;
3086                         goto check_star;
3087                 }
3088                 if (c == '\0') {
3089                         l->i = i;
3090                         RETURN_STATUS(bc_error("comment end could not be found"));
3091                 }
3092                 nls += (c == '\n');
3093         }
3094
3095         l->i = i + 1;
3096         l->line += nls;
3097         G.err_line = l->line;
3098
3099         RETURN_STATUS(BC_STATUS_SUCCESS);
3100 }
3101 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3102
3103 static BC_STATUS zbc_lex_token(BcLex *l)
3104 {
3105         BcStatus s = BC_STATUS_SUCCESS;
3106         char c = l->buf[l->i++], c2;
3107
3108         // This is the workhorse of the lexer.
3109         switch (c) {
3110 //              case '\0': // probably never reached
3111 //                      l->i--;
3112 //                      l->t.t = BC_LEX_EOF;
3113 //                      l->newline = true;
3114 //                      break;
3115                 case '\n':
3116                         l->t.t = BC_LEX_NLINE;
3117                         l->newline = true;
3118                         break;
3119                 case '\t':
3120                 case '\v':
3121                 case '\f':
3122                 case '\r':
3123                 case ' ':
3124                         bc_lex_whitespace(l);
3125                         break;
3126                 case '!':
3127                         bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3128                         if (l->t.t == BC_LEX_OP_BOOL_NOT) {
3129                                 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3130                                 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3131                         }
3132                         break;
3133                 case '"':
3134                         s = zbc_lex_string(l);
3135                         break;
3136                 case '#':
3137                         s = bc_POSIX_does_not_allow("'#' script comments");
3138                         IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3139                         bc_lex_lineComment(l);
3140                         break;
3141                 case '%':
3142                         bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3143                         break;
3144                 case '&':
3145                         c2 = l->buf[l->i];
3146                         if (c2 == '&') {
3147                                 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3148                                 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3149                                 ++l->i;
3150                                 l->t.t = BC_LEX_OP_BOOL_AND;
3151                         } else {
3152                                 l->t.t = BC_LEX_INVALID;
3153                                 s = bc_error_bad_character('&');
3154                         }
3155                         break;
3156                 case '(':
3157                 case ')':
3158                         l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3159                         break;
3160                 case '*':
3161                         bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3162                         break;
3163                 case '+':
3164                         c2 = l->buf[l->i];
3165                         if (c2 == '+') {
3166                                 ++l->i;
3167                                 l->t.t = BC_LEX_OP_INC;
3168                         } else
3169                                 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3170                         break;
3171                 case ',':
3172                         l->t.t = BC_LEX_COMMA;
3173                         break;
3174                 case '-':
3175                         c2 = l->buf[l->i];
3176                         if (c2 == '-') {
3177                                 ++l->i;
3178                                 l->t.t = BC_LEX_OP_DEC;
3179                         } else
3180                                 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3181                         break;
3182                 case '.':
3183                         if (isdigit(l->buf[l->i]))
3184                                 s = zbc_lex_number(l, c);
3185                         else {
3186                                 l->t.t = BC_LEX_KEY_LAST;
3187                                 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3188                         }
3189                         break;
3190                 case '/':
3191                         c2 = l->buf[l->i];
3192                         if (c2 == '*')
3193                                 s = zbc_lex_comment(l);
3194                         else
3195                                 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3196                         break;
3197                 case '0':
3198                 case '1':
3199                 case '2':
3200                 case '3':
3201                 case '4':
3202                 case '5':
3203                 case '6':
3204                 case '7':
3205                 case '8':
3206                 case '9':
3207                 case 'A':
3208                 case 'B':
3209                 case 'C':
3210                 case 'D':
3211                 case 'E':
3212                 case 'F':
3213                         s = zbc_lex_number(l, c);
3214                         break;
3215                 case ';':
3216                         l->t.t = BC_LEX_SCOLON;
3217                         break;
3218                 case '<':
3219                         bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3220                         break;
3221                 case '=':
3222                         bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3223                         break;
3224                 case '>':
3225                         bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3226                         break;
3227                 case '[':
3228                 case ']':
3229                         l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3230                         break;
3231                 case '\\':
3232                         if (l->buf[l->i] == '\n') {
3233                                 l->t.t = BC_LEX_WHITESPACE;
3234                                 ++l->i;
3235                         } else
3236                                 s = bc_error_bad_character(c);
3237                         break;
3238                 case '^':
3239                         bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3240                         break;
3241                 case 'a':
3242                 case 'b':
3243                 case 'c':
3244                 case 'd':
3245                 case 'e':
3246                 case 'f':
3247                 case 'g':
3248                 case 'h':
3249                 case 'i':
3250                 case 'j':
3251                 case 'k':
3252                 case 'l':
3253                 case 'm':
3254                 case 'n':
3255                 case 'o':
3256                 case 'p':
3257                 case 'q':
3258                 case 'r':
3259                 case 's':
3260                 case 't':
3261                 case 'u':
3262                 case 'v':
3263                 case 'w':
3264                 case 'x':
3265                 case 'y':
3266                 case 'z':
3267                         s = zbc_lex_identifier(l);
3268                         break;
3269                 case '{':
3270                 case '}':
3271                         l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3272                         break;
3273                 case '|':
3274                         c2 = l->buf[l->i];
3275                         if (c2 == '|') {
3276                                 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3277                                 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3278                                 ++l->i;
3279                                 l->t.t = BC_LEX_OP_BOOL_OR;
3280                         } else {
3281                                 l->t.t = BC_LEX_INVALID;
3282                                 s = bc_error_bad_character(c);
3283                         }
3284                         break;
3285                 default:
3286                         l->t.t = BC_LEX_INVALID;
3287                         s = bc_error_bad_character(c);
3288                         break;
3289         }
3290
3291         RETURN_STATUS(s);
3292 }
3293 #endif // ENABLE_BC
3294
3295 #if ENABLE_DC
3296 static BC_STATUS zdc_lex_register(BcLex *l)
3297 {
3298         if (isspace(l->buf[l->i - 1])) {
3299                 bc_lex_whitespace(l);
3300                 ++l->i;
3301                 if (!G_exreg)
3302                         RETURN_STATUS(bc_error("extended register"));
3303                 bc_lex_name(l);
3304         }
3305         else {
3306                 bc_vec_pop_all(&l->t.v);
3307                 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
3308                 bc_vec_pushZeroByte(&l->t.v);
3309                 l->t.t = BC_LEX_NAME;
3310         }
3311
3312         RETURN_STATUS(BC_STATUS_SUCCESS);
3313 }
3314 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3315
3316 static BC_STATUS zdc_lex_string(BcLex *l)
3317 {
3318         size_t depth, nls, i;
3319
3320         l->t.t = BC_LEX_STR;
3321         bc_vec_pop_all(&l->t.v);
3322
3323         nls = 0;
3324         depth = 1;
3325         i = l->i;
3326         for (;;) {
3327                 char c = l->buf[i];
3328                 if (c == '\0') {
3329                         l->i = i;
3330                         RETURN_STATUS(bc_error("string end could not be found"));
3331                 }
3332                 nls += (c == '\n');
3333                 if (i == l->i || l->buf[i - 1] != '\\') {
3334                         if (c == '[') depth++;
3335                         if (c == ']')
3336                                 if (--depth == 0)
3337                                         break;
3338                 }
3339                 bc_vec_push(&l->t.v, &l->buf[i]);
3340                 i++;
3341         }
3342         i++;
3343
3344         bc_vec_pushZeroByte(&l->t.v);
3345         // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3346         if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3347                 if (i - l->i > BC_MAX_STRING)
3348                         RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3349         }
3350
3351         l->i = i;
3352         l->line += nls;
3353         G.err_line = l->line;
3354
3355         RETURN_STATUS(BC_STATUS_SUCCESS);
3356 }
3357 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3358
3359 static BC_STATUS zdc_lex_token(BcLex *l)
3360 {
3361         static const //BcLexType - should be this type, but narrower type saves size:
3362         uint8_t
3363         dc_lex_regs[] = {
3364                 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
3365                 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
3366                 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
3367                 BC_LEX_STORE_PUSH,
3368         };
3369         static const //BcLexType - should be this type
3370         uint8_t
3371         dc_lex_tokens[] = {
3372                 /* %&'( */
3373                 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
3374                 /* )*+, */
3375                 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
3376                 /* -./ */
3377                 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
3378                 /* 0123456789 */
3379                 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3380                 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3381                 BC_LEX_INVALID, BC_LEX_INVALID,
3382                 /* :;<=>?@ */
3383                 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
3384                 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
3385                 /* ABCDEFGH */
3386                 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3387                 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
3388                 /* IJKLMNOP */
3389                 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
3390                 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
3391                 /* QRSTUVWXY */
3392                 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
3393                 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
3394                 /* Z[\] */
3395                 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3396                 /* ^_` */
3397                 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
3398                 /* abcdefgh */
3399                 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
3400                 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
3401                 /* ijklmnop */
3402                 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
3403                 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
3404                 /* qrstuvwx */
3405                 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
3406                 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
3407                 /* yz */
3408                 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
3409                 /* {|}~ */
3410                 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
3411         };
3412
3413         BcStatus s = BC_STATUS_SUCCESS;
3414         char c = l->buf[l->i++], c2;
3415         size_t i;
3416
3417         for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3418                 if (l->t.last == dc_lex_regs[i])
3419                         RETURN_STATUS(zdc_lex_register(l));
3420         }
3421
3422         if (c >= '%' && c <= '~'
3423          && (l->t.t = dc_lex_tokens[c - '%']) != BC_LEX_INVALID
3424         ) {
3425                 RETURN_STATUS(s);
3426         }
3427
3428         // This is the workhorse of the lexer.
3429         switch (c) {
3430 //              case '\0': // probably never reached
3431 //                      l->t.t = BC_LEX_EOF;
3432 //                      break;
3433                 case '\n':
3434                         // '\n' is BC_LEX_NLINE, not BC_LEX_WHITESPACE
3435                         // (and "case '\n'" is not just empty here)
3436                         // only to allow interactive dc have a way to exit
3437                         // "parse" stage of "parse,execute" loop
3438                         // on '\n', not on _next_ token (which would mean
3439                         // command are not executed on pressing <enter>).
3440                         // IOW: typing "1p<enter>" should print "1" _at once_,
3441                         // not after some more input.
3442                         l->t.t = BC_LEX_NLINE;
3443                         l->newline = true;
3444                         break;
3445                 case '\t':
3446                 case '\v':
3447                 case '\f':
3448                 case '\r':
3449                 case ' ':
3450                         l->newline = (c == '\n');
3451                         bc_lex_whitespace(l);
3452                         break;
3453                 case '!':
3454                         c2 = l->buf[l->i];
3455                         if (c2 == '=')
3456                                 l->t.t = BC_LEX_OP_REL_NE;
3457                         else if (c2 == '<')
3458                                 l->t.t = BC_LEX_OP_REL_LE;
3459                         else if (c2 == '>')
3460                                 l->t.t = BC_LEX_OP_REL_GE;
3461                         else
3462                                 RETURN_STATUS(bc_error_bad_character(c));
3463                         ++l->i;
3464                         break;
3465                 case '#':
3466                         bc_lex_lineComment(l);
3467                         break;
3468                 case '.':
3469                         if (isdigit(l->buf[l->i]))
3470                                 s = zbc_lex_number(l, c);
3471                         else
3472                                 s = bc_error_bad_character(c);
3473                         break;
3474                 case '0':
3475                 case '1':
3476                 case '2':
3477                 case '3':
3478                 case '4':
3479                 case '5':
3480                 case '6':
3481                 case '7':
3482                 case '8':
3483                 case '9':
3484                 case 'A':
3485                 case 'B':
3486                 case 'C':
3487                 case 'D':
3488                 case 'E':
3489                 case 'F':
3490                         s = zbc_lex_number(l, c);
3491                         break;
3492                 case '[':
3493                         s = zdc_lex_string(l);
3494                         break;
3495                 default:
3496                         l->t.t = BC_LEX_INVALID;
3497                         s = bc_error_bad_character(c);
3498                         break;
3499         }
3500
3501         RETURN_STATUS(s);
3502 }
3503 #endif // ENABLE_DC
3504
3505 static void bc_parse_push(BcParse *p, char i)
3506 {
3507         dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, p->func->code.len, i);
3508         bc_vec_pushByte(&p->func->code, i);
3509 }
3510
3511 static void bc_parse_pushName(BcParse *p, char *name)
3512 {
3513         while (*name)
3514                 bc_parse_push(p, *name++);
3515         bc_parse_push(p, BC_PARSE_STREND);
3516 }
3517
3518 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3519 {
3520         size_t mask;
3521         unsigned amt;
3522
3523         dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3524         mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3525         amt = sizeof(idx);
3526         do {
3527                 if (idx & mask) break;
3528                 mask >>= 8;
3529                 amt--;
3530         } while (amt != 0);
3531
3532         bc_parse_push(p, amt);
3533
3534         while (idx != 0) {
3535                 bc_parse_push(p, (unsigned char)idx);
3536                 idx >>= 8;
3537         }
3538 }
3539
3540 #if ENABLE_BC
3541 static void bc_parse_pushJUMP(BcParse *p, size_t idx)
3542 {
3543         bc_parse_push(p, BC_INST_JUMP);
3544         bc_parse_pushIndex(p, idx);
3545 }
3546
3547 static void bc_parse_pushJUMP_ZERO(BcParse *p, size_t idx)
3548 {
3549         bc_parse_push(p, BC_INST_JUMP_ZERO);
3550         bc_parse_pushIndex(p, idx);
3551 }
3552
3553 static BC_STATUS zbc_parse_pushSTR(BcParse *p)
3554 {
3555         char *str = xstrdup(p->l.t.v.v);
3556
3557         bc_parse_push(p, BC_INST_STR);
3558         bc_parse_pushIndex(p, p->func->strs.len);
3559         bc_vec_push(&p->func->strs, &str);
3560
3561         RETURN_STATUS(zbc_lex_next(&p->l));
3562 }
3563 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3564 #endif
3565
3566 static void bc_parse_pushNUM(BcParse *p)
3567 {
3568         char *num = xstrdup(p->l.t.v.v);
3569 #if ENABLE_BC && ENABLE_DC
3570         size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3571 #elif ENABLE_BC
3572         size_t idx = bc_vec_push(&p->func->consts, &num);
3573 #else // DC
3574         size_t idx = bc_vec_push(&G.prog.consts, &num);
3575 #endif
3576         bc_parse_push(p, BC_INST_NUM);
3577         bc_parse_pushIndex(p, idx);
3578 }
3579
3580 static BC_STATUS zbc_parse_text_init(BcParse *p, const char *text)
3581 {
3582         p->func = bc_program_func(p->fidx);
3583
3584         RETURN_STATUS(zbc_lex_text_init(&p->l, text));
3585 }
3586 #define zbc_parse_text_init(...) (zbc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3587
3588 // Called when parsing or execution detects a failure,
3589 // resets execution structures.
3590 static void bc_program_reset(void)
3591 {
3592         BcFunc *f;
3593         BcInstPtr *ip;
3594
3595         bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3596         bc_vec_pop_all(&G.prog.results);
3597
3598         f = bc_program_func_BC_PROG_MAIN();
3599         ip = bc_vec_top(&G.prog.exestack);
3600         ip->inst_idx = f->code.len;
3601 }
3602
3603 // Called when parsing code detects a failure,
3604 // resets parsing structures.
3605 static void bc_parse_reset(BcParse *p)
3606 {
3607         if (p->fidx != BC_PROG_MAIN) {
3608                 bc_func_free(p->func);
3609                 bc_func_init(p->func);
3610
3611                 p->fidx = BC_PROG_MAIN;
3612                 p->func = bc_program_func_BC_PROG_MAIN();
3613         }
3614
3615         p->l.i = p->l.len;
3616         p->l.t.t = BC_LEX_EOF;
3617
3618         IF_BC(bc_vec_pop_all(&p->exits);)
3619         IF_BC(bc_vec_pop_all(&p->conds);)
3620         IF_BC(bc_vec_pop_all(&p->ops);)
3621
3622         bc_program_reset();
3623 }
3624
3625 static void bc_parse_free(BcParse *p)
3626 {
3627         IF_BC(bc_vec_free(&p->exits);)
3628         IF_BC(bc_vec_free(&p->conds);)
3629         IF_BC(bc_vec_free(&p->ops);)
3630         bc_lex_free(&p->l);
3631 }
3632
3633 static void bc_parse_create(BcParse *p, size_t fidx)
3634 {
3635         memset(p, 0, sizeof(BcParse));
3636
3637         bc_lex_init(&p->l);
3638         IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3639         IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3640         IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3641
3642         p->fidx = fidx;
3643         p->func = bc_program_func(fidx);
3644 }
3645
3646 static void bc_program_add_fn(void)
3647 {
3648         //size_t idx;
3649         BcFunc f;
3650         bc_func_init(&f);
3651         //idx =
3652         bc_vec_push(&G.prog.fns, &f);
3653         //return idx;
3654 }
3655
3656 #if ENABLE_BC
3657
3658 // Note: takes ownership of 'name' (must be malloced)
3659 static size_t bc_program_addFunc(char *name)
3660 {
3661         size_t idx;
3662         BcId entry, *entry_ptr;
3663         int inserted;
3664
3665         entry.name = name;
3666         entry.idx = G.prog.fns.len;
3667
3668         inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3669         if (!inserted) free(name);
3670
3671         entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3672         idx = entry_ptr->idx;
3673
3674         if (!inserted) {
3675                 // There is already a function with this name.
3676                 // It'll be redefined now, clear old definition.
3677                 BcFunc *func = bc_program_func(entry_ptr->idx);
3678                 bc_func_free(func);
3679                 bc_func_init(func);
3680         } else {
3681                 bc_program_add_fn();
3682         }
3683
3684         return idx;
3685 }
3686
3687 #define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3688 #define BC_PARSE_LEAF(p, rparen)                                \
3689         (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3690          (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3691
3692 // We can calculate the conversion between tokens and exprs by subtracting the
3693 // position of the first operator in the lex enum and adding the position of the
3694 // first in the expr enum. Note: This only works for binary operators.
3695 #define BC_TOKEN_2_INST(t) ((char) ((t) - BC_LEX_NEG + BC_INST_NEG))
3696
3697 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags);
3698
3699 static BC_STATUS zbc_parse_expr(BcParse *p, uint8_t flags)
3700 {
3701         BcStatus s;
3702
3703         s = bc_parse_expr_empty_ok(p, flags);
3704         if (s == BC_STATUS_PARSE_EMPTY_EXP)
3705                 RETURN_STATUS(bc_error("empty expression"));
3706         RETURN_STATUS(s);
3707 }
3708 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3709
3710 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed);
3711 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3712
3713 static BC_STATUS zbc_parse_stmt(BcParse *p)
3714 {
3715         RETURN_STATUS(zbc_parse_stmt_possibly_auto(p, false));
3716 }
3717 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3718
3719 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(BcParse *p, const char *after_X)
3720 {
3721         // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3722         // Same for "else", "while()", "for()".
3723         BcStatus s = zbc_lex_next_and_skip_NLINE(&p->l);
3724         if (s) RETURN_STATUS(s);
3725         if (p->l.t.t == BC_LEX_NLINE)
3726                 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3727
3728         RETURN_STATUS(zbc_parse_stmt(p));
3729 }
3730 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3731
3732 static void bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3733                                   size_t *nexprs)
3734 {
3735         char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3736         bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
3737
3738         while (p->ops.len > start) {
3739                 BcLexType t = BC_PARSE_TOP_OP(p);
3740                 if (t == BC_LEX_LPAREN) break;
3741
3742                 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
3743                 if (l >= r && (l != r || !left)) break;
3744
3745                 bc_parse_push(p, BC_TOKEN_2_INST(t));
3746                 bc_vec_pop(&p->ops);
3747                 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG);
3748         }
3749
3750         bc_vec_push(&p->ops, &type);
3751 }
3752
3753 static BC_STATUS zbc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3754 {
3755         BcLexType top;
3756
3757         if (p->ops.len <= ops_bgn)
3758                 RETURN_STATUS(bc_error_bad_expression());
3759         top = BC_PARSE_TOP_OP(p);
3760
3761         while (top != BC_LEX_LPAREN) {
3762                 bc_parse_push(p, BC_TOKEN_2_INST(top));
3763
3764                 bc_vec_pop(&p->ops);
3765                 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3766
3767                 if (p->ops.len <= ops_bgn)
3768                         RETURN_STATUS(bc_error_bad_expression());
3769                 top = BC_PARSE_TOP_OP(p);
3770         }
3771
3772         bc_vec_pop(&p->ops);
3773
3774         RETURN_STATUS(zbc_lex_next(&p->l));
3775 }
3776 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3777
3778 static BC_STATUS zbc_parse_params(BcParse *p, uint8_t flags)
3779 {
3780         BcStatus s;
3781         size_t nparams;
3782
3783         dbg_lex("%s:%d p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
3784         flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3785
3786         s = zbc_lex_next(&p->l);
3787         if (s) RETURN_STATUS(s);
3788
3789         nparams = 0;
3790         if (p->l.t.t != BC_LEX_RPAREN) {
3791                 for (;;) {
3792                         s = zbc_parse_expr(p, flags);
3793                         if (s) RETURN_STATUS(s);
3794                         nparams++;
3795                         if (p->l.t.t != BC_LEX_COMMA) {
3796                                 if (p->l.t.t == BC_LEX_RPAREN)
3797                                         break;
3798                                 RETURN_STATUS(bc_error_bad_token());
3799                         }
3800                         s = zbc_lex_next(&p->l);
3801                         if (s) RETURN_STATUS(s);
3802                 }
3803         }
3804
3805         bc_parse_push(p, BC_INST_CALL);
3806         bc_parse_pushIndex(p, nparams);
3807
3808         RETURN_STATUS(BC_STATUS_SUCCESS);
3809 }
3810 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3811
3812 // Note: takes ownership of 'name' (must be malloced)
3813 static BC_STATUS zbc_parse_call(BcParse *p, char *name, uint8_t flags)
3814 {
3815         BcStatus s;
3816         BcId entry, *entry_ptr;
3817         size_t idx;
3818
3819         entry.name = name;
3820
3821         s = zbc_parse_params(p, flags);
3822         if (s) goto err;
3823
3824         if (p->l.t.t != BC_LEX_RPAREN) {
3825                 s = bc_error_bad_token();
3826                 goto err;
3827         }
3828
3829         idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3830
3831         if (idx == BC_VEC_INVALID_IDX) {
3832                 // No such function exists, create an empty one
3833                 bc_program_addFunc(name);
3834                 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3835         } else
3836                 free(name);
3837
3838         entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3839         bc_parse_pushIndex(p, entry_ptr->idx);
3840
3841         RETURN_STATUS(zbc_lex_next(&p->l));
3842  err:
3843         free(name);
3844         RETURN_STATUS(s);
3845 }
3846 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3847
3848 static BC_STATUS zbc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3849 {
3850         BcStatus s;
3851         char *name;
3852
3853         name = xstrdup(p->l.t.v.v);
3854         s = zbc_lex_next(&p->l);
3855         if (s) goto err;
3856
3857         if (p->l.t.t == BC_LEX_LBRACKET) {
3858                 s = zbc_lex_next(&p->l);
3859                 if (s) goto err;
3860
3861                 if (p->l.t.t == BC_LEX_RBRACKET) {
3862                         if (!(flags & BC_PARSE_ARRAY)) {
3863                                 s = bc_error_bad_expression();
3864                                 goto err;
3865                         }
3866                         *type = BC_INST_ARRAY;
3867                 } else {
3868                         *type = BC_INST_ARRAY_ELEM;
3869                         flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3870                         s = zbc_parse_expr(p, flags);
3871                         if (s) goto err;
3872                 }
3873                 s = zbc_lex_next(&p->l);
3874                 if (s) goto err;
3875                 bc_parse_push(p, *type);
3876                 bc_parse_pushName(p, name);
3877                 free(name);
3878         } else if (p->l.t.t == BC_LEX_LPAREN) {
3879                 if (flags & BC_PARSE_NOCALL) {
3880                         s = bc_error_bad_token();
3881                         goto err;
3882                 }
3883                 *type = BC_INST_CALL;
3884                 s = zbc_parse_call(p, name, flags);
3885         } else {
3886                 *type = BC_INST_VAR;
3887                 bc_parse_push(p, BC_INST_VAR);
3888                 bc_parse_pushName(p, name);
3889                 free(name);
3890         }
3891
3892         RETURN_STATUS(s);
3893  err:
3894         free(name);
3895         RETURN_STATUS(s);
3896 }
3897 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3898
3899 static BC_STATUS zbc_parse_read(BcParse *p)
3900 {
3901         BcStatus s;
3902
3903         s = zbc_lex_next(&p->l);
3904         if (s) RETURN_STATUS(s);
3905         if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3906
3907         s = zbc_lex_next(&p->l);
3908         if (s) RETURN_STATUS(s);
3909         if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3910
3911         bc_parse_push(p, BC_INST_READ);
3912
3913         RETURN_STATUS(zbc_lex_next(&p->l));
3914 }
3915 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3916
3917 static BC_STATUS zbc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3918                                  BcInst *prev)
3919 {
3920         BcStatus s;
3921
3922         s = zbc_lex_next(&p->l);
3923         if (s) RETURN_STATUS(s);
3924         if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3925
3926         flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3927
3928         s = zbc_lex_next(&p->l);
3929         if (s) RETURN_STATUS(s);
3930
3931         s = zbc_parse_expr(p, flags);
3932         if (s) RETURN_STATUS(s);
3933
3934         if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3935
3936         *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3937         bc_parse_push(p, *prev);
3938
3939         RETURN_STATUS(zbc_lex_next(&p->l));
3940 }
3941 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3942
3943 static BC_STATUS zbc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3944 {
3945         BcStatus s;
3946
3947         s = zbc_lex_next(&p->l);
3948         if (s) RETURN_STATUS(s);
3949
3950         if (p->l.t.t != BC_LEX_LPAREN) {
3951                 *type = BC_INST_SCALE;
3952                 bc_parse_push(p, BC_INST_SCALE);
3953                 RETURN_STATUS(BC_STATUS_SUCCESS);
3954         }
3955
3956         *type = BC_INST_SCALE_FUNC;
3957         flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3958
3959         s = zbc_lex_next(&p->l);
3960         if (s) RETURN_STATUS(s);
3961
3962         s = zbc_parse_expr(p, flags);
3963         if (s) RETURN_STATUS(s);
3964         if (p->l.t.t != BC_LEX_RPAREN)
3965                 RETURN_STATUS(bc_error_bad_token());
3966         bc_parse_push(p, BC_INST_SCALE_FUNC);
3967
3968         RETURN_STATUS(zbc_lex_next(&p->l));
3969 }
3970 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3971
3972 static BC_STATUS zbc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3973                                 size_t *nexprs, uint8_t flags)
3974 {
3975         BcStatus s;
3976         BcLexType type;
3977         char inst;
3978         BcInst etype = *prev;
3979
3980         if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM
3981          || etype == BC_INST_SCALE || etype == BC_INST_LAST
3982          || etype == BC_INST_IBASE || etype == BC_INST_OBASE
3983         ) {
3984                 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
3985                 bc_parse_push(p, inst);
3986                 s = zbc_lex_next(&p->l);
3987         } else {
3988                 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
3989                 *paren_expr = true;
3990
3991                 s = zbc_lex_next(&p->l);
3992                 if (s) RETURN_STATUS(s);
3993                 type = p->l.t.t;
3994
3995                 // Because we parse the next part of the expression
3996                 // right here, we need to increment this.
3997                 *nexprs = *nexprs + 1;
3998
3999                 switch (type) {
4000                         case BC_LEX_NAME:
4001                                 s = zbc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4002                                 break;
4003                         case BC_LEX_KEY_IBASE:
4004                         case BC_LEX_KEY_LAST:
4005                         case BC_LEX_KEY_OBASE:
4006                                 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4007                                 s = zbc_lex_next(&p->l);
4008                                 break;
4009                         case BC_LEX_KEY_SCALE:
4010                                 s = zbc_lex_next(&p->l);
4011                                 if (s) RETURN_STATUS(s);
4012                                 if (p->l.t.t == BC_LEX_LPAREN)
4013                                         s = bc_error_bad_token();
4014                                 else
4015                                         bc_parse_push(p, BC_INST_SCALE);
4016                                 break;
4017                         default:
4018                                 s = bc_error_bad_token();
4019                                 break;
4020                 }
4021
4022                 if (!s) bc_parse_push(p, inst);
4023         }
4024
4025         RETURN_STATUS(s);
4026 }
4027 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4028
4029 static BC_STATUS zbc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4030                                bool rparen, size_t *nexprs)
4031 {
4032         BcStatus s;
4033         BcLexType type;
4034         BcInst etype = *prev;
4035
4036         s = zbc_lex_next(&p->l);
4037         if (s) RETURN_STATUS(s);
4038
4039         type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4040                        (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4041                    BC_LEX_OP_MINUS :
4042                    BC_LEX_NEG;
4043         *prev = BC_TOKEN_2_INST(type);
4044
4045         // We can just push onto the op stack because this is the largest
4046         // precedence operator that gets pushed. Inc/dec does not.
4047         if (type != BC_LEX_OP_MINUS)
4048                 bc_vec_push(&p->ops, &type);
4049         else
4050                 bc_parse_operator(p, type, ops_bgn, nexprs);
4051
4052         RETURN_STATUS(s);
4053 }
4054 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4055
4056 static BC_STATUS zbc_parse_print(BcParse *p)
4057 {
4058         BcStatus s;
4059         BcLexType type;
4060
4061         for (;;) {
4062                 s = zbc_lex_next(&p->l);
4063                 if (s) RETURN_STATUS(s);
4064                 type = p->l.t.t;
4065                 if (type == BC_LEX_STR) {
4066                         s = zbc_parse_pushSTR(p);
4067                 } else {
4068                         s = zbc_parse_expr(p, 0);
4069                 }
4070                 if (s) RETURN_STATUS(s);
4071                 bc_parse_push(p, BC_INST_PRINT_POP);
4072                 if (p->l.t.t != BC_LEX_COMMA)
4073                         break;
4074         }
4075
4076         RETURN_STATUS(s);
4077 }
4078 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4079
4080 static BC_STATUS zbc_parse_return(BcParse *p)
4081 {
4082         BcStatus s;
4083         BcLexType t;
4084
4085         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4086         s = zbc_lex_next(&p->l);
4087         if (s) RETURN_STATUS(s);
4088
4089         t = p->l.t.t;
4090         if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4091                 bc_parse_push(p, BC_INST_RET0);
4092         else {
4093                 bool paren = (t == BC_LEX_LPAREN);
4094                 s = bc_parse_expr_empty_ok(p, 0);
4095                 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4096                         bc_parse_push(p, BC_INST_RET0);
4097                         s = zbc_lex_next(&p->l);
4098                 }
4099                 if (s) RETURN_STATUS(s);
4100
4101                 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
4102                         s = bc_POSIX_requires("parentheses around return expressions");
4103                         IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
4104                 }
4105
4106                 bc_parse_push(p, BC_INST_RET);
4107         }
4108
4109         dbg_lex_done("%s:%d done", __func__, __LINE__);
4110         RETURN_STATUS(s);
4111 }
4112 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4113
4114 static void rewrite_label_to_current(BcParse *p, size_t idx)
4115 {
4116         size_t *label = bc_vec_item(&p->func->labels, idx);
4117         *label = p->func->code.len;
4118 }
4119
4120 static BC_STATUS zbc_parse_if(BcParse *p)
4121 {
4122         BcStatus s;
4123         size_t ip_idx;
4124
4125         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4126         s = zbc_lex_next(&p->l);
4127         if (s) RETURN_STATUS(s);
4128         if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4129
4130         s = zbc_lex_next(&p->l);
4131         if (s) RETURN_STATUS(s);
4132         s = zbc_parse_expr(p, BC_PARSE_REL);
4133         if (s) RETURN_STATUS(s);
4134         if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4135
4136         // Encode "if zero, jump to ..."
4137         // Pushed value (destination of the jump) is uninitialized,
4138         // will be rewritten to be address of "end of if()" or of "else".
4139         ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4140         bc_parse_pushJUMP_ZERO(p, ip_idx);
4141
4142         s = zbc_parse_stmt_allow_NLINE_before(p, STRING_if);
4143         if (s) RETURN_STATUS(s);
4144
4145         dbg_lex("%s:%d in if after stmt: p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4146         if (p->l.t.t == BC_LEX_KEY_ELSE) {
4147                 size_t ip2_idx;
4148
4149                 // Encode "after then_stmt, jump to end of if()"
4150                 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4151                 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4152                 bc_parse_pushJUMP(p, ip2_idx);
4153
4154                 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4155                 rewrite_label_to_current(p, ip_idx);
4156
4157                 ip_idx = ip2_idx;
4158
4159                 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_else);
4160                 if (s) RETURN_STATUS(s);
4161         }
4162
4163         dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4164         rewrite_label_to_current(p, ip_idx);
4165
4166         dbg_lex_done("%s:%d done", __func__, __LINE__);
4167         RETURN_STATUS(s);
4168 }
4169 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4170
4171 static BC_STATUS zbc_parse_while(BcParse *p)
4172 {
4173         BcStatus s;
4174         size_t cond_idx;
4175         size_t ip_idx;
4176
4177         s = zbc_lex_next(&p->l);
4178         if (s) RETURN_STATUS(s);
4179         if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4180         s = zbc_lex_next(&p->l);
4181         if (s) RETURN_STATUS(s);
4182
4183         cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4184         ip_idx = cond_idx + 1;
4185         bc_vec_push(&p->conds, &cond_idx);
4186
4187         bc_vec_push(&p->exits, &ip_idx);
4188         bc_vec_push(&p->func->labels, &ip_idx);
4189
4190         s = zbc_parse_expr(p, BC_PARSE_REL);
4191         if (s) RETURN_STATUS(s);
4192         if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4193
4194         bc_parse_pushJUMP_ZERO(p, ip_idx);
4195
4196         s = zbc_parse_stmt_allow_NLINE_before(p, STRING_while);
4197         if (s) RETURN_STATUS(s);
4198
4199         dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4200         bc_parse_pushJUMP(p, cond_idx);
4201
4202         dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4203         rewrite_label_to_current(p, ip_idx);
4204
4205         bc_vec_pop(&p->exits);
4206         bc_vec_pop(&p->conds);
4207
4208         RETURN_STATUS(s);
4209 }
4210 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4211
4212 static BC_STATUS zbc_parse_for(BcParse *p)
4213 {
4214         BcStatus s;
4215         size_t cond_idx, exit_idx, body_idx, update_idx;
4216
4217         dbg_lex("%s:%d p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4218         s = zbc_lex_next(&p->l);
4219         if (s) RETURN_STATUS(s);
4220         if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4221         s = zbc_lex_next(&p->l);
4222         if (s) RETURN_STATUS(s);
4223
4224         if (p->l.t.t != BC_LEX_SCOLON) {
4225                 s = zbc_parse_expr(p, 0);
4226                 bc_parse_push(p, BC_INST_POP);
4227                 if (s) RETURN_STATUS(s);
4228         } else {
4229                 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4230                 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s);)
4231         }
4232
4233         if (p->l.t.t != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4234         s = zbc_lex_next(&p->l);
4235         if (s) RETURN_STATUS(s);
4236
4237         cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4238         update_idx = cond_idx + 1;
4239         body_idx = update_idx + 1;
4240         exit_idx = body_idx + 1;
4241
4242         if (p->l.t.t != BC_LEX_SCOLON)
4243                 s = zbc_parse_expr(p, BC_PARSE_REL);
4244         else {
4245                 // Set this for the next call to bc_parse_pushNUM().
4246                 // This is safe to set because the current token is a semicolon,
4247                 // which has no string requirement.
4248                 bc_vec_string(&p->l.t.v, 1, "1");
4249                 bc_parse_pushNUM(p);
4250                 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4251         }
4252         if (s) RETURN_STATUS(s);
4253
4254         if (p->l.t.t != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4255
4256         s = zbc_lex_next(&p->l);
4257         if (s) RETURN_STATUS(s);
4258
4259         bc_parse_pushJUMP_ZERO(p, exit_idx);
4260         bc_parse_pushJUMP(p, body_idx);
4261
4262         bc_vec_push(&p->conds, &update_idx);
4263         bc_vec_push(&p->func->labels, &p->func->code.len);
4264
4265         if (p->l.t.t != BC_LEX_RPAREN) {
4266                 s = zbc_parse_expr(p, 0);
4267                 if (s) RETURN_STATUS(s);
4268                 if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4269                 bc_parse_push(p, BC_INST_POP);
4270         } else {
4271                 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4272                 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s);)
4273         }
4274
4275         bc_parse_pushJUMP(p, cond_idx);
4276         bc_vec_push(&p->func->labels, &p->func->code.len);
4277
4278         bc_vec_push(&p->exits, &exit_idx);
4279         bc_vec_push(&p->func->labels, &exit_idx);
4280
4281         s = zbc_parse_stmt_allow_NLINE_before(p, STRING_for);
4282         if (s) RETURN_STATUS(s);
4283
4284         dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4285         bc_parse_pushJUMP(p, update_idx);
4286
4287         dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4288         rewrite_label_to_current(p, exit_idx);
4289
4290         bc_vec_pop(&p->exits);
4291         bc_vec_pop(&p->conds);
4292
4293         RETURN_STATUS(BC_STATUS_SUCCESS);
4294 }
4295 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4296
4297 static BC_STATUS zbc_parse_break_or_continue(BcParse *p, BcLexType type)
4298 {
4299         BcStatus s;
4300         size_t i;
4301
4302         if (type == BC_LEX_KEY_BREAK) {
4303                 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4304                         RETURN_STATUS(bc_error_bad_token());
4305                 i = *(size_t*)bc_vec_top(&p->exits);
4306         } else {
4307                 i = *(size_t*)bc_vec_top(&p->conds);
4308         }
4309
4310         bc_parse_pushJUMP(p, i);
4311
4312         s = zbc_lex_next(&p->l);
4313         if (s) RETURN_STATUS(s);
4314
4315         if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
4316                 RETURN_STATUS(bc_error_bad_token());
4317
4318         RETURN_STATUS(zbc_lex_next(&p->l));
4319 }
4320 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4321
4322 static BC_STATUS zbc_parse_funcdef(BcParse *p)
4323 {
4324         BcStatus s;
4325         bool var, comma = false;
4326         char *name;
4327
4328         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4329         s = zbc_lex_next(&p->l);
4330         if (s) RETURN_STATUS(s);
4331         if (p->l.t.t != BC_LEX_NAME)
4332                 RETURN_STATUS(bc_error("bad function definition"));
4333
4334         name = xstrdup(p->l.t.v.v);
4335         p->fidx = bc_program_addFunc(name);
4336         p->func = bc_program_func(p->fidx);
4337
4338         s = zbc_lex_next(&p->l);
4339         if (s) RETURN_STATUS(s);
4340         if (p->l.t.t != BC_LEX_LPAREN)
4341                 RETURN_STATUS(bc_error("bad function definition"));
4342         s = zbc_lex_next(&p->l);
4343         if (s) RETURN_STATUS(s);
4344
4345         while (p->l.t.t != BC_LEX_RPAREN) {
4346                 if (p->l.t.t != BC_LEX_NAME)
4347                         RETURN_STATUS(bc_error("bad function definition"));
4348
4349                 ++p->func->nparams;
4350
4351                 name = xstrdup(p->l.t.v.v);
4352                 s = zbc_lex_next(&p->l);
4353                 if (s) goto err;
4354
4355                 var = p->l.t.t != BC_LEX_LBRACKET;
4356
4357                 if (!var) {
4358                         s = zbc_lex_next(&p->l);
4359                         if (s) goto err;
4360
4361                         if (p->l.t.t != BC_LEX_RBRACKET) {
4362                                 s = bc_error("bad function definition");
4363                                 goto err;
4364                         }
4365
4366                         s = zbc_lex_next(&p->l);
4367                         if (s) goto err;
4368                 }
4369
4370                 comma = p->l.t.t == BC_LEX_COMMA;
4371                 if (comma) {
4372                         s = zbc_lex_next(&p->l);
4373                         if (s) goto err;
4374                 }
4375
4376                 s = zbc_func_insert(p->func, name, var);
4377                 if (s) goto err;
4378         }
4379
4380         if (comma) RETURN_STATUS(bc_error("bad function definition"));
4381
4382         s = zbc_lex_next(&p->l);
4383         if (s) RETURN_STATUS(s);
4384
4385         if (p->l.t.t != BC_LEX_LBRACE)
4386                 s = bc_POSIX_requires("the left brace be on the same line as the function header");
4387
4388         // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4389         s = zbc_lex_skip_if_at_NLINE(&p->l);
4390         if (s) RETURN_STATUS(s);
4391         //GNU bc requires a {} block even if function body has single stmt, enforce this?
4392         if (p->l.t.t != BC_LEX_LBRACE)
4393                 RETURN_STATUS(bc_error("function { body } expected"));
4394
4395         p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4396         s = zbc_parse_stmt_possibly_auto(p, true);
4397         p->in_funcdef--;
4398         if (s) RETURN_STATUS(s);
4399
4400         bc_parse_push(p, BC_INST_RET0);
4401
4402         // Subsequent code generation is into main program
4403         p->fidx = BC_PROG_MAIN;
4404         p->func = bc_program_func_BC_PROG_MAIN();
4405
4406         dbg_lex_done("%s:%d done", __func__, __LINE__);
4407         RETURN_STATUS(s);
4408  err:
4409         dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4410         free(name);
4411         RETURN_STATUS(s);
4412 }
4413 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4414
4415 static BC_STATUS zbc_parse_auto(BcParse *p)
4416 {
4417         BcStatus s;
4418         bool comma, var, one;
4419         char *name;
4420
4421         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4422         s = zbc_lex_next(&p->l);
4423         if (s) RETURN_STATUS(s);
4424
4425         comma = false;
4426         one = p->l.t.t == BC_LEX_NAME;
4427
4428         while (p->l.t.t == BC_LEX_NAME) {
4429                 name = xstrdup(p->l.t.v.v);
4430                 s = zbc_lex_next(&p->l);
4431                 if (s) goto err;
4432
4433                 var = p->l.t.t != BC_LEX_LBRACKET;
4434                 if (!var) {
4435                         s = zbc_lex_next(&p->l);
4436                         if (s) goto err;
4437
4438                         if (p->l.t.t != BC_LEX_RBRACKET) {
4439                                 s = bc_error("bad function definition");
4440                                 goto err;
4441                         }
4442
4443                         s = zbc_lex_next(&p->l);
4444                         if (s) goto err;
4445                 }
4446
4447                 comma = p->l.t.t == BC_LEX_COMMA;
4448                 if (comma) {
4449                         s = zbc_lex_next(&p->l);
4450                         if (s) goto err;
4451                 }
4452
4453                 s = zbc_func_insert(p->func, name, var);
4454                 if (s) goto err;
4455         }
4456
4457         if (comma) RETURN_STATUS(bc_error("bad function definition"));
4458         if (!one) RETURN_STATUS(bc_error("no auto variable found"));
4459
4460         if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
4461                 RETURN_STATUS(bc_error_bad_token());
4462
4463         dbg_lex_done("%s:%d done", __func__, __LINE__);
4464         RETURN_STATUS(zbc_lex_next(&p->l));
4465  err:
4466         free(name);
4467         dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4468         RETURN_STATUS(s);
4469 }
4470 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4471
4472 #undef zbc_parse_stmt_possibly_auto
4473 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed)
4474 {
4475         BcStatus s = BC_STATUS_SUCCESS;
4476
4477         dbg_lex_enter("%s:%d entered, p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4478
4479         if (p->l.t.t == BC_LEX_NLINE) {
4480                 dbg_lex_done("%s:%d done (seen BC_LEX_NLINE)", __func__, __LINE__);
4481                 RETURN_STATUS(zbc_lex_next(&p->l));
4482         }
4483         if (p->l.t.t == BC_LEX_SCOLON) {
4484                 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4485                 RETURN_STATUS(zbc_lex_next(&p->l));
4486         }
4487
4488         if (p->l.t.t == BC_LEX_LBRACE) {
4489                 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4490                 do {
4491                         s = zbc_lex_next(&p->l);
4492                         if (s) RETURN_STATUS(s);
4493                 } while (p->l.t.t == BC_LEX_NLINE);
4494                 if (auto_allowed && p->l.t.t == BC_LEX_KEY_AUTO) {
4495                         dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4496                         s = zbc_parse_auto(p);
4497                         if (s) RETURN_STATUS(s);
4498                 }
4499                 while (p->l.t.t != BC_LEX_RBRACE) {
4500                         dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4501                         s = zbc_parse_stmt(p);
4502                         if (s) RETURN_STATUS(s);
4503                 }
4504                 s = zbc_lex_next(&p->l);
4505                 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4506                 RETURN_STATUS(s);
4507         }
4508
4509         dbg_lex("%s:%d p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4510         switch (p->l.t.t) {
4511                 case BC_LEX_OP_INC:
4512                 case BC_LEX_OP_DEC:
4513                 case BC_LEX_OP_MINUS:
4514                 case BC_LEX_OP_BOOL_NOT:
4515                 case BC_LEX_LPAREN:
4516                 case BC_LEX_NAME:
4517                 case BC_LEX_NUMBER:
4518                 case BC_LEX_KEY_IBASE:
4519                 case BC_LEX_KEY_LAST:
4520                 case BC_LEX_KEY_LENGTH:
4521                 case BC_LEX_KEY_OBASE:
4522                 case BC_LEX_KEY_READ:
4523                 case BC_LEX_KEY_SCALE:
4524                 case BC_LEX_KEY_SQRT:
4525                         s = zbc_parse_expr(p, BC_PARSE_PRINT);
4526                         break;
4527                 case BC_LEX_STR:
4528                         s = zbc_parse_pushSTR(p);
4529                         bc_parse_push(p, BC_INST_PRINT_STR);
4530                         break;
4531                 case BC_LEX_KEY_BREAK:
4532                 case BC_LEX_KEY_CONTINUE:
4533                         s = zbc_parse_break_or_continue(p, p->l.t.t);
4534                         break;
4535                 case BC_LEX_KEY_FOR:
4536                         s = zbc_parse_for(p);
4537                         break;
4538                 case BC_LEX_KEY_HALT:
4539                         bc_parse_push(p, BC_INST_HALT);
4540                         s = zbc_lex_next(&p->l);
4541                         break;
4542                 case BC_LEX_KEY_IF:
4543                         s = zbc_parse_if(p);
4544                         break;
4545                 case BC_LEX_KEY_LIMITS:
4546                         // "limits" is a compile-time command,
4547                         // the output is produced at _parse time_.
4548                         printf(
4549                                 "BC_BASE_MAX     = "BC_MAX_OBASE_STR "\n"
4550                                 "BC_DIM_MAX      = "BC_MAX_DIM_STR   "\n"
4551                                 "BC_SCALE_MAX    = "BC_MAX_SCALE_STR "\n"
4552                                 "BC_STRING_MAX   = "BC_MAX_STRING_STR"\n"
4553                                 "BC_NAME_MAX     = "BC_MAX_NAME_STR  "\n"
4554                                 "BC_NUM_MAX      = "BC_MAX_NUM_STR   "\n"
4555                                 "MAX Exponent    = "BC_MAX_EXP_STR   "\n"
4556                                 "Number of vars  = "BC_MAX_VARS_STR  "\n"
4557                         );
4558                         s = zbc_lex_next(&p->l);
4559                         break;
4560                 case BC_LEX_KEY_PRINT:
4561                         s = zbc_parse_print(p);
4562                         break;
4563                 case BC_LEX_KEY_QUIT:
4564                         // "quit" is a compile-time command. For example,
4565                         // "if (0 == 1) quit" terminates when parsing the statement,
4566                         // not when it is executed
4567                         QUIT_OR_RETURN_TO_MAIN;
4568                 case BC_LEX_KEY_RETURN:
4569                         if (!p->in_funcdef)
4570                                 RETURN_STATUS(bc_error("'return' not in a function"));
4571                         s = zbc_parse_return(p);
4572                         break;
4573                 case BC_LEX_KEY_WHILE:
4574                         s = zbc_parse_while(p);
4575                         break;
4576                 default:
4577                         s = bc_error_bad_token();
4578                         break;
4579         }
4580
4581         dbg_lex_done("%s:%d done", __func__, __LINE__);
4582         RETURN_STATUS(s);
4583 }
4584 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4585
4586 static BC_STATUS zbc_parse_stmt_or_funcdef(BcParse *p)
4587 {
4588         BcStatus s;
4589
4590         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4591         if (p->l.t.t == BC_LEX_EOF)
4592                 s = bc_error("end of file");
4593         else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
4594                 dbg_lex("%s:%d p->l.t.t:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4595                 s = zbc_parse_funcdef(p);
4596         } else {
4597                 dbg_lex("%s:%d p->l.t.t:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->l.t.t);
4598                 s = zbc_parse_stmt(p);
4599         }
4600
4601         dbg_lex_done("%s:%d done", __func__, __LINE__);
4602         RETURN_STATUS(s);
4603 }
4604 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4605
4606 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4607 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags)
4608 {
4609         BcStatus s = BC_STATUS_SUCCESS;
4610         BcInst prev = BC_INST_PRINT;
4611         BcLexType top, t = p->l.t.t;
4612         size_t nexprs = 0, ops_bgn = p->ops.len;
4613         unsigned nparens, nrelops;
4614         bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4615
4616         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4617         paren_first = p->l.t.t == BC_LEX_LPAREN;
4618         nparens = nrelops = 0;
4619         paren_expr = rprn = done = get_token = assign = false;
4620         bin_last = true;
4621
4622         for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
4623                 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4624                 switch (t) {
4625                         case BC_LEX_OP_INC:
4626                         case BC_LEX_OP_DEC:
4627                                 s = zbc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4628                                 rprn = get_token = bin_last = false;
4629                                 break;
4630                         case BC_LEX_OP_MINUS:
4631                                 s = zbc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4632                                 rprn = get_token = false;
4633                                 bin_last = prev == BC_INST_MINUS;
4634                                 break;
4635                         case BC_LEX_OP_ASSIGN_POWER:
4636                         case BC_LEX_OP_ASSIGN_MULTIPLY:
4637                         case BC_LEX_OP_ASSIGN_DIVIDE:
4638                         case BC_LEX_OP_ASSIGN_MODULUS:
4639                         case BC_LEX_OP_ASSIGN_PLUS:
4640                         case BC_LEX_OP_ASSIGN_MINUS:
4641                         case BC_LEX_OP_ASSIGN:
4642                                 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM
4643                                  && prev != BC_INST_SCALE && prev != BC_INST_IBASE
4644                                  && prev != BC_INST_OBASE && prev != BC_INST_LAST
4645                                 ) {
4646                                         s = bc_error("bad assignment:"
4647                                                 " left side must be variable"
4648                                                 " or array element"
4649                                         ); // note: shared string
4650                                         break;
4651                                 }
4652                         // Fallthrough.
4653                         case BC_LEX_OP_POWER:
4654                         case BC_LEX_OP_MULTIPLY:
4655                         case BC_LEX_OP_DIVIDE:
4656                         case BC_LEX_OP_MODULUS:
4657                         case BC_LEX_OP_PLUS:
4658                         case BC_LEX_OP_REL_EQ:
4659                         case BC_LEX_OP_REL_LE:
4660                         case BC_LEX_OP_REL_GE:
4661                         case BC_LEX_OP_REL_NE:
4662                         case BC_LEX_OP_REL_LT:
4663                         case BC_LEX_OP_REL_GT:
4664                         case BC_LEX_OP_BOOL_NOT:
4665                         case BC_LEX_OP_BOOL_OR:
4666                         case BC_LEX_OP_BOOL_AND:
4667                                 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4668                                  || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4669                                 ) {
4670                                         return bc_error_bad_expression();
4671                                 }
4672                                 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4673                                 prev = BC_TOKEN_2_INST(t);
4674                                 bc_parse_operator(p, t, ops_bgn, &nexprs);
4675                                 s = zbc_lex_next(&p->l);
4676                                 rprn = get_token = false;
4677                                 bin_last = t != BC_LEX_OP_BOOL_NOT;
4678                                 break;
4679                         case BC_LEX_LPAREN:
4680                                 if (BC_PARSE_LEAF(prev, rprn))
4681                                         return bc_error_bad_expression();
4682                                 ++nparens;
4683                                 paren_expr = rprn = bin_last = false;
4684                                 get_token = true;
4685                                 bc_vec_push(&p->ops, &t);
4686                                 break;
4687                         case BC_LEX_RPAREN:
4688                                 if (bin_last || prev == BC_INST_BOOL_NOT)
4689                                         return bc_error_bad_expression();
4690                                 if (nparens == 0) {
4691                                         s = BC_STATUS_SUCCESS;
4692                                         done = true;
4693                                         get_token = false;
4694                                         break;
4695                                 }
4696                                 if (!paren_expr) {
4697                                         dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4698                                         return BC_STATUS_PARSE_EMPTY_EXP;
4699                                 }
4700                                 --nparens;
4701                                 paren_expr = rprn = true;
4702                                 get_token = bin_last = false;
4703                                 s = zbc_parse_rightParen(p, ops_bgn, &nexprs);
4704                                 break;
4705                         case BC_LEX_NAME:
4706                                 if (BC_PARSE_LEAF(prev, rprn))
4707                                         return bc_error_bad_expression();
4708                                 paren_expr = true;
4709                                 rprn = get_token = bin_last = false;
4710                                 s = zbc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4711                                 ++nexprs;
4712                                 break;
4713                         case BC_LEX_NUMBER:
4714                                 if (BC_PARSE_LEAF(prev, rprn))
4715                                         return bc_error_bad_expression();
4716                                 bc_parse_pushNUM(p);
4717                                 nexprs++;
4718                                 prev = BC_INST_NUM;
4719                                 paren_expr = get_token = true;
4720                                 rprn = bin_last = false;
4721                                 break;
4722                         case BC_LEX_KEY_IBASE:
4723                         case BC_LEX_KEY_LAST:
4724                         case BC_LEX_KEY_OBASE:
4725                                 if (BC_PARSE_LEAF(prev, rprn))
4726                                         return bc_error_bad_expression();
4727                                 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4728                                 bc_parse_push(p, (char) prev);
4729                                 paren_expr = get_token = true;
4730                                 rprn = bin_last = false;
4731                                 ++nexprs;
4732                                 break;
4733                         case BC_LEX_KEY_LENGTH:
4734                         case BC_LEX_KEY_SQRT:
4735                                 if (BC_PARSE_LEAF(prev, rprn))
4736                                         return bc_error_bad_expression();
4737                                 s = zbc_parse_builtin(p, t, flags, &prev);
4738                                 paren_expr = true;
4739                                 rprn = get_token = bin_last = false;
4740                                 ++nexprs;
4741                                 break;
4742                         case BC_LEX_KEY_READ:
4743                                 if (BC_PARSE_LEAF(prev, rprn))
4744                                         return bc_error_bad_expression();
4745                                 else
4746                                         s = zbc_parse_read(p);
4747                                 paren_expr = true;
4748                                 rprn = get_token = bin_last = false;
4749                                 ++nexprs;
4750                                 prev = BC_INST_READ;
4751                                 break;
4752                         case BC_LEX_KEY_SCALE:
4753                                 if (BC_PARSE_LEAF(prev, rprn))
4754                                         return bc_error_bad_expression();
4755                                 s = zbc_parse_scale(p, &prev, flags);
4756                                 paren_expr = true;
4757                                 rprn = get_token = bin_last = false;
4758                                 ++nexprs;
4759                                 prev = BC_INST_SCALE;
4760                                 break;
4761                         default:
4762                                 s = bc_error_bad_token();
4763                                 break;
4764                 }
4765
4766                 if (!s && get_token) s = zbc_lex_next(&p->l);
4767         }
4768
4769         if (s) return s;
4770         if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
4771
4772         while (p->ops.len > ops_bgn) {
4773                 top = BC_PARSE_TOP_OP(p);
4774                 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
4775
4776                 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4777                         return bc_error_bad_expression();
4778
4779                 bc_parse_push(p, BC_TOKEN_2_INST(top));
4780
4781                 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
4782                 bc_vec_pop(&p->ops);
4783         }
4784
4785         if (prev == BC_INST_BOOL_NOT || nexprs != 1)
4786                 return bc_error_bad_expression();
4787
4788         if (!(flags & BC_PARSE_REL) && nrelops) {
4789                 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
4790                 IF_ERROR_RETURN_POSSIBLE(if (s) return s);
4791         } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4792                 s = bc_POSIX_requires("exactly one comparison operator per condition");
4793                 IF_ERROR_RETURN_POSSIBLE(if (s) return s);
4794         }
4795
4796         if (flags & BC_PARSE_PRINT) {
4797                 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
4798                 bc_parse_push(p, BC_INST_POP);
4799         }
4800
4801         dbg_lex_done("%s:%d done", __func__, __LINE__);
4802         return s;
4803 }
4804
4805 #endif // ENABLE_BC
4806
4807 #if ENABLE_DC
4808
4809 static BC_STATUS zdc_parse_register(BcParse *p)
4810 {
4811         BcStatus s;
4812
4813         s = zbc_lex_next(&p->l);
4814         if (s) RETURN_STATUS(s);
4815         if (p->l.t.t != BC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4816
4817         bc_parse_pushName(p, p->l.t.v.v);
4818
4819         RETURN_STATUS(s);
4820 }
4821 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4822
4823 static void dc_parse_string(BcParse *p)
4824 {
4825         char *str;
4826         size_t len = G.prog.strs.len;
4827
4828         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4829
4830         str = xstrdup(p->l.t.v.v);
4831         bc_parse_push(p, BC_INST_STR);
4832         bc_parse_pushIndex(p, len);
4833         bc_vec_push(&G.prog.strs, &str);
4834
4835         // Explanation needed here
4836         bc_program_add_fn();
4837         p->func = bc_program_func(p->fidx);
4838
4839         dbg_lex_done("%s:%d done", __func__, __LINE__);
4840 }
4841
4842 static BC_STATUS zdc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
4843 {
4844         BcStatus s;
4845
4846         bc_parse_push(p, inst);
4847         if (name) {
4848                 s = zdc_parse_register(p);
4849                 if (s) RETURN_STATUS(s);
4850         }
4851
4852         if (store) {
4853                 bc_parse_push(p, BC_INST_SWAP);
4854                 bc_parse_push(p, BC_INST_ASSIGN);
4855                 bc_parse_push(p, BC_INST_POP);
4856         }
4857
4858         RETURN_STATUS(BC_STATUS_SUCCESS);
4859 }
4860 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4861
4862 static BC_STATUS zdc_parse_cond(BcParse *p, uint8_t inst)
4863 {
4864         BcStatus s;
4865
4866         bc_parse_push(p, inst);
4867         bc_parse_push(p, BC_INST_EXEC_COND);
4868
4869         s = zdc_parse_register(p);
4870         if (s) RETURN_STATUS(s);
4871
4872         s = zbc_lex_next(&p->l);
4873         if (s) RETURN_STATUS(s);
4874
4875         // Note that 'else' part can not be on the next line:
4876         // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4877         // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4878         if (p->l.t.t == BC_LEX_ELSE) {
4879                 s = zdc_parse_register(p);
4880                 if (s) RETURN_STATUS(s);
4881                 s = zbc_lex_next(&p->l);
4882         } else {
4883                 bc_parse_push(p, BC_PARSE_STREND);
4884         }
4885
4886         RETURN_STATUS(s);
4887 }
4888 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4889
4890 static BC_STATUS zdc_parse_token(BcParse *p, BcLexType t)
4891 {
4892         BcStatus s;
4893         uint8_t inst;
4894         bool assign, get_token;
4895
4896         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4897         s = BC_STATUS_SUCCESS;
4898         get_token = true;
4899         switch (t) {
4900                 case BC_LEX_OP_REL_EQ:
4901                 case BC_LEX_OP_REL_LE:
4902                 case BC_LEX_OP_REL_GE:
4903                 case BC_LEX_OP_REL_NE:
4904                 case BC_LEX_OP_REL_LT:
4905                 case BC_LEX_OP_REL_GT:
4906                         s = zdc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
4907                         get_token = false;
4908                         break;
4909                 case BC_LEX_SCOLON:
4910                 case BC_LEX_COLON:
4911                         s = zdc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
4912                         break;
4913                 case BC_LEX_STR:
4914                         dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
4915                         dc_parse_string(p);
4916                         break;
4917                 case BC_LEX_NEG:
4918                 case BC_LEX_NUMBER:
4919                         dbg_lex("%s:%d LEX_NEG/NUMBER", __func__, __LINE__);
4920                         if (t == BC_LEX_NEG) {
4921                                 s = zbc_lex_next(&p->l);
4922                                 if (s) RETURN_STATUS(s);
4923                                 if (p->l.t.t != BC_LEX_NUMBER)
4924                                         RETURN_STATUS(bc_error_bad_token());
4925                         }
4926                         bc_parse_pushNUM(p);
4927                         if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
4928                         break;
4929                 case BC_LEX_KEY_READ:
4930                         bc_parse_push(p, BC_INST_READ);
4931                         break;
4932                 case BC_LEX_OP_ASSIGN:
4933                 case BC_LEX_STORE_PUSH:
4934                         assign = t == BC_LEX_OP_ASSIGN;
4935                         inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
4936                         s = zdc_parse_mem(p, inst, true, assign);
4937                         break;
4938                 case BC_LEX_LOAD:
4939                 case BC_LEX_LOAD_POP:
4940                         inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
4941                         s = zdc_parse_mem(p, inst, true, false);
4942                         break;
4943                 case BC_LEX_STORE_IBASE:
4944                 case BC_LEX_STORE_SCALE:
4945                 case BC_LEX_STORE_OBASE:
4946                         inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
4947                         s = zdc_parse_mem(p, inst, false, true);
4948                         break;
4949                 default:
4950                         dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
4951                         RETURN_STATUS(bc_error_bad_token());
4952         }
4953
4954         if (!s && get_token) s = zbc_lex_next(&p->l);
4955
4956         dbg_lex_done("%s:%d done", __func__, __LINE__);
4957         RETURN_STATUS(s);
4958 }
4959 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
4960
4961 static BC_STATUS zdc_parse_expr(BcParse *p)
4962 {
4963         BcInst inst;
4964         BcStatus s;
4965
4966         inst = dc_parse_insts[p->l.t.t];
4967         if (inst != BC_INST_INVALID) {
4968                 bc_parse_push(p, inst);
4969                 s = zbc_lex_next(&p->l);
4970         } else {
4971                 s = zdc_parse_token(p, p->l.t.t);
4972         }
4973         RETURN_STATUS(s);
4974 }
4975 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
4976
4977 static BC_STATUS zdc_parse_exprs_until_eof(BcParse *p)
4978 {
4979         dbg_lex_enter("%s:%d entered, p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4980         while (p->l.t.t != BC_LEX_EOF) {
4981                 BcStatus s = zdc_parse_expr(p);
4982                 if (s) RETURN_STATUS(s);
4983         }
4984
4985         dbg_lex_done("%s:%d done", __func__, __LINE__);
4986         RETURN_STATUS(BC_STATUS_SUCCESS);
4987 }
4988 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
4989
4990 #endif // ENABLE_DC
4991
4992 static BcVec* bc_program_search(char *id, bool var)
4993 {
4994         BcId e, *ptr;
4995         BcVec *v, *map;
4996         size_t i;
4997         int new;
4998
4999         v = var ? &G.prog.vars : &G.prog.arrs;
5000         map = var ? &G.prog.var_map : &G.prog.arr_map;
5001
5002         e.name = id;
5003         e.idx = v->len;
5004         new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5005
5006         if (new) {
5007                 BcVec v2;
5008                 bc_array_init(&v2, var);
5009                 bc_vec_push(v, &v2);
5010         }
5011
5012         ptr = bc_vec_item(map, i);
5013         if (new) ptr->name = xstrdup(e.name);
5014         return bc_vec_item(v, ptr->idx);
5015 }
5016
5017 // 'num' need not be initialized on entry
5018 static BC_STATUS zbc_program_num(BcResult *r, BcNum **num, bool hex)
5019 {
5020         switch (r->t) {
5021                 case BC_RESULT_STR:
5022                 case BC_RESULT_TEMP:
5023                 case BC_RESULT_IBASE:
5024                 case BC_RESULT_SCALE:
5025                 case BC_RESULT_OBASE:
5026                         *num = &r->d.n;
5027                         break;
5028                 case BC_RESULT_CONSTANT: {
5029                         BcStatus s;
5030                         char *str;
5031                         unsigned base_t;
5032                         size_t len;
5033
5034                         str = *bc_program_const(r->d.id.idx);
5035                         len = strlen(str);
5036
5037                         bc_num_init(&r->d.n, len);
5038
5039                         hex = hex && len == 1;
5040                         base_t = hex ? 16 : G.prog.ib_t;
5041                         s = zbc_num_parse(&r->d.n, str, base_t);
5042                         if (s) {
5043                                 bc_num_free(&r->d.n);
5044                                 RETURN_STATUS(s);
5045                         }
5046                         *num = &r->d.n;
5047                         r->t = BC_RESULT_TEMP;
5048                         break;
5049                 }
5050                 case BC_RESULT_VAR:
5051                 case BC_RESULT_ARRAY:
5052                 case BC_RESULT_ARRAY_ELEM: {
5053                         BcVec *v;
5054
5055                         v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
5056
5057                         if (r->t == BC_RESULT_ARRAY_ELEM) {
5058                                 v = bc_vec_top(v);
5059                                 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5060                                 *num = bc_vec_item(v, r->d.id.idx);
5061                         } else
5062                                 *num = bc_vec_top(v);
5063                         break;
5064                 }
5065 #if ENABLE_BC
5066                 case BC_RESULT_LAST:
5067                         *num = &G.prog.last;
5068                         break;
5069                 case BC_RESULT_ONE:
5070                         *num = &G.prog.one;
5071                         break;
5072 #endif
5073                 default:
5074                         // Testing the theory that dc does not reach LAST/ONE
5075                         bb_error_msg_and_die("BUG:%d", r->t);
5076         }
5077
5078         RETURN_STATUS(BC_STATUS_SUCCESS);
5079 }
5080 #define zbc_program_num(...) (zbc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5081
5082 static BC_STATUS zbc_program_binOpPrep(BcResult **l, BcNum **ln,
5083                                      BcResult **r, BcNum **rn, bool assign)
5084 {
5085         BcStatus s;
5086         bool hex;
5087         BcResultType lt, rt;
5088
5089         if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5090                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5091
5092         *r = bc_vec_item_rev(&G.prog.results, 0);
5093         *l = bc_vec_item_rev(&G.prog.results, 1);
5094
5095         lt = (*l)->t;
5096         rt = (*r)->t;
5097         hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5098
5099         s = zbc_program_num(*l, ln, false);
5100         if (s) RETURN_STATUS(s);
5101         s = zbc_program_num(*r, rn, hex);
5102         if (s) RETURN_STATUS(s);
5103
5104         // We run this again under these conditions in case any vector has been
5105         // reallocated out from under the BcNums or arrays we had.
5106         if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
5107                 s = zbc_program_num(*l, ln, false);
5108                 if (s) RETURN_STATUS(s);
5109         }
5110
5111         if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
5112                 RETURN_STATUS(bc_error_variable_is_wrong_type());
5113         if (!assign && !BC_PROG_NUM((*r), (*ln)))
5114                 RETURN_STATUS(bc_error_variable_is_wrong_type());
5115
5116         RETURN_STATUS(s);
5117 }
5118 #define zbc_program_binOpPrep(...) (zbc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5119
5120 static void bc_program_binOpRetire(BcResult *r)
5121 {
5122         r->t = BC_RESULT_TEMP;
5123         bc_vec_pop(&G.prog.results);
5124         bc_result_pop_and_push(r);
5125 }
5126
5127 static BC_STATUS zbc_program_prep(BcResult **r, BcNum **n)
5128 {
5129         BcStatus s;
5130
5131         if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5132                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5133         *r = bc_vec_top(&G.prog.results);
5134
5135         s = zbc_program_num(*r, n, false);
5136         if (s) RETURN_STATUS(s);
5137
5138         if (!BC_PROG_NUM((*r), (*n)))
5139                 RETURN_STATUS(bc_error_variable_is_wrong_type());
5140
5141         RETURN_STATUS(s);
5142 }
5143 #define zbc_program_prep(...) (zbc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5144
5145 static void bc_program_retire(BcResult *r, BcResultType t)
5146 {
5147         r->t = t;
5148         bc_result_pop_and_push(r);
5149 }
5150
5151 static BC_STATUS zbc_program_op(char inst)
5152 {
5153         BcStatus s;
5154         BcResult *opd1, *opd2, res;
5155         BcNum *n1, *n2 = NULL;
5156
5157         s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5158         if (s) RETURN_STATUS(s);
5159         bc_num_init_DEF_SIZE(&res.d.n);
5160
5161         s = BC_STATUS_SUCCESS;
5162         IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5163         if (s) goto err;
5164         bc_program_binOpRetire(&res);
5165
5166         RETURN_STATUS(s);
5167  err:
5168         bc_num_free(&res.d.n);
5169         RETURN_STATUS(s);
5170 }
5171 #define zbc_program_op(...) (zbc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5172
5173 static BC_STATUS zbc_program_read(void)
5174 {
5175         const char *sv_file;
5176         BcStatus s;
5177         BcParse parse;
5178         BcVec buf;
5179         BcInstPtr ip;
5180         BcFunc *f;
5181
5182         f = bc_program_func(BC_PROG_READ);
5183         bc_vec_pop_all(&f->code);
5184
5185         sv_file = G.prog.file;
5186         G.prog.file = NULL;
5187
5188         bc_char_vec_init(&buf);
5189         bc_read_line(&buf, stdin);
5190
5191         bc_parse_create(&parse, BC_PROG_READ);
5192         bc_lex_file(&parse.l);
5193
5194         s = zbc_parse_text_init(&parse, buf.v);
5195         if (s) goto exec_err;
5196         if (IS_BC) {
5197                 IF_BC(s = zbc_parse_expr(&parse, 0));
5198         } else {
5199                 IF_DC(s = zdc_parse_exprs_until_eof(&parse));
5200         }
5201         if (s) goto exec_err;
5202
5203         if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
5204                 s = bc_error("bad read() expression");
5205                 goto exec_err;
5206         }
5207
5208         ip.func = BC_PROG_READ;
5209         ip.inst_idx = 0;
5210         IF_BC(ip.results_len_before_call = G.prog.results.len;)
5211
5212         bc_parse_push(&parse, BC_INST_RET);
5213         bc_vec_push(&G.prog.exestack, &ip);
5214  exec_err:
5215         bc_parse_free(&parse);
5216         G.prog.file = sv_file;
5217         bc_vec_free(&buf);
5218         RETURN_STATUS(s);
5219 }
5220 #define zbc_program_read(...) (zbc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5221
5222 static size_t bc_program_index(char *code, size_t *bgn)
5223 {
5224         unsigned char *bytes = (void*)(code + *bgn);
5225         unsigned amt;
5226         unsigned i;
5227         size_t res;
5228
5229         amt = *bytes++;
5230         *bgn += amt + 1;
5231
5232         amt *= 8;
5233         res = 0;
5234         for (i = 0; i < amt; i += 8)
5235                 res |= (size_t)(*bytes++) << i;
5236
5237         return res;
5238 }
5239
5240 static char *bc_program_name(char *code, size_t *bgn)
5241 {
5242         size_t i;
5243         char *s;
5244
5245         code += *bgn;
5246         s = xmalloc(strchr(code, BC_PARSE_STREND) - code + 1);
5247         i = 0;
5248         for (;;) {
5249                 char c = *code++;
5250                 if (c == BC_PARSE_STREND)
5251                         break;
5252                 s[i++] = c;
5253         }
5254         s[i] = '\0';
5255         *bgn += i + 1;
5256
5257         return s;
5258 }
5259
5260 static void bc_program_printString(const char *str)
5261 {
5262 #if ENABLE_DC
5263         if (!str[0]) {
5264                 // Example: echo '[]ap' | dc
5265                 // should print two bytes: 0x00, 0x0A
5266                 bb_putchar('\0');
5267                 return;
5268         }
5269 #endif
5270         while (*str) {
5271                 int c = *str++;
5272                 if (c != '\\' || !*str)
5273                         bb_putchar(c);
5274                 else {
5275                         c = *str++;
5276                         switch (c) {
5277                         case 'a':
5278                                 bb_putchar('\a');
5279                                 break;
5280                         case 'b':
5281                                 bb_putchar('\b');
5282                                 break;
5283                         case '\\':
5284                         case 'e':
5285                                 bb_putchar('\\');
5286                                 break;
5287                         case 'f':
5288                                 bb_putchar('\f');
5289                                 break;
5290                         case 'n':
5291                                 bb_putchar('\n');
5292                                 G.prog.nchars = SIZE_MAX;
5293                                 break;
5294                         case 'r':
5295                                 bb_putchar('\r');
5296                                 break;
5297                         case 'q':
5298                                 bb_putchar('"');
5299                                 break;
5300                         case 't':
5301                                 bb_putchar('\t');
5302                                 break;
5303                         default:
5304                                 // Just print the backslash and following character.
5305                                 bb_putchar('\\');
5306                                 ++G.prog.nchars;
5307                                 bb_putchar(c);
5308                                 break;
5309                         }
5310                 }
5311                 ++G.prog.nchars;
5312         }
5313 }
5314
5315 static void bc_num_printNewline(void)
5316 {
5317         if (G.prog.nchars == G.prog.len - 1) {
5318                 bb_putchar('\\');
5319                 bb_putchar('\n');
5320                 G.prog.nchars = 0;
5321         }
5322 }
5323
5324 #if ENABLE_DC
5325 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5326 {
5327         (void) radix;
5328         bb_putchar((char) num);
5329         G.prog.nchars += width;
5330 }
5331 #endif
5332
5333 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5334 {
5335         size_t exp, pow;
5336
5337         bc_num_printNewline();
5338         bb_putchar(radix ? '.' : ' ');
5339         ++G.prog.nchars;
5340
5341         bc_num_printNewline();
5342         for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5343                 continue;
5344
5345         for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5346                 size_t dig;
5347                 bc_num_printNewline();
5348                 dig = num / pow;
5349                 num -= dig * pow;
5350                 bb_putchar(((char) dig) + '0');
5351         }
5352 }
5353
5354 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5355 {
5356         if (radix) {
5357                 bc_num_printNewline();
5358                 bb_putchar('.');
5359                 G.prog.nchars++;
5360         }
5361
5362         bc_num_printNewline();
5363         bb_putchar(bb_hexdigits_upcase[num]);
5364         G.prog.nchars += width;
5365 }
5366
5367 static void bc_num_printDecimal(BcNum *n)
5368 {
5369         size_t i, rdx = n->rdx - 1;
5370
5371         if (n->neg) {
5372                 bb_putchar('-');
5373                 G.prog.nchars++;
5374         }
5375
5376         for (i = n->len - 1; i < n->len; --i)
5377                 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5378 }
5379
5380 static BC_STATUS zbc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5381 {
5382         BcStatus s;
5383         BcVec stack;
5384         BcNum base;
5385         BcDig base_digs[ULONG_NUM_BUFSIZE];
5386         BcNum intp, fracp, digit, frac_len;
5387         unsigned long dig, *ptr;
5388         size_t i;
5389         bool radix;
5390
5391         if (n->len == 0) {
5392                 print(0, width, false);
5393                 RETURN_STATUS(BC_STATUS_SUCCESS);
5394         }
5395
5396         bc_vec_init(&stack, sizeof(long), NULL);
5397         bc_num_init(&intp, n->len);
5398         bc_num_init(&fracp, n->rdx);
5399         bc_num_init(&digit, width);
5400         bc_num_init(&frac_len, BC_NUM_INT(n));
5401         bc_num_copy(&intp, n);
5402         bc_num_one(&frac_len);
5403         base.cap = ARRAY_SIZE(base_digs);
5404         base.num = base_digs;
5405         bc_num_ulong2num(&base, base_t);
5406
5407         bc_num_truncate(&intp, intp.rdx);
5408         s = zbc_num_sub(n, &intp, &fracp, 0);
5409         if (s) goto err;
5410
5411         while (intp.len != 0) {
5412                 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5413                 if (s) goto err;
5414                 s = zbc_num_ulong(&digit, &dig);
5415                 if (s) goto err;
5416                 bc_vec_push(&stack, &dig);
5417         }
5418
5419         for (i = 0; i < stack.len; ++i) {
5420                 ptr = bc_vec_item_rev(&stack, i);
5421                 print(*ptr, width, false);
5422         }
5423
5424         if (!n->rdx) goto err;
5425
5426         for (radix = true; frac_len.len <= n->rdx; radix = false) {
5427                 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5428                 if (s) goto err;
5429                 s = zbc_num_ulong(&fracp, &dig);
5430                 if (s) goto err;
5431                 bc_num_ulong2num(&intp, dig);
5432                 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5433                 if (s) goto err;
5434                 print(dig, width, radix);
5435                 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5436                 if (s) goto err;
5437         }
5438  err:
5439         bc_num_free(&frac_len);
5440         bc_num_free(&digit);
5441         bc_num_free(&fracp);
5442         bc_num_free(&intp);
5443         bc_vec_free(&stack);
5444         RETURN_STATUS(s);
5445 }
5446 #define zbc_num_printNum(...) (zbc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5447
5448 static BC_STATUS zbc_num_printBase(BcNum *n)
5449 {
5450         BcStatus s;
5451         size_t width;
5452         BcNumDigitOp print;
5453         bool neg = n->neg;
5454
5455         if (neg) {
5456                 bb_putchar('-');
5457                 G.prog.nchars++;
5458         }
5459
5460         n->neg = false;
5461
5462         if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5463                 width = 1;
5464                 print = bc_num_printHex;
5465         } else {
5466                 unsigned i = G.prog.ob_t - 1;
5467                 width = 0;
5468                 for (;;) {
5469                         width++;
5470                         i /= 10;
5471                         if (i == 0)
5472                                 break;
5473                 }
5474                 print = bc_num_printDigits;
5475         }
5476
5477         s = zbc_num_printNum(n, G.prog.ob_t, width, print);
5478         n->neg = neg;
5479
5480         RETURN_STATUS(s);
5481 }
5482 #define zbc_num_printBase(...) (zbc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5483
5484 static BC_STATUS zbc_num_print(BcNum *n, bool newline)
5485 {
5486         BcStatus s = BC_STATUS_SUCCESS;
5487
5488         bc_num_printNewline();
5489
5490         if (n->len == 0) {
5491                 bb_putchar('0');
5492                 ++G.prog.nchars;
5493         } else if (G.prog.ob_t == 10)
5494                 bc_num_printDecimal(n);
5495         else
5496                 s = zbc_num_printBase(n);
5497
5498         if (newline) {
5499                 bb_putchar('\n');
5500                 G.prog.nchars = 0;
5501         }
5502
5503         RETURN_STATUS(s);
5504 }
5505 #define zbc_num_print(...) (zbc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5506
5507 static BC_STATUS zbc_program_print(char inst, size_t idx)
5508 {
5509         BcStatus s;
5510         BcResult *r;
5511         BcNum *num;
5512         bool pop = inst != BC_INST_PRINT;
5513
5514         if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5515                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5516
5517         r = bc_vec_item_rev(&G.prog.results, idx);
5518         s = zbc_program_num(r, &num, false);
5519         if (s) RETURN_STATUS(s);
5520
5521         if (BC_PROG_NUM(r, num)) {
5522                 s = zbc_num_print(num, !pop);
5523 #if ENABLE_BC
5524                 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5525 #endif
5526         } else {
5527                 char *str;
5528
5529                 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
5530                 str = *bc_program_str(idx);
5531
5532                 if (inst == BC_INST_PRINT_STR) {
5533                         for (;;) {
5534                                 char c = *str++;
5535                                 if (c == '\0') break;
5536                                 bb_putchar(c);
5537                                 ++G.prog.nchars;
5538                                 if (c == '\n') G.prog.nchars = 0;
5539                         }
5540                 } else {
5541                         bc_program_printString(str);
5542                         if (inst == BC_INST_PRINT) bb_putchar('\n');
5543                 }
5544         }
5545
5546         if (!s && pop) bc_vec_pop(&G.prog.results);
5547
5548         RETURN_STATUS(s);
5549 }
5550 #define zbc_program_print(...) (zbc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5551
5552 static BC_STATUS zbc_program_negate(void)
5553 {
5554         BcStatus s;
5555         BcResult res, *ptr;
5556         BcNum *num = NULL;
5557
5558         s = zbc_program_prep(&ptr, &num);
5559         if (s) RETURN_STATUS(s);
5560
5561         bc_num_init(&res.d.n, num->len);
5562         bc_num_copy(&res.d.n, num);
5563         if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5564
5565         bc_program_retire(&res, BC_RESULT_TEMP);
5566
5567         RETURN_STATUS(s);
5568 }
5569 #define zbc_program_negate(...) (zbc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5570
5571 static BC_STATUS zbc_program_logical(char inst)
5572 {
5573         BcStatus s;
5574         BcResult *opd1, *opd2, res;
5575         BcNum *n1, *n2;
5576         ssize_t cond;
5577
5578         s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5579         if (s) RETURN_STATUS(s);
5580
5581         bc_num_init_DEF_SIZE(&res.d.n);
5582
5583         if (inst == BC_INST_BOOL_AND)
5584                 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5585         else if (inst == BC_INST_BOOL_OR)
5586                 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5587         else {
5588                 cond = bc_num_cmp(n1, n2);
5589                 switch (inst) {
5590                 case BC_INST_REL_EQ:
5591                         cond = (cond == 0);
5592                         break;
5593                 case BC_INST_REL_LE:
5594                         cond = (cond <= 0);
5595                         break;
5596                 case BC_INST_REL_GE:
5597                         cond = (cond >= 0);
5598                         break;
5599                 case BC_INST_REL_LT:
5600                         cond = (cond < 0);
5601                         break;
5602                 case BC_INST_REL_GT:
5603                         cond = (cond > 0);
5604                         break;
5605                 default: // = case BC_INST_REL_NE:
5606                         //cond = (cond != 0); - not needed
5607                         break;
5608                 }
5609         }
5610
5611         if (cond) bc_num_one(&res.d.n);
5612         //else bc_num_zero(&res.d.n); - already is
5613
5614         bc_program_binOpRetire(&res);
5615
5616         RETURN_STATUS(s);
5617 }
5618 #define zbc_program_logical(...) (zbc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5619
5620 #if ENABLE_DC
5621 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5622 {
5623         BcNum n2;
5624         BcResult res;
5625
5626         memset(&n2, 0, sizeof(BcNum));
5627         n2.rdx = res.d.id.idx = r->d.id.idx;
5628         res.t = BC_RESULT_STR;
5629
5630         if (!push) {
5631                 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5632                         RETURN_STATUS(bc_error_stack_has_too_few_elements());
5633                 bc_vec_pop(v);
5634                 bc_vec_pop(&G.prog.results);
5635         }
5636
5637         bc_result_pop_and_push(&res);
5638         bc_vec_push(v, &n2);
5639
5640         RETURN_STATUS(BC_STATUS_SUCCESS);
5641 }
5642 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5643 #endif // ENABLE_DC
5644
5645 static BC_STATUS zbc_program_copyToVar(char *name, bool var)
5646 {
5647         BcStatus s;
5648         BcResult *ptr, r;
5649         BcVec *v;
5650         BcNum *n;
5651
5652         if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5653                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5654
5655         ptr = bc_vec_top(&G.prog.results);
5656         if ((ptr->t == BC_RESULT_ARRAY) != !var)
5657                 RETURN_STATUS(bc_error_variable_is_wrong_type());
5658         v = bc_program_search(name, var);
5659
5660 #if ENABLE_DC
5661         if (ptr->t == BC_RESULT_STR && !var)
5662                 RETURN_STATUS(bc_error_variable_is_wrong_type());
5663         if (ptr->t == BC_RESULT_STR)
5664                 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5665 #endif
5666
5667         s = zbc_program_num(ptr, &n, false);
5668         if (s) RETURN_STATUS(s);
5669
5670         // Do this once more to make sure that pointers were not invalidated.
5671         v = bc_program_search(name, var);
5672
5673         if (var) {
5674                 bc_num_init_DEF_SIZE(&r.d.n);
5675                 bc_num_copy(&r.d.n, n);
5676         } else {
5677                 bc_array_init(&r.d.v, true);
5678                 bc_array_copy(&r.d.v, (BcVec *) n);
5679         }
5680
5681         bc_vec_push(v, &r.d);
5682         bc_vec_pop(&G.prog.results);
5683
5684         RETURN_STATUS(s);
5685 }
5686 #define zbc_program_copyToVar(...) (zbc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5687
5688 static BC_STATUS zbc_program_assign(char inst)
5689 {
5690         BcStatus s;
5691         BcResult *left, *right, res;
5692         BcNum *l = NULL, *r = NULL;
5693         bool assign = inst == BC_INST_ASSIGN, ib, sc;
5694
5695         s = zbc_program_binOpPrep(&left, &l, &right, &r, assign);
5696         if (s) RETURN_STATUS(s);
5697
5698         ib = left->t == BC_RESULT_IBASE;
5699         sc = left->t == BC_RESULT_SCALE;
5700
5701 #if ENABLE_DC
5702         if (right->t == BC_RESULT_STR) {
5703                 BcVec *v;
5704
5705                 if (left->t != BC_RESULT_VAR)
5706                         RETURN_STATUS(bc_error_variable_is_wrong_type());
5707                 v = bc_program_search(left->d.id.name, true);
5708
5709                 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5710         }
5711 #endif
5712
5713         if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
5714                 RETURN_STATUS(bc_error("bad assignment:"
5715                                 " left side must be variable"
5716                                 " or array element"
5717                 )); // note: shared string
5718
5719 #if ENABLE_BC
5720         if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5721                 RETURN_STATUS(bc_error("divide by zero"));
5722
5723         if (assign)
5724                 bc_num_copy(l, r);
5725         else {
5726                 s = BC_STATUS_SUCCESS;
5727                 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5728         }
5729         if (s) RETURN_STATUS(s);
5730 #else
5731         bc_num_copy(l, r);
5732 #endif
5733
5734         if (ib || sc || left->t == BC_RESULT_OBASE) {
5735                 static const char *const msg[] = {
5736                         "bad ibase; must be [2,16]",                 //BC_RESULT_IBASE
5737                         "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5738                         NULL, //can't happen                         //BC_RESULT_LAST
5739                         NULL, //can't happen                         //BC_RESULT_CONSTANT
5740                         NULL, //can't happen                         //BC_RESULT_ONE
5741                         "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
5742                 };
5743                 size_t *ptr;
5744                 size_t max;
5745                 unsigned long val;
5746
5747                 s = zbc_num_ulong(l, &val);
5748                 if (s) RETURN_STATUS(s);
5749                 s = left->t - BC_RESULT_IBASE;
5750                 if (sc) {
5751                         max = BC_MAX_SCALE;
5752                         ptr = &G.prog.scale;
5753                 } else {
5754                         if (val < 2)
5755                                 RETURN_STATUS(bc_error(msg[s]));
5756                         max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5757                         ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5758                 }
5759
5760                 if (val > max)
5761                         RETURN_STATUS(bc_error(msg[s]));
5762
5763                 *ptr = (size_t) val;
5764                 s = BC_STATUS_SUCCESS;
5765         }
5766
5767         bc_num_init(&res.d.n, l->len);
5768         bc_num_copy(&res.d.n, l);
5769         bc_program_binOpRetire(&res);
5770
5771         RETURN_STATUS(s);
5772 }
5773 #define zbc_program_assign(...) (zbc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5774
5775 #if !ENABLE_DC
5776 #define bc_program_pushVar(code, bgn, pop, copy) \
5777         bc_program_pushVar(code, bgn)
5778 // for bc, 'pop' and 'copy' are always false
5779 #endif
5780 static BC_STATUS bc_program_pushVar(char *code, size_t *bgn,
5781                                    bool pop, bool copy)
5782 {
5783         BcResult r;
5784         char *name = bc_program_name(code, bgn);
5785
5786         r.t = BC_RESULT_VAR;
5787         r.d.id.name = name;
5788
5789 #if ENABLE_DC
5790         if (pop || copy) {
5791                 BcVec *v = bc_program_search(name, true);
5792                 BcNum *num = bc_vec_top(v);
5793
5794                 free(name);
5795                 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5796                         RETURN_STATUS(bc_error_stack_has_too_few_elements());
5797                 }
5798
5799                 if (!BC_PROG_STR(num)) {
5800                         r.t = BC_RESULT_TEMP;
5801                         bc_num_init_DEF_SIZE(&r.d.n);
5802                         bc_num_copy(&r.d.n, num);
5803                 } else {
5804                         r.t = BC_RESULT_STR;
5805                         r.d.id.idx = num->rdx;
5806                 }
5807
5808                 if (!copy) bc_vec_pop(v);
5809         }
5810 #endif // ENABLE_DC
5811
5812         bc_vec_push(&G.prog.results, &r);
5813
5814         RETURN_STATUS(BC_STATUS_SUCCESS);
5815 }
5816 #define zbc_program_pushVar(...) (bc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5817
5818 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5819 {
5820         BcStatus s = BC_STATUS_SUCCESS;
5821         BcResult r;
5822         BcNum *num;
5823
5824         r.d.id.name = bc_program_name(code, bgn);
5825
5826         if (inst == BC_INST_ARRAY) {
5827                 r.t = BC_RESULT_ARRAY;
5828                 bc_vec_push(&G.prog.results, &r);
5829         } else {
5830                 BcResult *operand;
5831                 unsigned long temp;
5832
5833                 s = zbc_program_prep(&operand, &num);
5834                 if (s) goto err;
5835                 s = zbc_num_ulong(num, &temp);
5836                 if (s) goto err;
5837
5838                 if (temp > BC_MAX_DIM) {
5839                         s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5840                         goto err;
5841                 }
5842
5843                 r.d.id.idx = (size_t) temp;
5844                 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
5845         }
5846  err:
5847         if (s) free(r.d.id.name);
5848         RETURN_STATUS(s);
5849 }
5850 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5851
5852 #if ENABLE_BC
5853 static BC_STATUS zbc_program_incdec(char inst)
5854 {
5855         BcStatus s;
5856         BcResult *ptr, res, copy;
5857         BcNum *num = NULL;
5858         char inst2 = inst;
5859
5860         s = zbc_program_prep(&ptr, &num);
5861         if (s) RETURN_STATUS(s);
5862
5863         if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5864                 copy.t = BC_RESULT_TEMP;
5865                 bc_num_init(&copy.d.n, num->len);
5866                 bc_num_copy(&copy.d.n, num);
5867         }
5868
5869         res.t = BC_RESULT_ONE;
5870         inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
5871                    BC_INST_ASSIGN_PLUS :
5872                    BC_INST_ASSIGN_MINUS;
5873
5874         bc_vec_push(&G.prog.results, &res);
5875         s = zbc_program_assign(inst);
5876         if (s) RETURN_STATUS(s);
5877
5878         if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5879                 bc_result_pop_and_push(&copy);
5880         }
5881
5882         RETURN_STATUS(s);
5883 }
5884 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5885
5886 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5887 {
5888         BcInstPtr ip;
5889         size_t i, nparams;
5890         BcFunc *func;
5891         BcId *a;
5892         BcResult *arg;
5893
5894         nparams = bc_program_index(code, idx);
5895         ip.inst_idx = 0;
5896         ip.func = bc_program_index(code, idx);
5897         func = bc_program_func(ip.func);
5898
5899         if (func->code.len == 0) {
5900                 RETURN_STATUS(bc_error("undefined function"));
5901         }
5902         if (nparams != func->nparams) {
5903                 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5904         }
5905         ip.results_len_before_call = G.prog.results.len - nparams;
5906
5907         for (i = 0; i < nparams; ++i) {
5908                 BcStatus s;
5909
5910                 a = bc_vec_item(&func->autos, nparams - 1 - i);
5911                 arg = bc_vec_top(&G.prog.results);
5912
5913                 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
5914                         RETURN_STATUS(bc_error_variable_is_wrong_type());
5915
5916                 s = zbc_program_copyToVar(a->name, a->idx);
5917                 if (s) RETURN_STATUS(s);
5918         }
5919
5920         a = bc_vec_item(&func->autos, i);
5921         for (; i < func->autos.len; i++, a++) {
5922                 BcVec *v;
5923
5924                 v = bc_program_search(a->name, a->idx);
5925                 if (a->idx) {
5926                         BcNum n2;
5927                         bc_num_init_DEF_SIZE(&n2);
5928                         bc_vec_push(v, &n2);
5929                 } else {
5930                         BcVec v2;
5931                         bc_array_init(&v2, true);
5932                         bc_vec_push(v, &v2);
5933                 }
5934         }
5935
5936         bc_vec_push(&G.prog.exestack, &ip);
5937
5938         RETURN_STATUS(BC_STATUS_SUCCESS);
5939 }
5940 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
5941
5942 static BC_STATUS zbc_program_return(char inst)
5943 {
5944         BcResult res;
5945         BcFunc *f;
5946         BcId *a;
5947         size_t i;
5948         BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
5949
5950         if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == BC_INST_RET)))
5951                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5952
5953         f = bc_program_func(ip->func);
5954         res.t = BC_RESULT_TEMP;
5955
5956         if (inst == BC_INST_RET) {
5957                 BcStatus s;
5958                 BcNum *num;
5959                 BcResult *operand = bc_vec_top(&G.prog.results);
5960
5961                 s = zbc_program_num(operand, &num, false);
5962                 if (s) RETURN_STATUS(s);
5963                 bc_num_init(&res.d.n, num->len);
5964                 bc_num_copy(&res.d.n, num);
5965         } else {
5966                 bc_num_init_DEF_SIZE(&res.d.n);
5967                 //bc_num_zero(&res.d.n); - already is
5968         }
5969
5970         // We need to pop arguments as well, so this takes that into account.
5971         a = (void*)f->autos.v;
5972         for (i = 0; i < f->autos.len; i++, a++) {
5973                 BcVec *v;
5974                 v = bc_program_search(a->name, a->idx);
5975                 bc_vec_pop(v);
5976         }
5977
5978         bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
5979         bc_vec_push(&G.prog.results, &res);
5980         bc_vec_pop(&G.prog.exestack);
5981
5982         RETURN_STATUS(BC_STATUS_SUCCESS);
5983 }
5984 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
5985 #endif // ENABLE_BC
5986
5987 static unsigned long bc_program_scale(BcNum *n)
5988 {
5989         return (unsigned long) n->rdx;
5990 }
5991
5992 static unsigned long bc_program_len(BcNum *n)
5993 {
5994         size_t len = n->len;
5995
5996         if (n->rdx != len) return len;
5997         for (;;) {
5998                 if (len == 0) break;
5999                 len--;
6000                 if (n->num[len] != 0) break;
6001         }
6002         return len;
6003 }
6004
6005 static BC_STATUS zbc_program_builtin(char inst)
6006 {
6007         BcStatus s;
6008         BcResult *opnd;
6009         BcNum *num = NULL;
6010         BcResult res;
6011         bool len = inst == BC_INST_LENGTH;
6012
6013         if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6014                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6015         opnd = bc_vec_top(&G.prog.results);
6016
6017         s = zbc_program_num(opnd, &num, false);
6018         if (s) RETURN_STATUS(s);
6019
6020 #if ENABLE_DC
6021         if (!BC_PROG_NUM(opnd, num) && !len)
6022                 RETURN_STATUS(bc_error_variable_is_wrong_type());
6023 #endif
6024
6025         bc_num_init_DEF_SIZE(&res.d.n);
6026
6027         if (inst == BC_INST_SQRT)
6028                 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6029 #if ENABLE_BC
6030         else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
6031                 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6032         }
6033 #endif
6034 #if ENABLE_DC
6035         else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6036                 char **str;
6037                 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6038
6039                 str = bc_program_str(idx);
6040                 bc_num_ulong2num(&res.d.n, strlen(*str));
6041         }
6042 #endif
6043         else {
6044                 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6045         }
6046
6047         bc_program_retire(&res, BC_RESULT_TEMP);
6048
6049         RETURN_STATUS(s);
6050 }
6051 #define zbc_program_builtin(...) (zbc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6052
6053 #if ENABLE_DC
6054 static BC_STATUS zdc_program_divmod(void)
6055 {
6056         BcStatus s;
6057         BcResult *opd1, *opd2, res, res2;
6058         BcNum *n1, *n2 = NULL;
6059
6060         s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6061         if (s) RETURN_STATUS(s);
6062
6063         bc_num_init_DEF_SIZE(&res.d.n);
6064         bc_num_init(&res2.d.n, n2->len);
6065
6066         s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6067         if (s) goto err;
6068
6069         bc_program_binOpRetire(&res2);
6070         res.t = BC_RESULT_TEMP;
6071         bc_vec_push(&G.prog.results, &res);
6072
6073         RETURN_STATUS(s);
6074  err:
6075         bc_num_free(&res2.d.n);
6076         bc_num_free(&res.d.n);
6077         RETURN_STATUS(s);
6078 }
6079 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6080
6081 static BC_STATUS zdc_program_modexp(void)
6082 {
6083         BcStatus s;
6084         BcResult *r1, *r2, *r3, res;
6085         BcNum *n1, *n2, *n3;
6086
6087         if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6088                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6089         s = zbc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6090         if (s) RETURN_STATUS(s);
6091
6092         r1 = bc_vec_item_rev(&G.prog.results, 2);
6093         s = zbc_program_num(r1, &n1, false);
6094         if (s) RETURN_STATUS(s);
6095         if (!BC_PROG_NUM(r1, n1))
6096                 RETURN_STATUS(bc_error_variable_is_wrong_type());
6097
6098         // Make sure that the values have their pointers updated, if necessary.
6099         if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6100                 if (r1->t == r2->t) {
6101                         s = zbc_program_num(r2, &n2, false);
6102                         if (s) RETURN_STATUS(s);
6103                 }
6104                 if (r1->t == r3->t) {
6105                         s = zbc_program_num(r3, &n3, false);
6106                         if (s) RETURN_STATUS(s);
6107                 }
6108         }
6109
6110         bc_num_init(&res.d.n, n3->len);
6111         s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6112         if (s) goto err;
6113
6114         bc_vec_pop(&G.prog.results);
6115         bc_program_binOpRetire(&res);
6116
6117         RETURN_STATUS(s);
6118  err:
6119         bc_num_free(&res.d.n);
6120         RETURN_STATUS(s);
6121 }
6122 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6123
6124 static void dc_program_stackLen(void)
6125 {
6126         BcResult res;
6127         size_t len = G.prog.results.len;
6128
6129         res.t = BC_RESULT_TEMP;
6130
6131         bc_num_init_DEF_SIZE(&res.d.n);
6132         bc_num_ulong2num(&res.d.n, len);
6133         bc_vec_push(&G.prog.results, &res);
6134 }
6135
6136 static BC_STATUS zdc_program_asciify(void)
6137 {
6138         BcStatus s;
6139         BcResult *r, res;
6140         BcNum *num, n;
6141         char **strs;
6142         char *str;
6143         char c;
6144         size_t idx;
6145         unsigned long val;
6146
6147         if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6148                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6149         r = bc_vec_top(&G.prog.results);
6150
6151         s = zbc_program_num(r, &num, false);
6152         if (s) RETURN_STATUS(s);
6153
6154         if (BC_PROG_NUM(r, num)) {
6155                 BcNum strmb;
6156                 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6157
6158                 bc_num_init_DEF_SIZE(&n);
6159                 bc_num_copy(&n, num);
6160                 bc_num_truncate(&n, n.rdx);
6161
6162                 strmb.cap = ARRAY_SIZE(strmb_digs);
6163                 strmb.num = strmb_digs;
6164                 bc_num_ulong2num(&strmb, 0x100);
6165                 s = zbc_num_mod(&n, &strmb, &n, 0);
6166
6167                 if (s) goto num_err;
6168                 s = zbc_num_ulong(&n, &val);
6169                 if (s) goto num_err;
6170
6171                 c = (char) val;
6172
6173                 bc_num_free(&n);
6174         } else {
6175                 char *sp;
6176                 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
6177                 sp = *bc_program_str(idx);
6178                 c = sp[0];
6179         }
6180
6181         strs = (void*)G.prog.strs.v;
6182         for (idx = 0; idx < G.prog.strs.len; idx++) {
6183                 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6184                         goto dup;
6185                 }
6186         }
6187         str = xzalloc(2);
6188         str[0] = c;
6189         //str[1] = '\0'; - already is
6190         bc_vec_push(&G.prog.strs, &str);
6191  dup:
6192         res.t = BC_RESULT_STR;
6193         res.d.id.idx = idx;
6194         bc_result_pop_and_push(&res);
6195
6196         RETURN_STATUS(BC_STATUS_SUCCESS);
6197  num_err:
6198         bc_num_free(&n);
6199         RETURN_STATUS(s);
6200 }
6201 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6202
6203 static BC_STATUS zdc_program_printStream(void)
6204 {
6205         BcStatus s;
6206         BcResult *r;
6207         BcNum *n;
6208         size_t idx;
6209
6210         if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6211                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6212         r = bc_vec_top(&G.prog.results);
6213
6214         s = zbc_program_num(r, &n, false);
6215         if (s) RETURN_STATUS(s);
6216
6217         if (BC_PROG_NUM(r, n)) {
6218                 s = zbc_num_printNum(n, 0x100, 1, dc_num_printChar);
6219         } else {
6220                 char *str;
6221                 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
6222                 str = *bc_program_str(idx);
6223                 fputs(str, stdout);
6224         }
6225
6226         RETURN_STATUS(s);
6227 }
6228 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6229
6230 static BC_STATUS zdc_program_nquit(void)
6231 {
6232         BcStatus s;
6233         BcResult *opnd;
6234         BcNum *num = NULL;
6235         unsigned long val;
6236
6237         s = zbc_program_prep(&opnd, &num);
6238         if (s) RETURN_STATUS(s);
6239         s = zbc_num_ulong(num, &val);
6240         if (s) RETURN_STATUS(s);
6241
6242         bc_vec_pop(&G.prog.results);
6243
6244         if (G.prog.exestack.len < val)
6245                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6246         if (G.prog.exestack.len == val) {
6247                 QUIT_OR_RETURN_TO_MAIN;
6248         }
6249
6250         bc_vec_npop(&G.prog.exestack, val);
6251
6252         RETURN_STATUS(s);
6253 }
6254 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6255
6256 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6257 {
6258         BcStatus s = BC_STATUS_SUCCESS;
6259         BcResult *r;
6260         BcFunc *f;
6261         BcInstPtr ip;
6262         size_t fidx, sidx;
6263
6264         if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6265                 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6266
6267         r = bc_vec_top(&G.prog.results);
6268
6269         if (cond) {
6270                 BcNum *n = n; // for compiler
6271                 bool exec;
6272                 char *name;
6273                 char *then_name = bc_program_name(code, bgn);
6274                 char *else_name = NULL;
6275
6276                 if (code[*bgn] == BC_PARSE_STREND)
6277                         (*bgn) += 1;
6278                 else
6279                         else_name = bc_program_name(code, bgn);
6280
6281                 exec = r->d.n.len != 0;
6282                 name = then_name;
6283                 if (!exec && else_name != NULL) {
6284                         exec = true;
6285                         name = else_name;
6286                 }
6287
6288                 if (exec) {
6289                         BcVec *v;
6290                         v = bc_program_search(name, true);
6291                         n = bc_vec_top(v);
6292                 }
6293
6294                 free(then_name);
6295                 free(else_name);
6296
6297                 if (!exec) goto exit;
6298                 if (!BC_PROG_STR(n)) {
6299                         s = bc_error_variable_is_wrong_type();
6300                         goto exit;
6301                 }
6302
6303                 sidx = n->rdx;
6304         } else {
6305                 if (r->t == BC_RESULT_STR) {
6306                         sidx = r->d.id.idx;
6307                 } else if (r->t == BC_RESULT_VAR) {
6308                         BcNum *n;
6309                         s = zbc_program_num(r, &n, false);
6310                         if (s || !BC_PROG_STR(n)) goto exit;
6311                         sidx = n->rdx;
6312                 } else
6313                         goto exit;
6314         }
6315
6316         fidx = sidx + BC_PROG_REQ_FUNCS;
6317
6318         f = bc_program_func(fidx);
6319
6320         if (f->code.len == 0) {
6321                 FILE *sv_input_fp;
6322                 BcParse prs;
6323                 char *str;
6324
6325                 bc_parse_create(&prs, fidx);
6326                 str = *bc_program_str(sidx);
6327                 s = zbc_parse_text_init(&prs, str);
6328                 if (s) goto err;
6329
6330                 sv_input_fp = G.input_fp;
6331                 G.input_fp = NULL; // "do not read from input file when <EOL> reached"
6332                 s = zdc_parse_exprs_until_eof(&prs);
6333                 G.input_fp = sv_input_fp;
6334
6335                 if (s) goto err;
6336                 if (prs.l.t.t != BC_LEX_EOF) {
6337                         s = bc_error_bad_expression();
6338  err:
6339                         bc_parse_free(&prs);
6340                         bc_vec_pop_all(&f->code);
6341                         goto exit;
6342                 }
6343                 bc_parse_push(&prs, BC_INST_POP_EXEC);
6344                 bc_parse_free(&prs);
6345         }
6346
6347         ip.inst_idx = 0;
6348         ip.func = fidx;
6349
6350         bc_vec_pop(&G.prog.results);
6351         bc_vec_push(&G.prog.exestack, &ip);
6352
6353         RETURN_STATUS(BC_STATUS_SUCCESS);
6354  exit:
6355         bc_vec_pop(&G.prog.results);
6356         RETURN_STATUS(s);
6357 }
6358 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6359 #endif // ENABLE_DC
6360
6361 static void bc_program_pushGlobal(char inst)
6362 {
6363         BcResult res;
6364         unsigned long val;
6365
6366         res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6367         if (inst == BC_INST_IBASE)
6368                 val = (unsigned long) G.prog.ib_t;
6369         else if (inst == BC_INST_SCALE)
6370                 val = (unsigned long) G.prog.scale;
6371         else
6372                 val = (unsigned long) G.prog.ob_t;
6373
6374         bc_num_init_DEF_SIZE(&res.d.n);
6375         bc_num_ulong2num(&res.d.n, val);
6376         bc_vec_push(&G.prog.results, &res);
6377 }
6378
6379 static BC_STATUS zbc_program_exec(void)
6380 {
6381         BcResult r, *ptr;
6382         BcNum *num;
6383         BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6384         BcFunc *func = bc_program_func(ip->func);
6385         char *code = func->code.v;
6386
6387         dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6388                         ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6389         while (ip->inst_idx < func->code.len) {
6390                 BcStatus s = BC_STATUS_SUCCESS;
6391                 char inst = code[ip->inst_idx++];
6392
6393                 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6394                 switch (inst) {
6395 #if ENABLE_BC
6396                         case BC_INST_JUMP_ZERO: {
6397                                 bool zero;
6398                                 dbg_exec("BC_INST_JUMP_ZERO:");
6399                                 s = zbc_program_prep(&ptr, &num);
6400                                 if (s) RETURN_STATUS(s);
6401                                 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6402                                 bc_vec_pop(&G.prog.results);
6403                                 if (!zero) {
6404                                         bc_program_index(code, &ip->inst_idx);
6405                                         break;
6406                                 }
6407                                 // else: fall through
6408                         }
6409                         case BC_INST_JUMP: {
6410                                 size_t idx = bc_program_index(code, &ip->inst_idx);
6411                                 size_t *addr = bc_vec_item(&func->labels, idx);
6412                                 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6413                                 ip->inst_idx = *addr;
6414                                 break;
6415                         }
6416                         case BC_INST_CALL:
6417                                 dbg_exec("BC_INST_CALL:");
6418                                 s = zbc_program_call(code, &ip->inst_idx);
6419                                 goto read_updated_ip;
6420                         case BC_INST_INC_PRE:
6421                         case BC_INST_DEC_PRE:
6422                         case BC_INST_INC_POST:
6423                         case BC_INST_DEC_POST:
6424                                 dbg_exec("BC_INST_INCDEC:");
6425                                 s = zbc_program_incdec(inst);
6426                                 break;
6427                         case BC_INST_HALT:
6428                                 dbg_exec("BC_INST_HALT:");
6429                                 QUIT_OR_RETURN_TO_MAIN;
6430                                 break;
6431                         case BC_INST_RET:
6432                         case BC_INST_RET0:
6433                                 dbg_exec("BC_INST_RET[0]:");
6434                                 s = zbc_program_return(inst);
6435                                 goto read_updated_ip;
6436                         case BC_INST_BOOL_OR:
6437                         case BC_INST_BOOL_AND:
6438 #endif // ENABLE_BC
6439                         case BC_INST_REL_EQ:
6440                         case BC_INST_REL_LE:
6441                         case BC_INST_REL_GE:
6442                         case BC_INST_REL_NE:
6443                         case BC_INST_REL_LT:
6444                         case BC_INST_REL_GT:
6445                                 dbg_exec("BC_INST_BOOL:");
6446                                 s = zbc_program_logical(inst);
6447                                 break;
6448                         case BC_INST_READ:
6449                                 dbg_exec("BC_INST_READ:");
6450                                 s = zbc_program_read();
6451                                 goto read_updated_ip;
6452                         case BC_INST_VAR:
6453                                 dbg_exec("BC_INST_VAR:");
6454                                 s = zbc_program_pushVar(code, &ip->inst_idx, false, false);
6455                                 break;
6456                         case BC_INST_ARRAY_ELEM:
6457                         case BC_INST_ARRAY:
6458                                 dbg_exec("BC_INST_ARRAY[_ELEM]:");
6459                                 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6460                                 break;
6461                         case BC_INST_LAST:
6462 //TODO: this can't happen on dc, right?
6463                                 dbg_exec("BC_INST_LAST:");
6464                                 r.t = BC_RESULT_LAST;
6465                                 bc_vec_push(&G.prog.results, &r);
6466                                 break;
6467                         case BC_INST_IBASE:
6468                         case BC_INST_SCALE:
6469                         case BC_INST_OBASE:
6470                                 dbg_exec("BC_INST_internalvar:");
6471                                 bc_program_pushGlobal(inst);
6472                                 break;
6473                         case BC_INST_SCALE_FUNC:
6474                         case BC_INST_LENGTH:
6475                         case BC_INST_SQRT:
6476                                 dbg_exec("BC_INST_builtin:");
6477                                 s = zbc_program_builtin(inst);
6478                                 break;
6479                         case BC_INST_NUM:
6480                                 dbg_exec("BC_INST_NUM:");
6481                                 r.t = BC_RESULT_CONSTANT;
6482                                 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6483                                 bc_vec_push(&G.prog.results, &r);
6484                                 break;
6485                         case BC_INST_POP:
6486                                 dbg_exec("BC_INST_POP:");
6487                                 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6488                                         s = bc_error_stack_has_too_few_elements();
6489                                 else
6490                                         bc_vec_pop(&G.prog.results);
6491                                 break;
6492                         case BC_INST_PRINT:
6493                         case BC_INST_PRINT_POP:
6494                         case BC_INST_PRINT_STR:
6495                                 dbg_exec("BC_INST_PRINTxyz:");
6496                                 s = zbc_program_print(inst, 0);
6497                                 break;
6498                         case BC_INST_STR:
6499                                 dbg_exec("BC_INST_STR:");
6500                                 r.t = BC_RESULT_STR;
6501                                 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6502                                 bc_vec_push(&G.prog.results, &r);
6503                                 break;
6504                         case BC_INST_POWER:
6505                         case BC_INST_MULTIPLY:
6506                         case BC_INST_DIVIDE:
6507                         case BC_INST_MODULUS:
6508                         case BC_INST_PLUS:
6509                         case BC_INST_MINUS:
6510                                 dbg_exec("BC_INST_binaryop:");
6511                                 s = zbc_program_op(inst);
6512                                 break;
6513                         case BC_INST_BOOL_NOT:
6514                                 dbg_exec("BC_INST_BOOL_NOT:");
6515                                 s = zbc_program_prep(&ptr, &num);
6516                                 if (s) RETURN_STATUS(s);
6517                                 bc_num_init_DEF_SIZE(&r.d.n);
6518                                 if (!bc_num_cmp(num, &G.prog.zero))
6519                                         bc_num_one(&r.d.n);
6520                                 //else bc_num_zero(&r.d.n); - already is
6521                                 bc_program_retire(&r, BC_RESULT_TEMP);
6522                                 break;
6523                         case BC_INST_NEG:
6524                                 dbg_exec("BC_INST_NEG:");
6525                                 s = zbc_program_negate();
6526                                 break;
6527 #if ENABLE_BC
6528                         case BC_INST_ASSIGN_POWER:
6529                         case BC_INST_ASSIGN_MULTIPLY:
6530                         case BC_INST_ASSIGN_DIVIDE:
6531                         case BC_INST_ASSIGN_MODULUS:
6532                         case BC_INST_ASSIGN_PLUS:
6533                         case BC_INST_ASSIGN_MINUS:
6534 #endif
6535                         case BC_INST_ASSIGN:
6536                                 dbg_exec("BC_INST_ASSIGNxyz:");
6537                                 s = zbc_program_assign(inst);
6538                                 break;
6539 #if ENABLE_DC
6540                         case BC_INST_POP_EXEC:
6541                                 dbg_exec("BC_INST_POP_EXEC:");
6542                                 bc_vec_pop(&G.prog.exestack);
6543                                 goto read_updated_ip;
6544                         case BC_INST_MODEXP:
6545                                 dbg_exec("BC_INST_MODEXP:");
6546                                 s = zdc_program_modexp();
6547                                 break;
6548                         case BC_INST_DIVMOD:
6549                                 dbg_exec("BC_INST_DIVMOD:");
6550                                 s = zdc_program_divmod();
6551                                 break;
6552                         case BC_INST_EXECUTE:
6553                         case BC_INST_EXEC_COND:
6554                                 dbg_exec("BC_INST_EXEC[_COND]:");
6555                                 s = zdc_program_execStr(code, &ip->inst_idx, inst == BC_INST_EXEC_COND);
6556                                 goto read_updated_ip;
6557                         case BC_INST_PRINT_STACK: {
6558                                 size_t idx;
6559                                 dbg_exec("BC_INST_PRINT_STACK:");
6560                                 for (idx = 0; idx < G.prog.results.len; ++idx) {
6561                                         s = zbc_program_print(BC_INST_PRINT, idx);
6562                                         if (s) break;
6563                                 }
6564                                 break;
6565                         }
6566                         case BC_INST_CLEAR_STACK:
6567                                 dbg_exec("BC_INST_CLEAR_STACK:");
6568                                 bc_vec_pop_all(&G.prog.results);
6569                                 break;
6570                         case BC_INST_STACK_LEN:
6571                                 dbg_exec("BC_INST_STACK_LEN:");
6572                                 dc_program_stackLen();
6573                                 break;
6574                         case BC_INST_DUPLICATE:
6575                                 dbg_exec("BC_INST_DUPLICATE:");
6576                                 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6577                                         RETURN_STATUS(bc_error_stack_has_too_few_elements());
6578                                 ptr = bc_vec_top(&G.prog.results);
6579                                 dc_result_copy(&r, ptr);
6580                                 bc_vec_push(&G.prog.results, &r);
6581                                 break;
6582                         case BC_INST_SWAP: {
6583                                 BcResult *ptr2;
6584                                 dbg_exec("BC_INST_SWAP:");
6585                                 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6586                                         RETURN_STATUS(bc_error_stack_has_too_few_elements());
6587                                 ptr = bc_vec_item_rev(&G.prog.results, 0);
6588                                 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6589                                 memcpy(&r, ptr, sizeof(BcResult));
6590                                 memcpy(ptr, ptr2, sizeof(BcResult));
6591                                 memcpy(ptr2, &r, sizeof(BcResult));
6592                                 break;
6593                         }
6594                         case BC_INST_ASCIIFY:
6595                                 dbg_exec("BC_INST_ASCIIFY:");
6596                                 s = zdc_program_asciify();
6597                                 break;
6598                         case BC_INST_PRINT_STREAM:
6599                                 dbg_exec("BC_INST_STREAM:");
6600                                 s = zdc_program_printStream();
6601                                 break;
6602                         case BC_INST_LOAD:
6603                         case BC_INST_PUSH_VAR: {
6604                                 bool copy = inst == BC_INST_LOAD;
6605                                 s = zbc_program_pushVar(code, &ip->inst_idx, true, copy);
6606                                 break;
6607                         }
6608                         case BC_INST_PUSH_TO_VAR: {
6609                                 char *name = bc_program_name(code, &ip->inst_idx);
6610                                 s = zbc_program_copyToVar(name, true);
6611                                 free(name);
6612                                 break;
6613                         }
6614                         case BC_INST_QUIT:
6615                                 dbg_exec("BC_INST_QUIT:");
6616                                 if (G.prog.exestack.len <= 2)
6617                                         QUIT_OR_RETURN_TO_MAIN;
6618                                 bc_vec_npop(&G.prog.exestack, 2);
6619                                 goto read_updated_ip;
6620                         case BC_INST_NQUIT:
6621                                 dbg_exec("BC_INST_NQUIT:");
6622                                 s = zdc_program_nquit();
6623                                 //goto read_updated_ip; - just fall through to it
6624 #endif // ENABLE_DC
6625  read_updated_ip:
6626                                 // Instruction stack has changed, read new pointers
6627                                 ip = bc_vec_top(&G.prog.exestack);
6628                                 func = bc_program_func(ip->func);
6629                                 code = func->code.v;
6630                                 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6631                 }
6632
6633                 if (s || G_interrupt) {
6634                         bc_program_reset();
6635                         RETURN_STATUS(s);
6636                 }
6637
6638                 fflush_and_check();
6639         }
6640
6641         RETURN_STATUS(BC_STATUS_SUCCESS);
6642 }
6643 #define zbc_program_exec(...) (zbc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6644
6645 static unsigned bc_vm_envLen(const char *var)
6646 {
6647         char *lenv;
6648         unsigned len;
6649
6650         lenv = getenv(var);
6651         len = BC_NUM_PRINT_WIDTH;
6652         if (!lenv) return len;
6653
6654         len = bb_strtou(lenv, NULL, 10) - 1;
6655         if (errno || len < 2 || len >= INT_MAX)
6656                 len = BC_NUM_PRINT_WIDTH;
6657
6658         return len;
6659 }
6660
6661 static BC_STATUS zbc_vm_process(const char *text)
6662 {
6663         BcStatus s;
6664
6665         dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6666         s = zbc_parse_text_init(&G.prs, text); // does the first zbc_lex_next()
6667         if (s) RETURN_STATUS(s);
6668
6669         while (G.prs.l.t.t != BC_LEX_EOF) {
6670                 dbg_lex("%s:%d G.prs.l.t.t:%d, parsing...", __func__, __LINE__, G.prs.l.t.t);
6671                 if (IS_BC) {
6672 // FIXME: "eating" of stmt delimiters is coded inconsistently
6673 // (sometimes zbc_parse_stmt() eats the delimiter, sometimes don't),
6674 // which causes bugs such as "print 1 print 2" erroneously accepted,
6675 // or "print 1 else 2" detecting parse error only after executing
6676 // "print 1" part.
6677                         IF_BC(s = zbc_parse_stmt_or_funcdef(&G.prs));
6678                 } else {
6679                         IF_DC(s = zdc_parse_expr(&G.prs));
6680                 }
6681                 if (s || G_interrupt) {
6682                         bc_parse_reset(&G.prs); // includes bc_program_reset()
6683                         RETURN_STATUS(BC_STATUS_FAILURE);
6684                 }
6685
6686                 dbg_lex("%s:%d executing...", __func__, __LINE__);
6687                 s = zbc_program_exec();
6688                 if (s) {
6689                         bc_program_reset();
6690                         break;
6691                 }
6692                 // bc discards strings, constants and code after each
6693                 // top-level statement in the "main program".
6694                 // This prevents "yes 1 | bc" from growing its memory
6695                 // without bound. This can be done because data stack
6696                 // is empty and thus can't hold any references to
6697                 // strings or constants, there is no generated code
6698                 // which can hold references (after we discard one
6699                 // we just executed). Code of functions can have references,
6700                 // but bc stores function strings/constants in per-function
6701                 // storage.
6702                 if (IS_BC) {
6703                         BcFunc *f;
6704                         BcInstPtr *ip = (void*)G.prog.exestack.v;
6705
6706 #if SANITY_CHECKS
6707                         if (G.prog.results.len != 0) // should be empty
6708                                 bb_error_msg_and_die("BUG:data stack");
6709                         if (G.prog.exestack.len != 1) // should have only main's IP
6710                                 bb_error_msg_and_die("BUG:call stack");
6711                         if (ip->func != BC_PROG_MAIN)
6712                                 bb_error_msg_and_die("BUG:not MAIN");
6713 #endif
6714 //bb_error_msg("ip->func:%d >idx:%d >len:%d", ip->func, ip->inst_idx, ip->len);
6715                         f = bc_program_func_BC_PROG_MAIN();
6716 //bb_error_msg("MAIN->code.len:%d >strs.len:%d >consts.len:%d", f->code.len, f->strs.len, f->consts.len); // labels, autos, nparams
6717                         bc_vec_pop_all(&f->code);
6718                         ip->inst_idx = 0;
6719                         IF_BC(bc_vec_pop_all(&f->strs);)
6720                         IF_BC(bc_vec_pop_all(&f->consts);)
6721                 } else {
6722                         // Most of dc parsing assumes all whitespace,
6723                         // including '\n', is eaten.
6724                         if (G.prs.l.t.t == BC_LEX_NLINE) {
6725                                 s = zbc_lex_next(&G.prs.l);
6726                                 if (s) RETURN_STATUS(s);
6727                         }
6728                 }
6729         }
6730
6731         dbg_lex_done("%s:%d done", __func__, __LINE__);
6732         RETURN_STATUS(s);
6733 }
6734 #define zbc_vm_process(...) (zbc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6735
6736 static BC_STATUS zbc_vm_execute_FILE(FILE *fp, const char *filename)
6737 {
6738         // So far bc/dc have no way to include a file from another file,
6739         // therefore we know G.prog.file == NULL on entry
6740         //const char *sv_file;
6741         BcStatus s;
6742
6743         G.prog.file = filename;
6744         G.input_fp = fp;
6745         bc_lex_file(&G.prs.l);
6746
6747         do {
6748                 s = zbc_vm_process("");
6749                 // We do not stop looping on errors here if reading stdin.
6750                 // Example: start interactive bc and enter "return".
6751                 // It should say "'return' not in a function"
6752                 // but should not exit.
6753         } while (G.input_fp == stdin);
6754         G.prog.file = NULL;
6755         RETURN_STATUS(s);
6756 }
6757 #define zbc_vm_execute_FILE(...) (zbc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6758
6759 static BC_STATUS zbc_vm_file(const char *file)
6760 {
6761         BcStatus s;
6762         FILE *fp;
6763
6764         fp = xfopen_for_read(file);
6765         s = zbc_vm_execute_FILE(fp, file);
6766         fclose(fp);
6767
6768         RETURN_STATUS(s);
6769 }
6770 #define zbc_vm_file(...) (zbc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6771
6772 #if ENABLE_BC
6773 static void bc_vm_info(void)
6774 {
6775         printf("%s "BB_VER"\n"
6776                 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6777         , applet_name);
6778 }
6779
6780 static void bc_args(char **argv)
6781 {
6782         unsigned opts;
6783         int i;
6784
6785         GETOPT_RESET();
6786 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6787         opts = option_mask32 |= getopt32long(argv, "wvsqli",
6788                 "warn\0"              No_argument "w"
6789                 "version\0"           No_argument "v"
6790                 "standard\0"          No_argument "s"
6791                 "quiet\0"             No_argument "q"
6792                 "mathlib\0"           No_argument "l"
6793                 "interactive\0"       No_argument "i"
6794         );
6795 #else
6796         opts = option_mask32 |= getopt32(argv, "wvsqli");
6797 #endif
6798         if (getenv("POSIXLY_CORRECT"))
6799                 option_mask32 |= BC_FLAG_S;
6800
6801         if (opts & BC_FLAG_V) {
6802                 bc_vm_info();
6803                 exit(0);
6804         }
6805
6806         for (i = optind; argv[i]; ++i)
6807                 bc_vec_push(&G.files, argv + i);
6808 }
6809
6810 static void bc_vm_envArgs(void)
6811 {
6812         BcVec v;
6813         char *buf;
6814         char *env_args = getenv("BC_ENV_ARGS");
6815
6816         if (!env_args) return;
6817
6818         G.env_args = xstrdup(env_args);
6819         buf = G.env_args;
6820
6821         bc_vec_init(&v, sizeof(char *), NULL);
6822
6823         while (*(buf = skip_whitespace(buf)) != '\0') {
6824                 bc_vec_push(&v, &buf);
6825                 buf = skip_non_whitespace(buf);
6826                 if (!*buf)
6827                         break;
6828                 *buf++ = '\0';
6829         }
6830
6831         // NULL terminate, and pass argv[] so that first arg is argv[1]
6832         if (sizeof(int) == sizeof(char*)) {
6833                 bc_vec_push(&v, &const_int_0);
6834         } else {
6835                 static char *const nullptr = NULL;
6836                 bc_vec_push(&v, &nullptr);
6837         }
6838         bc_args(((char **)v.v) - 1);
6839
6840         bc_vec_free(&v);
6841 }
6842
6843 static const char bc_lib[] ALIGN1 = {
6844         "scale=20"
6845 "\n"    "define e(x){"
6846 "\n"            "auto b,s,n,r,d,i,p,f,v"
6847 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6848 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6849 //e(-.998896): GNU:.36828580434569428695
6850 //      above code:.36828580434569428696
6851 //    actual value:.3682858043456942869594...
6852 // but for now let's be "GNU compatible"
6853 "\n"            "b=ibase"
6854 "\n"            "ibase=A"
6855 "\n"            "if(x<0){"
6856 "\n"                    "n=1"
6857 "\n"                    "x=-x"
6858 "\n"            "}"
6859 "\n"            "s=scale"
6860 "\n"            "r=6+s+.44*x"
6861 "\n"            "scale=scale(x)+1"
6862 "\n"            "while(x>1){"
6863 "\n"                    "d+=1"
6864 "\n"                    "x/=2"
6865 "\n"                    "scale+=1"
6866 "\n"            "}"
6867 "\n"            "scale=r"
6868 "\n"            "r=x+1"
6869 "\n"            "p=x"
6870 "\n"            "f=v=1"
6871 "\n"            "for(i=2;v;++i){"
6872 "\n"                    "p*=x"
6873 "\n"                    "f*=i"
6874 "\n"                    "v=p/f"
6875 "\n"                    "r+=v"
6876 "\n"            "}"
6877 "\n"            "while(d--)r*=r"
6878 "\n"            "scale=s"
6879 "\n"            "ibase=b"
6880 "\n"            "if(n)return(1/r)"
6881 "\n"            "return(r/1)"
6882 "\n"    "}"
6883 "\n"    "define l(x){"
6884 "\n"            "auto b,s,r,p,a,q,i,v"
6885 "\n"            "b=ibase"
6886 "\n"            "ibase=A"
6887 "\n"            "if(x<=0){"
6888 "\n"                    "r=(1-10^scale)/1"
6889 "\n"                    "ibase=b"
6890 "\n"                    "return(r)"
6891 "\n"            "}"
6892 "\n"            "s=scale"
6893 "\n"            "scale+=6"
6894 "\n"            "p=2"
6895 "\n"            "while(x>=2){"
6896 "\n"                    "p*=2"
6897 "\n"                    "x=sqrt(x)"
6898 "\n"            "}"
6899 "\n"            "while(x<=.5){"
6900 "\n"                    "p*=2"
6901 "\n"                    "x=sqrt(x)"
6902 "\n"            "}"
6903 "\n"            "r=a=(x-1)/(x+1)"
6904 "\n"            "q=a*a"
6905 "\n"            "v=1"
6906 "\n"            "for(i=3;v;i+=2){"
6907 "\n"                    "a*=q"
6908 "\n"                    "v=a/i"
6909 "\n"                    "r+=v"
6910 "\n"            "}"
6911 "\n"            "r*=p"
6912 "\n"            "scale=s"
6913 "\n"            "ibase=b"
6914 "\n"            "return(r/1)"
6915 "\n"    "}"
6916 "\n"    "define s(x){"
6917 "\n"            "auto b,s,r,a,q,i"
6918 "\n"            "if(x<0)return(-s(-x))"
6919 "\n"            "b=ibase"
6920 "\n"            "ibase=A"
6921 "\n"            "s=scale"
6922 "\n"            "scale=1.1*s+2"
6923 "\n"            "a=a(1)"
6924 "\n"            "scale=0"
6925 "\n"            "q=(x/a+2)/4"
6926 "\n"            "x-=4*q*a"
6927 "\n"            "if(q%2)x=-x"
6928 "\n"            "scale=s+2"
6929 "\n"            "r=a=x"
6930 "\n"            "q=-x*x"
6931 "\n"            "for(i=3;a;i+=2){"
6932 "\n"                    "a*=q/(i*(i-1))"
6933 "\n"                    "r+=a"
6934 "\n"            "}"
6935 "\n"            "scale=s"
6936 "\n"            "ibase=b"
6937 "\n"            "return(r/1)"
6938 "\n"    "}"
6939 "\n"    "define c(x){"
6940 "\n"            "auto b,s"
6941 "\n"            "b=ibase"
6942 "\n"            "ibase=A"
6943 "\n"            "s=scale"
6944 "\n"            "scale*=1.2"
6945 "\n"            "x=s(2*a(1)+x)"
6946 "\n"            "scale=s"
6947 "\n"            "ibase=b"
6948 "\n"            "return(x/1)"
6949 "\n"    "}"
6950 "\n"    "define a(x){"
6951 "\n"            "auto b,s,r,n,a,m,t,f,i,u"
6952 "\n"            "b=ibase"
6953 "\n"            "ibase=A"
6954 "\n"            "n=1"
6955 "\n"            "if(x<0){"
6956 "\n"                    "n=-1"
6957 "\n"                    "x=-x"
6958 "\n"            "}"
6959 "\n"            "if(scale<65){"
6960 "\n"                    "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
6961 "\n"                    "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
6962 "\n"            "}"
6963 "\n"            "s=scale"
6964 "\n"            "if(x>.2){"
6965 "\n"                    "scale+=5"
6966 "\n"                    "a=a(.2)"
6967 "\n"            "}"
6968 "\n"            "scale=s+3"
6969 "\n"            "while(x>.2){"
6970 "\n"                    "m+=1"
6971 "\n"                    "x=(x-.2)/(1+.2*x)"
6972 "\n"            "}"
6973 "\n"            "r=u=x"
6974 "\n"            "f=-x*x"
6975 "\n"            "t=1"
6976 "\n"            "for(i=3;t;i+=2){"
6977 "\n"                    "u*=f"
6978 "\n"                    "t=u/i"
6979 "\n"                    "r+=t"
6980 "\n"            "}"
6981 "\n"            "scale=s"
6982 "\n"            "ibase=b"
6983 "\n"            "return((m*a+r)/n)"
6984 "\n"    "}"
6985 "\n"    "define j(n,x){"
6986 "\n"            "auto b,s,o,a,i,v,f"
6987 "\n"            "b=ibase"
6988 "\n"            "ibase=A"
6989 "\n"            "s=scale"
6990 "\n"            "scale=0"
6991 "\n"            "n/=1"
6992 "\n"            "if(n<0){"
6993 "\n"                    "n=-n"
6994 "\n"                    "o=n%2"
6995 "\n"            "}"
6996 "\n"            "a=1"
6997 "\n"            "for(i=2;i<=n;++i)a*=i"
6998 "\n"            "scale=1.5*s"
6999 "\n"            "a=(x^n)/2^n/a"
7000 "\n"            "r=v=1"
7001 "\n"            "f=-x*x/4"
7002 "\n"            "scale+=length(a)-scale(a)"
7003 "\n"            "for(i=1;v;++i){"
7004 "\n"                    "v=v*f/i/(n+i)"
7005 "\n"                    "r+=v"
7006 "\n"            "}"
7007 "\n"            "scale=s"
7008 "\n"            "ibase=b"
7009 "\n"            "if(o)a=-a"
7010 "\n"            "return(a*r/1)"
7011 "\n"    "}"
7012 };
7013 #endif // ENABLE_BC
7014
7015 static BC_STATUS zbc_vm_exec(void)
7016 {
7017         char **fname;
7018         BcStatus s;
7019         size_t i;
7020
7021 #if ENABLE_BC
7022         if (option_mask32 & BC_FLAG_L) {
7023                 // We know that internal library is not buggy,
7024                 // thus error checking is normally disabled.
7025 # define DEBUG_LIB 0
7026                 bc_lex_file(&G.prs.l);
7027                 s = zbc_vm_process(bc_lib);
7028                 if (DEBUG_LIB && s) RETURN_STATUS(s);
7029         }
7030 #endif
7031
7032         s = BC_STATUS_SUCCESS;
7033         fname = (void*)G.files.v;
7034         for (i = 0; i < G.files.len; i++) {
7035                 s = zbc_vm_file(*fname++);
7036                 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7037                         // Debug config, non-interactive mode:
7038                         // return all the way back to main.
7039                         // Non-debug builds do not come here
7040                         // in non-interactive mode, they exit.
7041                         RETURN_STATUS(s);
7042                 }
7043         }
7044
7045         if (IS_BC || (option_mask32 & BC_FLAG_I))
7046                 s = zbc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7047
7048         RETURN_STATUS(s);
7049 }
7050 #define zbc_vm_exec(...) (zbc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7051
7052 #if ENABLE_FEATURE_CLEAN_UP
7053 static void bc_program_free(void)
7054 {
7055         bc_vec_free(&G.prog.fns);
7056         IF_BC(bc_vec_free(&G.prog.fn_map);)
7057         bc_vec_free(&G.prog.vars);
7058         bc_vec_free(&G.prog.var_map);
7059         bc_vec_free(&G.prog.arrs);
7060         bc_vec_free(&G.prog.arr_map);
7061         IF_DC(bc_vec_free(&G.prog.strs);)
7062         IF_DC(bc_vec_free(&G.prog.consts);)
7063         bc_vec_free(&G.prog.results);
7064         bc_vec_free(&G.prog.exestack);
7065         IF_BC(bc_num_free(&G.prog.last);)
7066         IF_BC(bc_num_free(&G.prog.zero);)
7067         IF_BC(bc_num_free(&G.prog.one);)
7068         bc_vec_free(&G.input_buffer);
7069 }
7070
7071 static void bc_vm_free(void)
7072 {
7073         bc_vec_free(&G.files);
7074         bc_program_free();
7075         bc_parse_free(&G.prs);
7076         free(G.env_args);
7077 }
7078 #endif
7079
7080 static void bc_program_init(void)
7081 {
7082         BcInstPtr ip;
7083
7084         // memset(&G.prog, 0, sizeof(G.prog)); - already is
7085         memset(&ip, 0, sizeof(BcInstPtr));
7086
7087         // G.prog.nchars = G.prog.scale = 0; - already is
7088         G.prog.ib_t = 10;
7089         G.prog.ob_t = 10;
7090
7091         IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7092         //IF_BC(bc_num_zero(&G.prog.last);) - already is
7093
7094         bc_num_init_DEF_SIZE(&G.prog.zero);
7095         //bc_num_zero(&G.prog.zero); - already is
7096
7097         IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7098         IF_BC(bc_num_one(&G.prog.one);)
7099
7100         bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7101         IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7102
7103         if (IS_BC) {
7104                 // Names are chosen simply to be distinct and never match
7105                 // a valid function name (and be short)
7106                 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7107                 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7108         } else {
7109                 // in dc, functions have no names
7110                 bc_program_add_fn();
7111                 bc_program_add_fn();
7112         }
7113
7114         bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7115         bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7116
7117         bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7118         bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7119
7120         IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7121         IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7122         bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7123         bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7124         bc_vec_push(&G.prog.exestack, &ip);
7125
7126         bc_char_vec_init(&G.input_buffer);
7127 }
7128
7129 static int bc_vm_init(const char *env_len)
7130 {
7131 #if ENABLE_FEATURE_EDITING
7132         G.line_input_state = new_line_input_t(DO_HISTORY);
7133 #endif
7134         G.prog.len = bc_vm_envLen(env_len);
7135
7136         bc_vec_init(&G.files, sizeof(char *), NULL);
7137         IF_BC(if (IS_BC) bc_vm_envArgs();)
7138         bc_program_init();
7139         bc_parse_create(&G.prs, BC_PROG_MAIN);
7140
7141 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7142 //-i option unconditionally enables this regardless of isatty():
7143         if (isatty(0)) {
7144 #if ENABLE_FEATURE_BC_SIGNALS
7145                 G_ttyin = 1;
7146                 // With SA_RESTART, most system calls will restart
7147                 // (IOW: they won't fail with EINTR).
7148                 // In particular, this means ^C won't cause
7149                 // stdout to get into "error state" if SIGINT hits
7150                 // within write() syscall.
7151                 //
7152                 // The downside is that ^C while tty input is taken
7153                 // will only be handled after [Enter] since read()
7154                 // from stdin is not interrupted by ^C either,
7155                 // it restarts, thus fgetc() does not return on ^C.
7156                 // (This problem manifests only if line editing is disabled)
7157                 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7158
7159                 // Without SA_RESTART, this exhibits a bug:
7160                 // "while (1) print 1" and try ^C-ing it.
7161                 // Intermittently, instead of returning to input line,
7162                 // you'll get "output error: Interrupted system call"
7163                 // and exit.
7164                 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7165 #endif
7166                 return 1; // "tty"
7167         }
7168         return 0; // "not a tty"
7169 }
7170
7171 static BcStatus bc_vm_run(void)
7172 {
7173         BcStatus st = zbc_vm_exec();
7174 #if ENABLE_FEATURE_CLEAN_UP
7175         if (G_exiting) // it was actually "halt" or "quit"
7176                 st = EXIT_SUCCESS;
7177         bc_vm_free();
7178 # if ENABLE_FEATURE_EDITING
7179         free_line_input_t(G.line_input_state);
7180 # endif
7181         FREE_G();
7182 #endif
7183         dbg_exec("exiting with exitcode %d", st);
7184         return st;
7185 }
7186
7187 #if ENABLE_BC
7188 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7189 int bc_main(int argc UNUSED_PARAM, char **argv)
7190 {
7191         int is_tty;
7192
7193         INIT_G();
7194
7195         is_tty = bc_vm_init("BC_LINE_LENGTH");
7196
7197         bc_args(argv);
7198
7199         if (is_tty && !(option_mask32 & BC_FLAG_Q))
7200                 bc_vm_info();
7201
7202         return bc_vm_run();
7203 }
7204 #endif
7205
7206 #if ENABLE_DC
7207 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7208 int dc_main(int argc UNUSED_PARAM, char **argv)
7209 {
7210         int noscript;
7211
7212         INIT_G();
7213
7214         // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7215         // 1 char wider than bc from the same package.
7216         // Both default width, and xC_LINE_LENGTH=N are wider:
7217         // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7218         //      |1234\   |
7219         //      |56      |
7220         // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7221         //      |123\    |
7222         //      |456     |
7223         // Do the same, or it's a bug?
7224         bc_vm_init("DC_LINE_LENGTH");
7225
7226         // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7227         noscript = BC_FLAG_I;
7228         for (;;) {
7229                 int n = getopt(argc, argv, "e:f:x");
7230                 if (n <= 0)
7231                         break;
7232                 switch (n) {
7233                 case 'e':
7234                         noscript = 0;
7235                         n = zbc_vm_process(optarg);
7236                         if (n) return n;
7237                         break;
7238                 case 'f':
7239                         noscript = 0;
7240                         n = zbc_vm_file(optarg);
7241                         if (n) return n;
7242                         break;
7243                 case 'x':
7244                         option_mask32 |= DC_FLAG_X;
7245                         break;
7246                 default:
7247                         bb_show_usage();
7248                 }
7249         }
7250         argv += optind;
7251
7252         while (*argv) {
7253                 noscript = 0;
7254                 bc_vec_push(&G.files, argv++);
7255         }
7256
7257         option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7258
7259         return bc_vm_run();
7260 }
7261 #endif
7262
7263 #endif // not DC_SMALL