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