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