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