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