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