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