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