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