blob: dc4fa37a4e8240a84e4571b520d54987e82a5083 [file] [log] [blame]
Gavin Howard01055ba2018-11-03 11:00:21 -06001/* vi: set sw=4 ts=4: */
2/*
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Copyright (c) 2018 Gavin D. Howard and contributors.
5 *
6 * ** Automatically generated from https://github.com/gavinhoward/bc **
7 * ** Do not edit unless you know what you are doing. **
8 */
9//config:config BC
10//config: bool "bc (45 kb; 49 kb when combined with dc)"
11//config: default y
12//config: help
13//config: bc is a command-line, arbitrary-precision calculator with a
14//config: Turing-complete language. See the GNU bc manual
15//config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
16//config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
17//config: for details.
18//config:
19//config: This bc has four differences to the GNU bc:
20//config:
21//config: 1) The period (.) can also be used as a shortcut for "last", as in
22//config: the BSD bc.
23//config: 2) Arrays are copied before being passed as arguments to
24//config: functions. This behavior is required by the bc spec.
25//config: 3) Arrays can be passed to the builtin "length" function to get
26//config: the number of elements currently in the array. The following
27//config: example prints "1":
28//config:
29//config: a[0] = 0
30//config: length(a[])
31//config:
32//config: 4) The precedence of the boolean "not" operator (!) is equal to
33//config: that of the unary minus (-), or negation, operator. This still
34//config: allows POSIX-compliant scripts to work while somewhat
35//config: preserving expected behavior (versus C) and making parsing
36//config: easier.
37//config:
38//config: Options:
39//config:
40//config: -i --interactive force interactive mode
41//config: -l --mathlib use predefined math routines:
42//config:
43//config: s(expr) = sine of expr in radians
44//config: c(expr) = cosine of expr in radians
45//config: a(expr) = arctangent of expr, returning
46//config: radians
47//config: l(expr) = natural log of expr
48//config: e(expr) = raises e to the power of expr
49//config: j(n, x) = Bessel function of integer order
50//config: n of x
51//config:
52//config: -q --quiet don't print version and copyright.
53//config: -s --standard error if any non-POSIX extensions are used.
54//config: -w --warn warn if any non-POSIX extensions are used.
55//config: -v --version print version and copyright and exit.
56//config:
57//config: Long options are only available if FEATURE_BC_LONG_OPTIONS is
58//config: enabled.
59//config:
60//config:config DC
61//config: bool "dc (38 kb; 49 kb when combined with bc)"
62//config: default y
63//config: help
64//config: dc is a reverse-polish notation command-line calculator which
65//config: supports unlimited precision arithmetic. See the FreeBSD man page
66//config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
67//config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
68//config: for details.
69//config:
70//config: This dc has a few differences from the two above:
71//config:
72//config: 1) When printing a byte stream (command "P"), this bc follows what
73//config: the FreeBSD dc does.
74//config: 2) This dc implements the GNU extensions for divmod ("~") and
75//config: modular exponentiation ("|").
76//config: 3) This dc implements all FreeBSD extensions, except for "J" and
77//config: "M".
78//config: 4) Like the FreeBSD dc, this dc supports extended registers.
79//config: However, they are implemented differently. When it encounters
80//config: whitespace where a register should be, it skips the whitespace.
81//config: If the character following is not a lowercase letter, an error
82//config: is issued. Otherwise, the register name is parsed by the
83//config: following regex:
84//config:
85//config: [a-z][a-z0-9_]*
86//config:
87//config: This generally means that register names will be surrounded by
88//config: whitespace.
89//config:
90//config: Examples:
91//config:
92//config: l idx s temp L index S temp2 < do_thing
93//config:
94//config: Also note that, like the FreeBSD dc, extended registers are not
95//config: allowed unless the "-x" option is given.
96//config:
97//config:config FEATURE_BC_SIGNALS
98//config: bool "Enable bc/dc signal handling"
99//config: default y
100//config: depends on BC || DC
101//config: help
102//config: Enable signal handling for bc and dc.
103//config:
104//config:config FEATURE_BC_LONG_OPTIONS
105//config: bool "Enable bc/dc long options"
106//config: default y
107//config: depends on BC || DC
108//config: help
109//config: Enable long options for bc and dc.
110
111//applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
112//applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
113
114//kbuild:lib-$(CONFIG_BC) += bc.o
115//kbuild:lib-$(CONFIG_DC) += bc.o
116
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100117//See www.gnu.org/software/bc/manual/bc.html
Gavin Howard01055ba2018-11-03 11:00:21 -0600118//usage:#define bc_trivial_usage
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100119//usage: "[-sqliw] FILE..."
Gavin Howard01055ba2018-11-03 11:00:21 -0600120//usage:
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100121//usage:#define bc_full_usage "\n"
122//usage: "\nArbitrary precision calculator"
123//usage: "\n"
124//usage: "\n -i Interactive"
125//usage: "\n -l Load standard math library"
126//usage: "\n -s Be POSIX compatible"
127//usage: "\n -q Quiet"
128//usage: "\n -w Warn if extensions are used"
129///////: "\n -v Version"
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100130//usage: "\n$BC_LINE_LENGTH changes output width"
Gavin Howard01055ba2018-11-03 11:00:21 -0600131//usage:
132//usage:#define bc_example_usage
133//usage: "3 + 4.129\n"
134//usage: "1903 - 2893\n"
135//usage: "-129 * 213.28935\n"
136//usage: "12 / -1932\n"
137//usage: "12 % 12\n"
138//usage: "34 ^ 189\n"
139//usage: "scale = 13\n"
140//usage: "ibase = 2\n"
141//usage: "obase = A\n"
142//usage:
143//usage:#define dc_trivial_usage
144//usage: "EXPRESSION..."
145//usage:
146//usage:#define dc_full_usage "\n\n"
147//usage: "Tiny RPN calculator. Operations:\n"
148//usage: "+, add, -, sub, *, mul, /, div, %, mod, ^, exp, ~, divmod, |, "
149//usage: "modular exponentiation,\n"
150//usage: "p - print top of the stack (without popping),\n"
151//usage: "f - print entire stack,\n"
152//usage: "k - pop the value and set the precision.\n"
153//usage: "i - pop the value and set input radix.\n"
154//usage: "o - pop the value and set output radix.\n"
155//usage: "Examples: 'dc 2 2 add p' -> 4, 'dc 8 8 mul 2 2 + / p' -> 16"
156//usage:
157//usage:#define dc_example_usage
158//usage: "$ dc 2 2 + p\n"
159//usage: "4\n"
160//usage: "$ dc 8 8 \\* 2 2 + / p\n"
161//usage: "16\n"
162//usage: "$ dc 0 1 and p\n"
163//usage: "0\n"
164//usage: "$ dc 0 1 or p\n"
165//usage: "1\n"
166//usage: "$ echo 72 9 div 8 mul p | dc\n"
167//usage: "64\n"
168
169#include "libbb.h"
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100170#include "common_bufsiz.h"
Gavin Howard01055ba2018-11-03 11:00:21 -0600171
172typedef enum BcStatus {
Denys Vlasenko60cf7472018-12-04 20:05:28 +0100173 BC_STATUS_SUCCESS = 0,
174 BC_STATUS_FAILURE = 1,
175 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
Gavin Howard01055ba2018-11-03 11:00:21 -0600176} BcStatus;
177
Gavin Howard01055ba2018-11-03 11:00:21 -0600178#define BC_VEC_INVALID_IDX ((size_t) -1)
179#define BC_VEC_START_CAP (1 << 5)
180
181typedef void (*BcVecFree)(void *);
Gavin Howard01055ba2018-11-03 11:00:21 -0600182
183typedef struct BcVec {
184 char *v;
185 size_t len;
186 size_t cap;
187 size_t size;
188 BcVecFree dtor;
189} BcVec;
190
191#define bc_vec_pop(v) (bc_vec_npop((v), 1))
192#define bc_vec_top(v) (bc_vec_item_rev((v), 0))
193
Gavin Howard01055ba2018-11-03 11:00:21 -0600194typedef signed char BcDig;
195
196typedef struct BcNum {
197 BcDig *restrict num;
198 size_t rdx;
199 size_t len;
200 size_t cap;
201 bool neg;
202} BcNum;
203
204#define BC_NUM_MIN_BASE ((unsigned long) 2)
205#define BC_NUM_MAX_IBASE ((unsigned long) 16)
206#define BC_NUM_DEF_SIZE (16)
207#define BC_NUM_PRINT_WIDTH (69)
208
209#define BC_NUM_KARATSUBA_LEN (32)
210
211#define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
212#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
213#define BC_NUM_INT(n) ((n)->len - (n)->rdx)
214#define BC_NUM_AREQ(a, b) \
215 (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
216#define BC_NUM_MREQ(a, b, scale) \
217 (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
218
219typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
220typedef void (*BcNumDigitOp)(size_t, size_t, bool, size_t *, size_t);
221
Gavin Howard01055ba2018-11-03 11:00:21 -0600222static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
223static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
224static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
225static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
226static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
227static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
228static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
229static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
230 size_t scale);
231
232typedef enum BcInst {
233
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100234#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600235 BC_INST_INC_PRE,
236 BC_INST_DEC_PRE,
237 BC_INST_INC_POST,
238 BC_INST_DEC_POST,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100239#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600240
241 BC_INST_NEG,
242
243 BC_INST_POWER,
244 BC_INST_MULTIPLY,
245 BC_INST_DIVIDE,
246 BC_INST_MODULUS,
247 BC_INST_PLUS,
248 BC_INST_MINUS,
249
250 BC_INST_REL_EQ,
251 BC_INST_REL_LE,
252 BC_INST_REL_GE,
253 BC_INST_REL_NE,
254 BC_INST_REL_LT,
255 BC_INST_REL_GT,
256
257 BC_INST_BOOL_NOT,
258 BC_INST_BOOL_OR,
259 BC_INST_BOOL_AND,
260
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100261#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600262 BC_INST_ASSIGN_POWER,
263 BC_INST_ASSIGN_MULTIPLY,
264 BC_INST_ASSIGN_DIVIDE,
265 BC_INST_ASSIGN_MODULUS,
266 BC_INST_ASSIGN_PLUS,
267 BC_INST_ASSIGN_MINUS,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100268#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600269 BC_INST_ASSIGN,
270
271 BC_INST_NUM,
272 BC_INST_VAR,
273 BC_INST_ARRAY_ELEM,
274 BC_INST_ARRAY,
275
276 BC_INST_SCALE_FUNC,
277 BC_INST_IBASE,
278 BC_INST_SCALE,
279 BC_INST_LAST,
280 BC_INST_LENGTH,
281 BC_INST_READ,
282 BC_INST_OBASE,
283 BC_INST_SQRT,
284
285 BC_INST_PRINT,
286 BC_INST_PRINT_POP,
287 BC_INST_STR,
288 BC_INST_PRINT_STR,
289
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100290#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600291 BC_INST_JUMP,
292 BC_INST_JUMP_ZERO,
293
294 BC_INST_CALL,
295
296 BC_INST_RET,
297 BC_INST_RET0,
298
299 BC_INST_HALT,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100300#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600301
302 BC_INST_POP,
303 BC_INST_POP_EXEC,
304
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100305#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600306 BC_INST_MODEXP,
307 BC_INST_DIVMOD,
308
309 BC_INST_EXECUTE,
310 BC_INST_EXEC_COND,
311
312 BC_INST_ASCIIFY,
313 BC_INST_PRINT_STREAM,
314
315 BC_INST_PRINT_STACK,
316 BC_INST_CLEAR_STACK,
317 BC_INST_STACK_LEN,
318 BC_INST_DUPLICATE,
319 BC_INST_SWAP,
320
321 BC_INST_LOAD,
322 BC_INST_PUSH_VAR,
323 BC_INST_PUSH_TO_VAR,
324
325 BC_INST_QUIT,
326 BC_INST_NQUIT,
327
328 BC_INST_INVALID = -1,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100329#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600330
331} BcInst;
332
333typedef struct BcId {
334 char *name;
335 size_t idx;
336} BcId;
337
338typedef struct BcFunc {
339 BcVec code;
340 BcVec labels;
341 size_t nparams;
342 BcVec autos;
343} BcFunc;
344
345typedef enum BcResultType {
346
347 BC_RESULT_TEMP,
348
349 BC_RESULT_VAR,
350 BC_RESULT_ARRAY_ELEM,
351 BC_RESULT_ARRAY,
352
353 BC_RESULT_STR,
354
355 BC_RESULT_IBASE,
356 BC_RESULT_SCALE,
357 BC_RESULT_LAST,
358
359 // These are between to calculate ibase, obase, and last from instructions.
360 BC_RESULT_CONSTANT,
361 BC_RESULT_ONE,
362
363 BC_RESULT_OBASE,
364
365} BcResultType;
366
367typedef union BcResultData {
368 BcNum n;
369 BcVec v;
370 BcId id;
371} BcResultData;
372
373typedef struct BcResult {
374 BcResultType t;
375 BcResultData d;
376} BcResult;
377
378typedef struct BcInstPtr {
379 size_t func;
380 size_t idx;
381 size_t len;
382} BcInstPtr;
383
Gavin Howard01055ba2018-11-03 11:00:21 -0600384// BC_LEX_NEG is not used in lexing; it is only for parsing.
385typedef enum BcLexType {
386
387 BC_LEX_EOF,
388 BC_LEX_INVALID,
389
390 BC_LEX_OP_INC,
391 BC_LEX_OP_DEC,
392
393 BC_LEX_NEG,
394
395 BC_LEX_OP_POWER,
396 BC_LEX_OP_MULTIPLY,
397 BC_LEX_OP_DIVIDE,
398 BC_LEX_OP_MODULUS,
399 BC_LEX_OP_PLUS,
400 BC_LEX_OP_MINUS,
401
402 BC_LEX_OP_REL_EQ,
403 BC_LEX_OP_REL_LE,
404 BC_LEX_OP_REL_GE,
405 BC_LEX_OP_REL_NE,
406 BC_LEX_OP_REL_LT,
407 BC_LEX_OP_REL_GT,
408
409 BC_LEX_OP_BOOL_NOT,
410 BC_LEX_OP_BOOL_OR,
411 BC_LEX_OP_BOOL_AND,
412
413 BC_LEX_OP_ASSIGN_POWER,
414 BC_LEX_OP_ASSIGN_MULTIPLY,
415 BC_LEX_OP_ASSIGN_DIVIDE,
416 BC_LEX_OP_ASSIGN_MODULUS,
417 BC_LEX_OP_ASSIGN_PLUS,
418 BC_LEX_OP_ASSIGN_MINUS,
419 BC_LEX_OP_ASSIGN,
420
421 BC_LEX_NLINE,
422 BC_LEX_WHITESPACE,
423
424 BC_LEX_LPAREN,
425 BC_LEX_RPAREN,
426
427 BC_LEX_LBRACKET,
428 BC_LEX_COMMA,
429 BC_LEX_RBRACKET,
430
431 BC_LEX_LBRACE,
432 BC_LEX_SCOLON,
433 BC_LEX_RBRACE,
434
435 BC_LEX_STR,
436 BC_LEX_NAME,
437 BC_LEX_NUMBER,
438
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100439 BC_LEX_KEY_1st_keyword,
440 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
Gavin Howard01055ba2018-11-03 11:00:21 -0600441 BC_LEX_KEY_BREAK,
442 BC_LEX_KEY_CONTINUE,
443 BC_LEX_KEY_DEFINE,
444 BC_LEX_KEY_ELSE,
445 BC_LEX_KEY_FOR,
446 BC_LEX_KEY_HALT,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100447 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
448 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600449 BC_LEX_KEY_IF,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100450 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
Gavin Howard01055ba2018-11-03 11:00:21 -0600451 BC_LEX_KEY_LENGTH,
452 BC_LEX_KEY_LIMITS,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100453 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600454 BC_LEX_KEY_PRINT,
455 BC_LEX_KEY_QUIT,
456 BC_LEX_KEY_READ,
457 BC_LEX_KEY_RETURN,
458 BC_LEX_KEY_SCALE,
459 BC_LEX_KEY_SQRT,
460 BC_LEX_KEY_WHILE,
461
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100462#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600463 BC_LEX_EQ_NO_REG,
464 BC_LEX_OP_MODEXP,
465 BC_LEX_OP_DIVMOD,
466
467 BC_LEX_COLON,
468 BC_LEX_ELSE,
469 BC_LEX_EXECUTE,
470 BC_LEX_PRINT_STACK,
471 BC_LEX_CLEAR_STACK,
472 BC_LEX_STACK_LEVEL,
473 BC_LEX_DUPLICATE,
474 BC_LEX_SWAP,
475 BC_LEX_POP,
476
477 BC_LEX_ASCIIFY,
478 BC_LEX_PRINT_STREAM,
479
480 BC_LEX_STORE_IBASE,
481 BC_LEX_STORE_SCALE,
482 BC_LEX_LOAD,
483 BC_LEX_LOAD_POP,
484 BC_LEX_STORE_PUSH,
485 BC_LEX_STORE_OBASE,
486 BC_LEX_PRINT_POP,
487 BC_LEX_NQUIT,
488 BC_LEX_SCALE_FACTOR,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100489#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600490} BcLexType;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100491// must match order of BC_LEX_KEY_foo etc above
492#if ENABLE_BC
493struct BcLexKeyword {
494 char name8[8];
495};
496#define BC_LEX_KW_ENTRY(a, b, c) \
497 { .name8 = a /*, .len = b, .posix = c*/ }
498static const struct BcLexKeyword bc_lex_kws[20] = {
499 BC_LEX_KW_ENTRY("auto" , 4, 1), // 0
500 BC_LEX_KW_ENTRY("break" , 5, 1), // 1
501 BC_LEX_KW_ENTRY("continue", 8, 0), // 2 note: this one has no terminating NUL
502 BC_LEX_KW_ENTRY("define" , 6, 1), // 3
503
504 BC_LEX_KW_ENTRY("else" , 4, 0), // 4
505 BC_LEX_KW_ENTRY("for" , 3, 1), // 5
506 BC_LEX_KW_ENTRY("halt" , 4, 0), // 6
507 BC_LEX_KW_ENTRY("ibase" , 5, 1), // 7
508
509 BC_LEX_KW_ENTRY("if" , 2, 1), // 8
510 BC_LEX_KW_ENTRY("last" , 4, 0), // 9
511 BC_LEX_KW_ENTRY("length" , 6, 1), // 10
512 BC_LEX_KW_ENTRY("limits" , 6, 0), // 11
513
514 BC_LEX_KW_ENTRY("obase" , 5, 1), // 12
515 BC_LEX_KW_ENTRY("print" , 5, 0), // 13
516 BC_LEX_KW_ENTRY("quit" , 4, 1), // 14
517 BC_LEX_KW_ENTRY("read" , 4, 0), // 15
518
519 BC_LEX_KW_ENTRY("return" , 6, 1), // 16
520 BC_LEX_KW_ENTRY("scale" , 5, 1), // 17
521 BC_LEX_KW_ENTRY("sqrt" , 4, 1), // 18
522 BC_LEX_KW_ENTRY("while" , 5, 1), // 19
523};
524enum {
525 POSIX_KWORD_MASK = 0
526 | (1 << 0)
527 | (1 << 1)
528 | (0 << 2)
529 | (1 << 3)
530 \
531 | (0 << 4)
532 | (1 << 5)
533 | (0 << 6)
534 | (1 << 7)
535 \
536 | (1 << 8)
537 | (0 << 9)
538 | (1 << 10)
539 | (0 << 11)
540 \
541 | (1 << 12)
542 | (0 << 13)
543 | (1 << 14)
544 | (0 << 15)
545 \
546 | (1 << 16)
547 | (1 << 17)
548 | (1 << 18)
549 | (1 << 19)
550};
551#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600552
553struct BcLex;
554typedef BcStatus (*BcLexNext)(struct BcLex *);
555
556typedef struct BcLex {
557
558 const char *buf;
559 size_t i;
560 size_t line;
Gavin Howard01055ba2018-11-03 11:00:21 -0600561 size_t len;
562 bool newline;
563
564 struct {
565 BcLexType t;
566 BcLexType last;
567 BcVec v;
568 } t;
569
570 BcLexNext next;
571
572} BcLex;
573
574#define BC_PARSE_STREND ((char) UCHAR_MAX)
575
576#define bc_parse_push(p, i) (bc_vec_pushByte(&(p)->func->code, (char) (i)))
577#define bc_parse_updateFunc(p, f) \
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +0100578 ((p)->func = bc_vec_item(&G.prog.fns, ((p)->fidx = (f))))
Gavin Howard01055ba2018-11-03 11:00:21 -0600579
580#define BC_PARSE_REL (1 << 0)
581#define BC_PARSE_PRINT (1 << 1)
582#define BC_PARSE_NOCALL (1 << 2)
583#define BC_PARSE_NOREAD (1 << 3)
584#define BC_PARSE_ARRAY (1 << 4)
585
586#define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
587#define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
588
589#define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
590#define BC_PARSE_FUNC_INNER(parse) \
591 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
592
593#define BC_PARSE_FLAG_FUNC (1 << 1)
594#define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
595
596#define BC_PARSE_FLAG_BODY (1 << 2)
597#define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
598
599#define BC_PARSE_FLAG_LOOP (1 << 3)
600#define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
601
602#define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
603#define BC_PARSE_LOOP_INNER(parse) \
604 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
605
606#define BC_PARSE_FLAG_IF (1 << 5)
607#define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
608
609#define BC_PARSE_FLAG_ELSE (1 << 6)
610#define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
611
612#define BC_PARSE_FLAG_IF_END (1 << 7)
613#define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
614
615#define BC_PARSE_CAN_EXEC(parse) \
616 (!(BC_PARSE_TOP_FLAG(parse) & \
617 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
618 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
619 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
620
Gavin Howard01055ba2018-11-03 11:00:21 -0600621typedef struct BcParseNext {
622 uint32_t len;
623 BcLexType tokens[4];
624} BcParseNext;
625
626#define BC_PARSE_NEXT_TOKENS(...) .tokens = { __VA_ARGS__ }
627#define BC_PARSE_NEXT(a, ...) \
628 { \
629 .len = (a), BC_PARSE_NEXT_TOKENS(__VA_ARGS__) \
630 }
631
632struct BcParse;
633
634struct BcProgram;
635
Gavin Howard01055ba2018-11-03 11:00:21 -0600636typedef BcStatus (*BcParseParse)(struct BcParse *);
Gavin Howard01055ba2018-11-03 11:00:21 -0600637
638typedef struct BcParse {
639
640 BcParseParse parse;
641
642 BcLex l;
643
644 BcVec flags;
645
646 BcVec exits;
647 BcVec conds;
648
649 BcVec ops;
650
Gavin Howard01055ba2018-11-03 11:00:21 -0600651 BcFunc *func;
652 size_t fidx;
653
654 size_t nbraces;
655 bool auto_part;
656
657} BcParse;
658
Gavin Howard01055ba2018-11-03 11:00:21 -0600659typedef struct BcProgram {
660
661 size_t len;
662 size_t scale;
663
664 BcNum ib;
665 size_t ib_t;
666 BcNum ob;
667 size_t ob_t;
668
669 BcNum hexb;
670
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100671#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600672 BcNum strmb;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100673#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600674
675 BcVec results;
676 BcVec stack;
677
678 BcVec fns;
679 BcVec fn_map;
680
681 BcVec vars;
682 BcVec var_map;
683
684 BcVec arrs;
685 BcVec arr_map;
686
687 BcVec strs;
688 BcVec consts;
689
690 const char *file;
691
692 BcNum last;
693 BcNum zero;
694 BcNum one;
695
696 size_t nchars;
697
Gavin Howard01055ba2018-11-03 11:00:21 -0600698} BcProgram;
699
700#define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
701
702#define BC_PROG_MAIN (0)
703#define BC_PROG_READ (1)
704
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100705#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600706#define BC_PROG_REQ_FUNCS (2)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100707#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600708
709#define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
710#define BC_PROG_NUM(r, n) \
711 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
712
713typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
714
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +0100715static void bc_program_addFunc(char *name, size_t *idx);
Denys Vlasenkod38af482018-12-04 19:11:02 +0100716static void bc_program_reset(void);
Gavin Howard01055ba2018-11-03 11:00:21 -0600717
718#define BC_FLAG_X (1 << 0)
719#define BC_FLAG_W (1 << 1)
720#define BC_FLAG_V (1 << 2)
721#define BC_FLAG_S (1 << 3)
722#define BC_FLAG_Q (1 << 4)
723#define BC_FLAG_L (1 << 5)
724#define BC_FLAG_I (1 << 6)
725
726#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
727#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
728
Denys Vlasenkod9d66552018-12-02 21:02:54 +0100729#define BC_MAX_OBASE ((unsigned) 999)
730#define BC_MAX_DIM ((unsigned) INT_MAX)
731#define BC_MAX_SCALE ((unsigned) UINT_MAX)
732#define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
733#define BC_MAX_NAME BC_MAX_STRING
734#define BC_MAX_NUM BC_MAX_STRING
735#define BC_MAX_EXP ((unsigned long) LONG_MAX)
736#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
Gavin Howard01055ba2018-11-03 11:00:21 -0600737
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100738struct globals {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100739 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100740 smallint eof;
Gavin Howard01055ba2018-11-03 11:00:21 -0600741 char sbgn;
742 char send;
Gavin Howard01055ba2018-11-03 11:00:21 -0600743
744 BcParse prs;
745 BcProgram prog;
746
Denys Vlasenko5318f812018-12-05 17:48:01 +0100747 // For error messages. Can be set to current parsed line,
748 // or [TODO] to current executing line (can be before last parsed one)
749 unsigned err_line;
750
Gavin Howard01055ba2018-11-03 11:00:21 -0600751 BcVec files;
752
753 char *env_args;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100754
755#if ENABLE_FEATURE_EDITING
756 line_input_t *line_input_state;
757#endif
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100758} FIX_ALIASING;
759#define G (*ptr_to_globals)
760#define INIT_G() do { \
761 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
762} while (0)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100763#define FREE_G() do { \
764 FREE_PTR_TO_GLOBALS(); \
765} while (0)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100766#define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
767#define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
768#define G_exreg (ENABLE_DC && (option_mask32 & BC_FLAG_X))
Denys Vlasenkoab3c5682018-12-02 16:32:36 +0100769#define G_interrupt (ENABLE_FEATURE_BC_SIGNALS ? bb_got_signal : 0)
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100770#if ENABLE_FEATURE_BC_SIGNALS
771# define G_ttyin G.ttyin
772#else
773# define G_ttyin 0
774#endif
Denys Vlasenko00d77792018-11-30 23:13:42 +0100775#define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
776
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100777#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600778
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100779// This is a bit array that corresponds to token types. An entry is
Gavin Howard01055ba2018-11-03 11:00:21 -0600780// true if the token is valid in an expression, false otherwise.
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100781enum {
782 BC_PARSE_EXPRS_BITS = 0
783 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
784 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
785 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
786 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
787 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
788 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
789 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
790 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
Gavin Howard01055ba2018-11-03 11:00:21 -0600791};
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100792static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
793{
794#if ULONG_MAX > 0xffffffff
795 // 64-bit version (will not work correctly for 32-bit longs!)
796 return BC_PARSE_EXPRS_BITS & (1UL << i);
797#else
798 // 32-bit version
799 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
800 if (i >= 32) {
801 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
802 i &= 31;
803 }
804 return m & (1UL << i);
805#endif
806}
Gavin Howard01055ba2018-11-03 11:00:21 -0600807
808// This is an array of data for operators that correspond to token types.
Denys Vlasenko65437582018-12-05 19:37:19 +0100809static const uint8_t bc_parse_ops[] = {
810#define OP(p,l) ((int)(l) * 0x10 + (p))
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100811 OP(0, false), OP( 0, false ), // inc dec
812 OP(1, false), // neg
Denys Vlasenko65437582018-12-05 19:37:19 +0100813 OP(2, false),
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100814 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
815 OP(4, true ), OP( 4, true ), // mod + -
816 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
817 OP(1, false), // not
818 OP(7, true ), OP( 7, true ), // or and
819 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
820 OP(5, false), OP( 5, false ), // -= =
Denys Vlasenko65437582018-12-05 19:37:19 +0100821#undef OP
Gavin Howard01055ba2018-11-03 11:00:21 -0600822};
Denys Vlasenko65437582018-12-05 19:37:19 +0100823#define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
824#define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
Gavin Howard01055ba2018-11-03 11:00:21 -0600825
826// These identify what tokens can come after expressions in certain cases.
827static const BcParseNext bc_parse_next_expr =
828 BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF);
829static const BcParseNext bc_parse_next_param =
830 BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA);
831static const BcParseNext bc_parse_next_print =
832 BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF);
833static const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN);
834static const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET);
835static const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON);
836static const BcParseNext bc_parse_next_read =
837 BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF);
838#endif // ENABLE_BC
839
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100840#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600841static const BcLexType dc_lex_regs[] = {
842 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
843 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
844 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
845 BC_LEX_STORE_PUSH,
846};
847
Gavin Howard01055ba2018-11-03 11:00:21 -0600848static const BcLexType dc_lex_tokens[] = {
849 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
850 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
851 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
852 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
853 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
854 BC_LEX_INVALID, BC_LEX_INVALID,
855 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
856 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
857 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
858 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
859 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
860 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
861 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
862 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
863 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
864 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
865 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
866 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
867 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
868 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
869 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
870 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
871 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
872 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
873 BC_LEX_INVALID
874};
875
876static const BcInst dc_parse_insts[] = {
877 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
878 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
879 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
880 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
881 BC_INST_INVALID, BC_INST_INVALID,
882 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
883 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
884 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
885 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
886 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
887 BC_INST_INVALID, BC_INST_INVALID,
888 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
889 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
890 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
891 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
892 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
893 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
894 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
895 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
896 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
897 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
898 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
899 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
900};
901#endif // ENABLE_DC
902
Gavin Howard01055ba2018-11-03 11:00:21 -0600903static const BcNumBinaryOp bc_program_ops[] = {
904 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
905};
906
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100907static void fflush_and_check(void)
908{
909 fflush_all();
910 if (ferror(stdout) || ferror(stderr))
911 bb_perror_msg_and_die("output error");
912}
913
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100914#if ENABLE_FEATURE_CLEAN_UP
915#define quit_or_return_for_exit() \
916do { \
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100917 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100918 return BC_STATUS_FAILURE; \
919} while (0)
920#else
921#define quit_or_return_for_exit() quit()
922#endif
923
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100924static void quit(void) NORETURN;
925static void quit(void)
926{
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100927 if (ferror(stdin))
928 bb_perror_msg_and_die("input error");
929 fflush_and_check();
930 exit(0);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100931}
932
Denys Vlasenko5318f812018-12-05 17:48:01 +0100933static void bc_verror_msg(const char *fmt, va_list p)
934{
935 const char *sv = sv; /* for compiler */
936 if (G.prog.file) {
937 sv = applet_name;
938 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
939 }
940 bb_verror_msg(fmt, p, NULL);
941 if (G.prog.file) {
942 free((char*)applet_name);
943 applet_name = sv;
944 }
945}
946
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100947static NOINLINE int bc_error_fmt(const char *fmt, ...)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100948{
949 va_list p;
950
951 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +0100952 bc_verror_msg(fmt, p);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100953 va_end(p);
Denys Vlasenko0409ad32018-12-05 16:39:22 +0100954
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100955 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100956 exit(1);
957 return BC_STATUS_FAILURE;
958}
959
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100960static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100961{
962 va_list p;
963
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100964 // Are non-POSIX constructs totally ok?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100965 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100966 return BC_STATUS_SUCCESS; // yes
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100967
968 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +0100969 bc_verror_msg(fmt, p);
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100970 va_end(p);
971
972 // Do we treat non-POSIX constructs as errors?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100973 if (!(option_mask32 & BC_FLAG_S))
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100974 return BC_STATUS_SUCCESS; // no, it's a warning
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100975 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100976 exit(1);
977 return BC_STATUS_FAILURE;
978}
979
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100980// We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
981// This idiom begs for tail-call optimization, but for it to work,
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100982// function must not have caller-cleaned parameters on stack.
983// Unfortunately, vararg function API does exactly that on most arches.
984// Thus, use these shims for the cases when we have no vararg PARAMS:
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100985static int bc_error(const char *msg)
986{
987 return bc_error_fmt("%s", msg);
988}
989static int bc_posix_error(const char *msg)
990{
991 return bc_posix_error_fmt("%s", msg);
992}
Denys Vlasenko00646792018-12-05 18:12:27 +0100993static int bc_POSIX_does_not_allow(const char *msg)
994{
995 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
996}
997static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
998{
999 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1000}
1001static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1002{
1003 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1004}
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001005static int bc_error_bad_character(char c)
1006{
1007 return bc_error_fmt("bad character '%c'", c);
1008}
1009static int bc_error_bad_expression(void)
1010{
1011 return bc_error("bad expression");
1012}
1013static int bc_error_bad_token(void)
1014{
1015 return bc_error("bad token");
1016}
1017static int bc_error_stack_has_too_few_elements(void)
1018{
1019 return bc_error("stack has too few elements");
1020}
1021static int bc_error_variable_is_wrong_type(void)
1022{
1023 return bc_error("variable is wrong type");
1024}
1025static int bc_error_nested_read_call(void)
1026{
1027 return bc_error("read() call inside of a read() call");
1028}
1029
Gavin Howard01055ba2018-11-03 11:00:21 -06001030static void bc_vec_grow(BcVec *v, size_t n)
1031{
1032 size_t cap = v->cap * 2;
1033 while (cap < v->len + n) cap *= 2;
1034 v->v = xrealloc(v->v, v->size * cap);
1035 v->cap = cap;
1036}
1037
1038static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1039{
1040 v->size = esize;
1041 v->cap = BC_VEC_START_CAP;
1042 v->len = 0;
1043 v->dtor = dtor;
1044 v->v = xmalloc(esize * BC_VEC_START_CAP);
1045}
1046
Denys Vlasenko7d628012018-12-04 21:46:47 +01001047static void bc_char_vec_init(BcVec *v)
1048{
1049 bc_vec_init(v, sizeof(char), NULL);
1050}
1051
Gavin Howard01055ba2018-11-03 11:00:21 -06001052static void bc_vec_expand(BcVec *v, size_t req)
1053{
1054 if (v->cap < req) {
1055 v->v = xrealloc(v->v, v->size * req);
1056 v->cap = req;
1057 }
1058}
1059
1060static void bc_vec_npop(BcVec *v, size_t n)
1061{
1062 if (!v->dtor)
1063 v->len -= n;
1064 else {
1065 size_t len = v->len - n;
1066 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1067 }
1068}
1069
Denys Vlasenko7d628012018-12-04 21:46:47 +01001070static void bc_vec_pop_all(BcVec *v)
1071{
1072 bc_vec_npop(v, v->len);
1073}
1074
Gavin Howard01055ba2018-11-03 11:00:21 -06001075static void bc_vec_push(BcVec *v, const void *data)
1076{
1077 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1078 memmove(v->v + (v->size * v->len), data, v->size);
1079 v->len += 1;
1080}
1081
1082static void bc_vec_pushByte(BcVec *v, char data)
1083{
1084 bc_vec_push(v, &data);
1085}
1086
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001087static void bc_vec_pushZeroByte(BcVec *v)
1088{
1089 //bc_vec_pushByte(v, '\0');
1090 // better:
1091 bc_vec_push(v, &const_int_0);
1092}
1093
Gavin Howard01055ba2018-11-03 11:00:21 -06001094static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1095{
1096 if (idx == v->len)
1097 bc_vec_push(v, data);
1098 else {
1099
1100 char *ptr;
1101
1102 if (v->len == v->cap) bc_vec_grow(v, 1);
1103
1104 ptr = v->v + v->size * idx;
1105
1106 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1107 memmove(ptr, data, v->size);
1108 }
1109}
1110
1111static void bc_vec_string(BcVec *v, size_t len, const char *str)
1112{
Denys Vlasenko7d628012018-12-04 21:46:47 +01001113 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001114 bc_vec_expand(v, len + 1);
1115 memcpy(v->v, str, len);
1116 v->len = len;
1117
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001118 bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001119}
1120
1121static void bc_vec_concat(BcVec *v, const char *str)
1122{
1123 size_t len;
1124
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001125 if (v->len == 0) bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001126
1127 len = v->len + strlen(str);
1128
1129 if (v->cap < len) bc_vec_grow(v, len - v->len);
1130 strcat(v->v, str);
1131
1132 v->len = len;
1133}
1134
1135static void *bc_vec_item(const BcVec *v, size_t idx)
1136{
1137 return v->v + v->size * idx;
1138}
1139
1140static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1141{
1142 return v->v + v->size * (v->len - idx - 1);
1143}
1144
1145static void bc_vec_free(void *vec)
1146{
1147 BcVec *v = (BcVec *) vec;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001148 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001149 free(v->v);
1150}
1151
Denys Vlasenkocca79a02018-12-05 21:15:46 +01001152static int bc_id_cmp(const void *e1, const void *e2)
1153{
1154 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1155}
1156
1157static void bc_id_free(void *id)
1158{
1159 free(((BcId *) id)->name);
1160}
1161
Gavin Howard01055ba2018-11-03 11:00:21 -06001162static size_t bc_map_find(const BcVec *v, const void *ptr)
1163{
1164 size_t low = 0, high = v->len;
1165
1166 while (low < high) {
1167
1168 size_t mid = (low + high) / 2;
1169 BcId *id = bc_vec_item(v, mid);
1170 int result = bc_id_cmp(ptr, id);
1171
1172 if (result == 0)
1173 return mid;
1174 else if (result < 0)
1175 high = mid;
1176 else
1177 low = mid + 1;
1178 }
1179
1180 return low;
1181}
1182
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001183static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
Gavin Howard01055ba2018-11-03 11:00:21 -06001184{
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001185 size_t n = *i = bc_map_find(v, ptr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001186
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001187 if (n == v->len)
Gavin Howard01055ba2018-11-03 11:00:21 -06001188 bc_vec_push(v, ptr);
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001189 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1190 return 0; // "was not inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001191 else
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001192 bc_vec_pushAt(v, ptr, n);
1193 return 1; // "was inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001194}
1195
1196static size_t bc_map_index(const BcVec *v, const void *ptr)
1197{
1198 size_t i = bc_map_find(v, ptr);
1199 if (i >= v->len) return BC_VEC_INVALID_IDX;
1200 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1201}
1202
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001203static int push_input_byte(BcVec *vec, char c)
1204{
1205 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1206 || c > 0x7e
1207 ) {
1208 // Bad chars on this line, ignore entire line
1209 bc_error_fmt("illegal character 0x%02x", c);
1210 return 1;
1211 }
1212 bc_vec_pushByte(vec, (char)c);
1213 return 0;
1214}
1215
Gavin Howard01055ba2018-11-03 11:00:21 -06001216static BcStatus bc_read_line(BcVec *vec, const char *prompt)
1217{
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001218 bool bad_chars;
Gavin Howard01055ba2018-11-03 11:00:21 -06001219
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001220 if (G_posix) prompt = "";
1221
Denys Vlasenko00d77792018-11-30 23:13:42 +01001222 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001223 int c;
Gavin Howard01055ba2018-11-03 11:00:21 -06001224
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001225 bad_chars = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001226 bc_vec_pop_all(vec);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001227
1228 fflush_and_check();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001229
Gavin Howard01055ba2018-11-03 11:00:21 -06001230#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001231 if (bb_got_signal) { // ^C was pressed
1232 intr:
1233 bb_got_signal = 0; // resets G_interrupt to zero
1234 fputs(IS_BC
1235 ? "\ninterrupt (type \"quit\" to exit)\n"
1236 : "\ninterrupt (type \"q\" to exit)\n"
1237 , stderr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001238 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001239# if ENABLE_FEATURE_EDITING
1240 if (G_ttyin) {
1241 int n, i;
1242# define line_buf bb_common_bufsiz1
1243 n = read_line_input(G.line_input_state, prompt, line_buf, COMMON_BUFSIZE);
1244 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1245 if (n == 0) // ^C
1246 goto intr;
1247 G.eof = 1;
1248 break;
1249 }
1250 i = 0;
1251 for (;;) {
1252 c = line_buf[i++];
1253 if (!c) break;
1254 bad_chars |= push_input_byte(vec, c);
1255 }
1256# undef line_buf
1257 } else
1258# endif
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001259#endif
Denys Vlasenkoed849352018-12-06 10:26:13 +01001260 {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001261 if (G_ttyin)
Denys Vlasenkoed849352018-12-06 10:26:13 +01001262 fputs(prompt, stderr);
Denys Vlasenkoed849352018-12-06 10:26:13 +01001263 IF_FEATURE_BC_SIGNALS(errno = 0;)
1264 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001265 c = fgetc(stdin);
1266#if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1267 // Both conditions appear simultaneously, check both just in case
1268 if (errno == EINTR || bb_got_signal) {
1269 // ^C was pressed
1270 clearerr(stdin);
1271 goto intr;
1272 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001273#endif
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001274 if (c == EOF) {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001275 if (ferror(stdin))
1276 quit(); // this emits error message
1277 G.eof = 1;
1278 // Note: EOF does not append '\n', therefore:
1279 // printf 'print 123\n' | bc - works
1280 // printf 'print 123' | bc - fails (syntax error)
1281 break;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001282 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001283 bad_chars |= push_input_byte(vec, c);
1284 } while (c != '\n');
Denys Vlasenkoed849352018-12-06 10:26:13 +01001285 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001286 } while (bad_chars);
Gavin Howard01055ba2018-11-03 11:00:21 -06001287
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001288 bc_vec_pushZeroByte(vec);
Gavin Howard01055ba2018-11-03 11:00:21 -06001289
1290 return BC_STATUS_SUCCESS;
1291}
1292
Denys Vlasenkodf515392018-12-02 19:27:48 +01001293static char* bc_read_file(const char *path)
Gavin Howard01055ba2018-11-03 11:00:21 -06001294{
Denys Vlasenkodf515392018-12-02 19:27:48 +01001295 char *buf;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001296 size_t size = ((size_t) -1);
1297 size_t i;
Gavin Howard01055ba2018-11-03 11:00:21 -06001298
Denys Vlasenkodf515392018-12-02 19:27:48 +01001299 buf = xmalloc_open_read_close(path, &size);
Gavin Howard01055ba2018-11-03 11:00:21 -06001300
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001301 for (i = 0; i < size; ++i) {
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001302 char c = buf[i];
1303 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1304 || c > 0x7e
1305 ) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01001306 free(buf);
1307 buf = NULL;
1308 break;
1309 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001310 }
1311
Denys Vlasenkodf515392018-12-02 19:27:48 +01001312 return buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06001313}
1314
Gavin Howard01055ba2018-11-03 11:00:21 -06001315static void bc_num_setToZero(BcNum *n, size_t scale)
1316{
1317 n->len = 0;
1318 n->neg = false;
1319 n->rdx = scale;
1320}
1321
1322static void bc_num_zero(BcNum *n)
1323{
1324 bc_num_setToZero(n, 0);
1325}
1326
1327static void bc_num_one(BcNum *n)
1328{
1329 bc_num_setToZero(n, 0);
1330 n->len = 1;
1331 n->num[0] = 1;
1332}
1333
1334static void bc_num_ten(BcNum *n)
1335{
1336 bc_num_setToZero(n, 0);
1337 n->len = 2;
1338 n->num[0] = 0;
1339 n->num[1] = 1;
1340}
1341
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001342static void bc_num_init(BcNum *n, size_t req)
1343{
1344 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1345 memset(n, 0, sizeof(BcNum));
1346 n->num = xmalloc(req);
1347 n->cap = req;
1348}
1349
1350static void bc_num_expand(BcNum *n, size_t req)
1351{
1352 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1353 if (req > n->cap) {
1354 n->num = xrealloc(n->num, req);
1355 n->cap = req;
1356 }
1357}
1358
1359static void bc_num_free(void *num)
1360{
1361 free(((BcNum *) num)->num);
1362}
1363
1364static void bc_num_copy(BcNum *d, BcNum *s)
1365{
1366 if (d != s) {
1367 bc_num_expand(d, s->cap);
1368 d->len = s->len;
1369 d->neg = s->neg;
1370 d->rdx = s->rdx;
1371 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1372 }
1373}
1374
1375static BcStatus bc_num_ulong(BcNum *n, unsigned long *result)
1376{
1377 size_t i;
1378 unsigned long pow;
1379
1380 if (n->neg) return bc_error("negative number");
1381
1382 for (*result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1383
1384 unsigned long prev = *result, powprev = pow;
1385
1386 *result += ((unsigned long) n->num[i]) * pow;
1387 pow *= 10;
1388
1389 if (*result < prev || pow < powprev)
1390 return bc_error("overflow");
1391 }
1392
1393 return BC_STATUS_SUCCESS;
1394}
1395
1396static void bc_num_ulong2num(BcNum *n, unsigned long val)
1397{
1398 size_t len;
1399 BcDig *ptr;
1400 unsigned long i;
1401
1402 bc_num_zero(n);
1403
1404 if (val == 0) return;
1405
1406 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1407 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1408}
1409
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001410static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001411 size_t len)
1412{
1413 size_t i, j;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001414 for (i = 0; i < len; ++i) {
1415 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001416 a[i + j++] += 10;
1417 a[i + j] -= 1;
1418 }
1419 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001420}
1421
1422static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1423{
1424 size_t i;
1425 int c = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001426 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
Gavin Howard01055ba2018-11-03 11:00:21 -06001427 return BC_NUM_NEG(i + 1, c < 0);
1428}
1429
1430static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1431{
1432 size_t i, min, a_int, b_int, diff;
1433 BcDig *max_num, *min_num;
1434 bool a_max, neg = false;
1435 ssize_t cmp;
1436
1437 if (a == b) return 0;
1438 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1439 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1440 if (a->neg) {
1441 if (b->neg)
1442 neg = true;
1443 else
1444 return -1;
1445 }
1446 else if (b->neg)
1447 return 1;
1448
1449 a_int = BC_NUM_INT(a);
1450 b_int = BC_NUM_INT(b);
1451 a_int -= b_int;
1452 a_max = (a->rdx > b->rdx);
1453
1454 if (a_int != 0) return (ssize_t) a_int;
1455
1456 if (a_max) {
1457 min = b->rdx;
1458 diff = a->rdx - b->rdx;
1459 max_num = a->num + diff;
1460 min_num = b->num;
1461 }
1462 else {
1463 min = a->rdx;
1464 diff = b->rdx - a->rdx;
1465 max_num = b->num + diff;
1466 min_num = a->num;
1467 }
1468
1469 cmp = bc_num_compare(max_num, min_num, b_int + min);
1470 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1471
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001472 for (max_num -= diff, i = diff - 1; i < diff; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001473 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1474 }
1475
1476 return 0;
1477}
1478
1479static void bc_num_truncate(BcNum *n, size_t places)
1480{
1481 if (places == 0) return;
1482
1483 n->rdx -= places;
1484
1485 if (n->len != 0) {
1486 n->len -= places;
1487 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1488 }
1489}
1490
1491static void bc_num_extend(BcNum *n, size_t places)
1492{
1493 size_t len = n->len + places;
1494
1495 if (places != 0) {
1496
1497 if (n->cap < len) bc_num_expand(n, len);
1498
1499 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1500 memset(n->num, 0, sizeof(BcDig) * places);
1501
1502 n->len += places;
1503 n->rdx += places;
1504 }
1505}
1506
1507static void bc_num_clean(BcNum *n)
1508{
1509 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1510 if (n->len == 0)
1511 n->neg = false;
1512 else if (n->len < n->rdx)
1513 n->len = n->rdx;
1514}
1515
1516static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1517{
1518 if (n->rdx < scale)
1519 bc_num_extend(n, scale - n->rdx);
1520 else
1521 bc_num_truncate(n, n->rdx - scale);
1522
1523 bc_num_clean(n);
1524 if (n->len != 0) n->neg = !neg1 != !neg2;
1525}
1526
1527static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1528 BcNum *restrict b)
1529{
1530 if (idx < n->len) {
1531
1532 b->len = n->len - idx;
1533 a->len = idx;
1534 a->rdx = b->rdx = 0;
1535
1536 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1537 memcpy(a->num, n->num, idx * sizeof(BcDig));
1538 }
1539 else {
1540 bc_num_zero(b);
1541 bc_num_copy(a, n);
1542 }
1543
1544 bc_num_clean(a);
1545 bc_num_clean(b);
1546}
1547
1548static BcStatus bc_num_shift(BcNum *n, size_t places)
1549{
1550 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001551 if (places + n->len > BC_MAX_NUM)
1552 return bc_error("number too long: must be [1, BC_NUM_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06001553
1554 if (n->rdx >= places)
1555 n->rdx -= places;
1556 else {
1557 bc_num_extend(n, places - n->rdx);
1558 n->rdx = 0;
1559 }
1560
1561 bc_num_clean(n);
1562
1563 return BC_STATUS_SUCCESS;
1564}
1565
1566static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1567{
1568 BcNum one;
1569 BcDig num[2];
1570
1571 one.cap = 2;
1572 one.num = num;
1573 bc_num_one(&one);
1574
1575 return bc_num_div(&one, a, b, scale);
1576}
1577
1578static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1579{
1580 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1581 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1582 int carry, in;
1583
1584 // Because this function doesn't need to use scale (per the bc spec),
1585 // I am hijacking it to say whether it's doing an add or a subtract.
1586
1587 if (a->len == 0) {
1588 bc_num_copy(c, b);
1589 if (sub && c->len) c->neg = !c->neg;
1590 return BC_STATUS_SUCCESS;
1591 }
1592 else if (b->len == 0) {
1593 bc_num_copy(c, a);
1594 return BC_STATUS_SUCCESS;
1595 }
1596
1597 c->neg = a->neg;
1598 c->rdx = BC_MAX(a->rdx, b->rdx);
1599 min_rdx = BC_MIN(a->rdx, b->rdx);
1600 c->len = 0;
1601
1602 if (a->rdx > b->rdx) {
1603 diff = a->rdx - b->rdx;
1604 ptr = a->num;
1605 ptr_a = a->num + diff;
1606 ptr_b = b->num;
1607 }
1608 else {
1609 diff = b->rdx - a->rdx;
1610 ptr = b->num;
1611 ptr_a = a->num;
1612 ptr_b = b->num + diff;
1613 }
1614
1615 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1616
1617 ptr_c += diff;
1618 a_int = BC_NUM_INT(a);
1619 b_int = BC_NUM_INT(b);
1620
1621 if (a_int > b_int) {
1622 min_int = b_int;
1623 max = a_int;
1624 ptr = ptr_a;
1625 }
1626 else {
1627 min_int = a_int;
1628 max = b_int;
1629 ptr = ptr_b;
1630 }
1631
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001632 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001633 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1634 carry = in / 10;
1635 ptr_c[i] = (BcDig)(in % 10);
1636 }
1637
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001638 for (; i < max + min_rdx; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001639 in = ((int) ptr[i]) + carry;
1640 carry = in / 10;
1641 ptr_c[i] = (BcDig)(in % 10);
1642 }
1643
1644 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1645
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001646 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001647}
1648
1649static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1650{
Gavin Howard01055ba2018-11-03 11:00:21 -06001651 ssize_t cmp;
1652 BcNum *minuend, *subtrahend;
1653 size_t start;
1654 bool aneg, bneg, neg;
1655
1656 // Because this function doesn't need to use scale (per the bc spec),
1657 // I am hijacking it to say whether it's doing an add or a subtract.
1658
1659 if (a->len == 0) {
1660 bc_num_copy(c, b);
1661 if (sub && c->len) c->neg = !c->neg;
1662 return BC_STATUS_SUCCESS;
1663 }
1664 else if (b->len == 0) {
1665 bc_num_copy(c, a);
1666 return BC_STATUS_SUCCESS;
1667 }
1668
1669 aneg = a->neg;
1670 bneg = b->neg;
1671 a->neg = b->neg = false;
1672
1673 cmp = bc_num_cmp(a, b);
1674
1675 a->neg = aneg;
1676 b->neg = bneg;
1677
1678 if (cmp == 0) {
1679 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1680 return BC_STATUS_SUCCESS;
1681 }
1682 else if (cmp > 0) {
1683 neg = a->neg;
1684 minuend = a;
1685 subtrahend = b;
1686 }
1687 else {
1688 neg = b->neg;
1689 if (sub) neg = !neg;
1690 minuend = b;
1691 subtrahend = a;
1692 }
1693
1694 bc_num_copy(c, minuend);
1695 c->neg = neg;
1696
1697 if (c->rdx < subtrahend->rdx) {
1698 bc_num_extend(c, subtrahend->rdx - c->rdx);
1699 start = 0;
1700 }
1701 else
1702 start = c->rdx - subtrahend->rdx;
1703
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001704 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001705
1706 bc_num_clean(c);
1707
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001708 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001709}
1710
1711static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1712 BcNum *restrict c)
1713{
1714 BcStatus s;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001715 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
Gavin Howard01055ba2018-11-03 11:00:21 -06001716 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001717 bool aone;
Gavin Howard01055ba2018-11-03 11:00:21 -06001718
Gavin Howard01055ba2018-11-03 11:00:21 -06001719 if (a->len == 0 || b->len == 0) {
1720 bc_num_zero(c);
1721 return BC_STATUS_SUCCESS;
1722 }
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001723 aone = BC_NUM_ONE(a);
1724 if (aone || BC_NUM_ONE(b)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001725 bc_num_copy(c, aone ? b : a);
1726 return BC_STATUS_SUCCESS;
1727 }
1728
1729 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1730 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1731 {
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001732 size_t i, j, len;
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001733 unsigned carry;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001734
Gavin Howard01055ba2018-11-03 11:00:21 -06001735 bc_num_expand(c, a->len + b->len + 1);
1736
1737 memset(c->num, 0, sizeof(BcDig) * c->cap);
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001738 c->len = len = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06001739
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001740 for (i = 0; i < b->len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001741
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001742 carry = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001743 for (j = 0; j < a->len; ++j) {
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001744 unsigned in = c->num[i + j];
1745 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1746 // note: compilers prefer _unsigned_ div/const
Gavin Howard01055ba2018-11-03 11:00:21 -06001747 carry = in / 10;
1748 c->num[i + j] = (BcDig)(in % 10);
1749 }
1750
1751 c->num[i + j] += (BcDig) carry;
1752 len = BC_MAX(len, i + j + !!carry);
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01001753
1754 // a=2^1000000
1755 // a*a <- without check below, this will not be interruptible
1756 if (G_interrupt) return BC_STATUS_FAILURE;
Gavin Howard01055ba2018-11-03 11:00:21 -06001757 }
1758
1759 c->len = len;
1760
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001761 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06001762 }
1763
1764 bc_num_init(&l1, max);
1765 bc_num_init(&h1, max);
1766 bc_num_init(&l2, max);
1767 bc_num_init(&h2, max);
1768 bc_num_init(&m1, max);
1769 bc_num_init(&m2, max);
1770 bc_num_init(&z0, max);
1771 bc_num_init(&z1, max);
1772 bc_num_init(&z2, max);
1773 bc_num_init(&temp, max + max);
1774
1775 bc_num_split(a, max2, &l1, &h1);
1776 bc_num_split(b, max2, &l2, &h2);
1777
1778 s = bc_num_add(&h1, &l1, &m1, 0);
1779 if (s) goto err;
1780 s = bc_num_add(&h2, &l2, &m2, 0);
1781 if (s) goto err;
1782
1783 s = bc_num_k(&h1, &h2, &z0);
1784 if (s) goto err;
1785 s = bc_num_k(&m1, &m2, &z1);
1786 if (s) goto err;
1787 s = bc_num_k(&l1, &l2, &z2);
1788 if (s) goto err;
1789
1790 s = bc_num_sub(&z1, &z0, &temp, 0);
1791 if (s) goto err;
1792 s = bc_num_sub(&temp, &z2, &z1, 0);
1793 if (s) goto err;
1794
1795 s = bc_num_shift(&z0, max2 * 2);
1796 if (s) goto err;
1797 s = bc_num_shift(&z1, max2);
1798 if (s) goto err;
1799 s = bc_num_add(&z0, &z1, &temp, 0);
1800 if (s) goto err;
1801 s = bc_num_add(&temp, &z2, c, 0);
1802
1803err:
1804 bc_num_free(&temp);
1805 bc_num_free(&z2);
1806 bc_num_free(&z1);
1807 bc_num_free(&z0);
1808 bc_num_free(&m2);
1809 bc_num_free(&m1);
1810 bc_num_free(&h2);
1811 bc_num_free(&l2);
1812 bc_num_free(&h1);
1813 bc_num_free(&l1);
1814 return s;
1815}
1816
1817static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1818{
1819 BcStatus s;
1820 BcNum cpa, cpb;
1821 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1822
1823 scale = BC_MAX(scale, a->rdx);
1824 scale = BC_MAX(scale, b->rdx);
1825 scale = BC_MIN(a->rdx + b->rdx, scale);
1826 maxrdx = BC_MAX(maxrdx, scale);
1827
1828 bc_num_init(&cpa, a->len);
1829 bc_num_init(&cpb, b->len);
1830
1831 bc_num_copy(&cpa, a);
1832 bc_num_copy(&cpb, b);
1833 cpa.neg = cpb.neg = false;
1834
1835 s = bc_num_shift(&cpa, maxrdx);
1836 if (s) goto err;
1837 s = bc_num_shift(&cpb, maxrdx);
1838 if (s) goto err;
1839 s = bc_num_k(&cpa, &cpb, c);
1840 if (s) goto err;
1841
1842 maxrdx += scale;
1843 bc_num_expand(c, c->len + maxrdx);
1844
1845 if (c->len < maxrdx) {
1846 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1847 c->len += maxrdx;
1848 }
1849
1850 c->rdx = maxrdx;
1851 bc_num_retireMul(c, scale, a->neg, b->neg);
1852
1853err:
1854 bc_num_free(&cpb);
1855 bc_num_free(&cpa);
1856 return s;
1857}
1858
1859static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1860{
1861 BcStatus s = BC_STATUS_SUCCESS;
1862 BcDig *n, *p, q;
1863 size_t len, end, i;
1864 BcNum cp;
1865 bool zero = true;
1866
1867 if (b->len == 0)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001868 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001869 else if (a->len == 0) {
1870 bc_num_setToZero(c, scale);
1871 return BC_STATUS_SUCCESS;
1872 }
1873 else if (BC_NUM_ONE(b)) {
1874 bc_num_copy(c, a);
1875 bc_num_retireMul(c, scale, a->neg, b->neg);
1876 return BC_STATUS_SUCCESS;
1877 }
1878
1879 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1880 bc_num_copy(&cp, a);
1881 len = b->len;
1882
1883 if (len > cp.len) {
1884 bc_num_expand(&cp, len + 2);
1885 bc_num_extend(&cp, len - cp.len);
1886 }
1887
1888 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1889 cp.rdx -= b->rdx;
1890 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1891
1892 if (b->rdx == b->len) {
1893 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1894 len -= i - 1;
1895 }
1896
1897 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1898
1899 // We want an extra zero in front to make things simpler.
1900 cp.num[cp.len++] = 0;
1901 end = cp.len - len;
1902
1903 bc_num_expand(c, cp.len);
1904
1905 bc_num_zero(c);
1906 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1907 c->rdx = cp.rdx;
1908 c->len = cp.len;
1909 p = b->num;
1910
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001911 for (i = end - 1; !s && i < end; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001912 n = cp.num + i;
1913 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001914 bc_num_subArrays(n, p, len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001915 c->num[i] = q;
Denys Vlasenkof381a882018-12-05 19:21:34 +01001916 // a=2^100000
1917 // scale=40000
1918 // 1/a <- without check below, this will not be interruptible
1919 if (G_interrupt) {
1920 s = BC_STATUS_FAILURE;
1921 break;
1922 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001923 }
1924
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001925 bc_num_retireMul(c, scale, a->neg, b->neg);
Gavin Howard01055ba2018-11-03 11:00:21 -06001926 bc_num_free(&cp);
1927
Denys Vlasenkof381a882018-12-05 19:21:34 +01001928 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06001929}
1930
1931static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
1932 BcNum *restrict d, size_t scale, size_t ts)
1933{
1934 BcStatus s;
1935 BcNum temp;
1936 bool neg;
1937
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001938 if (b->len == 0)
1939 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001940
1941 if (a->len == 0) {
1942 bc_num_setToZero(d, ts);
1943 return BC_STATUS_SUCCESS;
1944 }
1945
1946 bc_num_init(&temp, d->cap);
Denys Vlasenkof381a882018-12-05 19:21:34 +01001947 s = bc_num_d(a, b, c, scale);
1948 if (s) goto err;
Gavin Howard01055ba2018-11-03 11:00:21 -06001949
1950 if (scale != 0) scale = ts;
1951
1952 s = bc_num_m(c, b, &temp, scale);
1953 if (s) goto err;
1954 s = bc_num_sub(a, &temp, d, scale);
1955 if (s) goto err;
1956
1957 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
1958
1959 neg = d->neg;
1960 bc_num_retireMul(d, ts, a->neg, b->neg);
1961 d->neg = neg;
1962
1963err:
1964 bc_num_free(&temp);
1965 return s;
1966}
1967
1968static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1969{
1970 BcStatus s;
1971 BcNum c1;
1972 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
1973
1974 bc_num_init(&c1, len);
1975 s = bc_num_r(a, b, &c1, c, scale, ts);
1976 bc_num_free(&c1);
1977
1978 return s;
1979}
1980
1981static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1982{
1983 BcStatus s = BC_STATUS_SUCCESS;
1984 BcNum copy;
1985 unsigned long pow;
1986 size_t i, powrdx, resrdx;
1987 bool neg, zero;
1988
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001989 if (b->rdx) return bc_error("non integer number");
Gavin Howard01055ba2018-11-03 11:00:21 -06001990
1991 if (b->len == 0) {
1992 bc_num_one(c);
1993 return BC_STATUS_SUCCESS;
1994 }
1995 else if (a->len == 0) {
1996 bc_num_setToZero(c, scale);
1997 return BC_STATUS_SUCCESS;
1998 }
1999 else if (BC_NUM_ONE(b)) {
2000 if (!b->neg)
2001 bc_num_copy(c, a);
2002 else
2003 s = bc_num_inv(a, c, scale);
2004 return s;
2005 }
2006
2007 neg = b->neg;
2008 b->neg = false;
2009
2010 s = bc_num_ulong(b, &pow);
2011 if (s) return s;
2012
2013 bc_num_init(&copy, a->len);
2014 bc_num_copy(&copy, a);
2015
2016 if (!neg) scale = BC_MIN(a->rdx * pow, BC_MAX(scale, a->rdx));
2017
2018 b->neg = neg;
2019
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002020 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002021 powrdx <<= 1;
2022 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2023 if (s) goto err;
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002024 // Not needed: bc_num_mul() has a check for ^C:
2025 //if (G_interrupt) {
2026 // s = BC_STATUS_FAILURE;
2027 // goto err;
2028 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002029 }
2030
Gavin Howard01055ba2018-11-03 11:00:21 -06002031 bc_num_copy(c, &copy);
2032
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002033 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002034
2035 powrdx <<= 1;
2036 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2037 if (s) goto err;
2038
2039 if (pow & 1) {
2040 resrdx += powrdx;
2041 s = bc_num_mul(c, &copy, c, resrdx);
2042 if (s) goto err;
2043 }
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002044 // Not needed: bc_num_mul() has a check for ^C:
2045 //if (G_interrupt) {
2046 // s = BC_STATUS_FAILURE;
2047 // goto err;
2048 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002049 }
2050
2051 if (neg) {
2052 s = bc_num_inv(c, c, scale);
2053 if (s) goto err;
2054 }
2055
Gavin Howard01055ba2018-11-03 11:00:21 -06002056 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2057
2058 // We can't use bc_num_clean() here.
2059 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2060 if (zero) bc_num_setToZero(c, scale);
2061
2062err:
2063 bc_num_free(&copy);
2064 return s;
2065}
2066
2067static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2068 BcNumBinaryOp op, size_t req)
2069{
2070 BcStatus s;
2071 BcNum num2, *ptr_a, *ptr_b;
2072 bool init = false;
2073
2074 if (c == a) {
2075 ptr_a = &num2;
2076 memcpy(ptr_a, c, sizeof(BcNum));
2077 init = true;
2078 }
2079 else
2080 ptr_a = a;
2081
2082 if (c == b) {
2083 ptr_b = &num2;
2084 if (c != a) {
2085 memcpy(ptr_b, c, sizeof(BcNum));
2086 init = true;
2087 }
2088 }
2089 else
2090 ptr_b = b;
2091
2092 if (init)
2093 bc_num_init(c, req);
2094 else
2095 bc_num_expand(c, req);
2096
2097 s = op(ptr_a, ptr_b, c, scale);
2098
2099 if (init) bc_num_free(&num2);
2100
2101 return s;
2102}
2103
2104static bool bc_num_strValid(const char *val, size_t base)
2105{
2106 BcDig b;
2107 bool small, radix = false;
2108 size_t i, len = strlen(val);
2109
2110 if (!len) return true;
2111
2112 small = base <= 10;
2113 b = (BcDig)(small ? base + '0' : base - 10 + 'A');
2114
2115 for (i = 0; i < len; ++i) {
2116
2117 BcDig c = val[i];
2118
2119 if (c == '.') {
2120
2121 if (radix) return false;
2122
2123 radix = true;
2124 continue;
2125 }
2126
2127 if (c < '0' || (small && c >= b) || (c > '9' && (c < 'A' || c >= b)))
2128 return false;
2129 }
2130
2131 return true;
2132}
2133
2134static void bc_num_parseDecimal(BcNum *n, const char *val)
2135{
2136 size_t len, i;
2137 const char *ptr;
2138 bool zero = true;
2139
2140 for (i = 0; val[i] == '0'; ++i);
2141
2142 val += i;
2143 len = strlen(val);
2144 bc_num_zero(n);
2145
2146 if (len != 0) {
2147 for (i = 0; zero && i < len; ++i) zero = val[i] == '0' || val[i] == '.';
2148 bc_num_expand(n, len);
2149 }
2150
2151 ptr = strchr(val, '.');
2152
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002153 n->rdx = 0;
2154 if (ptr != NULL)
2155 n->rdx = (size_t)((val + len) - (ptr + 1));
Gavin Howard01055ba2018-11-03 11:00:21 -06002156
2157 if (!zero) {
2158 for (i = len - 1; i < len; ++n->len, i -= 1 + (i && val[i - 1] == '.'))
2159 n->num[n->len] = val[i] - '0';
2160 }
2161}
2162
2163static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2164{
2165 BcStatus s;
2166 BcNum temp, mult, result;
2167 BcDig c = '\0';
2168 bool zero = true;
2169 unsigned long v;
2170 size_t i, digits, len = strlen(val);
2171
2172 bc_num_zero(n);
2173
2174 for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
2175 if (zero) return;
2176
2177 bc_num_init(&temp, BC_NUM_DEF_SIZE);
2178 bc_num_init(&mult, BC_NUM_DEF_SIZE);
2179
2180 for (i = 0; i < len; ++i) {
2181
2182 c = val[i];
2183 if (c == '.') break;
2184
2185 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2186
2187 s = bc_num_mul(n, base, &mult, 0);
2188 if (s) goto int_err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002189 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002190 s = bc_num_add(&mult, &temp, n, 0);
2191 if (s) goto int_err;
2192 }
2193
2194 if (i == len) {
2195 c = val[i];
2196 if (c == 0) goto int_err;
2197 }
2198
2199 bc_num_init(&result, base->len);
2200 bc_num_zero(&result);
2201 bc_num_one(&mult);
2202
2203 for (i += 1, digits = 0; i < len; ++i, ++digits) {
2204
2205 c = val[i];
2206 if (c == 0) break;
2207
2208 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2209
2210 s = bc_num_mul(&result, base, &result, 0);
2211 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002212 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002213 s = bc_num_add(&result, &temp, &result, 0);
2214 if (s) goto err;
2215 s = bc_num_mul(&mult, base, &mult, 0);
2216 if (s) goto err;
2217 }
2218
2219 s = bc_num_div(&result, &mult, &result, digits);
2220 if (s) goto err;
2221 s = bc_num_add(n, &result, n, digits);
2222 if (s) goto err;
2223
2224 if (n->len != 0) {
2225 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2226 }
2227 else
2228 bc_num_zero(n);
2229
2230err:
2231 bc_num_free(&result);
2232int_err:
2233 bc_num_free(&mult);
2234 bc_num_free(&temp);
2235}
2236
2237static void bc_num_printNewline(size_t *nchars, size_t line_len)
2238{
2239 if (*nchars == line_len - 1) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002240 bb_putchar('\\');
2241 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06002242 *nchars = 0;
2243 }
2244}
2245
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002246#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002247static void bc_num_printChar(size_t num, size_t width, bool radix,
2248 size_t *nchars, size_t line_len)
2249{
2250 (void) radix, (void) line_len;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002251 bb_putchar((char) num);
Gavin Howard01055ba2018-11-03 11:00:21 -06002252 *nchars = *nchars + width;
2253}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002254#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002255
2256static void bc_num_printDigits(size_t num, size_t width, bool radix,
2257 size_t *nchars, size_t line_len)
2258{
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002259 size_t exp, pow;
Gavin Howard01055ba2018-11-03 11:00:21 -06002260
2261 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002262 bb_putchar(radix ? '.' : ' ');
Gavin Howard01055ba2018-11-03 11:00:21 -06002263 ++(*nchars);
2264
2265 bc_num_printNewline(nchars, line_len);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002266 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2267 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002268
2269 for (exp = 0; exp < width; pow /= 10, ++(*nchars), ++exp) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002270 size_t dig;
Gavin Howard01055ba2018-11-03 11:00:21 -06002271 bc_num_printNewline(nchars, line_len);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002272 dig = num / pow;
2273 num -= dig * pow;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002274 bb_putchar(((char) dig) + '0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002275 }
2276}
2277
2278static void bc_num_printHex(size_t num, size_t width, bool radix,
2279 size_t *nchars, size_t line_len)
2280{
2281 if (radix) {
2282 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002283 bb_putchar('.');
Gavin Howard01055ba2018-11-03 11:00:21 -06002284 *nchars += 1;
2285 }
2286
2287 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002288 bb_putchar(bb_hexdigits_upcase[num]);
Gavin Howard01055ba2018-11-03 11:00:21 -06002289 *nchars = *nchars + width;
2290}
2291
2292static void bc_num_printDecimal(BcNum *n, size_t *nchars, size_t len)
2293{
2294 size_t i, rdx = n->rdx - 1;
2295
Denys Vlasenko00d77792018-11-30 23:13:42 +01002296 if (n->neg) bb_putchar('-');
Gavin Howard01055ba2018-11-03 11:00:21 -06002297 (*nchars) += n->neg;
2298
2299 for (i = n->len - 1; i < n->len; --i)
2300 bc_num_printHex((size_t) n->num[i], 1, i == rdx, nchars, len);
2301}
2302
2303static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width,
2304 size_t *nchars, size_t len, BcNumDigitOp print)
2305{
2306 BcStatus s;
2307 BcVec stack;
2308 BcNum intp, fracp, digit, frac_len;
2309 unsigned long dig, *ptr;
2310 size_t i;
2311 bool radix;
2312
2313 if (n->len == 0) {
2314 print(0, width, false, nchars, len);
2315 return BC_STATUS_SUCCESS;
2316 }
2317
2318 bc_vec_init(&stack, sizeof(long), NULL);
2319 bc_num_init(&intp, n->len);
2320 bc_num_init(&fracp, n->rdx);
2321 bc_num_init(&digit, width);
2322 bc_num_init(&frac_len, BC_NUM_INT(n));
2323 bc_num_copy(&intp, n);
2324 bc_num_one(&frac_len);
2325
2326 bc_num_truncate(&intp, intp.rdx);
2327 s = bc_num_sub(n, &intp, &fracp, 0);
2328 if (s) goto err;
2329
2330 while (intp.len != 0) {
2331 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2332 if (s) goto err;
2333 s = bc_num_ulong(&digit, &dig);
2334 if (s) goto err;
2335 bc_vec_push(&stack, &dig);
2336 }
2337
2338 for (i = 0; i < stack.len; ++i) {
2339 ptr = bc_vec_item_rev(&stack, i);
2340 print(*ptr, width, false, nchars, len);
2341 }
2342
2343 if (!n->rdx) goto err;
2344
2345 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2346 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2347 if (s) goto err;
2348 s = bc_num_ulong(&fracp, &dig);
2349 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002350 bc_num_ulong2num(&intp, dig);
Gavin Howard01055ba2018-11-03 11:00:21 -06002351 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2352 if (s) goto err;
2353 print(dig, width, radix, nchars, len);
2354 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2355 if (s) goto err;
2356 }
2357
2358err:
2359 bc_num_free(&frac_len);
2360 bc_num_free(&digit);
2361 bc_num_free(&fracp);
2362 bc_num_free(&intp);
2363 bc_vec_free(&stack);
2364 return s;
2365}
2366
2367static BcStatus bc_num_printBase(BcNum *n, BcNum *base, size_t base_t,
2368 size_t *nchars, size_t line_len)
2369{
2370 BcStatus s;
2371 size_t width, i;
2372 BcNumDigitOp print;
2373 bool neg = n->neg;
2374
Denys Vlasenko00d77792018-11-30 23:13:42 +01002375 if (neg) bb_putchar('-');
Gavin Howard01055ba2018-11-03 11:00:21 -06002376 (*nchars) += neg;
2377
2378 n->neg = false;
2379
2380 if (base_t <= BC_NUM_MAX_IBASE) {
2381 width = 1;
2382 print = bc_num_printHex;
2383 }
2384 else {
2385 for (i = base_t - 1, width = 0; i != 0; i /= 10, ++width);
2386 print = bc_num_printDigits;
2387 }
2388
2389 s = bc_num_printNum(n, base, width, nchars, line_len, print);
2390 n->neg = neg;
2391
2392 return s;
2393}
2394
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002395#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002396static BcStatus bc_num_stream(BcNum *n, BcNum *base, size_t *nchars, size_t len)
2397{
2398 return bc_num_printNum(n, base, 1, nchars, len, bc_num_printChar);
2399}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002400#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002401
Gavin Howard01055ba2018-11-03 11:00:21 -06002402static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2403 size_t base_t)
2404{
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002405 if (!bc_num_strValid(val, base_t))
2406 return bc_error("bad number string");
Gavin Howard01055ba2018-11-03 11:00:21 -06002407
2408 if (base_t == 10)
2409 bc_num_parseDecimal(n, val);
2410 else
2411 bc_num_parseBase(n, val, base);
2412
2413 return BC_STATUS_SUCCESS;
2414}
2415
2416static BcStatus bc_num_print(BcNum *n, BcNum *base, size_t base_t, bool newline,
2417 size_t *nchars, size_t line_len)
2418{
2419 BcStatus s = BC_STATUS_SUCCESS;
2420
2421 bc_num_printNewline(nchars, line_len);
2422
2423 if (n->len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002424 bb_putchar('0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002425 ++(*nchars);
2426 }
2427 else if (base_t == 10)
2428 bc_num_printDecimal(n, nchars, line_len);
2429 else
2430 s = bc_num_printBase(n, base, base_t, nchars, line_len);
2431
2432 if (newline) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002433 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06002434 *nchars = 0;
2435 }
2436
2437 return s;
2438}
2439
Gavin Howard01055ba2018-11-03 11:00:21 -06002440static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2441{
2442 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2443 (void) scale;
2444 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2445}
2446
2447static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2448{
2449 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2450 (void) scale;
2451 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2452}
2453
2454static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2455{
2456 size_t req = BC_NUM_MREQ(a, b, scale);
2457 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2458}
2459
2460static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2461{
2462 size_t req = BC_NUM_MREQ(a, b, scale);
2463 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2464}
2465
2466static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2467{
2468 size_t req = BC_NUM_MREQ(a, b, scale);
2469 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2470}
2471
2472static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2473{
2474 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2475}
2476
2477static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2478{
2479 BcStatus s;
2480 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2481 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2482 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2483
2484 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2485 bc_num_expand(b, req);
2486
2487 if (a->len == 0) {
2488 bc_num_setToZero(b, scale);
2489 return BC_STATUS_SUCCESS;
2490 }
2491 else if (a->neg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002492 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002493 else if (BC_NUM_ONE(a)) {
2494 bc_num_one(b);
2495 bc_num_extend(b, scale);
2496 return BC_STATUS_SUCCESS;
2497 }
2498
2499 scale = BC_MAX(scale, a->rdx) + 1;
2500 len = a->len + scale;
2501
2502 bc_num_init(&num1, len);
2503 bc_num_init(&num2, len);
2504 bc_num_init(&half, BC_NUM_DEF_SIZE);
2505
2506 bc_num_one(&half);
2507 half.num[0] = 5;
2508 half.rdx = 1;
2509
2510 bc_num_init(&f, len);
2511 bc_num_init(&fprime, len);
2512
2513 x0 = &num1;
2514 x1 = &num2;
2515
2516 bc_num_one(x0);
2517 pow = BC_NUM_INT(a);
2518
2519 if (pow) {
2520
2521 if (pow & 1)
2522 x0->num[0] = 2;
2523 else
2524 x0->num[0] = 6;
2525
2526 pow -= 2 - (pow & 1);
2527
2528 bc_num_extend(x0, pow);
2529
2530 // Make sure to move the radix back.
2531 x0->rdx -= pow;
2532 }
2533
2534 x0->rdx = digs = digs1 = 0;
2535 resrdx = scale + 2;
2536 len = BC_NUM_INT(x0) + resrdx - 1;
2537
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002538 while (cmp != 0 || digs < len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002539
2540 s = bc_num_div(a, x0, &f, resrdx);
2541 if (s) goto err;
2542 s = bc_num_add(x0, &f, &fprime, resrdx);
2543 if (s) goto err;
2544 s = bc_num_mul(&fprime, &half, x1, resrdx);
2545 if (s) goto err;
2546
2547 cmp = bc_num_cmp(x1, x0);
2548 digs = x1->len - (unsigned long long) llabs(cmp);
2549
2550 if (cmp == cmp2 && digs == digs1)
2551 times += 1;
2552 else
2553 times = 0;
2554
2555 resrdx += times > 4;
2556
2557 cmp2 = cmp1;
2558 cmp1 = cmp;
2559 digs1 = digs;
2560
2561 temp = x0;
2562 x0 = x1;
2563 x1 = temp;
2564 }
2565
Gavin Howard01055ba2018-11-03 11:00:21 -06002566 bc_num_copy(b, x0);
2567 scale -= 1;
2568 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2569
2570err:
2571 bc_num_free(&fprime);
2572 bc_num_free(&f);
2573 bc_num_free(&half);
2574 bc_num_free(&num2);
2575 bc_num_free(&num1);
2576 return s;
2577}
2578
2579static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2580 size_t scale)
2581{
2582 BcStatus s;
2583 BcNum num2, *ptr_a;
2584 bool init = false;
2585 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2586
2587 if (c == a) {
2588 memcpy(&num2, c, sizeof(BcNum));
2589 ptr_a = &num2;
2590 bc_num_init(c, len);
2591 init = true;
2592 }
2593 else {
2594 ptr_a = a;
2595 bc_num_expand(c, len);
2596 }
2597
2598 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2599
2600 if (init) bc_num_free(&num2);
2601
2602 return s;
2603}
2604
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002605#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002606static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2607{
2608 BcStatus s;
2609 BcNum base, exp, two, temp;
2610
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002611 if (c->len == 0)
2612 return bc_error("divide by zero");
2613 if (a->rdx || b->rdx || c->rdx)
2614 return bc_error("non integer number");
2615 if (b->neg)
2616 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002617
2618 bc_num_expand(d, c->len);
2619 bc_num_init(&base, c->len);
2620 bc_num_init(&exp, b->len);
2621 bc_num_init(&two, BC_NUM_DEF_SIZE);
2622 bc_num_init(&temp, b->len);
2623
2624 bc_num_one(&two);
2625 two.num[0] = 2;
2626 bc_num_one(d);
2627
2628 s = bc_num_rem(a, c, &base, 0);
2629 if (s) goto err;
2630 bc_num_copy(&exp, b);
2631
2632 while (exp.len != 0) {
2633
2634 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2635 if (s) goto err;
2636
2637 if (BC_NUM_ONE(&temp)) {
2638 s = bc_num_mul(d, &base, &temp, 0);
2639 if (s) goto err;
2640 s = bc_num_rem(&temp, c, d, 0);
2641 if (s) goto err;
2642 }
2643
2644 s = bc_num_mul(&base, &base, &temp, 0);
2645 if (s) goto err;
2646 s = bc_num_rem(&temp, c, &base, 0);
2647 if (s) goto err;
2648 }
2649
2650err:
2651 bc_num_free(&temp);
2652 bc_num_free(&two);
2653 bc_num_free(&exp);
2654 bc_num_free(&base);
2655 return s;
2656}
2657#endif // ENABLE_DC
2658
Gavin Howard01055ba2018-11-03 11:00:21 -06002659static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2660{
2661 BcId a;
2662 size_t i;
2663
2664 for (i = 0; i < f->autos.len; ++i) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002665 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2666 return bc_error("function parameter or auto var has the same name as another");
Gavin Howard01055ba2018-11-03 11:00:21 -06002667 }
2668
2669 a.idx = var;
2670 a.name = name;
2671
2672 bc_vec_push(&f->autos, &a);
2673
2674 return BC_STATUS_SUCCESS;
2675}
2676
2677static void bc_func_init(BcFunc *f)
2678{
Denys Vlasenko7d628012018-12-04 21:46:47 +01002679 bc_char_vec_init(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06002680 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2681 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2682 f->nparams = 0;
2683}
2684
2685static void bc_func_free(void *func)
2686{
2687 BcFunc *f = (BcFunc *) func;
2688 bc_vec_free(&f->code);
2689 bc_vec_free(&f->autos);
2690 bc_vec_free(&f->labels);
2691}
2692
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002693static void bc_array_expand(BcVec *a, size_t len);
2694
Gavin Howard01055ba2018-11-03 11:00:21 -06002695static void bc_array_init(BcVec *a, bool nums)
2696{
2697 if (nums)
2698 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2699 else
2700 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2701 bc_array_expand(a, 1);
2702}
2703
Gavin Howard01055ba2018-11-03 11:00:21 -06002704static void bc_array_expand(BcVec *a, size_t len)
2705{
2706 BcResultData data;
2707
2708 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2709 while (len > a->len) {
2710 bc_num_init(&data.n, BC_NUM_DEF_SIZE);
2711 bc_vec_push(a, &data.n);
2712 }
2713 }
2714 else {
2715 while (len > a->len) {
2716 bc_array_init(&data.v, true);
2717 bc_vec_push(a, &data.v);
2718 }
2719 }
2720}
2721
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002722static void bc_array_copy(BcVec *d, const BcVec *s)
2723{
2724 size_t i;
2725
2726 bc_vec_pop_all(d);
2727 bc_vec_expand(d, s->cap);
2728 d->len = s->len;
2729
2730 for (i = 0; i < s->len; ++i) {
2731 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2732 bc_num_init(dnum, snum->len);
2733 bc_num_copy(dnum, snum);
2734 }
2735}
2736
Gavin Howard01055ba2018-11-03 11:00:21 -06002737static void bc_string_free(void *string)
2738{
2739 free(*((char **) string));
2740}
2741
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002742#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002743static void bc_result_copy(BcResult *d, BcResult *src)
2744{
2745 d->t = src->t;
2746
2747 switch (d->t) {
2748
2749 case BC_RESULT_TEMP:
2750 case BC_RESULT_IBASE:
2751 case BC_RESULT_SCALE:
2752 case BC_RESULT_OBASE:
2753 {
2754 bc_num_init(&d->d.n, src->d.n.len);
2755 bc_num_copy(&d->d.n, &src->d.n);
2756 break;
2757 }
2758
2759 case BC_RESULT_VAR:
2760 case BC_RESULT_ARRAY:
2761 case BC_RESULT_ARRAY_ELEM:
2762 {
2763 d->d.id.name = xstrdup(src->d.id.name);
2764 break;
2765 }
2766
2767 case BC_RESULT_CONSTANT:
2768 case BC_RESULT_LAST:
2769 case BC_RESULT_ONE:
2770 case BC_RESULT_STR:
2771 {
2772 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2773 break;
2774 }
2775 }
2776}
2777#endif // ENABLE_DC
2778
2779static void bc_result_free(void *result)
2780{
2781 BcResult *r = (BcResult *) result;
2782
2783 switch (r->t) {
2784
2785 case BC_RESULT_TEMP:
2786 case BC_RESULT_IBASE:
2787 case BC_RESULT_SCALE:
2788 case BC_RESULT_OBASE:
2789 {
2790 bc_num_free(&r->d.n);
2791 break;
2792 }
2793
2794 case BC_RESULT_VAR:
2795 case BC_RESULT_ARRAY:
2796 case BC_RESULT_ARRAY_ELEM:
2797 {
2798 free(r->d.id.name);
2799 break;
2800 }
2801
2802 default:
2803 {
2804 // Do nothing.
2805 break;
2806 }
2807 }
2808}
2809
2810static void bc_lex_lineComment(BcLex *l)
2811{
2812 l->t.t = BC_LEX_WHITESPACE;
2813 while (l->i < l->len && l->buf[l->i++] != '\n');
2814 --l->i;
2815}
2816
2817static void bc_lex_whitespace(BcLex *l)
2818{
2819 char c;
2820 l->t.t = BC_LEX_WHITESPACE;
2821 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2822}
2823
2824static BcStatus bc_lex_number(BcLex *l, char start)
2825{
2826 const char *buf = l->buf + l->i;
2827 size_t len, hits = 0, bslashes = 0, i = 0, j;
2828 char c = buf[i];
2829 bool last_pt, pt = start == '.';
2830
2831 last_pt = pt;
2832 l->t.t = BC_LEX_NUMBER;
2833
2834 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2835 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2836 {
2837 if (c != '\\') {
2838 last_pt = c == '.';
2839 pt = pt || last_pt;
2840 }
2841 else {
2842 ++i;
2843 bslashes += 1;
2844 }
2845
2846 c = buf[++i];
2847 }
2848
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002849 len = i + !last_pt - bslashes * 2;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002850 if (len > BC_MAX_NUM)
2851 return bc_error("number too long: must be [1, BC_NUM_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06002852
Denys Vlasenko7d628012018-12-04 21:46:47 +01002853 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002854 bc_vec_expand(&l->t.v, len + 1);
2855 bc_vec_push(&l->t.v, &start);
2856
2857 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2858
2859 c = buf[j];
2860
2861 // If we have hit a backslash, skip it. We don't have
2862 // to check for a newline because it's guaranteed.
2863 if (hits < bslashes && c == '\\') {
2864 ++hits;
2865 ++j;
2866 continue;
2867 }
2868
2869 bc_vec_push(&l->t.v, &c);
2870 }
2871
Denys Vlasenko08c033c2018-12-05 16:55:08 +01002872 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002873 l->i += i;
2874
2875 return BC_STATUS_SUCCESS;
2876}
2877
2878static BcStatus bc_lex_name(BcLex *l)
2879{
2880 size_t i = 0;
2881 const char *buf = l->buf + l->i - 1;
2882 char c = buf[i];
2883
2884 l->t.t = BC_LEX_NAME;
2885
2886 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2887
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002888 if (i > BC_MAX_STRING)
2889 return bc_error("name too long: must be [1, BC_NAME_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06002890 bc_vec_string(&l->t.v, i, buf);
2891
2892 // Increment the index. We minus 1 because it has already been incremented.
2893 l->i += i - 1;
2894
2895 return BC_STATUS_SUCCESS;
2896}
2897
2898static void bc_lex_init(BcLex *l, BcLexNext next)
2899{
2900 l->next = next;
Denys Vlasenko7d628012018-12-04 21:46:47 +01002901 bc_char_vec_init(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002902}
2903
2904static void bc_lex_free(BcLex *l)
2905{
2906 bc_vec_free(&l->t.v);
2907}
2908
Denys Vlasenko0409ad32018-12-05 16:39:22 +01002909static void bc_lex_file(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06002910{
Denys Vlasenko5318f812018-12-05 17:48:01 +01002911 G.err_line = l->line = 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06002912 l->newline = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06002913}
2914
2915static BcStatus bc_lex_next(BcLex *l)
2916{
2917 BcStatus s;
2918
2919 l->t.last = l->t.t;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002920 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06002921
2922 l->line += l->newline;
Denys Vlasenko5318f812018-12-05 17:48:01 +01002923 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06002924 l->t.t = BC_LEX_EOF;
2925
2926 l->newline = (l->i == l->len);
2927 if (l->newline) return BC_STATUS_SUCCESS;
2928
2929 // Loop until failure or we don't have whitespace. This
2930 // is so the parser doesn't get inundated with whitespace.
2931 do {
2932 s = l->next(l);
2933 } while (!s && l->t.t == BC_LEX_WHITESPACE);
2934
2935 return s;
2936}
2937
2938static BcStatus bc_lex_text(BcLex *l, const char *text)
2939{
2940 l->buf = text;
2941 l->i = 0;
2942 l->len = strlen(text);
2943 l->t.t = l->t.last = BC_LEX_INVALID;
2944 return bc_lex_next(l);
2945}
2946
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002947#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002948static BcStatus bc_lex_identifier(BcLex *l)
2949{
2950 BcStatus s;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002951 unsigned i;
Gavin Howard01055ba2018-11-03 11:00:21 -06002952 const char *buf = l->buf + l->i - 1;
2953
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002954 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2955 const char *keyword8 = bc_lex_kws[i].name8;
2956 unsigned j = 0;
2957 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2958 j++;
2959 if (j == 8) goto match;
Gavin Howard01055ba2018-11-03 11:00:21 -06002960 }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002961 if (keyword8[j] != '\0')
2962 continue;
2963 match:
2964 // buf starts with keyword bc_lex_kws[i]
2965 l->t.t = BC_LEX_KEY_1st_keyword + i;
Denys Vlasenko00646792018-12-05 18:12:27 +01002966 if (!((1 << i) & POSIX_KWORD_MASK)) {
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01002967 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002968 if (s) return s;
2969 }
2970
2971 // We minus 1 because the index has already been incremented.
2972 l->i += j - 1;
2973 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06002974 }
2975
2976 s = bc_lex_name(l);
2977 if (s) return s;
2978
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01002979 if (l->t.v.len > 2) {
2980 // Prevent this:
2981 // >>> qwe=1
2982 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
2983 // '
2984 unsigned len = strchrnul(buf, '\n') - buf;
2985 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
2986 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002987
2988 return s;
2989}
2990
2991static BcStatus bc_lex_string(BcLex *l)
2992{
2993 size_t len, nls = 0, i = l->i;
2994 char c;
2995
2996 l->t.t = BC_LEX_STR;
2997
2998 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
2999
3000 if (c == '\0') {
3001 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003002 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003003 }
3004
3005 len = i - l->i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003006 if (len > BC_MAX_STRING)
3007 return bc_error("string too long: must be [1, BC_STRING_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06003008 bc_vec_string(&l->t.v, len, l->buf + l->i);
3009
3010 l->i = i + 1;
3011 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003012 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003013
3014 return BC_STATUS_SUCCESS;
3015}
3016
3017static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3018{
3019 if (l->buf[l->i] == '=') {
3020 ++l->i;
3021 l->t.t = with;
3022 }
3023 else
3024 l->t.t = without;
3025}
3026
3027static BcStatus bc_lex_comment(BcLex *l)
3028{
3029 size_t i, nls = 0;
3030 const char *buf = l->buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003031
3032 l->t.t = BC_LEX_WHITESPACE;
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003033 i = ++l->i;
3034 for (;;) {
3035 char c = buf[i];
3036 check_star:
3037 if (c == '*') {
3038 c = buf[++i];
3039 if (c == '/')
3040 break;
3041 goto check_star;
3042 }
3043 if (c == '\0') {
Gavin Howard01055ba2018-11-03 11:00:21 -06003044 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003045 return bc_error("comment end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003046 }
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003047 nls += (c == '\n');
3048 i++;
Gavin Howard01055ba2018-11-03 11:00:21 -06003049 }
3050
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003051 l->i = i + 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003052 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003053 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003054
3055 return BC_STATUS_SUCCESS;
3056}
3057
3058static BcStatus bc_lex_token(BcLex *l)
3059{
3060 BcStatus s = BC_STATUS_SUCCESS;
3061 char c = l->buf[l->i++], c2;
3062
3063 // This is the workhorse of the lexer.
3064 switch (c) {
3065
3066 case '\0':
3067 case '\n':
3068 {
3069 l->newline = true;
3070 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3071 break;
3072 }
3073
3074 case '\t':
3075 case '\v':
3076 case '\f':
3077 case '\r':
3078 case ' ':
3079 {
3080 bc_lex_whitespace(l);
3081 break;
3082 }
3083
3084 case '!':
3085 {
3086 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3087
3088 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
Denys Vlasenko00646792018-12-05 18:12:27 +01003089 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
Gavin Howard01055ba2018-11-03 11:00:21 -06003090 if (s) return s;
3091 }
3092
3093 break;
3094 }
3095
3096 case '"':
3097 {
3098 s = bc_lex_string(l);
3099 break;
3100 }
3101
3102 case '#':
3103 {
Denys Vlasenko00646792018-12-05 18:12:27 +01003104 s = bc_POSIX_does_not_allow("'#' script comments");
Gavin Howard01055ba2018-11-03 11:00:21 -06003105 if (s) return s;
3106
3107 bc_lex_lineComment(l);
3108
3109 break;
3110 }
3111
3112 case '%':
3113 {
3114 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3115 break;
3116 }
3117
3118 case '&':
3119 {
3120 c2 = l->buf[l->i];
3121 if (c2 == '&') {
3122
Denys Vlasenko00646792018-12-05 18:12:27 +01003123 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
Gavin Howard01055ba2018-11-03 11:00:21 -06003124 if (s) return s;
3125
3126 ++l->i;
3127 l->t.t = BC_LEX_OP_BOOL_AND;
3128 }
3129 else {
3130 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003131 s = bc_error_bad_character('&');
Gavin Howard01055ba2018-11-03 11:00:21 -06003132 }
3133
3134 break;
3135 }
3136
3137 case '(':
3138 case ')':
3139 {
3140 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3141 break;
3142 }
3143
3144 case '*':
3145 {
3146 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3147 break;
3148 }
3149
3150 case '+':
3151 {
3152 c2 = l->buf[l->i];
3153 if (c2 == '+') {
3154 ++l->i;
3155 l->t.t = BC_LEX_OP_INC;
3156 }
3157 else
3158 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3159 break;
3160 }
3161
3162 case ',':
3163 {
3164 l->t.t = BC_LEX_COMMA;
3165 break;
3166 }
3167
3168 case '-':
3169 {
3170 c2 = l->buf[l->i];
3171 if (c2 == '-') {
3172 ++l->i;
3173 l->t.t = BC_LEX_OP_DEC;
3174 }
3175 else
3176 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3177 break;
3178 }
3179
3180 case '.':
3181 {
3182 if (isdigit(l->buf[l->i]))
3183 s = bc_lex_number(l, c);
3184 else {
3185 l->t.t = BC_LEX_KEY_LAST;
Denys Vlasenko00646792018-12-05 18:12:27 +01003186 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
Gavin Howard01055ba2018-11-03 11:00:21 -06003187 }
3188 break;
3189 }
3190
3191 case '/':
3192 {
3193 c2 = l->buf[l->i];
3194 if (c2 == '*')
3195 s = bc_lex_comment(l);
3196 else
3197 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3198 break;
3199 }
3200
3201 case '0':
3202 case '1':
3203 case '2':
3204 case '3':
3205 case '4':
3206 case '5':
3207 case '6':
3208 case '7':
3209 case '8':
3210 case '9':
3211 case 'A':
3212 case 'B':
3213 case 'C':
3214 case 'D':
3215 case 'E':
3216 case 'F':
3217 {
3218 s = bc_lex_number(l, c);
3219 break;
3220 }
3221
3222 case ';':
3223 {
3224 l->t.t = BC_LEX_SCOLON;
3225 break;
3226 }
3227
3228 case '<':
3229 {
3230 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3231 break;
3232 }
3233
3234 case '=':
3235 {
3236 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3237 break;
3238 }
3239
3240 case '>':
3241 {
3242 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3243 break;
3244 }
3245
3246 case '[':
3247 case ']':
3248 {
3249 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3250 break;
3251 }
3252
3253 case '\\':
3254 {
3255 if (l->buf[l->i] == '\n') {
3256 l->t.t = BC_LEX_WHITESPACE;
3257 ++l->i;
3258 }
3259 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003260 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003261 break;
3262 }
3263
3264 case '^':
3265 {
3266 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3267 break;
3268 }
3269
3270 case 'a':
3271 case 'b':
3272 case 'c':
3273 case 'd':
3274 case 'e':
3275 case 'f':
3276 case 'g':
3277 case 'h':
3278 case 'i':
3279 case 'j':
3280 case 'k':
3281 case 'l':
3282 case 'm':
3283 case 'n':
3284 case 'o':
3285 case 'p':
3286 case 'q':
3287 case 'r':
3288 case 's':
3289 case 't':
3290 case 'u':
3291 case 'v':
3292 case 'w':
3293 case 'x':
3294 case 'y':
3295 case 'z':
3296 {
3297 s = bc_lex_identifier(l);
3298 break;
3299 }
3300
3301 case '{':
3302 case '}':
3303 {
3304 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3305 break;
3306 }
3307
3308 case '|':
3309 {
3310 c2 = l->buf[l->i];
3311
3312 if (c2 == '|') {
Denys Vlasenko00646792018-12-05 18:12:27 +01003313 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
Gavin Howard01055ba2018-11-03 11:00:21 -06003314 if (s) return s;
3315
3316 ++l->i;
3317 l->t.t = BC_LEX_OP_BOOL_OR;
3318 }
3319 else {
3320 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003321 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003322 }
3323
3324 break;
3325 }
3326
3327 default:
3328 {
3329 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003330 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003331 break;
3332 }
3333 }
3334
3335 return s;
3336}
3337#endif // ENABLE_BC
3338
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003339#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06003340static BcStatus dc_lex_register(BcLex *l)
3341{
3342 BcStatus s = BC_STATUS_SUCCESS;
3343
3344 if (isspace(l->buf[l->i - 1])) {
3345 bc_lex_whitespace(l);
3346 ++l->i;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01003347 if (!G_exreg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003348 s = bc_error("extended register");
Gavin Howard01055ba2018-11-03 11:00:21 -06003349 else
3350 s = bc_lex_name(l);
3351 }
3352 else {
Denys Vlasenko7d628012018-12-04 21:46:47 +01003353 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003354 bc_vec_pushByte(&l->t.v, l->buf[l->i - 1]);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003355 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003356 l->t.t = BC_LEX_NAME;
3357 }
3358
3359 return s;
3360}
3361
3362static BcStatus dc_lex_string(BcLex *l)
3363{
3364 size_t depth = 1, nls = 0, i = l->i;
3365 char c;
3366
3367 l->t.t = BC_LEX_STR;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003368 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003369
3370 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3371
3372 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3373 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3374 nls += (c == '\n');
3375
3376 if (depth) bc_vec_push(&l->t.v, &c);
3377 }
3378
3379 if (c == '\0') {
3380 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003381 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003382 }
3383
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003384 bc_vec_pushZeroByte(&l->t.v);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003385 if (i - l->i > BC_MAX_STRING)
3386 return bc_error("string too long: must be [1, BC_STRING_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06003387
3388 l->i = i;
3389 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003390 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003391
3392 return BC_STATUS_SUCCESS;
3393}
3394
3395static BcStatus dc_lex_token(BcLex *l)
3396{
3397 BcStatus s = BC_STATUS_SUCCESS;
3398 char c = l->buf[l->i++], c2;
3399 size_t i;
3400
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003401 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3402 if (l->t.last == dc_lex_regs[i])
3403 return dc_lex_register(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003404 }
3405
3406 if (c >= '%' && c <= '~' &&
3407 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3408 {
3409 return s;
3410 }
3411
3412 // This is the workhorse of the lexer.
3413 switch (c) {
3414
3415 case '\0':
3416 {
3417 l->t.t = BC_LEX_EOF;
3418 break;
3419 }
3420
3421 case '\n':
3422 case '\t':
3423 case '\v':
3424 case '\f':
3425 case '\r':
3426 case ' ':
3427 {
3428 l->newline = (c == '\n');
3429 bc_lex_whitespace(l);
3430 break;
3431 }
3432
3433 case '!':
3434 {
3435 c2 = l->buf[l->i];
3436
3437 if (c2 == '=')
3438 l->t.t = BC_LEX_OP_REL_NE;
3439 else if (c2 == '<')
3440 l->t.t = BC_LEX_OP_REL_LE;
3441 else if (c2 == '>')
3442 l->t.t = BC_LEX_OP_REL_GE;
3443 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003444 return bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003445
3446 ++l->i;
3447 break;
3448 }
3449
3450 case '#':
3451 {
3452 bc_lex_lineComment(l);
3453 break;
3454 }
3455
3456 case '.':
3457 {
3458 if (isdigit(l->buf[l->i]))
3459 s = bc_lex_number(l, c);
3460 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003461 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003462 break;
3463 }
3464
3465 case '0':
3466 case '1':
3467 case '2':
3468 case '3':
3469 case '4':
3470 case '5':
3471 case '6':
3472 case '7':
3473 case '8':
3474 case '9':
3475 case 'A':
3476 case 'B':
3477 case 'C':
3478 case 'D':
3479 case 'E':
3480 case 'F':
3481 {
3482 s = bc_lex_number(l, c);
3483 break;
3484 }
3485
3486 case '[':
3487 {
3488 s = dc_lex_string(l);
3489 break;
3490 }
3491
3492 default:
3493 {
3494 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003495 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003496 break;
3497 }
3498 }
3499
3500 return s;
3501}
3502#endif // ENABLE_DC
3503
3504static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3505{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003506 bc_program_addFunc(name, idx);
3507 p->func = bc_vec_item(&G.prog.fns, p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003508}
3509
3510static void bc_parse_pushName(BcParse *p, char *name)
3511{
3512 size_t i = 0, len = strlen(name);
3513
3514 for (; i < len; ++i) bc_parse_push(p, name[i]);
3515 bc_parse_push(p, BC_PARSE_STREND);
3516
3517 free(name);
3518}
3519
3520static void bc_parse_pushIndex(BcParse *p, size_t idx)
3521{
3522 unsigned char amt, i, nums[sizeof(size_t)];
3523
3524 for (amt = 0; idx; ++amt) {
3525 nums[amt] = (char) idx;
3526 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3527 }
3528
3529 bc_parse_push(p, amt);
3530 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3531}
3532
3533static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3534{
3535 char *num = xstrdup(p->l.t.v.v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003536 size_t idx = G.prog.consts.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06003537
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003538 bc_vec_push(&G.prog.consts, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06003539
3540 bc_parse_push(p, BC_INST_NUM);
3541 bc_parse_pushIndex(p, idx);
3542
3543 ++(*nexs);
3544 (*prev) = BC_INST_NUM;
3545}
3546
3547static BcStatus bc_parse_text(BcParse *p, const char *text)
3548{
3549 BcStatus s;
3550
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003551 p->func = bc_vec_item(&G.prog.fns, p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003552
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003553 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003554 p->l.t.t = BC_LEX_INVALID;
3555 s = p->parse(p);
3556 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003557 if (!BC_PARSE_CAN_EXEC(p))
3558 return bc_error("file is not executable");
Gavin Howard01055ba2018-11-03 11:00:21 -06003559 }
3560
3561 return bc_lex_text(&p->l, text);
3562}
3563
Denys Vlasenkod38af482018-12-04 19:11:02 +01003564// Called when bc/dc_parse_parse() detects a failure,
3565// resets parsing structures.
3566static void bc_parse_reset(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06003567{
3568 if (p->fidx != BC_PROG_MAIN) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003569 p->func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003570 bc_vec_pop_all(&p->func->code);
3571 bc_vec_pop_all(&p->func->autos);
3572 bc_vec_pop_all(&p->func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06003573
3574 bc_parse_updateFunc(p, BC_PROG_MAIN);
3575 }
3576
3577 p->l.i = p->l.len;
3578 p->l.t.t = BC_LEX_EOF;
3579 p->auto_part = (p->nbraces = 0);
3580
3581 bc_vec_npop(&p->flags, p->flags.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01003582 bc_vec_pop_all(&p->exits);
3583 bc_vec_pop_all(&p->conds);
3584 bc_vec_pop_all(&p->ops);
Gavin Howard01055ba2018-11-03 11:00:21 -06003585
Denys Vlasenkod38af482018-12-04 19:11:02 +01003586 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06003587}
3588
3589static void bc_parse_free(BcParse *p)
3590{
3591 bc_vec_free(&p->flags);
3592 bc_vec_free(&p->exits);
3593 bc_vec_free(&p->conds);
3594 bc_vec_free(&p->ops);
3595 bc_lex_free(&p->l);
3596}
3597
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003598static void bc_parse_create(BcParse *p, size_t func,
Gavin Howard01055ba2018-11-03 11:00:21 -06003599 BcParseParse parse, BcLexNext next)
3600{
3601 memset(p, 0, sizeof(BcParse));
3602
3603 bc_lex_init(&p->l, next);
3604 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3605 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3606 bc_vec_init(&p->conds, sizeof(size_t), NULL);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003607 bc_vec_pushZeroByte(&p->flags);
Gavin Howard01055ba2018-11-03 11:00:21 -06003608 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3609
3610 p->parse = parse;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01003611 // p->auto_part = p->nbraces = 0; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06003612 bc_parse_updateFunc(p, func);
3613}
3614
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003615#if ENABLE_BC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003616
3617#define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3618#define BC_PARSE_LEAF(p, rparen) \
3619 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3620 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3621
3622// We can calculate the conversion between tokens and exprs by subtracting the
3623// position of the first operator in the lex enum and adding the position of the
3624// first in the expr enum. Note: This only works for binary operators.
3625#define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3626
Gavin Howard01055ba2018-11-03 11:00:21 -06003627static BcStatus bc_parse_else(BcParse *p);
3628static BcStatus bc_parse_stmt(BcParse *p);
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003629static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01003630static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
Gavin Howard01055ba2018-11-03 11:00:21 -06003631
3632static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3633 size_t *nexprs, bool next)
3634{
3635 BcStatus s = BC_STATUS_SUCCESS;
3636 BcLexType t;
Denys Vlasenko65437582018-12-05 19:37:19 +01003637 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3638 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003639
3640 while (p->ops.len > start) {
3641
3642 t = BC_PARSE_TOP_OP(p);
3643 if (t == BC_LEX_LPAREN) break;
3644
Denys Vlasenko65437582018-12-05 19:37:19 +01003645 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003646 if (l >= r && (l != r || !left)) break;
3647
3648 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3649 bc_vec_pop(&p->ops);
3650 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3651 }
3652
3653 bc_vec_push(&p->ops, &type);
3654 if (next) s = bc_lex_next(&p->l);
3655
3656 return s;
3657}
3658
3659static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3660{
3661 BcLexType top;
3662
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003663 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003664 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003665 top = BC_PARSE_TOP_OP(p);
3666
3667 while (top != BC_LEX_LPAREN) {
3668
3669 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3670
3671 bc_vec_pop(&p->ops);
3672 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3673
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003674 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003675 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003676 top = BC_PARSE_TOP_OP(p);
3677 }
3678
3679 bc_vec_pop(&p->ops);
3680
3681 return bc_lex_next(&p->l);
3682}
3683
3684static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3685{
3686 BcStatus s;
3687 bool comma = false;
3688 size_t nparams;
3689
3690 s = bc_lex_next(&p->l);
3691 if (s) return s;
3692
3693 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3694
3695 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3696 s = bc_parse_expr(p, flags, bc_parse_next_param);
3697 if (s) return s;
3698
3699 comma = p->l.t.t == BC_LEX_COMMA;
3700 if (comma) {
3701 s = bc_lex_next(&p->l);
3702 if (s) return s;
3703 }
3704 }
3705
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003706 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003707 bc_parse_push(p, BC_INST_CALL);
3708 bc_parse_pushIndex(p, nparams);
3709
3710 return BC_STATUS_SUCCESS;
3711}
3712
3713static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3714{
3715 BcStatus s;
3716 BcId entry, *entry_ptr;
3717 size_t idx;
3718
3719 entry.name = name;
3720
3721 s = bc_parse_params(p, flags);
3722 if (s) goto err;
3723
3724 if (p->l.t.t != BC_LEX_RPAREN) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003725 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003726 goto err;
3727 }
3728
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003729 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003730
3731 if (idx == BC_VEC_INVALID_IDX) {
3732 name = xstrdup(entry.name);
3733 bc_parse_addFunc(p, name, &idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003734 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003735 free(entry.name);
3736 }
3737 else
3738 free(name);
3739
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003740 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003741 bc_parse_pushIndex(p, entry_ptr->idx);
3742
3743 return bc_lex_next(&p->l);
3744
3745err:
3746 free(name);
3747 return s;
3748}
3749
3750static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3751{
3752 BcStatus s;
3753 char *name;
3754
3755 name = xstrdup(p->l.t.v.v);
3756 s = bc_lex_next(&p->l);
3757 if (s) goto err;
3758
3759 if (p->l.t.t == BC_LEX_LBRACKET) {
3760
3761 s = bc_lex_next(&p->l);
3762 if (s) goto err;
3763
3764 if (p->l.t.t == BC_LEX_RBRACKET) {
3765
3766 if (!(flags & BC_PARSE_ARRAY)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003767 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003768 goto err;
3769 }
3770
3771 *type = BC_INST_ARRAY;
3772 }
3773 else {
3774
3775 *type = BC_INST_ARRAY_ELEM;
3776
3777 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3778 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3779 if (s) goto err;
3780 }
3781
3782 s = bc_lex_next(&p->l);
3783 if (s) goto err;
3784 bc_parse_push(p, *type);
3785 bc_parse_pushName(p, name);
3786 }
3787 else if (p->l.t.t == BC_LEX_LPAREN) {
3788
3789 if (flags & BC_PARSE_NOCALL) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003790 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003791 goto err;
3792 }
3793
3794 *type = BC_INST_CALL;
3795 s = bc_parse_call(p, name, flags);
3796 }
3797 else {
3798 *type = BC_INST_VAR;
3799 bc_parse_push(p, BC_INST_VAR);
3800 bc_parse_pushName(p, name);
3801 }
3802
3803 return s;
3804
3805err:
3806 free(name);
3807 return s;
3808}
3809
3810static BcStatus bc_parse_read(BcParse *p)
3811{
3812 BcStatus s;
3813
3814 s = bc_lex_next(&p->l);
3815 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003816 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003817
3818 s = bc_lex_next(&p->l);
3819 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003820 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003821
3822 bc_parse_push(p, BC_INST_READ);
3823
3824 return bc_lex_next(&p->l);
3825}
3826
3827static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3828 BcInst *prev)
3829{
3830 BcStatus s;
3831
3832 s = bc_lex_next(&p->l);
3833 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003834 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003835
3836 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3837
3838 s = bc_lex_next(&p->l);
3839 if (s) return s;
3840
3841 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3842 if (s) return s;
3843
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003844 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003845
3846 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3847 bc_parse_push(p, *prev);
3848
3849 return bc_lex_next(&p->l);
3850}
3851
3852static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3853{
3854 BcStatus s;
3855
3856 s = bc_lex_next(&p->l);
3857 if (s) return s;
3858
3859 if (p->l.t.t != BC_LEX_LPAREN) {
3860 *type = BC_INST_SCALE;
3861 bc_parse_push(p, BC_INST_SCALE);
3862 return BC_STATUS_SUCCESS;
3863 }
3864
3865 *type = BC_INST_SCALE_FUNC;
3866 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3867
3868 s = bc_lex_next(&p->l);
3869 if (s) return s;
3870
3871 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3872 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003873 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003874 bc_parse_push(p, BC_INST_SCALE_FUNC);
3875
3876 return bc_lex_next(&p->l);
3877}
3878
3879static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3880 size_t *nexprs, uint8_t flags)
3881{
3882 BcStatus s;
3883 BcLexType type;
3884 char inst;
3885 BcInst etype = *prev;
3886
3887 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
3888 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
3889 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
3890 {
3891 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
3892 bc_parse_push(p, inst);
3893 s = bc_lex_next(&p->l);
3894 }
3895 else {
3896
3897 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
3898 *paren_expr = true;
3899
3900 s = bc_lex_next(&p->l);
3901 if (s) return s;
3902 type = p->l.t.t;
3903
3904 // Because we parse the next part of the expression
3905 // right here, we need to increment this.
3906 *nexprs = *nexprs + 1;
3907
3908 switch (type) {
3909
3910 case BC_LEX_NAME:
3911 {
3912 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
3913 break;
3914 }
3915
3916 case BC_LEX_KEY_IBASE:
3917 case BC_LEX_KEY_LAST:
3918 case BC_LEX_KEY_OBASE:
3919 {
3920 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
3921 s = bc_lex_next(&p->l);
3922 break;
3923 }
3924
3925 case BC_LEX_KEY_SCALE:
3926 {
3927 s = bc_lex_next(&p->l);
3928 if (s) return s;
3929 if (p->l.t.t == BC_LEX_LPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003930 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003931 else
3932 bc_parse_push(p, BC_INST_SCALE);
3933 break;
3934 }
3935
3936 default:
3937 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003938 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003939 break;
3940 }
3941 }
3942
3943 if (!s) bc_parse_push(p, inst);
3944 }
3945
3946 return s;
3947}
3948
3949static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
3950 bool rparen, size_t *nexprs)
3951{
3952 BcStatus s;
3953 BcLexType type;
3954 BcInst etype = *prev;
3955
3956 s = bc_lex_next(&p->l);
3957 if (s) return s;
3958
3959 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
3960 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
3961 BC_LEX_OP_MINUS :
3962 BC_LEX_NEG;
3963 *prev = BC_PARSE_TOKEN_INST(type);
3964
3965 // We can just push onto the op stack because this is the largest
3966 // precedence operator that gets pushed. Inc/dec does not.
3967 if (type != BC_LEX_OP_MINUS)
3968 bc_vec_push(&p->ops, &type);
3969 else
3970 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
3971
3972 return s;
3973}
3974
3975static BcStatus bc_parse_string(BcParse *p, char inst)
3976{
3977 char *str = xstrdup(p->l.t.v.v);
3978
3979 bc_parse_push(p, BC_INST_STR);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003980 bc_parse_pushIndex(p, G.prog.strs.len);
3981 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06003982 bc_parse_push(p, inst);
3983
3984 return bc_lex_next(&p->l);
3985}
3986
3987static BcStatus bc_parse_print(BcParse *p)
3988{
3989 BcStatus s;
3990 BcLexType type;
3991 bool comma = false;
3992
3993 s = bc_lex_next(&p->l);
3994 if (s) return s;
3995
3996 type = p->l.t.t;
3997
3998 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003999 return bc_error("bad print statement");
Gavin Howard01055ba2018-11-03 11:00:21 -06004000
4001 while (!s && type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4002
4003 if (type == BC_LEX_STR)
4004 s = bc_parse_string(p, BC_INST_PRINT_POP);
4005 else {
4006 s = bc_parse_expr(p, 0, bc_parse_next_print);
4007 if (s) return s;
4008 bc_parse_push(p, BC_INST_PRINT_POP);
4009 }
4010
4011 if (s) return s;
4012
4013 comma = p->l.t.t == BC_LEX_COMMA;
4014 if (comma) s = bc_lex_next(&p->l);
4015 type = p->l.t.t;
4016 }
4017
4018 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004019 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004020
4021 return bc_lex_next(&p->l);
4022}
4023
4024static BcStatus bc_parse_return(BcParse *p)
4025{
4026 BcStatus s;
4027 BcLexType t;
4028 bool paren;
4029
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004030 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004031
4032 s = bc_lex_next(&p->l);
4033 if (s) return s;
4034
4035 t = p->l.t.t;
4036 paren = t == BC_LEX_LPAREN;
4037
4038 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4039 bc_parse_push(p, BC_INST_RET0);
4040 else {
4041
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004042 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004043 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004044 bc_parse_push(p, BC_INST_RET0);
4045 s = bc_lex_next(&p->l);
Gavin Howard01055ba2018-11-03 11:00:21 -06004046 }
Denys Vlasenko452df922018-12-05 20:28:26 +01004047 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06004048
4049 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01004050 s = bc_posix_error("POSIX requires parentheses around return expressions");
Gavin Howard01055ba2018-11-03 11:00:21 -06004051 if (s) return s;
4052 }
4053
4054 bc_parse_push(p, BC_INST_RET);
4055 }
4056
4057 return s;
4058}
4059
4060static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4061{
4062 BcStatus s = BC_STATUS_SUCCESS;
4063
4064 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004065 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004066
4067 if (brace) {
4068
4069 if (p->l.t.t == BC_LEX_RBRACE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004070 if (!p->nbraces) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004071 --p->nbraces;
4072 s = bc_lex_next(&p->l);
4073 if (s) return s;
4074 }
4075 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004076 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004077 }
4078
4079 if (BC_PARSE_IF(p)) {
4080
4081 uint8_t *flag_ptr;
4082
4083 while (p->l.t.t == BC_LEX_NLINE) {
4084 s = bc_lex_next(&p->l);
4085 if (s) return s;
4086 }
4087
4088 bc_vec_pop(&p->flags);
4089
4090 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4091 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4092
4093 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4094 }
4095 else if (BC_PARSE_ELSE(p)) {
4096
4097 BcInstPtr *ip;
4098 size_t *label;
4099
4100 bc_vec_pop(&p->flags);
4101
4102 ip = bc_vec_top(&p->exits);
4103 label = bc_vec_item(&p->func->labels, ip->idx);
4104 *label = p->func->code.len;
4105
4106 bc_vec_pop(&p->exits);
4107 }
4108 else if (BC_PARSE_FUNC_INNER(p)) {
4109 bc_parse_push(p, BC_INST_RET0);
4110 bc_parse_updateFunc(p, BC_PROG_MAIN);
4111 bc_vec_pop(&p->flags);
4112 }
4113 else {
4114
4115 BcInstPtr *ip = bc_vec_top(&p->exits);
4116 size_t *label = bc_vec_top(&p->conds);
4117
4118 bc_parse_push(p, BC_INST_JUMP);
4119 bc_parse_pushIndex(p, *label);
4120
4121 label = bc_vec_item(&p->func->labels, ip->idx);
4122 *label = p->func->code.len;
4123
4124 bc_vec_pop(&p->flags);
4125 bc_vec_pop(&p->exits);
4126 bc_vec_pop(&p->conds);
4127 }
4128
4129 return s;
4130}
4131
4132static void bc_parse_startBody(BcParse *p, uint8_t flags)
4133{
4134 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4135 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4136 flags |= BC_PARSE_FLAG_BODY;
4137 bc_vec_push(&p->flags, &flags);
4138}
4139
4140static void bc_parse_noElse(BcParse *p)
4141{
4142 BcInstPtr *ip;
4143 size_t *label;
4144 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4145
4146 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4147
4148 ip = bc_vec_top(&p->exits);
4149 label = bc_vec_item(&p->func->labels, ip->idx);
4150 *label = p->func->code.len;
4151
4152 bc_vec_pop(&p->exits);
4153}
4154
4155static BcStatus bc_parse_if(BcParse *p)
4156{
4157 BcStatus s;
4158 BcInstPtr ip;
4159
4160 s = bc_lex_next(&p->l);
4161 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004162 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004163
4164 s = bc_lex_next(&p->l);
4165 if (s) return s;
4166 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4167 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004168 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004169
4170 s = bc_lex_next(&p->l);
4171 if (s) return s;
4172 bc_parse_push(p, BC_INST_JUMP_ZERO);
4173
4174 ip.idx = p->func->labels.len;
4175 ip.func = ip.len = 0;
4176
4177 bc_parse_pushIndex(p, ip.idx);
4178 bc_vec_push(&p->exits, &ip);
4179 bc_vec_push(&p->func->labels, &ip.idx);
4180 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4181
4182 return BC_STATUS_SUCCESS;
4183}
4184
4185static BcStatus bc_parse_else(BcParse *p)
4186{
4187 BcInstPtr ip;
4188
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004189 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004190
4191 ip.idx = p->func->labels.len;
4192 ip.func = ip.len = 0;
4193
4194 bc_parse_push(p, BC_INST_JUMP);
4195 bc_parse_pushIndex(p, ip.idx);
4196
4197 bc_parse_noElse(p);
4198
4199 bc_vec_push(&p->exits, &ip);
4200 bc_vec_push(&p->func->labels, &ip.idx);
4201 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4202
4203 return bc_lex_next(&p->l);
4204}
4205
4206static BcStatus bc_parse_while(BcParse *p)
4207{
4208 BcStatus s;
4209 BcInstPtr ip;
4210
4211 s = bc_lex_next(&p->l);
4212 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004213 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004214 s = bc_lex_next(&p->l);
4215 if (s) return s;
4216
4217 ip.idx = p->func->labels.len;
4218
4219 bc_vec_push(&p->func->labels, &p->func->code.len);
4220 bc_vec_push(&p->conds, &ip.idx);
4221
4222 ip.idx = p->func->labels.len;
4223 ip.func = 1;
4224 ip.len = 0;
4225
4226 bc_vec_push(&p->exits, &ip);
4227 bc_vec_push(&p->func->labels, &ip.idx);
4228
4229 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4230 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004231 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004232 s = bc_lex_next(&p->l);
4233 if (s) return s;
4234
4235 bc_parse_push(p, BC_INST_JUMP_ZERO);
4236 bc_parse_pushIndex(p, ip.idx);
4237 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4238
4239 return BC_STATUS_SUCCESS;
4240}
4241
4242static BcStatus bc_parse_for(BcParse *p)
4243{
4244 BcStatus s;
4245 BcInstPtr ip;
4246 size_t cond_idx, exit_idx, body_idx, update_idx;
4247
4248 s = bc_lex_next(&p->l);
4249 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004250 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004251 s = bc_lex_next(&p->l);
4252 if (s) return s;
4253
4254 if (p->l.t.t != BC_LEX_SCOLON)
4255 s = bc_parse_expr(p, 0, bc_parse_next_for);
4256 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004257 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
Gavin Howard01055ba2018-11-03 11:00:21 -06004258
4259 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004260 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004261 s = bc_lex_next(&p->l);
4262 if (s) return s;
4263
4264 cond_idx = p->func->labels.len;
4265 update_idx = cond_idx + 1;
4266 body_idx = update_idx + 1;
4267 exit_idx = body_idx + 1;
4268
4269 bc_vec_push(&p->func->labels, &p->func->code.len);
4270
4271 if (p->l.t.t != BC_LEX_SCOLON)
4272 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4273 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004274 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004275
4276 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004277 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004278
4279 s = bc_lex_next(&p->l);
4280 if (s) return s;
4281
4282 bc_parse_push(p, BC_INST_JUMP_ZERO);
4283 bc_parse_pushIndex(p, exit_idx);
4284 bc_parse_push(p, BC_INST_JUMP);
4285 bc_parse_pushIndex(p, body_idx);
4286
4287 ip.idx = p->func->labels.len;
4288
4289 bc_vec_push(&p->conds, &update_idx);
4290 bc_vec_push(&p->func->labels, &p->func->code.len);
4291
4292 if (p->l.t.t != BC_LEX_RPAREN)
4293 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4294 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004295 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
Gavin Howard01055ba2018-11-03 11:00:21 -06004296
4297 if (s) return s;
4298
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004299 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004300 bc_parse_push(p, BC_INST_JUMP);
4301 bc_parse_pushIndex(p, cond_idx);
4302 bc_vec_push(&p->func->labels, &p->func->code.len);
4303
4304 ip.idx = exit_idx;
4305 ip.func = 1;
4306 ip.len = 0;
4307
4308 bc_vec_push(&p->exits, &ip);
4309 bc_vec_push(&p->func->labels, &ip.idx);
4310 bc_lex_next(&p->l);
4311 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4312
4313 return BC_STATUS_SUCCESS;
4314}
4315
4316static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4317{
4318 BcStatus s;
4319 size_t i;
4320 BcInstPtr *ip;
4321
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004322 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004323
4324 if (type == BC_LEX_KEY_BREAK) {
4325
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004326 if (p->exits.len == 0) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004327
4328 i = p->exits.len - 1;
4329 ip = bc_vec_item(&p->exits, i);
4330
4331 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004332 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004333
4334 i = ip->idx;
4335 }
4336 else
4337 i = *((size_t *) bc_vec_top(&p->conds));
4338
4339 bc_parse_push(p, BC_INST_JUMP);
4340 bc_parse_pushIndex(p, i);
4341
4342 s = bc_lex_next(&p->l);
4343 if (s) return s;
4344
4345 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004346 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004347
4348 return bc_lex_next(&p->l);
4349}
4350
4351static BcStatus bc_parse_func(BcParse *p)
4352{
4353 BcStatus s;
4354 bool var, comma = false;
4355 uint8_t flags;
4356 char *name;
4357
4358 s = bc_lex_next(&p->l);
4359 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004360 if (p->l.t.t != BC_LEX_NAME)
4361 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004362
4363 name = xstrdup(p->l.t.v.v);
4364 bc_parse_addFunc(p, name, &p->fidx);
4365
4366 s = bc_lex_next(&p->l);
4367 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004368 if (p->l.t.t != BC_LEX_LPAREN)
4369 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004370 s = bc_lex_next(&p->l);
4371 if (s) return s;
4372
4373 while (p->l.t.t != BC_LEX_RPAREN) {
4374
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004375 if (p->l.t.t != BC_LEX_NAME)
4376 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004377
4378 ++p->func->nparams;
4379
4380 name = xstrdup(p->l.t.v.v);
4381 s = bc_lex_next(&p->l);
4382 if (s) goto err;
4383
4384 var = p->l.t.t != BC_LEX_LBRACKET;
4385
4386 if (!var) {
4387
4388 s = bc_lex_next(&p->l);
4389 if (s) goto err;
4390
4391 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004392 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004393 goto err;
4394 }
4395
4396 s = bc_lex_next(&p->l);
4397 if (s) goto err;
4398 }
4399
4400 comma = p->l.t.t == BC_LEX_COMMA;
4401 if (comma) {
4402 s = bc_lex_next(&p->l);
4403 if (s) goto err;
4404 }
4405
4406 s = bc_func_insert(p->func, name, var);
4407 if (s) goto err;
4408 }
4409
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004410 if (comma) return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004411
4412 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4413 bc_parse_startBody(p, flags);
4414
4415 s = bc_lex_next(&p->l);
4416 if (s) return s;
4417
4418 if (p->l.t.t != BC_LEX_LBRACE)
Denys Vlasenko9b70f192018-12-04 20:51:40 +01004419 s = bc_posix_error("POSIX requires the left brace be on the same line as the function header");
Gavin Howard01055ba2018-11-03 11:00:21 -06004420
4421 return s;
4422
4423err:
4424 free(name);
4425 return s;
4426}
4427
4428static BcStatus bc_parse_auto(BcParse *p)
4429{
4430 BcStatus s;
4431 bool comma, var, one;
4432 char *name;
4433
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004434 if (!p->auto_part) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004435 s = bc_lex_next(&p->l);
4436 if (s) return s;
4437
4438 p->auto_part = comma = false;
4439 one = p->l.t.t == BC_LEX_NAME;
4440
4441 while (p->l.t.t == BC_LEX_NAME) {
4442
4443 name = xstrdup(p->l.t.v.v);
4444 s = bc_lex_next(&p->l);
4445 if (s) goto err;
4446
4447 var = p->l.t.t != BC_LEX_LBRACKET;
4448 if (!var) {
4449
4450 s = bc_lex_next(&p->l);
4451 if (s) goto err;
4452
4453 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004454 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004455 goto err;
4456 }
4457
4458 s = bc_lex_next(&p->l);
4459 if (s) goto err;
4460 }
4461
4462 comma = p->l.t.t == BC_LEX_COMMA;
4463 if (comma) {
4464 s = bc_lex_next(&p->l);
4465 if (s) goto err;
4466 }
4467
4468 s = bc_func_insert(p->func, name, var);
4469 if (s) goto err;
4470 }
4471
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004472 if (comma) return bc_error("bad function definition");
Denys Vlasenkoabbc4332018-12-03 21:46:41 +01004473 if (!one) return bc_error("no auto variable found");
Gavin Howard01055ba2018-11-03 11:00:21 -06004474
4475 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004476 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004477
4478 return bc_lex_next(&p->l);
4479
4480err:
4481 free(name);
4482 return s;
4483}
4484
4485static BcStatus bc_parse_body(BcParse *p, bool brace)
4486{
4487 BcStatus s = BC_STATUS_SUCCESS;
4488 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4489
4490 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4491
4492 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4493
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004494 if (!brace) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004495 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4496
4497 if (!p->auto_part) {
4498 s = bc_parse_auto(p);
4499 if (s) return s;
4500 }
4501
4502 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4503 }
4504 else {
4505 s = bc_parse_stmt(p);
4506 if (!s && !brace) s = bc_parse_endBody(p, false);
4507 }
4508
4509 return s;
4510}
4511
4512static BcStatus bc_parse_stmt(BcParse *p)
4513{
4514 BcStatus s = BC_STATUS_SUCCESS;
4515
4516 switch (p->l.t.t) {
4517
4518 case BC_LEX_NLINE:
4519 {
4520 return bc_lex_next(&p->l);
4521 }
4522
4523 case BC_LEX_KEY_ELSE:
4524 {
4525 p->auto_part = false;
4526 break;
4527 }
4528
4529 case BC_LEX_LBRACE:
4530 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004531 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004532
4533 ++p->nbraces;
4534 s = bc_lex_next(&p->l);
4535 if (s) return s;
4536
4537 return bc_parse_body(p, true);
4538 }
4539
4540 case BC_LEX_KEY_AUTO:
4541 {
4542 return bc_parse_auto(p);
4543 }
4544
4545 default:
4546 {
4547 p->auto_part = false;
4548
4549 if (BC_PARSE_IF_END(p)) {
4550 bc_parse_noElse(p);
4551 return BC_STATUS_SUCCESS;
4552 }
4553 else if (BC_PARSE_BODY(p))
4554 return bc_parse_body(p, false);
4555
4556 break;
4557 }
4558 }
4559
4560 switch (p->l.t.t) {
4561
4562 case BC_LEX_OP_INC:
4563 case BC_LEX_OP_DEC:
4564 case BC_LEX_OP_MINUS:
4565 case BC_LEX_OP_BOOL_NOT:
4566 case BC_LEX_LPAREN:
4567 case BC_LEX_NAME:
4568 case BC_LEX_NUMBER:
4569 case BC_LEX_KEY_IBASE:
4570 case BC_LEX_KEY_LAST:
4571 case BC_LEX_KEY_LENGTH:
4572 case BC_LEX_KEY_OBASE:
4573 case BC_LEX_KEY_READ:
4574 case BC_LEX_KEY_SCALE:
4575 case BC_LEX_KEY_SQRT:
4576 {
4577 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4578 break;
4579 }
4580
4581 case BC_LEX_KEY_ELSE:
4582 {
4583 s = bc_parse_else(p);
4584 break;
4585 }
4586
4587 case BC_LEX_SCOLON:
4588 {
4589 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4590 break;
4591 }
4592
4593 case BC_LEX_RBRACE:
4594 {
4595 s = bc_parse_endBody(p, true);
4596 break;
4597 }
4598
4599 case BC_LEX_STR:
4600 {
4601 s = bc_parse_string(p, BC_INST_PRINT_STR);
4602 break;
4603 }
4604
4605 case BC_LEX_KEY_BREAK:
4606 case BC_LEX_KEY_CONTINUE:
4607 {
4608 s = bc_parse_loopExit(p, p->l.t.t);
4609 break;
4610 }
4611
4612 case BC_LEX_KEY_FOR:
4613 {
4614 s = bc_parse_for(p);
4615 break;
4616 }
4617
4618 case BC_LEX_KEY_HALT:
4619 {
4620 bc_parse_push(p, BC_INST_HALT);
4621 s = bc_lex_next(&p->l);
4622 break;
4623 }
4624
4625 case BC_LEX_KEY_IF:
4626 {
4627 s = bc_parse_if(p);
4628 break;
4629 }
4630
4631 case BC_LEX_KEY_LIMITS:
4632 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004633 // "limits" is a compile-time command,
4634 // the output is produced at _parse time_.
Gavin Howard01055ba2018-11-03 11:00:21 -06004635 s = bc_lex_next(&p->l);
4636 if (s) return s;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004637 printf("BC_BASE_MAX = %u\n", BC_MAX_OBASE);
4638 printf("BC_DIM_MAX = %u\n", BC_MAX_DIM);
4639 printf("BC_SCALE_MAX = %u\n", BC_MAX_SCALE);
4640 printf("BC_STRING_MAX = %u\n", BC_MAX_STRING);
4641 printf("BC_NAME_MAX = %u\n", BC_MAX_NAME);
4642 printf("BC_NUM_MAX = %u\n", BC_MAX_NUM);
4643 printf("MAX Exponent = %lu\n", BC_MAX_EXP);
4644 printf("Number of vars = %lu\n", BC_MAX_VARS);
Gavin Howard01055ba2018-11-03 11:00:21 -06004645 break;
4646 }
4647
4648 case BC_LEX_KEY_PRINT:
4649 {
4650 s = bc_parse_print(p);
4651 break;
4652 }
4653
4654 case BC_LEX_KEY_QUIT:
4655 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004656 // "quit" is a compile-time command. For example,
4657 // "if (0 == 1) quit" terminates when parsing the statement,
4658 // not when it is executed
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01004659 quit_or_return_for_exit();
Gavin Howard01055ba2018-11-03 11:00:21 -06004660 }
4661
4662 case BC_LEX_KEY_RETURN:
4663 {
4664 s = bc_parse_return(p);
4665 break;
4666 }
4667
4668 case BC_LEX_KEY_WHILE:
4669 {
4670 s = bc_parse_while(p);
4671 break;
4672 }
4673
4674 default:
4675 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004676 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004677 break;
4678 }
4679 }
4680
4681 return s;
4682}
4683
4684static BcStatus bc_parse_parse(BcParse *p)
4685{
4686 BcStatus s;
4687
4688 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004689 s = p->flags.len > 0 ? bc_error("block end could not be found") : bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06004690 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004691 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004692 s = bc_parse_func(p);
4693 }
4694 else
4695 s = bc_parse_stmt(p);
4696
Denys Vlasenkod38af482018-12-04 19:11:02 +01004697 if (s || G_interrupt) {
4698 bc_parse_reset(p);
4699 s = BC_STATUS_FAILURE;
4700 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004701
4702 return s;
4703}
4704
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004705static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
Gavin Howard01055ba2018-11-03 11:00:21 -06004706{
4707 BcStatus s = BC_STATUS_SUCCESS;
4708 BcInst prev = BC_INST_PRINT;
4709 BcLexType top, t = p->l.t.t;
4710 size_t nexprs = 0, ops_bgn = p->ops.len;
4711 uint32_t i, nparens, nrelops;
4712 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4713
4714 paren_first = p->l.t.t == BC_LEX_LPAREN;
4715 nparens = nrelops = 0;
4716 paren_expr = rprn = done = get_token = assign = false;
4717 bin_last = true;
4718
Denys Vlasenkobcb62a72018-12-05 20:17:48 +01004719 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004720 switch (t) {
4721
4722 case BC_LEX_OP_INC:
4723 case BC_LEX_OP_DEC:
4724 {
4725 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4726 rprn = get_token = bin_last = false;
4727 break;
4728 }
4729
4730 case BC_LEX_OP_MINUS:
4731 {
4732 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4733 rprn = get_token = false;
4734 bin_last = prev == BC_INST_MINUS;
4735 break;
4736 }
4737
4738 case BC_LEX_OP_ASSIGN_POWER:
4739 case BC_LEX_OP_ASSIGN_MULTIPLY:
4740 case BC_LEX_OP_ASSIGN_DIVIDE:
4741 case BC_LEX_OP_ASSIGN_MODULUS:
4742 case BC_LEX_OP_ASSIGN_PLUS:
4743 case BC_LEX_OP_ASSIGN_MINUS:
4744 case BC_LEX_OP_ASSIGN:
4745 {
4746 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4747 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4748 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4749 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004750 s = bc_error("bad assignment:"
4751 " left side must be scale,"
4752 " ibase, obase, last, var,"
4753 " or array element"
4754 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004755 break;
4756 }
4757 }
4758 // Fallthrough.
4759 case BC_LEX_OP_POWER:
4760 case BC_LEX_OP_MULTIPLY:
4761 case BC_LEX_OP_DIVIDE:
4762 case BC_LEX_OP_MODULUS:
4763 case BC_LEX_OP_PLUS:
4764 case BC_LEX_OP_REL_EQ:
4765 case BC_LEX_OP_REL_LE:
4766 case BC_LEX_OP_REL_GE:
4767 case BC_LEX_OP_REL_NE:
4768 case BC_LEX_OP_REL_LT:
4769 case BC_LEX_OP_REL_GT:
4770 case BC_LEX_OP_BOOL_NOT:
4771 case BC_LEX_OP_BOOL_OR:
4772 case BC_LEX_OP_BOOL_AND:
4773 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004774 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4775 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4776 ) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004777 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004778 }
4779
4780 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4781 prev = BC_PARSE_TOKEN_INST(t);
4782 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4783 rprn = get_token = false;
4784 bin_last = t != BC_LEX_OP_BOOL_NOT;
4785
4786 break;
4787 }
4788
4789 case BC_LEX_LPAREN:
4790 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004791 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004792 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004793 ++nparens;
4794 paren_expr = rprn = bin_last = false;
4795 get_token = true;
4796 bc_vec_push(&p->ops, &t);
4797
4798 break;
4799 }
4800
4801 case BC_LEX_RPAREN:
4802 {
4803 if (bin_last || prev == BC_INST_BOOL_NOT)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004804 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004805
4806 if (nparens == 0) {
4807 s = BC_STATUS_SUCCESS;
4808 done = true;
4809 get_token = false;
4810 break;
4811 }
4812 else if (!paren_expr)
4813 return BC_STATUS_PARSE_EMPTY_EXP;
4814
4815 --nparens;
4816 paren_expr = rprn = true;
4817 get_token = bin_last = false;
4818
4819 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4820
4821 break;
4822 }
4823
4824 case BC_LEX_NAME:
4825 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004826 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004827 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004828 paren_expr = true;
4829 rprn = get_token = bin_last = false;
4830 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4831 ++nexprs;
4832
4833 break;
4834 }
4835
4836 case BC_LEX_NUMBER:
4837 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004838 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004839 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004840 bc_parse_number(p, &prev, &nexprs);
4841 paren_expr = get_token = true;
4842 rprn = bin_last = false;
4843
4844 break;
4845 }
4846
4847 case BC_LEX_KEY_IBASE:
4848 case BC_LEX_KEY_LAST:
4849 case BC_LEX_KEY_OBASE:
4850 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004851 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004852 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004853 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4854 bc_parse_push(p, (char) prev);
4855
4856 paren_expr = get_token = true;
4857 rprn = bin_last = false;
4858 ++nexprs;
4859
4860 break;
4861 }
4862
4863 case BC_LEX_KEY_LENGTH:
4864 case BC_LEX_KEY_SQRT:
4865 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004866 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004867 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004868 s = bc_parse_builtin(p, t, flags, &prev);
4869 paren_expr = true;
4870 rprn = get_token = bin_last = false;
4871 ++nexprs;
4872
4873 break;
4874 }
4875
4876 case BC_LEX_KEY_READ:
4877 {
4878 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004879 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004880 else if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004881 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06004882 else
4883 s = bc_parse_read(p);
4884
4885 paren_expr = true;
4886 rprn = get_token = bin_last = false;
4887 ++nexprs;
4888 prev = BC_INST_READ;
4889
4890 break;
4891 }
4892
4893 case BC_LEX_KEY_SCALE:
4894 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004895 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004896 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004897 s = bc_parse_scale(p, &prev, flags);
4898 paren_expr = true;
4899 rprn = get_token = bin_last = false;
4900 ++nexprs;
4901 prev = BC_INST_SCALE;
4902
4903 break;
4904 }
4905
4906 default:
4907 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004908 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004909 break;
4910 }
4911 }
4912
4913 if (!s && get_token) s = bc_lex_next(&p->l);
4914 }
4915
4916 if (s) return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01004917 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
Gavin Howard01055ba2018-11-03 11:00:21 -06004918
4919 while (p->ops.len > ops_bgn) {
4920
4921 top = BC_PARSE_TOP_OP(p);
4922 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
4923
4924 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004925 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004926
4927 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
4928
4929 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
4930 bc_vec_pop(&p->ops);
4931 }
4932
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004933 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004934 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004935
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004936 for (i = 0; i < next.len; ++i)
4937 if (t == next.tokens[i])
4938 goto ok;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004939 return bc_error_bad_expression();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004940 ok:
Gavin Howard01055ba2018-11-03 11:00:21 -06004941
4942 if (!(flags & BC_PARSE_REL) && nrelops) {
Denys Vlasenko00646792018-12-05 18:12:27 +01004943 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
Gavin Howard01055ba2018-11-03 11:00:21 -06004944 if (s) return s;
4945 }
4946 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01004947 s = bc_posix_error("POSIX requires exactly one comparison operator per condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004948 if (s) return s;
4949 }
4950
4951 if (flags & BC_PARSE_PRINT) {
4952 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
4953 bc_parse_push(p, BC_INST_POP);
4954 }
4955
4956 return s;
4957}
4958
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004959static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
4960{
4961 BcStatus s;
4962
4963 s = bc_parse_expr_empty_ok(p, flags, next);
4964 if (s == BC_STATUS_PARSE_EMPTY_EXP)
4965 return bc_error("empty expression");
4966 return s;
4967}
4968
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004969static void bc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06004970{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004971 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06004972}
4973
4974static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
4975{
4976 return bc_parse_expr(p, flags, bc_parse_next_read);
4977}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01004978
Gavin Howard01055ba2018-11-03 11:00:21 -06004979#endif // ENABLE_BC
4980
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01004981#if ENABLE_DC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01004982
4983#define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
4984
Gavin Howard01055ba2018-11-03 11:00:21 -06004985static BcStatus dc_parse_register(BcParse *p)
4986{
4987 BcStatus s;
4988 char *name;
4989
4990 s = bc_lex_next(&p->l);
4991 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004992 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004993
4994 name = xstrdup(p->l.t.v.v);
4995 bc_parse_pushName(p, name);
4996
4997 return s;
4998}
4999
5000static BcStatus dc_parse_string(BcParse *p)
5001{
5002 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005003 size_t idx, len = G.prog.strs.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005004
5005 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5006 name = xstrdup(b);
5007
5008 str = xstrdup(p->l.t.v.v);
5009 bc_parse_push(p, BC_INST_STR);
5010 bc_parse_pushIndex(p, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005011 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06005012 bc_parse_addFunc(p, name, &idx);
5013
5014 return bc_lex_next(&p->l);
5015}
5016
5017static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5018{
5019 BcStatus s;
5020
5021 bc_parse_push(p, inst);
5022 if (name) {
5023 s = dc_parse_register(p);
5024 if (s) return s;
5025 }
5026
5027 if (store) {
5028 bc_parse_push(p, BC_INST_SWAP);
5029 bc_parse_push(p, BC_INST_ASSIGN);
5030 bc_parse_push(p, BC_INST_POP);
5031 }
5032
5033 return bc_lex_next(&p->l);
5034}
5035
5036static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5037{
5038 BcStatus s;
5039
5040 bc_parse_push(p, inst);
5041 bc_parse_push(p, BC_INST_EXEC_COND);
5042
5043 s = dc_parse_register(p);
5044 if (s) return s;
5045
5046 s = bc_lex_next(&p->l);
5047 if (s) return s;
5048
5049 if (p->l.t.t == BC_LEX_ELSE) {
5050 s = dc_parse_register(p);
5051 if (s) return s;
5052 s = bc_lex_next(&p->l);
5053 }
5054 else
5055 bc_parse_push(p, BC_PARSE_STREND);
5056
5057 return s;
5058}
5059
5060static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5061{
5062 BcStatus s = BC_STATUS_SUCCESS;
5063 BcInst prev;
5064 uint8_t inst;
5065 bool assign, get_token = false;
5066
5067 switch (t) {
5068
5069 case BC_LEX_OP_REL_EQ:
5070 case BC_LEX_OP_REL_LE:
5071 case BC_LEX_OP_REL_GE:
5072 case BC_LEX_OP_REL_NE:
5073 case BC_LEX_OP_REL_LT:
5074 case BC_LEX_OP_REL_GT:
5075 {
5076 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5077 break;
5078 }
5079
5080 case BC_LEX_SCOLON:
5081 case BC_LEX_COLON:
5082 {
5083 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5084 break;
5085 }
5086
5087 case BC_LEX_STR:
5088 {
5089 s = dc_parse_string(p);
5090 break;
5091 }
5092
5093 case BC_LEX_NEG:
5094 case BC_LEX_NUMBER:
5095 {
5096 if (t == BC_LEX_NEG) {
5097 s = bc_lex_next(&p->l);
5098 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005099 if (p->l.t.t != BC_LEX_NUMBER)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005100 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005101 }
5102
5103 bc_parse_number(p, &prev, &p->nbraces);
5104
5105 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5106 get_token = true;
5107
5108 break;
5109 }
5110
5111 case BC_LEX_KEY_READ:
5112 {
5113 if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005114 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005115 else
5116 bc_parse_push(p, BC_INST_READ);
5117 get_token = true;
5118 break;
5119 }
5120
5121 case BC_LEX_OP_ASSIGN:
5122 case BC_LEX_STORE_PUSH:
5123 {
5124 assign = t == BC_LEX_OP_ASSIGN;
5125 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5126 s = dc_parse_mem(p, inst, true, assign);
5127 break;
5128 }
5129
5130 case BC_LEX_LOAD:
5131 case BC_LEX_LOAD_POP:
5132 {
5133 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5134 s = dc_parse_mem(p, inst, true, false);
5135 break;
5136 }
5137
5138 case BC_LEX_STORE_IBASE:
5139 case BC_LEX_STORE_SCALE:
5140 case BC_LEX_STORE_OBASE:
5141 {
5142 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5143 s = dc_parse_mem(p, inst, false, true);
5144 break;
5145 }
5146
5147 default:
5148 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005149 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005150 get_token = true;
5151 break;
5152 }
5153 }
5154
5155 if (!s && get_token) s = bc_lex_next(&p->l);
5156
5157 return s;
5158}
5159
5160static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5161{
5162 BcStatus s = BC_STATUS_SUCCESS;
5163 BcInst inst;
5164 BcLexType t;
5165
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005166 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005167
5168 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5169
5170 inst = dc_parse_insts[t];
5171
5172 if (inst != BC_INST_INVALID) {
5173 bc_parse_push(p, inst);
5174 s = bc_lex_next(&p->l);
5175 }
5176 else
5177 s = dc_parse_token(p, t, flags);
5178 }
5179
5180 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5181 bc_parse_push(p, BC_INST_POP_EXEC);
5182
5183 return s;
5184}
5185
5186static BcStatus dc_parse_parse(BcParse *p)
5187{
5188 BcStatus s;
5189
5190 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005191 s = bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06005192 else
5193 s = dc_parse_expr(p, 0);
5194
Denys Vlasenkod38af482018-12-04 19:11:02 +01005195 if (s || G_interrupt) {
5196 bc_parse_reset(p);
5197 s = BC_STATUS_FAILURE;
5198 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005199
5200 return s;
5201}
5202
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005203static void dc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005204{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005205 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005206}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005207
Gavin Howard01055ba2018-11-03 11:00:21 -06005208#endif // ENABLE_DC
5209
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005210static void common_parse_init(BcParse *p, size_t func)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005211{
5212 if (IS_BC) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005213 bc_parse_init(p, func);
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005214 } else {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005215 dc_parse_init(p, func);
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005216 }
5217}
5218
5219static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5220{
5221 if (IS_BC) {
5222 return bc_parse_expression(p, flags);
5223 } else {
5224 return dc_parse_expr(p, flags);
5225 }
5226}
5227
Denys Vlasenkodf515392018-12-02 19:27:48 +01005228static BcVec* bc_program_search(char *id, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005229{
Gavin Howard01055ba2018-11-03 11:00:21 -06005230 BcId e, *ptr;
5231 BcVec *v, *map;
5232 size_t i;
5233 BcResultData data;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005234 int new;
Gavin Howard01055ba2018-11-03 11:00:21 -06005235
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005236 v = var ? &G.prog.vars : &G.prog.arrs;
5237 map = var ? &G.prog.var_map : &G.prog.arr_map;
Gavin Howard01055ba2018-11-03 11:00:21 -06005238
5239 e.name = id;
5240 e.idx = v->len;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005241 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
Gavin Howard01055ba2018-11-03 11:00:21 -06005242
5243 if (new) {
5244 bc_array_init(&data.v, var);
5245 bc_vec_push(v, &data.v);
5246 }
5247
5248 ptr = bc_vec_item(map, i);
5249 if (new) ptr->name = xstrdup(e.name);
Denys Vlasenkodf515392018-12-02 19:27:48 +01005250 return bc_vec_item(v, ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005251}
5252
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005253static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
Gavin Howard01055ba2018-11-03 11:00:21 -06005254{
5255 BcStatus s = BC_STATUS_SUCCESS;
5256
5257 switch (r->t) {
5258
5259 case BC_RESULT_STR:
5260 case BC_RESULT_TEMP:
5261 case BC_RESULT_IBASE:
5262 case BC_RESULT_SCALE:
5263 case BC_RESULT_OBASE:
5264 {
5265 *num = &r->d.n;
5266 break;
5267 }
5268
5269 case BC_RESULT_CONSTANT:
5270 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005271 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005272 size_t base_t, len = strlen(*str);
5273 BcNum *base;
5274
5275 bc_num_init(&r->d.n, len);
5276
5277 hex = hex && len == 1;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005278 base = hex ? &G.prog.hexb : &G.prog.ib;
5279 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005280 s = bc_num_parse(&r->d.n, *str, base, base_t);
5281
5282 if (s) {
5283 bc_num_free(&r->d.n);
5284 return s;
5285 }
5286
5287 *num = &r->d.n;
5288 r->t = BC_RESULT_TEMP;
5289
5290 break;
5291 }
5292
5293 case BC_RESULT_VAR:
5294 case BC_RESULT_ARRAY:
5295 case BC_RESULT_ARRAY_ELEM:
5296 {
5297 BcVec *v;
5298
Denys Vlasenkodf515392018-12-02 19:27:48 +01005299 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
Gavin Howard01055ba2018-11-03 11:00:21 -06005300
5301 if (r->t == BC_RESULT_ARRAY_ELEM) {
5302 v = bc_vec_top(v);
5303 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5304 *num = bc_vec_item(v, r->d.id.idx);
5305 }
5306 else
5307 *num = bc_vec_top(v);
5308
5309 break;
5310 }
5311
5312 case BC_RESULT_LAST:
5313 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005314 *num = &G.prog.last;
Gavin Howard01055ba2018-11-03 11:00:21 -06005315 break;
5316 }
5317
5318 case BC_RESULT_ONE:
5319 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005320 *num = &G.prog.one;
Gavin Howard01055ba2018-11-03 11:00:21 -06005321 break;
5322 }
5323 }
5324
5325 return s;
5326}
5327
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005328static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
Gavin Howard01055ba2018-11-03 11:00:21 -06005329 BcResult **r, BcNum **rn, bool assign)
5330{
5331 BcStatus s;
5332 bool hex;
5333 BcResultType lt, rt;
5334
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005335 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005336 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005337
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005338 *r = bc_vec_item_rev(&G.prog.results, 0);
5339 *l = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06005340
5341 lt = (*l)->t;
5342 rt = (*r)->t;
5343 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5344
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005345 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005346 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005347 s = bc_program_num(*r, rn, hex);
Gavin Howard01055ba2018-11-03 11:00:21 -06005348 if (s) return s;
5349
5350 // We run this again under these conditions in case any vector has been
5351 // reallocated out from under the BcNums or arrays we had.
5352 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005353 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005354 if (s) return s;
5355 }
5356
5357 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005358 return bc_error_variable_is_wrong_type();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005359 if (!assign && !BC_PROG_NUM((*r), (*ln)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005360 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005361
Gavin Howard01055ba2018-11-03 11:00:21 -06005362 return s;
5363}
5364
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005365static void bc_program_binOpRetire(BcResult *r)
Gavin Howard01055ba2018-11-03 11:00:21 -06005366{
5367 r->t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005368 bc_vec_pop(&G.prog.results);
5369 bc_vec_pop(&G.prog.results);
5370 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005371}
5372
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005373static BcStatus bc_program_prep(BcResult **r, BcNum **n)
Gavin Howard01055ba2018-11-03 11:00:21 -06005374{
5375 BcStatus s;
5376
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005377 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005378 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005379 *r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005380
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005381 s = bc_program_num(*r, n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005382 if (s) return s;
5383
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005384 if (!BC_PROG_NUM((*r), (*n)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005385 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005386
5387 return s;
5388}
5389
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005390static void bc_program_retire(BcResult *r, BcResultType t)
Gavin Howard01055ba2018-11-03 11:00:21 -06005391{
5392 r->t = t;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005393 bc_vec_pop(&G.prog.results);
5394 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005395}
5396
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005397static BcStatus bc_program_op(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005398{
5399 BcStatus s;
5400 BcResult *opd1, *opd2, res;
5401 BcNum *n1, *n2 = NULL;
5402
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005403 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005404 if (s) return s;
5405 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5406
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005407 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005408 if (s) goto err;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005409 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005410
5411 return s;
5412
5413err:
5414 bc_num_free(&res.d.n);
5415 return s;
5416}
5417
Denys Vlasenko785e4b32018-12-02 17:18:52 +01005418static BcStatus bc_program_read(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005419{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005420 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005421 BcStatus s;
5422 BcParse parse;
5423 BcVec buf;
5424 BcInstPtr ip;
5425 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005426 BcFunc *f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005427
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005428 for (i = 0; i < G.prog.stack.len; ++i) {
5429 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005430 if (ip_ptr->func == BC_PROG_READ)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005431 return bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005432 }
5433
Denys Vlasenko7d628012018-12-04 21:46:47 +01005434 bc_vec_pop_all(&f->code);
5435 bc_char_vec_init(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005436
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005437 sv_file = G.prog.file;
5438 G.prog.file = NULL;
5439
Gavin Howard01055ba2018-11-03 11:00:21 -06005440 s = bc_read_line(&buf, "read> ");
5441 if (s) goto io_err;
5442
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005443 common_parse_init(&parse, BC_PROG_READ);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005444 bc_lex_file(&parse.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005445
5446 s = bc_parse_text(&parse, buf.v);
5447 if (s) goto exec_err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005448 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
Gavin Howard01055ba2018-11-03 11:00:21 -06005449 if (s) goto exec_err;
5450
5451 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005452 s = bc_error("bad read() expression");
Gavin Howard01055ba2018-11-03 11:00:21 -06005453 goto exec_err;
5454 }
5455
5456 ip.func = BC_PROG_READ;
5457 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005458 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005459
5460 // Update this pointer, just in case.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005461 f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005462
5463 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005464 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06005465
5466exec_err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005467 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005468 bc_parse_free(&parse);
5469io_err:
5470 bc_vec_free(&buf);
5471 return s;
5472}
5473
5474static size_t bc_program_index(char *code, size_t *bgn)
5475{
5476 char amt = code[(*bgn)++], i = 0;
5477 size_t res = 0;
5478
5479 for (; i < amt; ++i, ++(*bgn))
5480 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5481
5482 return res;
5483}
5484
5485static char *bc_program_name(char *code, size_t *bgn)
5486{
5487 size_t i;
5488 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5489
5490 s = xmalloc(ptr - str + 1);
5491 c = code[(*bgn)++];
5492
5493 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5494 s[i] = c;
5495
5496 s[i] = '\0';
5497
5498 return s;
5499}
5500
5501static void bc_program_printString(const char *str, size_t *nchars)
5502{
5503 size_t i, len = strlen(str);
5504
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005505#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005506 if (len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005507 bb_putchar('\0');
Gavin Howard01055ba2018-11-03 11:00:21 -06005508 return;
5509 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005510#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005511
5512 for (i = 0; i < len; ++i, ++(*nchars)) {
5513
5514 int c = str[i];
5515
5516 if (c != '\\' || i == len - 1)
Denys Vlasenko00d77792018-11-30 23:13:42 +01005517 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005518 else {
5519
5520 c = str[++i];
5521
5522 switch (c) {
5523
5524 case 'a':
5525 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005526 bb_putchar('\a');
Gavin Howard01055ba2018-11-03 11:00:21 -06005527 break;
5528 }
5529
5530 case 'b':
5531 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005532 bb_putchar('\b');
Gavin Howard01055ba2018-11-03 11:00:21 -06005533 break;
5534 }
5535
5536 case '\\':
5537 case 'e':
5538 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005539 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005540 break;
5541 }
5542
5543 case 'f':
5544 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005545 bb_putchar('\f');
Gavin Howard01055ba2018-11-03 11:00:21 -06005546 break;
5547 }
5548
5549 case 'n':
5550 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005551 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005552 *nchars = SIZE_MAX;
5553 break;
5554 }
5555
5556 case 'r':
5557 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005558 bb_putchar('\r');
Gavin Howard01055ba2018-11-03 11:00:21 -06005559 break;
5560 }
5561
5562 case 'q':
5563 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005564 bb_putchar('"');
Gavin Howard01055ba2018-11-03 11:00:21 -06005565 break;
5566 }
5567
5568 case 't':
5569 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005570 bb_putchar('\t');
Gavin Howard01055ba2018-11-03 11:00:21 -06005571 break;
5572 }
5573
5574 default:
5575 {
5576 // Just print the backslash and following character.
Denys Vlasenko00d77792018-11-30 23:13:42 +01005577 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005578 ++(*nchars);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005579 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005580 break;
5581 }
5582 }
5583 }
5584 }
5585}
5586
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005587static BcStatus bc_program_print(char inst, size_t idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005588{
5589 BcStatus s = BC_STATUS_SUCCESS;
5590 BcResult *r;
5591 size_t len, i;
5592 char *str;
5593 BcNum *num = NULL;
5594 bool pop = inst != BC_INST_PRINT;
5595
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005596 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005597 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005598
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005599 r = bc_vec_item_rev(&G.prog.results, idx);
5600 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005601 if (s) return s;
5602
5603 if (BC_PROG_NUM(r, num)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005604 s = bc_num_print(num, &G.prog.ob, G.prog.ob_t, !pop, &G.prog.nchars, G.prog.len);
5605 if (!s) bc_num_copy(&G.prog.last, num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005606 }
5607 else {
5608
5609 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005610 str = *((char **) bc_vec_item(&G.prog.strs, idx));
Gavin Howard01055ba2018-11-03 11:00:21 -06005611
5612 if (inst == BC_INST_PRINT_STR) {
5613 for (i = 0, len = strlen(str); i < len; ++i) {
5614 char c = str[i];
Denys Vlasenko00d77792018-11-30 23:13:42 +01005615 bb_putchar(c);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005616 if (c == '\n') G.prog.nchars = SIZE_MAX;
5617 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06005618 }
5619 }
5620 else {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005621 bc_program_printString(str, &G.prog.nchars);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005622 if (inst == BC_INST_PRINT) bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005623 }
5624 }
5625
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005626 if (!s && pop) bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005627
5628 return s;
5629}
5630
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005631static BcStatus bc_program_negate(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005632{
5633 BcStatus s;
5634 BcResult res, *ptr;
5635 BcNum *num = NULL;
5636
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005637 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005638 if (s) return s;
5639
5640 bc_num_init(&res.d.n, num->len);
5641 bc_num_copy(&res.d.n, num);
5642 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5643
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005644 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06005645
5646 return s;
5647}
5648
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005649static BcStatus bc_program_logical(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005650{
5651 BcStatus s;
5652 BcResult *opd1, *opd2, res;
5653 BcNum *n1, *n2;
5654 bool cond = 0;
5655 ssize_t cmp;
5656
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005657 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005658 if (s) return s;
5659 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5660
5661 if (inst == BC_INST_BOOL_AND)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005662 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005663 else if (inst == BC_INST_BOOL_OR)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005664 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005665 else {
5666
5667 cmp = bc_num_cmp(n1, n2);
5668
5669 switch (inst) {
5670
5671 case BC_INST_REL_EQ:
5672 {
5673 cond = cmp == 0;
5674 break;
5675 }
5676
5677 case BC_INST_REL_LE:
5678 {
5679 cond = cmp <= 0;
5680 break;
5681 }
5682
5683 case BC_INST_REL_GE:
5684 {
5685 cond = cmp >= 0;
5686 break;
5687 }
5688
5689 case BC_INST_REL_NE:
5690 {
5691 cond = cmp != 0;
5692 break;
5693 }
5694
5695 case BC_INST_REL_LT:
5696 {
5697 cond = cmp < 0;
5698 break;
5699 }
5700
5701 case BC_INST_REL_GT:
5702 {
5703 cond = cmp > 0;
5704 break;
5705 }
5706 }
5707 }
5708
5709 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5710
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005711 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005712
5713 return s;
5714}
5715
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005716#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005717static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
Gavin Howard01055ba2018-11-03 11:00:21 -06005718 bool push)
5719{
5720 BcNum n2;
5721 BcResult res;
5722
5723 memset(&n2, 0, sizeof(BcNum));
5724 n2.rdx = res.d.id.idx = r->d.id.idx;
5725 res.t = BC_RESULT_STR;
5726
5727 if (!push) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005728 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005729 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005730 bc_vec_pop(v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005731 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005732 }
5733
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005734 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005735
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005736 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005737 bc_vec_push(v, &n2);
5738
5739 return BC_STATUS_SUCCESS;
5740}
5741#endif // ENABLE_DC
5742
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005743static BcStatus bc_program_copyToVar(char *name, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005744{
5745 BcStatus s;
5746 BcResult *ptr, r;
5747 BcVec *v;
5748 BcNum *n;
5749
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005750 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005751 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005752
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005753 ptr = bc_vec_top(&G.prog.results);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005754 if ((ptr->t == BC_RESULT_ARRAY) != !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005755 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005756 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005757
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005758#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005759 if (ptr->t == BC_RESULT_STR && !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005760 return bc_error_variable_is_wrong_type();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005761 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005762#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005763
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005764 s = bc_program_num(ptr, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005765 if (s) return s;
5766
5767 // Do this once more to make sure that pointers were not invalidated.
Denys Vlasenkodf515392018-12-02 19:27:48 +01005768 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005769
5770 if (var) {
5771 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5772 bc_num_copy(&r.d.n, n);
5773 }
5774 else {
5775 bc_array_init(&r.d.v, true);
5776 bc_array_copy(&r.d.v, (BcVec *) n);
5777 }
5778
5779 bc_vec_push(v, &r.d);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005780 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005781
5782 return s;
5783}
5784
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005785static BcStatus bc_program_assign(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005786{
5787 BcStatus s;
5788 BcResult *left, *right, res;
5789 BcNum *l = NULL, *r = NULL;
5790 unsigned long val, max;
5791 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5792
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005793 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
Gavin Howard01055ba2018-11-03 11:00:21 -06005794 if (s) return s;
5795
5796 ib = left->t == BC_RESULT_IBASE;
5797 sc = left->t == BC_RESULT_SCALE;
5798
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005799#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005800
5801 if (right->t == BC_RESULT_STR) {
5802
5803 BcVec *v;
5804
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005805 if (left->t != BC_RESULT_VAR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005806 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005807 v = bc_program_search(left->d.id.name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06005808
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005809 return bc_program_assignStr(right, v, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005810 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005811#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005812
5813 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005814 return bc_error("bad assignment:"
5815 " left side must be scale,"
5816 " ibase, obase, last, var,"
5817 " or array element"
5818 );
Gavin Howard01055ba2018-11-03 11:00:21 -06005819
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005820#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005821 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005822 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06005823
5824 if (assign)
5825 bc_num_copy(l, r);
5826 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005827 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005828
5829 if (s) return s;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005830#else
Gavin Howard01055ba2018-11-03 11:00:21 -06005831 bc_num_copy(l, r);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005832#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005833
5834 if (ib || sc || left->t == BC_RESULT_OBASE) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005835 static const char *const msg[] = {
5836 "bad ibase; must be [2, 16]", //BC_RESULT_IBASE
5837 "bad scale; must be [0, BC_SCALE_MAX]", //BC_RESULT_SCALE
Denys Vlasenkoaad652a2018-12-05 20:33:23 +01005838 NULL, //can't happen //BC_RESULT_LAST
5839 NULL, //can't happen //BC_RESULT_CONSTANT
5840 NULL, //can't happen //BC_RESULT_ONE
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005841 "bad obase; must be [2, BC_BASE_MAX]", //BC_RESULT_OBASE
5842 };
Gavin Howard01055ba2018-11-03 11:00:21 -06005843 size_t *ptr;
5844
5845 s = bc_num_ulong(l, &val);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005846 if (s)
5847 return s;
5848 s = left->t - BC_RESULT_IBASE;
Gavin Howard01055ba2018-11-03 11:00:21 -06005849 if (sc) {
5850 max = BC_MAX_SCALE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005851 ptr = &G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06005852 }
5853 else {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005854 if (val < BC_NUM_MIN_BASE)
5855 return bc_error(msg[s]);
Gavin Howard01055ba2018-11-03 11:00:21 -06005856 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005857 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005858 }
5859
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005860 if (val > max)
5861 return bc_error(msg[s]);
5862 if (!sc)
5863 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005864
5865 *ptr = (size_t) val;
5866 s = BC_STATUS_SUCCESS;
5867 }
5868
5869 bc_num_init(&res.d.n, l->len);
5870 bc_num_copy(&res.d.n, l);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005871 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005872
5873 return s;
5874}
5875
Denys Vlasenko416ce762018-12-02 20:57:17 +01005876#if !ENABLE_DC
5877#define bc_program_pushVar(code, bgn, pop, copy) \
5878 bc_program_pushVar(code, bgn)
5879// for bc, 'pop' and 'copy' are always false
5880#endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005881static BcStatus bc_program_pushVar(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06005882 bool pop, bool copy)
5883{
5884 BcStatus s = BC_STATUS_SUCCESS;
5885 BcResult r;
5886 char *name = bc_program_name(code, bgn);
Gavin Howard01055ba2018-11-03 11:00:21 -06005887
5888 r.t = BC_RESULT_VAR;
5889 r.d.id.name = name;
5890
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005891#if ENABLE_DC
Denys Vlasenko416ce762018-12-02 20:57:17 +01005892 {
5893 BcVec *v = bc_program_search(name, true);
5894 BcNum *num = bc_vec_top(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06005895
Denys Vlasenko416ce762018-12-02 20:57:17 +01005896 if (pop || copy) {
Gavin Howard01055ba2018-11-03 11:00:21 -06005897
Denys Vlasenko416ce762018-12-02 20:57:17 +01005898 if (!BC_PROG_STACK(v, 2 - copy)) {
5899 free(name);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005900 return bc_error_stack_has_too_few_elements();
Denys Vlasenko416ce762018-12-02 20:57:17 +01005901 }
5902
Gavin Howard01055ba2018-11-03 11:00:21 -06005903 free(name);
Denys Vlasenko416ce762018-12-02 20:57:17 +01005904 name = NULL;
5905
5906 if (!BC_PROG_STR(num)) {
5907
5908 r.t = BC_RESULT_TEMP;
5909
5910 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5911 bc_num_copy(&r.d.n, num);
5912 }
5913 else {
5914 r.t = BC_RESULT_STR;
5915 r.d.id.idx = num->rdx;
5916 }
5917
5918 if (!copy) bc_vec_pop(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06005919 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005920 }
5921#endif // ENABLE_DC
5922
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005923 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005924
5925 return s;
5926}
5927
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005928static BcStatus bc_program_pushArray(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06005929 char inst)
5930{
5931 BcStatus s = BC_STATUS_SUCCESS;
5932 BcResult r;
5933 BcNum *num;
5934
5935 r.d.id.name = bc_program_name(code, bgn);
5936
5937 if (inst == BC_INST_ARRAY) {
5938 r.t = BC_RESULT_ARRAY;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005939 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005940 }
5941 else {
5942
5943 BcResult *operand;
5944 unsigned long temp;
5945
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005946 s = bc_program_prep(&operand, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005947 if (s) goto err;
5948 s = bc_num_ulong(num, &temp);
5949 if (s) goto err;
5950
5951 if (temp > BC_MAX_DIM) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005952 s = bc_error("array too long; must be [1, BC_DIM_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06005953 goto err;
5954 }
5955
5956 r.d.id.idx = (size_t) temp;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005957 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
Gavin Howard01055ba2018-11-03 11:00:21 -06005958 }
5959
5960err:
5961 if (s) free(r.d.id.name);
5962 return s;
5963}
5964
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005965#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005966static BcStatus bc_program_incdec(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005967{
5968 BcStatus s;
5969 BcResult *ptr, res, copy;
5970 BcNum *num = NULL;
5971 char inst2 = inst;
5972
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005973 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005974 if (s) return s;
5975
5976 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5977 copy.t = BC_RESULT_TEMP;
5978 bc_num_init(&copy.d.n, num->len);
5979 bc_num_copy(&copy.d.n, num);
5980 }
5981
5982 res.t = BC_RESULT_ONE;
5983 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
5984 BC_INST_ASSIGN_PLUS :
5985 BC_INST_ASSIGN_MINUS;
5986
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005987 bc_vec_push(&G.prog.results, &res);
5988 bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06005989
5990 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005991 bc_vec_pop(&G.prog.results);
5992 bc_vec_push(&G.prog.results, &copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06005993 }
5994
5995 return s;
5996}
5997
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005998static BcStatus bc_program_call(char *code, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005999{
6000 BcStatus s = BC_STATUS_SUCCESS;
6001 BcInstPtr ip;
6002 size_t i, nparams = bc_program_index(code, idx);
6003 BcFunc *func;
Gavin Howard01055ba2018-11-03 11:00:21 -06006004 BcId *a;
6005 BcResultData param;
6006 BcResult *arg;
6007
6008 ip.idx = 0;
6009 ip.func = bc_program_index(code, idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006010 func = bc_vec_item(&G.prog.fns, ip.func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006011
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006012 if (func->code.len == 0) {
6013 return bc_error("undefined function");
6014 }
6015 if (nparams != func->nparams) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006016 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006017 }
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006018 ip.len = G.prog.results.len - nparams;
Gavin Howard01055ba2018-11-03 11:00:21 -06006019
6020 for (i = 0; i < nparams; ++i) {
6021
6022 a = bc_vec_item(&func->autos, nparams - 1 - i);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006023 arg = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006024
6025 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006026 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006027
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006028 s = bc_program_copyToVar(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006029 if (s) return s;
6030 }
6031
6032 for (; i < func->autos.len; ++i) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006033 BcVec *v;
Gavin Howard01055ba2018-11-03 11:00:21 -06006034
6035 a = bc_vec_item(&func->autos, i);
Denys Vlasenkodf515392018-12-02 19:27:48 +01006036 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006037
6038 if (a->idx) {
6039 bc_num_init(&param.n, BC_NUM_DEF_SIZE);
6040 bc_vec_push(v, &param.n);
6041 }
6042 else {
6043 bc_array_init(&param.v, true);
6044 bc_vec_push(v, &param.v);
6045 }
6046 }
6047
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006048 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006049
6050 return BC_STATUS_SUCCESS;
6051}
6052
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006053static BcStatus bc_program_return(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006054{
6055 BcStatus s;
6056 BcResult res;
6057 BcFunc *f;
6058 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006059 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006060
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006061 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006062 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006063
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006064 f = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006065 res.t = BC_RESULT_TEMP;
6066
6067 if (inst == BC_INST_RET) {
6068
6069 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006070 BcResult *operand = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006071
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006072 s = bc_program_num(operand, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006073 if (s) return s;
6074 bc_num_init(&res.d.n, num->len);
6075 bc_num_copy(&res.d.n, num);
6076 }
6077 else {
6078 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6079 bc_num_zero(&res.d.n);
6080 }
6081
6082 // We need to pop arguments as well, so this takes that into account.
6083 for (i = 0; i < f->autos.len; ++i) {
6084
6085 BcVec *v;
6086 BcId *a = bc_vec_item(&f->autos, i);
6087
Denys Vlasenkodf515392018-12-02 19:27:48 +01006088 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006089 bc_vec_pop(v);
6090 }
6091
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006092 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6093 bc_vec_push(&G.prog.results, &res);
6094 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006095
6096 return BC_STATUS_SUCCESS;
6097}
6098#endif // ENABLE_BC
6099
6100static unsigned long bc_program_scale(BcNum *n)
6101{
6102 return (unsigned long) n->rdx;
6103}
6104
6105static unsigned long bc_program_len(BcNum *n)
6106{
6107 unsigned long len = n->len;
6108 size_t i;
6109
6110 if (n->rdx != n->len) return len;
6111 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6112
6113 return len;
6114}
6115
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006116static BcStatus bc_program_builtin(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006117{
6118 BcStatus s;
6119 BcResult *opnd;
6120 BcNum *num = NULL;
6121 BcResult res;
6122 bool len = inst == BC_INST_LENGTH;
6123
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006124 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006125 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006126 opnd = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006127
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006128 s = bc_program_num(opnd, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006129 if (s) return s;
6130
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006131#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006132 if (!BC_PROG_NUM(opnd, num) && !len)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006133 return bc_error_variable_is_wrong_type();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006134#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006135
6136 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6137
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006138 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006139#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006140 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006141 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006142 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006143#endif
6144#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006145 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6146
6147 char **str;
6148 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6149
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006150 str = bc_vec_item(&G.prog.strs, idx);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006151 bc_num_ulong2num(&res.d.n, strlen(*str));
Gavin Howard01055ba2018-11-03 11:00:21 -06006152 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006153#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006154 else {
6155 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006156 bc_num_ulong2num(&res.d.n, f(num));
Gavin Howard01055ba2018-11-03 11:00:21 -06006157 }
6158
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006159 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006160
6161 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006162}
6163
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006164#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006165static BcStatus bc_program_divmod(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006166{
6167 BcStatus s;
6168 BcResult *opd1, *opd2, res, res2;
6169 BcNum *n1, *n2 = NULL;
6170
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006171 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006172 if (s) return s;
6173
6174 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6175 bc_num_init(&res2.d.n, n2->len);
6176
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006177 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006178 if (s) goto err;
6179
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006180 bc_program_binOpRetire(&res2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006181 res.t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006182 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006183
6184 return s;
6185
6186err:
6187 bc_num_free(&res2.d.n);
6188 bc_num_free(&res.d.n);
6189 return s;
6190}
6191
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006192static BcStatus bc_program_modexp(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006193{
6194 BcStatus s;
6195 BcResult *r1, *r2, *r3, res;
6196 BcNum *n1, *n2, *n3;
6197
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006198 if (!BC_PROG_STACK(&G.prog.results, 3))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006199 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006200 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006201 if (s) return s;
6202
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006203 r1 = bc_vec_item_rev(&G.prog.results, 2);
6204 s = bc_program_num(r1, &n1, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006205 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006206 if (!BC_PROG_NUM(r1, n1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006207 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006208
6209 // Make sure that the values have their pointers updated, if necessary.
6210 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6211
6212 if (r1->t == r2->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006213 s = bc_program_num(r2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006214 if (s) return s;
6215 }
6216
6217 if (r1->t == r3->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006218 s = bc_program_num(r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006219 if (s) return s;
6220 }
6221 }
6222
6223 bc_num_init(&res.d.n, n3->len);
6224 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6225 if (s) goto err;
6226
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006227 bc_vec_pop(&G.prog.results);
6228 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006229
6230 return s;
6231
6232err:
6233 bc_num_free(&res.d.n);
6234 return s;
6235}
6236
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006237static void bc_program_stackLen(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006238{
Gavin Howard01055ba2018-11-03 11:00:21 -06006239 BcResult res;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006240 size_t len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006241
6242 res.t = BC_RESULT_TEMP;
6243
6244 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006245 bc_num_ulong2num(&res.d.n, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006246 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006247}
6248
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006249static BcStatus bc_program_asciify(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006250{
6251 BcStatus s;
6252 BcResult *r, res;
6253 BcNum *num = NULL, n;
6254 char *str, *str2, c;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006255 size_t len = G.prog.strs.len, idx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006256 unsigned long val;
6257
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006258 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006259 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006260 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006261
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006262 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006263 if (s) return s;
6264
6265 if (BC_PROG_NUM(r, num)) {
6266
6267 bc_num_init(&n, BC_NUM_DEF_SIZE);
6268 bc_num_copy(&n, num);
6269 bc_num_truncate(&n, n.rdx);
6270
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006271 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006272 if (s) goto num_err;
6273 s = bc_num_ulong(&n, &val);
6274 if (s) goto num_err;
6275
6276 c = (char) val;
6277
6278 bc_num_free(&n);
6279 }
6280 else {
6281 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006282 str2 = *((char **) bc_vec_item(&G.prog.strs, idx));
Gavin Howard01055ba2018-11-03 11:00:21 -06006283 c = str2[0];
6284 }
6285
6286 str = xmalloc(2);
6287 str[0] = c;
6288 str[1] = '\0';
6289
6290 str2 = xstrdup(str);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006291 bc_program_addFunc(str2, &idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006292
6293 if (idx != len + BC_PROG_REQ_FUNCS) {
6294
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006295 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6296 if (!strcmp(*((char **) bc_vec_item(&G.prog.strs, idx)), str)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006297 len = idx;
6298 break;
6299 }
6300 }
6301
6302 free(str);
6303 }
6304 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006305 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006306
6307 res.t = BC_RESULT_STR;
6308 res.d.id.idx = len;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006309 bc_vec_pop(&G.prog.results);
6310 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006311
6312 return BC_STATUS_SUCCESS;
6313
6314num_err:
6315 bc_num_free(&n);
6316 return s;
6317}
6318
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006319static BcStatus bc_program_printStream(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006320{
6321 BcStatus s;
6322 BcResult *r;
6323 BcNum *n = NULL;
6324 size_t idx;
6325 char *str;
6326
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006327 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006328 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006329 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006330
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006331 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006332 if (s) return s;
6333
6334 if (BC_PROG_NUM(r, n))
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006335 s = bc_num_stream(n, &G.prog.strmb, &G.prog.nchars, G.prog.len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006336 else {
6337 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006338 str = *((char **) bc_vec_item(&G.prog.strs, idx));
Denys Vlasenko00d77792018-11-30 23:13:42 +01006339 printf("%s", str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006340 }
6341
6342 return s;
6343}
6344
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006345static BcStatus bc_program_nquit(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006346{
6347 BcStatus s;
6348 BcResult *opnd;
6349 BcNum *num = NULL;
6350 unsigned long val;
6351
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006352 s = bc_program_prep(&opnd, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006353 if (s) return s;
6354 s = bc_num_ulong(num, &val);
6355 if (s) return s;
6356
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006357 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006358
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006359 if (G.prog.stack.len < val)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006360 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006361 if (G.prog.stack.len == val) {
6362 if (ENABLE_FEATURE_CLEAN_UP)
6363 return BC_STATUS_FAILURE;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006364 quit();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006365 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006366
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006367 bc_vec_npop(&G.prog.stack, val);
Gavin Howard01055ba2018-11-03 11:00:21 -06006368
6369 return s;
6370}
6371
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006372static BcStatus bc_program_execStr(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006373 bool cond)
6374{
6375 BcStatus s = BC_STATUS_SUCCESS;
6376 BcResult *r;
6377 char **str;
6378 BcFunc *f;
6379 BcParse prs;
6380 BcInstPtr ip;
6381 size_t fidx, sidx;
6382 BcNum *n;
6383 bool exec;
6384
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006385 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006386 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006387
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006388 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006389
6390 if (cond) {
6391
Gavin Howard01055ba2018-11-03 11:00:21 -06006392 char *name, *then_name = bc_program_name(code, bgn), *else_name = NULL;
6393
6394 if (code[*bgn] == BC_PARSE_STREND)
6395 (*bgn) += 1;
6396 else
6397 else_name = bc_program_name(code, bgn);
6398
6399 exec = r->d.n.len != 0;
6400
6401 if (exec)
6402 name = then_name;
6403 else if (else_name != NULL) {
6404 exec = true;
6405 name = else_name;
6406 }
6407
6408 if (exec) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006409 BcVec *v;
6410 v = bc_program_search(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006411 n = bc_vec_top(v);
6412 }
6413
6414 free(then_name);
6415 free(else_name);
6416
6417 if (!exec) goto exit;
6418 if (!BC_PROG_STR(n)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006419 s = bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006420 goto exit;
6421 }
6422
6423 sidx = n->rdx;
6424 }
6425 else {
6426
6427 if (r->t == BC_RESULT_STR)
6428 sidx = r->d.id.idx;
6429 else if (r->t == BC_RESULT_VAR) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006430 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006431 if (s || !BC_PROG_STR(n)) goto exit;
6432 sidx = n->rdx;
6433 }
6434 else
6435 goto exit;
6436 }
6437
6438 fidx = sidx + BC_PROG_REQ_FUNCS;
6439
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006440 str = bc_vec_item(&G.prog.strs, sidx);
6441 f = bc_vec_item(&G.prog.fns, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006442
6443 if (f->code.len == 0) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006444 common_parse_init(&prs, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006445 s = bc_parse_text(&prs, *str);
6446 if (s) goto err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01006447 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006448 if (s) goto err;
6449
6450 if (prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006451 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06006452 goto err;
6453 }
6454
6455 bc_parse_free(&prs);
6456 }
6457
6458 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006459 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006460 ip.func = fidx;
6461
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006462 bc_vec_pop(&G.prog.results);
6463 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006464
6465 return BC_STATUS_SUCCESS;
6466
6467err:
6468 bc_parse_free(&prs);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006469 f = bc_vec_item(&G.prog.fns, fidx);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006470 bc_vec_pop_all(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06006471exit:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006472 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006473 return s;
6474}
6475#endif // ENABLE_DC
6476
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006477static void bc_program_pushGlobal(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006478{
Gavin Howard01055ba2018-11-03 11:00:21 -06006479 BcResult res;
6480 unsigned long val;
6481
6482 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6483 if (inst == BC_INST_IBASE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006484 val = (unsigned long) G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006485 else if (inst == BC_INST_SCALE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006486 val = (unsigned long) G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006487 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006488 val = (unsigned long) G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006489
6490 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006491 bc_num_ulong2num(&res.d.n, val);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006492 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006493}
6494
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006495static void bc_program_addFunc(char *name, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006496{
Gavin Howard01055ba2018-11-03 11:00:21 -06006497 BcId entry, *entry_ptr;
6498 BcFunc f;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006499 int inserted;
Gavin Howard01055ba2018-11-03 11:00:21 -06006500
6501 entry.name = name;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006502 entry.idx = G.prog.fns.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006503
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006504 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6505 if (!inserted) free(name);
Gavin Howard01055ba2018-11-03 11:00:21 -06006506
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006507 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006508 *idx = entry_ptr->idx;
6509
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006510 if (!inserted) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006511
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006512 BcFunc *func = bc_vec_item(&G.prog.fns, entry_ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006513
6514 // We need to reset these, so the function can be repopulated.
6515 func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01006516 bc_vec_pop_all(&func->autos);
6517 bc_vec_pop_all(&func->code);
6518 bc_vec_pop_all(&func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06006519 }
6520 else {
6521 bc_func_init(&f);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006522 bc_vec_push(&G.prog.fns, &f);
Gavin Howard01055ba2018-11-03 11:00:21 -06006523 }
6524}
6525
Denys Vlasenkod38af482018-12-04 19:11:02 +01006526// Called when parsing or execution detects a failure,
6527// resets execution structures.
6528static void bc_program_reset(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006529{
6530 BcFunc *f;
6531 BcInstPtr *ip;
6532
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006533 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006534 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006535
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006536 f = bc_vec_item(&G.prog.fns, 0);
6537 ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006538 ip->idx = f->code.len;
6539
Denys Vlasenkod38af482018-12-04 19:11:02 +01006540 // If !tty, no need to check for ^C: we don't have ^C handler,
6541 // we would be killed by a signal and won't reach this place
Gavin Howard01055ba2018-11-03 11:00:21 -06006542}
6543
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006544static BcStatus bc_program_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006545{
6546 BcStatus s = BC_STATUS_SUCCESS;
6547 size_t idx;
6548 BcResult r, *ptr;
6549 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006550 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6551 BcFunc *func = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006552 char *code = func->code.v;
6553 bool cond = false;
6554
6555 while (!s && ip->idx < func->code.len) {
6556
6557 char inst = code[(ip->idx)++];
6558
6559 switch (inst) {
6560
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006561#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006562 case BC_INST_JUMP_ZERO:
6563 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006564 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006565 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006566 cond = !bc_num_cmp(num, &G.prog.zero);
6567 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006568 }
6569 // Fallthrough.
6570 case BC_INST_JUMP:
6571 {
6572 size_t *addr;
6573 idx = bc_program_index(code, &ip->idx);
6574 addr = bc_vec_item(&func->labels, idx);
6575 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6576 break;
6577 }
6578
6579 case BC_INST_CALL:
6580 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006581 s = bc_program_call(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006582 break;
6583 }
6584
6585 case BC_INST_INC_PRE:
6586 case BC_INST_DEC_PRE:
6587 case BC_INST_INC_POST:
6588 case BC_INST_DEC_POST:
6589 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006590 s = bc_program_incdec(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006591 break;
6592 }
6593
6594 case BC_INST_HALT:
6595 {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006596 quit_or_return_for_exit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006597 break;
6598 }
6599
6600 case BC_INST_RET:
6601 case BC_INST_RET0:
6602 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006603 s = bc_program_return(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006604 break;
6605 }
6606
6607 case BC_INST_BOOL_OR:
6608 case BC_INST_BOOL_AND:
6609#endif // ENABLE_BC
6610 case BC_INST_REL_EQ:
6611 case BC_INST_REL_LE:
6612 case BC_INST_REL_GE:
6613 case BC_INST_REL_NE:
6614 case BC_INST_REL_LT:
6615 case BC_INST_REL_GT:
6616 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006617 s = bc_program_logical(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006618 break;
6619 }
6620
6621 case BC_INST_READ:
6622 {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006623 s = bc_program_read();
Gavin Howard01055ba2018-11-03 11:00:21 -06006624 break;
6625 }
6626
6627 case BC_INST_VAR:
6628 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006629 s = bc_program_pushVar(code, &ip->idx, false, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006630 break;
6631 }
6632
6633 case BC_INST_ARRAY_ELEM:
6634 case BC_INST_ARRAY:
6635 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006636 s = bc_program_pushArray(code, &ip->idx, inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006637 break;
6638 }
6639
6640 case BC_INST_LAST:
6641 {
6642 r.t = BC_RESULT_LAST;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006643 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006644 break;
6645 }
6646
6647 case BC_INST_IBASE:
6648 case BC_INST_SCALE:
6649 case BC_INST_OBASE:
6650 {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006651 bc_program_pushGlobal(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006652 break;
6653 }
6654
6655 case BC_INST_SCALE_FUNC:
6656 case BC_INST_LENGTH:
6657 case BC_INST_SQRT:
6658 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006659 s = bc_program_builtin(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006660 break;
6661 }
6662
6663 case BC_INST_NUM:
6664 {
6665 r.t = BC_RESULT_CONSTANT;
6666 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006667 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006668 break;
6669 }
6670
6671 case BC_INST_POP:
6672 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006673 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006674 s = bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006675 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006676 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006677 break;
6678 }
6679
6680 case BC_INST_POP_EXEC:
6681 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006682 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006683 break;
6684 }
6685
6686 case BC_INST_PRINT:
6687 case BC_INST_PRINT_POP:
6688 case BC_INST_PRINT_STR:
6689 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006690 s = bc_program_print(inst, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006691 break;
6692 }
6693
6694 case BC_INST_STR:
6695 {
6696 r.t = BC_RESULT_STR;
6697 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006698 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006699 break;
6700 }
6701
6702 case BC_INST_POWER:
6703 case BC_INST_MULTIPLY:
6704 case BC_INST_DIVIDE:
6705 case BC_INST_MODULUS:
6706 case BC_INST_PLUS:
6707 case BC_INST_MINUS:
6708 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006709 s = bc_program_op(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006710 break;
6711 }
6712
6713 case BC_INST_BOOL_NOT:
6714 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006715 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006716 if (s) return s;
6717
6718 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006719 (!bc_num_cmp(num, &G.prog.zero) ? bc_num_one : bc_num_zero)(&r.d.n);
6720 bc_program_retire(&r, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006721
6722 break;
6723 }
6724
6725 case BC_INST_NEG:
6726 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006727 s = bc_program_negate();
Gavin Howard01055ba2018-11-03 11:00:21 -06006728 break;
6729 }
6730
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006731#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006732 case BC_INST_ASSIGN_POWER:
6733 case BC_INST_ASSIGN_MULTIPLY:
6734 case BC_INST_ASSIGN_DIVIDE:
6735 case BC_INST_ASSIGN_MODULUS:
6736 case BC_INST_ASSIGN_PLUS:
6737 case BC_INST_ASSIGN_MINUS:
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006738#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006739 case BC_INST_ASSIGN:
6740 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006741 s = bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006742 break;
6743 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006744#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006745 case BC_INST_MODEXP:
6746 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006747 s = bc_program_modexp();
Gavin Howard01055ba2018-11-03 11:00:21 -06006748 break;
6749 }
6750
6751 case BC_INST_DIVMOD:
6752 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006753 s = bc_program_divmod();
Gavin Howard01055ba2018-11-03 11:00:21 -06006754 break;
6755 }
6756
6757 case BC_INST_EXECUTE:
6758 case BC_INST_EXEC_COND:
6759 {
6760 cond = inst == BC_INST_EXEC_COND;
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006761 s = bc_program_execStr(code, &ip->idx, cond);
Gavin Howard01055ba2018-11-03 11:00:21 -06006762 break;
6763 }
6764
6765 case BC_INST_PRINT_STACK:
6766 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006767 for (idx = 0; !s && idx < G.prog.results.len; ++idx)
6768 s = bc_program_print(BC_INST_PRINT, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006769 break;
6770 }
6771
6772 case BC_INST_CLEAR_STACK:
6773 {
Denys Vlasenko7d628012018-12-04 21:46:47 +01006774 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006775 break;
6776 }
6777
6778 case BC_INST_STACK_LEN:
6779 {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006780 bc_program_stackLen();
Gavin Howard01055ba2018-11-03 11:00:21 -06006781 break;
6782 }
6783
6784 case BC_INST_DUPLICATE:
6785 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006786 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006787 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006788 ptr = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006789 bc_result_copy(&r, ptr);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006790 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006791 break;
6792 }
6793
6794 case BC_INST_SWAP:
6795 {
6796 BcResult *ptr2;
6797
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006798 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006799 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006800
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006801 ptr = bc_vec_item_rev(&G.prog.results, 0);
6802 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006803 memcpy(&r, ptr, sizeof(BcResult));
6804 memcpy(ptr, ptr2, sizeof(BcResult));
6805 memcpy(ptr2, &r, sizeof(BcResult));
6806
6807 break;
6808 }
6809
6810 case BC_INST_ASCIIFY:
6811 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006812 s = bc_program_asciify();
Gavin Howard01055ba2018-11-03 11:00:21 -06006813 break;
6814 }
6815
6816 case BC_INST_PRINT_STREAM:
6817 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006818 s = bc_program_printStream();
Gavin Howard01055ba2018-11-03 11:00:21 -06006819 break;
6820 }
6821
6822 case BC_INST_LOAD:
6823 case BC_INST_PUSH_VAR:
6824 {
6825 bool copy = inst == BC_INST_LOAD;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006826 s = bc_program_pushVar(code, &ip->idx, true, copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006827 break;
6828 }
6829
6830 case BC_INST_PUSH_TO_VAR:
6831 {
6832 char *name = bc_program_name(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006833 s = bc_program_copyToVar(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006834 free(name);
6835 break;
6836 }
6837
6838 case BC_INST_QUIT:
6839 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006840 if (G.prog.stack.len <= 2)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006841 quit_or_return_for_exit();
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006842 bc_vec_npop(&G.prog.stack, 2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006843 break;
6844 }
6845
6846 case BC_INST_NQUIT:
6847 {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006848 s = bc_program_nquit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006849 break;
6850 }
6851#endif // ENABLE_DC
6852 }
6853
Denys Vlasenkod38af482018-12-04 19:11:02 +01006854 if (s || G_interrupt) {
6855 bc_program_reset();
6856 break;
6857 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006858
6859 // If the stack has changed, pointers may be invalid.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006860 ip = bc_vec_top(&G.prog.stack);
6861 func = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006862 code = func->code.v;
6863 }
6864
6865 return s;
6866}
6867
Denys Vlasenko54214c32018-12-06 09:07:06 +01006868static void bc_vm_info(void)
6869{
6870 printf("%s "BB_VER"\n"
6871 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6872 "Report bugs at: https://github.com/gavinhoward/bc\n"
6873 "This is free software with ABSOLUTELY NO WARRANTY\n"
6874 , applet_name);
6875}
6876
6877static void bc_args(char **argv)
6878{
6879 unsigned opts;
6880 int i;
6881
6882 GETOPT_RESET();
6883#if ENABLE_FEATURE_BC_LONG_OPTIONS
6884 opts = option_mask32 |= getopt32long(argv, "xwvsqli",
6885 "extended-register\0" No_argument "x"
6886 "warn\0" No_argument "w"
6887 "version\0" No_argument "v"
6888 "standard\0" No_argument "s"
6889 "quiet\0" No_argument "q"
6890 "mathlib\0" No_argument "l"
6891 "interactive\0" No_argument "i"
6892 );
6893#else
6894 opts = option_mask32 |= getopt32(argv, "xwvsqli");
6895#endif
6896 if (getenv("POSIXLY_CORRECT"))
6897 option_mask32 |= BC_FLAG_S;
6898
6899///should be in bc_vm_run() instead??
6900 if (opts & BC_FLAG_V) {
6901 bc_vm_info();
6902 exit(0);
6903 }
6904
6905 for (i = optind; argv[i]; ++i)
6906 bc_vec_push(&G.files, argv + i);
6907}
6908
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006909#if ENABLE_BC
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006910static void bc_vm_envArgs(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006911{
Gavin Howard01055ba2018-11-03 11:00:21 -06006912 BcVec v;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006913 char *buf;
Denys Vlasenko54214c32018-12-06 09:07:06 +01006914 char *env_args = getenv("BC_ENV_ARGS");
Gavin Howard01055ba2018-11-03 11:00:21 -06006915
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01006916 if (!env_args) return;
Gavin Howard01055ba2018-11-03 11:00:21 -06006917
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006918 G.env_args = xstrdup(env_args);
6919 buf = G.env_args;
Gavin Howard01055ba2018-11-03 11:00:21 -06006920
6921 bc_vec_init(&v, sizeof(char *), NULL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006922
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006923 while (*(buf = skip_whitespace(buf)) != '\0') {
6924 bc_vec_push(&v, &buf);
6925 buf = skip_non_whitespace(buf);
6926 if (!*buf)
6927 break;
6928 *buf++ = '\0';
Gavin Howard01055ba2018-11-03 11:00:21 -06006929 }
6930
Denys Vlasenko54214c32018-12-06 09:07:06 +01006931 // NULL terminate, and pass argv[] so that first arg is argv[1]
6932 if (sizeof(int) == sizeof(char*)) {
6933 bc_vec_push(&v, &const_int_0);
6934 } else {
6935 static char *const nullptr = NULL;
6936 bc_vec_push(&v, &nullptr);
6937 }
6938 bc_args(((char **)v.v) - 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006939
6940 bc_vec_free(&v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006941}
6942#endif // ENABLE_BC
6943
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006944static unsigned bc_vm_envLen(const char *var)
Gavin Howard01055ba2018-11-03 11:00:21 -06006945{
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006946 char *lenv;
6947 unsigned len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006948
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006949 lenv = getenv(var);
6950 len = BC_NUM_PRINT_WIDTH;
Gavin Howard01055ba2018-11-03 11:00:21 -06006951 if (!lenv) return len;
6952
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006953 len = bb_strtou(lenv, NULL, 10) - 1;
6954 if (errno || len < 2 || len >= INT_MAX)
Gavin Howard01055ba2018-11-03 11:00:21 -06006955 len = BC_NUM_PRINT_WIDTH;
6956
6957 return len;
6958}
6959
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006960static BcStatus bc_vm_process(const char *text)
Gavin Howard01055ba2018-11-03 11:00:21 -06006961{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006962 BcStatus s = bc_parse_text(&G.prs, text);
Gavin Howard01055ba2018-11-03 11:00:21 -06006963
Gavin Howard01055ba2018-11-03 11:00:21 -06006964 if (s) return s;
6965
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006966 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006967 s = G.prs.parse(&G.prs);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006968 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006969 }
6970
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006971 if (BC_PARSE_CAN_EXEC(&G.prs)) {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006972 s = bc_program_exec();
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01006973 fflush_and_check();
Denys Vlasenko9b70f192018-12-04 20:51:40 +01006974 if (s)
Denys Vlasenkod38af482018-12-04 19:11:02 +01006975 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06006976 }
6977
6978 return s;
6979}
6980
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006981static BcStatus bc_vm_file(const char *file)
Gavin Howard01055ba2018-11-03 11:00:21 -06006982{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01006983 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06006984 char *data;
Denys Vlasenko0409ad32018-12-05 16:39:22 +01006985 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006986 BcFunc *main_func;
6987 BcInstPtr *ip;
6988
Denys Vlasenkodf515392018-12-02 19:27:48 +01006989 data = bc_read_file(file);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006990 if (!data) return bc_error_fmt("file '%s' is not text", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06006991
Denys Vlasenko0409ad32018-12-05 16:39:22 +01006992 sv_file = G.prog.file;
6993 G.prog.file = file;
6994 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006995 s = bc_vm_process(data);
Gavin Howard01055ba2018-11-03 11:00:21 -06006996 if (s) goto err;
6997
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006998 main_func = bc_vec_item(&G.prog.fns, BC_PROG_MAIN);
6999 ip = bc_vec_item(&G.prog.stack, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06007000
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007001 if (main_func->code.len < ip->idx)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007002 s = bc_error_fmt("file '%s' is not executable", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007003
7004err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007005 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007006 free(data);
7007 return s;
7008}
7009
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007010static BcStatus bc_vm_stdin(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007011{
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007012 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007013 BcVec buf, buffer;
Gavin Howard01055ba2018-11-03 11:00:21 -06007014 size_t len, i, str = 0;
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007015 bool comment = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06007016
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007017 G.prog.file = NULL;
7018 bc_lex_file(&G.prs.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06007019
Denys Vlasenko7d628012018-12-04 21:46:47 +01007020 bc_char_vec_init(&buffer);
7021 bc_char_vec_init(&buf);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01007022 bc_vec_pushZeroByte(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007023
7024 // This loop is complex because the vm tries not to send any lines that end
7025 // with a backslash to the parser. The reason for that is because the parser
7026 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7027 // case, and for strings and comments, the parser will expect more stuff.
Denys Vlasenko657d6bb2018-12-05 20:25:03 +01007028 s = BC_STATUS_SUCCESS;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01007029 while (!G.eof && (s = bc_read_line(&buf, ">>> ")) == BC_STATUS_SUCCESS) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007030
7031 char *string = buf.v;
7032
7033 len = buf.len - 1;
7034
7035 if (len == 1) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007036 if (str && buf.v[0] == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007037 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007038 else if (buf.v[0] == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007039 str += 1;
7040 }
7041 else if (len > 1 || comment) {
7042
7043 for (i = 0; i < len; ++i) {
7044
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007045 bool notend = len > i + 1;
7046 char c = string[i];
Gavin Howard01055ba2018-11-03 11:00:21 -06007047
7048 if (i - 1 > len || string[i - 1] != '\\') {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007049 if (G.sbgn == G.send)
7050 str ^= c == G.sbgn;
7051 else if (c == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007052 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007053 else if (c == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007054 str += 1;
7055 }
7056
7057 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7058 comment = true;
7059 break;
7060 }
7061 else if (c == '*' && notend && comment && string[i + 1] == '/')
7062 comment = false;
7063 }
7064
7065 if (str || comment || string[len - 2] == '\\') {
7066 bc_vec_concat(&buffer, buf.v);
7067 continue;
7068 }
7069 }
7070
7071 bc_vec_concat(&buffer, buf.v);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007072 s = bc_vm_process(buffer.v);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007073 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007074 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007075 // Debug config, non-interactive mode:
7076 // return all the way back to main.
7077 // Non-debug builds do not come here, they exit.
7078 break;
7079 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007080 fflush_and_check();
7081 fputs("ready for more input\n", stderr);
7082 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007083
Denys Vlasenko7d628012018-12-04 21:46:47 +01007084 bc_vec_pop_all(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007085 }
7086
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007087 if (str) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007088 s = bc_error("string end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007089 }
7090 else if (comment) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007091 s = bc_error("comment end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007092 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007093
Gavin Howard01055ba2018-11-03 11:00:21 -06007094 bc_vec_free(&buf);
7095 bc_vec_free(&buffer);
7096 return s;
7097}
7098
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007099#if ENABLE_BC
7100static const char bc_lib[] = {
7101 "scale=20"
7102"\n" "define e(x){"
7103"\n" "auto b,s,n,r,d,i,p,f,v"
7104"\n" "b=ibase"
7105"\n" "ibase=A"
7106"\n" "if(x<0){"
7107"\n" "n=1"
7108"\n" "x=-x"
7109"\n" "}"
7110"\n" "s=scale"
7111"\n" "r=6+s+0.44*x"
7112"\n" "scale=scale(x)+1"
7113"\n" "while(x>1){"
7114"\n" "d+=1"
7115"\n" "x/=2"
7116"\n" "scale+=1"
7117"\n" "}"
7118"\n" "scale=r"
7119"\n" "r=x+1"
7120"\n" "p=x"
7121"\n" "f=v=1"
7122"\n" "for(i=2;v!=0;++i){"
7123"\n" "p*=x"
7124"\n" "f*=i"
7125"\n" "v=p/f"
7126"\n" "r+=v"
7127"\n" "}"
7128"\n" "while((d--)!=0)r*=r"
7129"\n" "scale=s"
7130"\n" "ibase=b"
7131"\n" "if(n!=0)return(1/r)"
7132"\n" "return(r/1)"
7133"\n" "}"
7134"\n" "define l(x){"
7135"\n" "auto b,s,r,p,a,q,i,v"
7136"\n" "b=ibase"
7137"\n" "ibase=A"
7138"\n" "if(x<=0){"
7139"\n" "r=(1-10^scale)/1"
7140"\n" "ibase=b"
7141"\n" "return(r)"
7142"\n" "}"
7143"\n" "s=scale"
7144"\n" "scale+=6"
7145"\n" "p=2"
7146"\n" "while(x>=2){"
7147"\n" "p*=2"
7148"\n" "x=sqrt(x)"
7149"\n" "}"
7150"\n" "while(x<=0.5){"
7151"\n" "p*=2"
7152"\n" "x=sqrt(x)"
7153"\n" "}"
7154"\n" "r=a=(x-1)/(x+1)"
7155"\n" "q=a*a"
7156"\n" "v=1"
7157"\n" "for(i=3;v!=0;i+=2){"
7158"\n" "a*=q"
7159"\n" "v=a/i"
7160"\n" "r+=v"
7161"\n" "}"
7162"\n" "r*=p"
7163"\n" "scale=s"
7164"\n" "ibase=b"
7165"\n" "return(r/1)"
7166"\n" "}"
7167"\n" "define s(x){"
7168"\n" "auto b,s,r,n,a,q,i"
7169"\n" "b=ibase"
7170"\n" "ibase=A"
7171"\n" "s=scale"
7172"\n" "scale=1.1*s+2"
7173"\n" "a=a(1)"
7174"\n" "if(x<0){"
7175"\n" "n=1"
7176"\n" "x=-x"
7177"\n" "}"
7178"\n" "scale=0"
7179"\n" "q=(x/a+2)/4"
7180"\n" "x=x-4*q*a"
7181"\n" "if(q%2!=0)x=-x"
7182"\n" "scale=s+2"
7183"\n" "r=a=x"
7184"\n" "q=-x*x"
7185"\n" "for(i=3;a!=0;i+=2){"
7186"\n" "a*=q/(i*(i-1))"
7187"\n" "r+=a"
7188"\n" "}"
7189"\n" "scale=s"
7190"\n" "ibase=b"
7191"\n" "if(n!=0)return(-r/1)"
7192"\n" "return(r/1)"
7193"\n" "}"
7194"\n" "define c(x){"
7195"\n" "auto b,s"
7196"\n" "b=ibase"
7197"\n" "ibase=A"
7198"\n" "s=scale"
7199"\n" "scale*=1.2"
7200"\n" "x=s(2*a(1)+x)"
7201"\n" "scale=s"
7202"\n" "ibase=b"
7203"\n" "return(x/1)"
7204"\n" "}"
7205"\n" "define a(x){"
7206"\n" "auto b,s,r,n,a,m,t,f,i,u"
7207"\n" "b=ibase"
7208"\n" "ibase=A"
7209"\n" "n=1"
7210"\n" "if(x<0){"
7211"\n" "n=-1"
7212"\n" "x=-x"
7213"\n" "}"
7214"\n" "if(x==1){"
7215"\n" "if(scale<65){"
7216"\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7217"\n" "}"
7218"\n" "}"
7219"\n" "if(x==.2){"
7220"\n" "if(scale<65){"
7221"\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7222"\n" "}"
7223"\n" "}"
7224"\n" "s=scale"
7225"\n" "if(x>.2){"
7226"\n" "scale+=5"
7227"\n" "a=a(.2)"
7228"\n" "}"
7229"\n" "scale=s+3"
7230"\n" "while(x>.2){"
7231"\n" "m+=1"
7232"\n" "x=(x-.2)/(1+.2*x)"
7233"\n" "}"
7234"\n" "r=u=x"
7235"\n" "f=-x*x"
7236"\n" "t=1"
7237"\n" "for(i=3;t!=0;i+=2){"
7238"\n" "u*=f"
7239"\n" "t=u/i"
7240"\n" "r+=t"
7241"\n" "}"
7242"\n" "scale=s"
7243"\n" "ibase=b"
7244"\n" "return((m*a+r)/n)"
7245"\n" "}"
7246"\n" "define j(n,x){"
7247"\n" "auto b,s,o,a,i,v,f"
7248"\n" "b=ibase"
7249"\n" "ibase=A"
7250"\n" "s=scale"
7251"\n" "scale=0"
7252"\n" "n/=1"
7253"\n" "if(n<0){"
7254"\n" "n=-n"
7255"\n" "if(n%2==1)o=1"
7256"\n" "}"
7257"\n" "a=1"
7258"\n" "for(i=2;i<=n;++i)a*=i"
7259"\n" "scale=1.5*s"
7260"\n" "a=(x^n)/2^n/a"
7261"\n" "r=v=1"
7262"\n" "f=-x*x/4"
7263"\n" "scale=scale+length(a)-scale(a)"
7264"\n" "for(i=1;v!=0;++i){"
7265"\n" "v=v*f/i/(n+i)"
7266"\n" "r+=v"
7267"\n" "}"
7268"\n" "scale=s"
7269"\n" "ibase=b"
7270"\n" "if(o!=0)a=-a"
7271"\n" "return(a*r/1)"
7272"\n" "}"
7273};
7274#endif // ENABLE_BC
7275
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007276static BcStatus bc_vm_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007277{
7278 BcStatus s = BC_STATUS_SUCCESS;
7279 size_t i;
7280
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007281#if ENABLE_BC
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007282 if (option_mask32 & BC_FLAG_L) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007283
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007284 // We know that internal library is not buggy,
7285 // thus error checking is normally disabled.
7286# define DEBUG_LIB 0
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007287 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007288 s = bc_parse_text(&G.prs, bc_lib);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007289 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007290
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007291 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007292 s = G.prs.parse(&G.prs);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007293 if (DEBUG_LIB && s) return s;
7294 }
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007295 s = bc_program_exec();
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007296 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007297 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007298#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007299
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007300 for (i = 0; !s && i < G.files.len; ++i)
7301 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007302 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007303 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007304 // Debug config, non-interactive mode:
7305 // return all the way back to main.
7306 // Non-debug builds do not come here, they exit.
7307 return s;
7308 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007309 fflush_and_check();
7310 fputs("ready for more input\n", stderr);
7311 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007312
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007313 if (IS_BC || !G.files.len)
7314 s = bc_vm_stdin();
7315 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7316 s = bc_vm_process("");
Gavin Howard01055ba2018-11-03 11:00:21 -06007317
Denys Vlasenko00d77792018-11-30 23:13:42 +01007318 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007319}
7320
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007321#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007322static void bc_program_free(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007323{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007324 bc_num_free(&G.prog.ib);
7325 bc_num_free(&G.prog.ob);
7326 bc_num_free(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007327# if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007328 bc_num_free(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007329# endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007330 bc_vec_free(&G.prog.fns);
7331 bc_vec_free(&G.prog.fn_map);
7332 bc_vec_free(&G.prog.vars);
7333 bc_vec_free(&G.prog.var_map);
7334 bc_vec_free(&G.prog.arrs);
7335 bc_vec_free(&G.prog.arr_map);
7336 bc_vec_free(&G.prog.strs);
7337 bc_vec_free(&G.prog.consts);
7338 bc_vec_free(&G.prog.results);
7339 bc_vec_free(&G.prog.stack);
7340 bc_num_free(&G.prog.last);
7341 bc_num_free(&G.prog.zero);
7342 bc_num_free(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007343}
7344
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007345static void bc_vm_free(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007346{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007347 bc_vec_free(&G.files);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007348 bc_program_free();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007349 bc_parse_free(&G.prs);
7350 free(G.env_args);
Gavin Howard01055ba2018-11-03 11:00:21 -06007351}
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007352#endif
7353
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007354static void bc_program_init(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007355{
7356 size_t idx;
7357 BcInstPtr ip;
7358
7359 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7360 memset(&ip, 0, sizeof(BcInstPtr));
7361
7362 /* G.prog.nchars = G.prog.scale = 0; - already is */
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007363
7364 bc_num_init(&G.prog.ib, BC_NUM_DEF_SIZE);
7365 bc_num_ten(&G.prog.ib);
7366 G.prog.ib_t = 10;
7367
7368 bc_num_init(&G.prog.ob, BC_NUM_DEF_SIZE);
7369 bc_num_ten(&G.prog.ob);
7370 G.prog.ob_t = 10;
7371
7372 bc_num_init(&G.prog.hexb, BC_NUM_DEF_SIZE);
7373 bc_num_ten(&G.prog.hexb);
7374 G.prog.hexb.num[0] = 6;
7375
7376#if ENABLE_DC
7377 bc_num_init(&G.prog.strmb, BC_NUM_DEF_SIZE);
7378 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7379#endif
7380
7381 bc_num_init(&G.prog.last, BC_NUM_DEF_SIZE);
7382 bc_num_zero(&G.prog.last);
7383
7384 bc_num_init(&G.prog.zero, BC_NUM_DEF_SIZE);
7385 bc_num_zero(&G.prog.zero);
7386
7387 bc_num_init(&G.prog.one, BC_NUM_DEF_SIZE);
7388 bc_num_one(&G.prog.one);
7389
7390 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007391 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007392
Denys Vlasenko1f67e932018-12-03 00:08:59 +01007393 bc_program_addFunc(xstrdup("(main)"), &idx);
7394 bc_program_addFunc(xstrdup("(read)"), &idx);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007395
7396 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007397 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007398
7399 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007400 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007401
7402 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7403 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7404 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7405 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7406 bc_vec_push(&G.prog.stack, &ip);
7407}
Gavin Howard01055ba2018-11-03 11:00:21 -06007408
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007409static void bc_vm_init(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007410{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007411 bc_vec_init(&G.files, sizeof(char *), NULL);
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007412 if (IS_BC)
Denys Vlasenkoab3c5682018-12-02 16:32:36 +01007413 bc_vm_envArgs();
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007414 bc_program_init();
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007415 if (IS_BC) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007416 bc_parse_init(&G.prs, BC_PROG_MAIN);
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007417 } else {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007418 dc_parse_init(&G.prs, BC_PROG_MAIN);
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007419 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007420}
7421
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007422static BcStatus bc_vm_run(char **argv, const char *env_len)
Gavin Howard01055ba2018-11-03 11:00:21 -06007423{
7424 BcStatus st;
Gavin Howard01055ba2018-11-03 11:00:21 -06007425
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007426#if ENABLE_FEATURE_EDITING
7427 G.line_input_state = new_line_input_t(DO_HISTORY);
7428#endif
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007429 G.prog.len = bc_vm_envLen(env_len);
7430
7431 bc_vm_init();
7432 bc_args(argv);
Gavin Howard01055ba2018-11-03 11:00:21 -06007433
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007434 if (isatty(0)) {
Denys Vlasenkod38af482018-12-04 19:11:02 +01007435#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007436 G_ttyin = 1;
Denys Vlasenko17c54722018-12-04 21:21:32 +01007437 // With SA_RESTART, most system calls will restart
7438 // (IOW: they won't fail with EINTR).
7439 // In particular, this means ^C won't cause
7440 // stdout to get into "error state" if SIGINT hits
7441 // within write() syscall.
7442 // The downside is that ^C while line input is taken
7443 // will only be handled after [Enter] since read()
7444 // from stdin is not interrupted by ^C either,
7445 // it restarts, thus fgetc() does not return on ^C.
7446 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7447
7448 // Without SA_RESTART, this exhibits a bug:
7449 // "while (1) print 1" and try ^C-ing it.
7450 // Intermittently, instead of returning to input line,
7451 // you'll get "output error: Interrupted system call"
7452 // and exit.
7453 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
Denys Vlasenkod38af482018-12-04 19:11:02 +01007454#endif
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007455 if (!(option_mask32 & BC_FLAG_Q))
Denys Vlasenkod38af482018-12-04 19:11:02 +01007456 bc_vm_info();
7457 }
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007458
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007459 st = bc_vm_exec();
Gavin Howard01055ba2018-11-03 11:00:21 -06007460
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007461#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007462 bc_vm_free();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007463# if ENABLE_FEATURE_EDITING
7464 free_line_input_t(G.line_input_state);
7465# endif
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007466 FREE_G();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007467#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007468 return st;
7469}
7470
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007471#if ENABLE_BC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007472int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007473int bc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007474{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007475 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007476 G.sbgn = G.send = '"';
Gavin Howard01055ba2018-11-03 11:00:21 -06007477
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007478 return bc_vm_run(argv, "BC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007479}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007480#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007481
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007482#if ENABLE_DC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007483int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007484int dc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007485{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007486 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007487 G.sbgn = '[';
7488 G.send = ']';
Gavin Howard01055ba2018-11-03 11:00:21 -06007489
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007490 return bc_vm_run(argv, "DC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007491}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007492#endif