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