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