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