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