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