blob: c756d8cd6284ba8c76529da13fc59fedcc71d271 [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.
Gavin Howard01055ba2018-11-03 11:00:21 -06005 */
6//config:config BC
7//config: bool "bc (45 kb; 49 kb when combined with dc)"
8//config: default y
9//config: help
10//config: bc is a command-line, arbitrary-precision calculator with a
11//config: Turing-complete language. See the GNU bc manual
12//config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
13//config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
14//config: for details.
15//config:
16//config: This bc has four differences to the GNU bc:
17//config:
18//config: 1) The period (.) can also be used as a shortcut for "last", as in
19//config: the BSD bc.
20//config: 2) Arrays are copied before being passed as arguments to
21//config: functions. This behavior is required by the bc spec.
22//config: 3) Arrays can be passed to the builtin "length" function to get
23//config: the number of elements currently in the array. The following
24//config: example prints "1":
25//config:
26//config: a[0] = 0
27//config: length(a[])
28//config:
29//config: 4) The precedence of the boolean "not" operator (!) is equal to
30//config: that of the unary minus (-), or negation, operator. This still
31//config: allows POSIX-compliant scripts to work while somewhat
32//config: preserving expected behavior (versus C) and making parsing
33//config: easier.
34//config:
35//config: Options:
36//config:
37//config: -i --interactive force interactive mode
38//config: -l --mathlib use predefined math routines:
39//config:
40//config: s(expr) = sine of expr in radians
41//config: c(expr) = cosine of expr in radians
42//config: a(expr) = arctangent of expr, returning
43//config: radians
44//config: l(expr) = natural log of expr
45//config: e(expr) = raises e to the power of expr
46//config: j(n, x) = Bessel function of integer order
47//config: n of x
48//config:
49//config: -q --quiet don't print version and copyright.
50//config: -s --standard error if any non-POSIX extensions are used.
51//config: -w --warn warn if any non-POSIX extensions are used.
52//config: -v --version print version and copyright and exit.
53//config:
54//config: Long options are only available if FEATURE_BC_LONG_OPTIONS is
55//config: enabled.
56//config:
57//config:config DC
58//config: bool "dc (38 kb; 49 kb when combined with bc)"
59//config: default y
60//config: help
61//config: dc is a reverse-polish notation command-line calculator which
62//config: supports unlimited precision arithmetic. See the FreeBSD man page
63//config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
64//config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
65//config: for details.
66//config:
67//config: This dc has a few differences from the two above:
68//config:
69//config: 1) When printing a byte stream (command "P"), this bc follows what
70//config: the FreeBSD dc does.
71//config: 2) This dc implements the GNU extensions for divmod ("~") and
72//config: modular exponentiation ("|").
73//config: 3) This dc implements all FreeBSD extensions, except for "J" and
74//config: "M".
75//config: 4) Like the FreeBSD dc, this dc supports extended registers.
76//config: However, they are implemented differently. When it encounters
77//config: whitespace where a register should be, it skips the whitespace.
78//config: If the character following is not a lowercase letter, an error
79//config: is issued. Otherwise, the register name is parsed by the
80//config: following regex:
81//config:
82//config: [a-z][a-z0-9_]*
83//config:
84//config: This generally means that register names will be surrounded by
85//config: whitespace.
86//config:
87//config: Examples:
88//config:
89//config: l idx s temp L index S temp2 < do_thing
90//config:
91//config: Also note that, like the FreeBSD dc, extended registers are not
92//config: allowed unless the "-x" option is given.
93//config:
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +010094//config:config FEATURE_DC_SMALL
95//config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
96//config: depends on DC && !BC
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +010097//config: default n
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +010098//config:
99//config:config FEATURE_DC_LIBM
100//config: bool "Enable power and exp functions (requires libm)"
101//config: default y
102//config: depends on FEATURE_DC_SMALL
103//config: help
104//config: Enable power and exp functions.
105//config: NOTE: This will require libm to be present for linking.
106//config:
Gavin Howard01055ba2018-11-03 11:00:21 -0600107//config:config FEATURE_BC_SIGNALS
108//config: bool "Enable bc/dc signal handling"
109//config: default y
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100110//config: depends on (BC || DC) && !FEATURE_DC_SMALL
Gavin Howard01055ba2018-11-03 11:00:21 -0600111//config: help
112//config: Enable signal handling for bc and dc.
113//config:
114//config:config FEATURE_BC_LONG_OPTIONS
115//config: bool "Enable bc/dc long options"
116//config: default y
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100117//config: depends on (BC || DC) && !FEATURE_DC_SMALL
Gavin Howard01055ba2018-11-03 11:00:21 -0600118//config: help
119//config: Enable long options for bc and dc.
120
121//applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
122//applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
123
124//kbuild:lib-$(CONFIG_BC) += bc.o
125//kbuild:lib-$(CONFIG_DC) += bc.o
126
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100127//See www.gnu.org/software/bc/manual/bc.html
Gavin Howard01055ba2018-11-03 11:00:21 -0600128//usage:#define bc_trivial_usage
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100129//usage: "[-sqliw] FILE..."
Gavin Howard01055ba2018-11-03 11:00:21 -0600130//usage:
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100131//usage:#define bc_full_usage "\n"
132//usage: "\nArbitrary precision calculator"
133//usage: "\n"
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100134///////: "\n -i Interactive" - has no effect for now
135//usage: "\n -q Quiet"
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100136//usage: "\n -l Load standard math library"
137//usage: "\n -s Be POSIX compatible"
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100138//usage: "\n -w Warn if extensions are used"
139///////: "\n -v Version"
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100140//usage: "\n"
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100141//usage: "\n$BC_LINE_LENGTH changes output width"
Gavin Howard01055ba2018-11-03 11:00:21 -0600142//usage:
143//usage:#define bc_example_usage
144//usage: "3 + 4.129\n"
145//usage: "1903 - 2893\n"
146//usage: "-129 * 213.28935\n"
147//usage: "12 / -1932\n"
148//usage: "12 % 12\n"
149//usage: "34 ^ 189\n"
150//usage: "scale = 13\n"
151//usage: "ibase = 2\n"
152//usage: "obase = A\n"
153//usage:
154//usage:#define dc_trivial_usage
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +0100155//usage: IF_NOT_FEATURE_DC_SMALL("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
Gavin Howard01055ba2018-11-03 11:00:21 -0600156//usage:
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100157//usage:#define dc_full_usage "\n"
158//usage: "\nTiny RPN calculator. Operations:"
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +0100159//usage: "\n+, -, *, /, %, ~, ^," IF_NOT_FEATURE_DC_SMALL(" |,")
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100160//usage: "\np - print top of the stack (without popping)"
161//usage: "\nf - print entire stack"
162//usage: "\nk - pop the value and set the precision"
163//usage: "\ni - pop the value and set input radix"
164//usage: "\no - pop the value and set output radix"
165//usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
Gavin Howard01055ba2018-11-03 11:00:21 -0600166//usage:
167//usage:#define dc_example_usage
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100168//usage: "$ dc -e'2 2 + p'\n"
Gavin Howard01055ba2018-11-03 11:00:21 -0600169//usage: "4\n"
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100170//usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
Gavin Howard01055ba2018-11-03 11:00:21 -0600171//usage: "16\n"
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100172//usage: "$ dc -e'0 1 & p'\n"
Gavin Howard01055ba2018-11-03 11:00:21 -0600173//usage: "0\n"
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100174//usage: "$ dc -e'0 1 | p'\n"
Gavin Howard01055ba2018-11-03 11:00:21 -0600175//usage: "1\n"
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100176//usage: "$ echo '72 9 / 8 * p' | dc\n"
Gavin Howard01055ba2018-11-03 11:00:21 -0600177//usage: "64\n"
178
179#include "libbb.h"
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100180#include "common_bufsiz.h"
Gavin Howard01055ba2018-11-03 11:00:21 -0600181
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100182#if ENABLE_FEATURE_DC_SMALL
183# include "dc.c"
184#else
185
Gavin Howard01055ba2018-11-03 11:00:21 -0600186typedef enum BcStatus {
Denys Vlasenko60cf7472018-12-04 20:05:28 +0100187 BC_STATUS_SUCCESS = 0,
188 BC_STATUS_FAILURE = 1,
189 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
Denys Vlasenkof522dd92018-12-07 16:35:43 +0100190 BC_STATUS_EOF = 3, // bc_vm_stdin() uses this
Gavin Howard01055ba2018-11-03 11:00:21 -0600191} BcStatus;
192
Gavin Howard01055ba2018-11-03 11:00:21 -0600193#define BC_VEC_INVALID_IDX ((size_t) -1)
194#define BC_VEC_START_CAP (1 << 5)
195
Denys Vlasenko5ba55f12018-12-10 15:37:14 +0100196typedef void (*BcVecFree)(void *) FAST_FUNC;
Gavin Howard01055ba2018-11-03 11:00:21 -0600197
198typedef struct BcVec {
199 char *v;
200 size_t len;
201 size_t cap;
202 size_t size;
203 BcVecFree dtor;
204} BcVec;
205
Gavin Howard01055ba2018-11-03 11:00:21 -0600206typedef signed char BcDig;
207
208typedef struct BcNum {
209 BcDig *restrict num;
210 size_t rdx;
211 size_t len;
212 size_t cap;
213 bool neg;
214} BcNum;
215
Denys Vlasenko2fa11b62018-12-06 12:34:39 +0100216#define BC_NUM_MIN_BASE ((unsigned long) 2)
217#define BC_NUM_MAX_IBASE ((unsigned long) 16)
218// larger value might speed up BIGNUM calculations a bit:
219#define BC_NUM_DEF_SIZE (16)
220#define BC_NUM_PRINT_WIDTH (69)
Gavin Howard01055ba2018-11-03 11:00:21 -0600221
Denys Vlasenko2fa11b62018-12-06 12:34:39 +0100222#define BC_NUM_KARATSUBA_LEN (32)
Gavin Howard01055ba2018-11-03 11:00:21 -0600223
Denys Vlasenko5ba55f12018-12-10 15:37:14 +0100224typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
Denys Vlasenko2a8ad482018-12-08 21:56:37 +0100225
Denys Vlasenko5ba55f12018-12-10 15:37:14 +0100226typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
Gavin Howard01055ba2018-11-03 11:00:21 -0600227
Denys Vlasenko5ba55f12018-12-10 15:37:14 +0100228static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
229static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
230static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
231static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
232static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
233static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
Gavin Howard01055ba2018-11-03 11:00:21 -0600234static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
235static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
236 size_t scale);
237
238typedef enum BcInst {
239
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100240#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600241 BC_INST_INC_PRE,
242 BC_INST_DEC_PRE,
243 BC_INST_INC_POST,
244 BC_INST_DEC_POST,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100245#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600246
247 BC_INST_NEG,
248
249 BC_INST_POWER,
250 BC_INST_MULTIPLY,
251 BC_INST_DIVIDE,
252 BC_INST_MODULUS,
253 BC_INST_PLUS,
254 BC_INST_MINUS,
255
256 BC_INST_REL_EQ,
257 BC_INST_REL_LE,
258 BC_INST_REL_GE,
259 BC_INST_REL_NE,
260 BC_INST_REL_LT,
261 BC_INST_REL_GT,
262
263 BC_INST_BOOL_NOT,
264 BC_INST_BOOL_OR,
265 BC_INST_BOOL_AND,
266
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100267#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600268 BC_INST_ASSIGN_POWER,
269 BC_INST_ASSIGN_MULTIPLY,
270 BC_INST_ASSIGN_DIVIDE,
271 BC_INST_ASSIGN_MODULUS,
272 BC_INST_ASSIGN_PLUS,
273 BC_INST_ASSIGN_MINUS,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100274#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600275 BC_INST_ASSIGN,
276
277 BC_INST_NUM,
278 BC_INST_VAR,
279 BC_INST_ARRAY_ELEM,
280 BC_INST_ARRAY,
281
282 BC_INST_SCALE_FUNC,
283 BC_INST_IBASE,
284 BC_INST_SCALE,
285 BC_INST_LAST,
286 BC_INST_LENGTH,
287 BC_INST_READ,
288 BC_INST_OBASE,
289 BC_INST_SQRT,
290
291 BC_INST_PRINT,
292 BC_INST_PRINT_POP,
293 BC_INST_STR,
294 BC_INST_PRINT_STR,
295
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100296#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600297 BC_INST_JUMP,
298 BC_INST_JUMP_ZERO,
299
300 BC_INST_CALL,
301
302 BC_INST_RET,
303 BC_INST_RET0,
304
305 BC_INST_HALT,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100306#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600307
308 BC_INST_POP,
309 BC_INST_POP_EXEC,
310
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100311#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600312 BC_INST_MODEXP,
313 BC_INST_DIVMOD,
314
315 BC_INST_EXECUTE,
316 BC_INST_EXEC_COND,
317
318 BC_INST_ASCIIFY,
319 BC_INST_PRINT_STREAM,
320
321 BC_INST_PRINT_STACK,
322 BC_INST_CLEAR_STACK,
323 BC_INST_STACK_LEN,
324 BC_INST_DUPLICATE,
325 BC_INST_SWAP,
326
327 BC_INST_LOAD,
328 BC_INST_PUSH_VAR,
329 BC_INST_PUSH_TO_VAR,
330
331 BC_INST_QUIT,
332 BC_INST_NQUIT,
333
334 BC_INST_INVALID = -1,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100335#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600336
337} BcInst;
338
339typedef struct BcId {
340 char *name;
341 size_t idx;
342} BcId;
343
344typedef struct BcFunc {
345 BcVec code;
346 BcVec labels;
347 size_t nparams;
348 BcVec autos;
349} BcFunc;
350
351typedef enum BcResultType {
352
353 BC_RESULT_TEMP,
354
355 BC_RESULT_VAR,
356 BC_RESULT_ARRAY_ELEM,
357 BC_RESULT_ARRAY,
358
359 BC_RESULT_STR,
360
361 BC_RESULT_IBASE,
362 BC_RESULT_SCALE,
363 BC_RESULT_LAST,
364
365 // These are between to calculate ibase, obase, and last from instructions.
366 BC_RESULT_CONSTANT,
367 BC_RESULT_ONE,
368
369 BC_RESULT_OBASE,
370
371} BcResultType;
372
373typedef union BcResultData {
374 BcNum n;
375 BcVec v;
376 BcId id;
377} BcResultData;
378
379typedef struct BcResult {
380 BcResultType t;
381 BcResultData d;
382} BcResult;
383
384typedef struct BcInstPtr {
385 size_t func;
386 size_t idx;
387 size_t len;
388} BcInstPtr;
389
Gavin Howard01055ba2018-11-03 11:00:21 -0600390// BC_LEX_NEG is not used in lexing; it is only for parsing.
391typedef enum BcLexType {
392
393 BC_LEX_EOF,
394 BC_LEX_INVALID,
395
396 BC_LEX_OP_INC,
397 BC_LEX_OP_DEC,
398
399 BC_LEX_NEG,
400
401 BC_LEX_OP_POWER,
402 BC_LEX_OP_MULTIPLY,
403 BC_LEX_OP_DIVIDE,
404 BC_LEX_OP_MODULUS,
405 BC_LEX_OP_PLUS,
406 BC_LEX_OP_MINUS,
407
408 BC_LEX_OP_REL_EQ,
409 BC_LEX_OP_REL_LE,
410 BC_LEX_OP_REL_GE,
411 BC_LEX_OP_REL_NE,
412 BC_LEX_OP_REL_LT,
413 BC_LEX_OP_REL_GT,
414
415 BC_LEX_OP_BOOL_NOT,
416 BC_LEX_OP_BOOL_OR,
417 BC_LEX_OP_BOOL_AND,
418
419 BC_LEX_OP_ASSIGN_POWER,
420 BC_LEX_OP_ASSIGN_MULTIPLY,
421 BC_LEX_OP_ASSIGN_DIVIDE,
422 BC_LEX_OP_ASSIGN_MODULUS,
423 BC_LEX_OP_ASSIGN_PLUS,
424 BC_LEX_OP_ASSIGN_MINUS,
425 BC_LEX_OP_ASSIGN,
426
427 BC_LEX_NLINE,
428 BC_LEX_WHITESPACE,
429
430 BC_LEX_LPAREN,
431 BC_LEX_RPAREN,
432
433 BC_LEX_LBRACKET,
434 BC_LEX_COMMA,
435 BC_LEX_RBRACKET,
436
437 BC_LEX_LBRACE,
438 BC_LEX_SCOLON,
439 BC_LEX_RBRACE,
440
441 BC_LEX_STR,
442 BC_LEX_NAME,
443 BC_LEX_NUMBER,
444
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100445 BC_LEX_KEY_1st_keyword,
446 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
Gavin Howard01055ba2018-11-03 11:00:21 -0600447 BC_LEX_KEY_BREAK,
448 BC_LEX_KEY_CONTINUE,
449 BC_LEX_KEY_DEFINE,
450 BC_LEX_KEY_ELSE,
451 BC_LEX_KEY_FOR,
452 BC_LEX_KEY_HALT,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100453 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
454 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600455 BC_LEX_KEY_IF,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100456 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
Gavin Howard01055ba2018-11-03 11:00:21 -0600457 BC_LEX_KEY_LENGTH,
458 BC_LEX_KEY_LIMITS,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100459 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600460 BC_LEX_KEY_PRINT,
461 BC_LEX_KEY_QUIT,
462 BC_LEX_KEY_READ,
463 BC_LEX_KEY_RETURN,
464 BC_LEX_KEY_SCALE,
465 BC_LEX_KEY_SQRT,
466 BC_LEX_KEY_WHILE,
467
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100468#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600469 BC_LEX_EQ_NO_REG,
470 BC_LEX_OP_MODEXP,
471 BC_LEX_OP_DIVMOD,
472
473 BC_LEX_COLON,
474 BC_LEX_ELSE,
475 BC_LEX_EXECUTE,
476 BC_LEX_PRINT_STACK,
477 BC_LEX_CLEAR_STACK,
478 BC_LEX_STACK_LEVEL,
479 BC_LEX_DUPLICATE,
480 BC_LEX_SWAP,
481 BC_LEX_POP,
482
483 BC_LEX_ASCIIFY,
484 BC_LEX_PRINT_STREAM,
485
486 BC_LEX_STORE_IBASE,
487 BC_LEX_STORE_SCALE,
488 BC_LEX_LOAD,
489 BC_LEX_LOAD_POP,
490 BC_LEX_STORE_PUSH,
491 BC_LEX_STORE_OBASE,
492 BC_LEX_PRINT_POP,
493 BC_LEX_NQUIT,
494 BC_LEX_SCALE_FACTOR,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100495#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600496} BcLexType;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100497// must match order of BC_LEX_KEY_foo etc above
498#if ENABLE_BC
499struct BcLexKeyword {
500 char name8[8];
501};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100502#define BC_LEX_KW_ENTRY(a, b) \
503 { .name8 = a /*, .posix = b */ }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100504static const struct BcLexKeyword bc_lex_kws[20] = {
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100505 BC_LEX_KW_ENTRY("auto" , 1), // 0
506 BC_LEX_KW_ENTRY("break" , 1), // 1
507 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
508 BC_LEX_KW_ENTRY("define" , 1), // 3
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100509
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100510 BC_LEX_KW_ENTRY("else" , 0), // 4
511 BC_LEX_KW_ENTRY("for" , 1), // 5
512 BC_LEX_KW_ENTRY("halt" , 0), // 6
513 BC_LEX_KW_ENTRY("ibase" , 1), // 7
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100514
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100515 BC_LEX_KW_ENTRY("if" , 1), // 8
516 BC_LEX_KW_ENTRY("last" , 0), // 9
517 BC_LEX_KW_ENTRY("length" , 1), // 10
518 BC_LEX_KW_ENTRY("limits" , 0), // 11
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100519
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100520 BC_LEX_KW_ENTRY("obase" , 1), // 12
521 BC_LEX_KW_ENTRY("print" , 0), // 13
522 BC_LEX_KW_ENTRY("quit" , 1), // 14
523 BC_LEX_KW_ENTRY("read" , 0), // 15
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100524
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100525 BC_LEX_KW_ENTRY("return" , 1), // 16
526 BC_LEX_KW_ENTRY("scale" , 1), // 17
527 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
528 BC_LEX_KW_ENTRY("while" , 1), // 19
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100529};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100530#undef BC_LEX_KW_ENTRY
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100531enum {
532 POSIX_KWORD_MASK = 0
533 | (1 << 0)
534 | (1 << 1)
535 | (0 << 2)
536 | (1 << 3)
537 \
538 | (0 << 4)
539 | (1 << 5)
540 | (0 << 6)
541 | (1 << 7)
542 \
543 | (1 << 8)
544 | (0 << 9)
545 | (1 << 10)
546 | (0 << 11)
547 \
548 | (1 << 12)
549 | (0 << 13)
550 | (1 << 14)
551 | (0 << 15)
552 \
553 | (1 << 16)
554 | (1 << 17)
555 | (1 << 18)
556 | (1 << 19)
557};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100558#define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100559#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600560
561struct BcLex;
Denys Vlasenko5ba55f12018-12-10 15:37:14 +0100562typedef BcStatus (*BcLexNext)(struct BcLex *) FAST_FUNC;
Gavin Howard01055ba2018-11-03 11:00:21 -0600563
564typedef struct BcLex {
565
566 const char *buf;
567 size_t i;
568 size_t line;
Gavin Howard01055ba2018-11-03 11:00:21 -0600569 size_t len;
570 bool newline;
571
572 struct {
573 BcLexType t;
574 BcLexType last;
575 BcVec v;
576 } t;
577
578 BcLexNext next;
579
580} BcLex;
581
582#define BC_PARSE_STREND ((char) UCHAR_MAX)
583
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100584#define BC_PARSE_REL (1 << 0)
585#define BC_PARSE_PRINT (1 << 1)
Gavin Howard01055ba2018-11-03 11:00:21 -0600586#define BC_PARSE_NOCALL (1 << 2)
587#define BC_PARSE_NOREAD (1 << 3)
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100588#define BC_PARSE_ARRAY (1 << 4)
Gavin Howard01055ba2018-11-03 11:00:21 -0600589
590#define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
591#define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
592
593#define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
594#define BC_PARSE_FUNC_INNER(parse) \
595 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
596
597#define BC_PARSE_FLAG_FUNC (1 << 1)
598#define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
599
600#define BC_PARSE_FLAG_BODY (1 << 2)
601#define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
602
603#define BC_PARSE_FLAG_LOOP (1 << 3)
604#define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
605
606#define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
607#define BC_PARSE_LOOP_INNER(parse) \
608 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
609
610#define BC_PARSE_FLAG_IF (1 << 5)
611#define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
612
613#define BC_PARSE_FLAG_ELSE (1 << 6)
614#define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
615
616#define BC_PARSE_FLAG_IF_END (1 << 7)
617#define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
618
619#define BC_PARSE_CAN_EXEC(parse) \
620 (!(BC_PARSE_TOP_FLAG(parse) & \
621 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
622 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
623 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
624
Gavin Howard01055ba2018-11-03 11:00:21 -0600625struct BcParse;
626
627struct BcProgram;
628
Denys Vlasenko5ba55f12018-12-10 15:37:14 +0100629typedef BcStatus (*BcParseParse)(struct BcParse *) FAST_FUNC;
Gavin Howard01055ba2018-11-03 11:00:21 -0600630
631typedef struct BcParse {
632
633 BcParseParse parse;
634
635 BcLex l;
636
637 BcVec flags;
638
639 BcVec exits;
640 BcVec conds;
641
642 BcVec ops;
643
Gavin Howard01055ba2018-11-03 11:00:21 -0600644 BcFunc *func;
645 size_t fidx;
646
647 size_t nbraces;
648 bool auto_part;
649
650} BcParse;
651
Gavin Howard01055ba2018-11-03 11:00:21 -0600652typedef struct BcProgram {
653
654 size_t len;
655 size_t scale;
656
657 BcNum ib;
658 size_t ib_t;
659 BcNum ob;
660 size_t ob_t;
661
662 BcNum hexb;
663
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100664#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600665 BcNum strmb;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100666#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600667
668 BcVec results;
669 BcVec stack;
670
671 BcVec fns;
672 BcVec fn_map;
673
674 BcVec vars;
675 BcVec var_map;
676
677 BcVec arrs;
678 BcVec arr_map;
679
680 BcVec strs;
681 BcVec consts;
682
683 const char *file;
684
685 BcNum last;
686 BcNum zero;
687 BcNum one;
688
689 size_t nchars;
690
Gavin Howard01055ba2018-11-03 11:00:21 -0600691} BcProgram;
692
693#define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
694
695#define BC_PROG_MAIN (0)
696#define BC_PROG_READ (1)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100697#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600698#define BC_PROG_REQ_FUNCS (2)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100699#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600700
701#define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
702#define BC_PROG_NUM(r, n) \
703 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
704
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100705#define BC_FLAG_W (1 << 0)
706#define BC_FLAG_V (1 << 1)
707#define BC_FLAG_S (1 << 2)
708#define BC_FLAG_Q (1 << 3)
709#define BC_FLAG_L (1 << 4)
710#define BC_FLAG_I (1 << 5)
711#define DC_FLAG_X (1 << 6)
Gavin Howard01055ba2018-11-03 11:00:21 -0600712
713#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
714#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
715
Denys Vlasenko64074a12018-12-07 15:50:14 +0100716#define BC_MAX_OBASE ((unsigned) 999)
717#define BC_MAX_DIM ((unsigned) INT_MAX)
718#define BC_MAX_SCALE ((unsigned) UINT_MAX)
719#define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
720#define BC_MAX_NUM BC_MAX_STRING
721// Unused apart from "limits" message. Just show a "biggish number" there.
722//#define BC_MAX_NAME BC_MAX_STRING
723//#define BC_MAX_EXP ((unsigned long) LONG_MAX)
724//#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
725#define BC_MAX_NAME_STR "999999999"
726#define BC_MAX_EXP_STR "999999999"
727#define BC_MAX_VARS_STR "999999999"
728
729#define BC_MAX_OBASE_STR "999"
730
731#if INT_MAX == 2147483647
732# define BC_MAX_DIM_STR "2147483647"
733#elif INT_MAX == 9223372036854775807
734# define BC_MAX_DIM_STR "9223372036854775807"
735#else
736# error Strange INT_MAX
737#endif
738
739#if UINT_MAX == 4294967295
740# define BC_MAX_SCALE_STR "4294967295"
741# define BC_MAX_STRING_STR "4294967294"
742#elif UINT_MAX == 18446744073709551615
743# define BC_MAX_SCALE_STR "18446744073709551615"
744# define BC_MAX_STRING_STR "18446744073709551614"
745#else
746# error Strange UINT_MAX
747#endif
748#define BC_MAX_NUM_STR BC_MAX_STRING_STR
Gavin Howard01055ba2018-11-03 11:00:21 -0600749
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100750struct globals {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100751 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100752 IF_FEATURE_CLEAN_UP(smallint exiting;)
Gavin Howard01055ba2018-11-03 11:00:21 -0600753 char sbgn;
754 char send;
Gavin Howard01055ba2018-11-03 11:00:21 -0600755
756 BcParse prs;
757 BcProgram prog;
758
Denys Vlasenko5318f812018-12-05 17:48:01 +0100759 // For error messages. Can be set to current parsed line,
760 // or [TODO] to current executing line (can be before last parsed one)
761 unsigned err_line;
762
Gavin Howard01055ba2018-11-03 11:00:21 -0600763 BcVec files;
764
765 char *env_args;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100766
767#if ENABLE_FEATURE_EDITING
768 line_input_t *line_input_state;
769#endif
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100770} FIX_ALIASING;
771#define G (*ptr_to_globals)
772#define INIT_G() do { \
773 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
774} while (0)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100775#define FREE_G() do { \
776 FREE_PTR_TO_GLOBALS(); \
777} while (0)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100778#define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
779#define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100780#define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100781#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkob9c321d2018-12-07 12:41:42 +0100782# define G_interrupt bb_got_signal
783# define G_ttyin G.ttyin
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100784#else
Denys Vlasenkob9c321d2018-12-07 12:41:42 +0100785# define G_interrupt 0
786# define G_ttyin 0
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100787#endif
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100788#if ENABLE_FEATURE_CLEAN_UP
789# define G_exiting G.exiting
790#else
791# define G_exiting 0
792#endif
Denys Vlasenko00d77792018-11-30 23:13:42 +0100793#define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
794
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100795#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600796
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100797// This is a bit array that corresponds to token types. An entry is
Gavin Howard01055ba2018-11-03 11:00:21 -0600798// true if the token is valid in an expression, false otherwise.
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100799enum {
800 BC_PARSE_EXPRS_BITS = 0
801 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
802 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
803 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
804 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
805 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
806 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
807 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
808 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
Gavin Howard01055ba2018-11-03 11:00:21 -0600809};
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100810static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
811{
812#if ULONG_MAX > 0xffffffff
813 // 64-bit version (will not work correctly for 32-bit longs!)
814 return BC_PARSE_EXPRS_BITS & (1UL << i);
815#else
816 // 32-bit version
817 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
818 if (i >= 32) {
819 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
820 i &= 31;
821 }
822 return m & (1UL << i);
823#endif
824}
Gavin Howard01055ba2018-11-03 11:00:21 -0600825
826// This is an array of data for operators that correspond to token types.
Denys Vlasenko65437582018-12-05 19:37:19 +0100827static const uint8_t bc_parse_ops[] = {
828#define OP(p,l) ((int)(l) * 0x10 + (p))
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100829 OP(0, false), OP( 0, false ), // inc dec
830 OP(1, false), // neg
Denys Vlasenko65437582018-12-05 19:37:19 +0100831 OP(2, false),
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100832 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
833 OP(4, true ), OP( 4, true ), // mod + -
834 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
835 OP(1, false), // not
836 OP(7, true ), OP( 7, true ), // or and
837 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
838 OP(5, false), OP( 5, false ), // -= =
Denys Vlasenko65437582018-12-05 19:37:19 +0100839#undef OP
Gavin Howard01055ba2018-11-03 11:00:21 -0600840};
Denys Vlasenko65437582018-12-05 19:37:19 +0100841#define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
842#define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
Gavin Howard01055ba2018-11-03 11:00:21 -0600843
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100844// Byte array of up to 4 BC_LEX's, packed into 32-bit word
845typedef uint32_t BcParseNext;
846
Gavin Howard01055ba2018-11-03 11:00:21 -0600847// These identify what tokens can come after expressions in certain cases.
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100848enum {
849#define BC_PARSE_NEXT4(a,b,c,d) ( (a) | ((b)<<8) | ((c)<<16) | ((((d)|0x80)<<24)) )
850#define BC_PARSE_NEXT2(a,b) BC_PARSE_NEXT4(a,b,0xff,0xff)
851#define BC_PARSE_NEXT1(a) BC_PARSE_NEXT4(a,0xff,0xff,0xff)
852 bc_parse_next_expr = BC_PARSE_NEXT4(BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF),
853 bc_parse_next_param = BC_PARSE_NEXT2(BC_LEX_RPAREN, BC_LEX_COMMA),
854 bc_parse_next_print = BC_PARSE_NEXT4(BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF),
855 bc_parse_next_rel = BC_PARSE_NEXT1(BC_LEX_RPAREN),
856 bc_parse_next_elem = BC_PARSE_NEXT1(BC_LEX_RBRACKET),
857 bc_parse_next_for = BC_PARSE_NEXT1(BC_LEX_SCOLON),
858 bc_parse_next_read = BC_PARSE_NEXT2(BC_LEX_NLINE, BC_LEX_EOF),
859#undef BC_PARSE_NEXT4
860#undef BC_PARSE_NEXT2
861#undef BC_PARSE_NEXT1
862};
Gavin Howard01055ba2018-11-03 11:00:21 -0600863#endif // ENABLE_BC
864
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100865#if ENABLE_DC
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100866static const //BcLexType - should be this type, but narrower type saves size:
867uint8_t
868dc_lex_regs[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600869 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
870 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
871 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
872 BC_LEX_STORE_PUSH,
873};
874
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100875static const //BcLexType - should be this type
876uint8_t
877dc_lex_tokens[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600878 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
879 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
880 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
881 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
882 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
883 BC_LEX_INVALID, BC_LEX_INVALID,
884 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
885 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
886 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
887 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
888 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
889 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
890 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
891 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
892 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
893 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
894 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
895 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
896 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
897 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
898 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
899 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
900 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
901 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
902 BC_LEX_INVALID
903};
904
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100905static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
906int8_t
907dc_parse_insts[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600908 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
909 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
910 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
911 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
912 BC_INST_INVALID, BC_INST_INVALID,
913 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
914 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
915 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
916 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
917 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
918 BC_INST_INVALID, BC_INST_INVALID,
919 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
920 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
921 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
922 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
923 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
924 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
925 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
926 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
927 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
928 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
929 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
930 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
931};
932#endif // ENABLE_DC
933
Gavin Howard01055ba2018-11-03 11:00:21 -0600934static const BcNumBinaryOp bc_program_ops[] = {
935 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
936};
937
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100938static void fflush_and_check(void)
939{
940 fflush_all();
941 if (ferror(stdout) || ferror(stderr))
942 bb_perror_msg_and_die("output error");
943}
944
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100945#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100946#define QUIT_OR_RETURN_TO_MAIN \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100947do { \
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100948 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100949 G_exiting = 1; \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100950 return BC_STATUS_FAILURE; \
951} while (0)
952#else
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100953#define QUIT_OR_RETURN_TO_MAIN quit()
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100954#endif
955
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100956static void quit(void) NORETURN;
957static void quit(void)
958{
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100959 if (ferror(stdin))
960 bb_perror_msg_and_die("input error");
961 fflush_and_check();
962 exit(0);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100963}
964
Denys Vlasenko5318f812018-12-05 17:48:01 +0100965static void bc_verror_msg(const char *fmt, va_list p)
966{
967 const char *sv = sv; /* for compiler */
968 if (G.prog.file) {
969 sv = applet_name;
970 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
971 }
972 bb_verror_msg(fmt, p, NULL);
973 if (G.prog.file) {
974 free((char*)applet_name);
975 applet_name = sv;
976 }
977}
978
Denys Vlasenko86e63cd2018-12-10 19:46:53 +0100979#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkofa35e592018-12-10 20:17:24 +0100980# define ERRORFUNC /*nothing*/
981# define ERROR_RETURN(a) a
982# define ERRORS_ARE_FATAL 0
Denys Vlasenko86e63cd2018-12-10 19:46:53 +0100983#else
984# if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkofa35e592018-12-10 20:17:24 +0100985# define ERRORFUNC /*nothing*/
986# define ERROR_RETURN(a) a
987# define ERRORS_ARE_FATAL 0
Denys Vlasenko86e63cd2018-12-10 19:46:53 +0100988# else
Denys Vlasenkofa35e592018-12-10 20:17:24 +0100989# define ERRORFUNC NORETURN
990# define ERROR_RETURN(a) /*nothing*/
991# define ERRORS_ARE_FATAL 1
Denys Vlasenko86e63cd2018-12-10 19:46:53 +0100992# endif
993#endif
994
995static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100996{
997 va_list p;
998
999 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +01001000 bc_verror_msg(fmt, p);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001001 va_end(p);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01001002
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01001003 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001004 exit(1);
Denys Vlasenko86e63cd2018-12-10 19:46:53 +01001005 ERROR_RETURN(return BC_STATUS_FAILURE;)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001006}
1007
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001008#if ENABLE_BC
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001009static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001010{
1011 va_list p;
1012
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001013 // Are non-POSIX constructs totally ok?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01001014 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001015 return BC_STATUS_SUCCESS; // yes
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001016
1017 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +01001018 bc_verror_msg(fmt, p);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001019 va_end(p);
1020
1021 // Do we treat non-POSIX constructs as errors?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01001022 if (!(option_mask32 & BC_FLAG_S))
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001023 return BC_STATUS_SUCCESS; // no, it's a warning
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01001024 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001025 exit(1);
1026 return BC_STATUS_FAILURE;
1027}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001028#endif
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001029
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001030// We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
1031// This idiom begs for tail-call optimization, but for it to work,
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001032// function must not have caller-cleaned parameters on stack.
1033// Unfortunately, vararg function API does exactly that on most arches.
1034// Thus, use these shims for the cases when we have no vararg PARAMS:
Denys Vlasenko86e63cd2018-12-10 19:46:53 +01001035static ERRORFUNC int bc_error(const char *msg)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001036{
Denys Vlasenko86e63cd2018-12-10 19:46:53 +01001037 ERROR_RETURN(return) bc_error_fmt("%s", msg);
1038}
1039static ERRORFUNC int bc_error_bad_character(char c)
1040{
1041 ERROR_RETURN(return) bc_error_fmt("bad character '%c'", c);
1042}
1043static ERRORFUNC int bc_error_bad_expression(void)
1044{
1045 ERROR_RETURN(return) bc_error("bad expression");
1046}
1047static ERRORFUNC int bc_error_bad_token(void)
1048{
1049 ERROR_RETURN(return) bc_error("bad token");
1050}
1051static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1052{
1053 ERROR_RETURN(return) bc_error("stack has too few elements");
1054}
1055static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1056{
1057 ERROR_RETURN(return) bc_error("variable is wrong type");
1058}
1059static ERRORFUNC int bc_error_nested_read_call(void)
1060{
1061 ERROR_RETURN(return) bc_error("read() call inside of a read() call");
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001062}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001063#if ENABLE_BC
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001064static int bc_POSIX_requires(const char *msg)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001065{
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001066 return bc_posix_error_fmt("POSIX requires %s", msg);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001067}
Denys Vlasenko00646792018-12-05 18:12:27 +01001068static int bc_POSIX_does_not_allow(const char *msg)
1069{
1070 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1071}
1072static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1073{
1074 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1075}
1076static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1077{
1078 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1079}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001080#endif
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001081
Gavin Howard01055ba2018-11-03 11:00:21 -06001082static void bc_vec_grow(BcVec *v, size_t n)
1083{
1084 size_t cap = v->cap * 2;
1085 while (cap < v->len + n) cap *= 2;
1086 v->v = xrealloc(v->v, v->size * cap);
1087 v->cap = cap;
1088}
1089
1090static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1091{
1092 v->size = esize;
1093 v->cap = BC_VEC_START_CAP;
1094 v->len = 0;
1095 v->dtor = dtor;
1096 v->v = xmalloc(esize * BC_VEC_START_CAP);
1097}
1098
Denys Vlasenko7d628012018-12-04 21:46:47 +01001099static void bc_char_vec_init(BcVec *v)
1100{
1101 bc_vec_init(v, sizeof(char), NULL);
1102}
1103
Gavin Howard01055ba2018-11-03 11:00:21 -06001104static void bc_vec_expand(BcVec *v, size_t req)
1105{
1106 if (v->cap < req) {
1107 v->v = xrealloc(v->v, v->size * req);
1108 v->cap = req;
1109 }
1110}
1111
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001112static void bc_vec_pop(BcVec *v)
1113{
1114 v->len--;
1115 if (v->dtor)
1116 v->dtor(v->v + (v->size * v->len));
1117}
Denys Vlasenko2fa11b62018-12-06 12:34:39 +01001118
Gavin Howard01055ba2018-11-03 11:00:21 -06001119static void bc_vec_npop(BcVec *v, size_t n)
1120{
1121 if (!v->dtor)
1122 v->len -= n;
1123 else {
1124 size_t len = v->len - n;
1125 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1126 }
1127}
1128
Denys Vlasenko7d628012018-12-04 21:46:47 +01001129static void bc_vec_pop_all(BcVec *v)
1130{
1131 bc_vec_npop(v, v->len);
1132}
1133
Gavin Howard01055ba2018-11-03 11:00:21 -06001134static void bc_vec_push(BcVec *v, const void *data)
1135{
1136 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1137 memmove(v->v + (v->size * v->len), data, v->size);
1138 v->len += 1;
1139}
1140
1141static void bc_vec_pushByte(BcVec *v, char data)
1142{
1143 bc_vec_push(v, &data);
1144}
1145
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001146static void bc_vec_pushZeroByte(BcVec *v)
1147{
1148 //bc_vec_pushByte(v, '\0');
1149 // better:
1150 bc_vec_push(v, &const_int_0);
1151}
1152
Gavin Howard01055ba2018-11-03 11:00:21 -06001153static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1154{
1155 if (idx == v->len)
1156 bc_vec_push(v, data);
1157 else {
1158
1159 char *ptr;
1160
1161 if (v->len == v->cap) bc_vec_grow(v, 1);
1162
1163 ptr = v->v + v->size * idx;
1164
1165 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1166 memmove(ptr, data, v->size);
1167 }
1168}
1169
1170static void bc_vec_string(BcVec *v, size_t len, const char *str)
1171{
Denys Vlasenko7d628012018-12-04 21:46:47 +01001172 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001173 bc_vec_expand(v, len + 1);
1174 memcpy(v->v, str, len);
1175 v->len = len;
1176
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001177 bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001178}
1179
1180static void bc_vec_concat(BcVec *v, const char *str)
1181{
Denys Vlasenko8b4cf0d2018-12-10 15:12:58 +01001182 size_t len, slen;
Gavin Howard01055ba2018-11-03 11:00:21 -06001183
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001184 if (v->len == 0) bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001185
Denys Vlasenko8b4cf0d2018-12-10 15:12:58 +01001186 slen = strlen(str);
1187 len = v->len + slen;
Gavin Howard01055ba2018-11-03 11:00:21 -06001188
Denys Vlasenko8b4cf0d2018-12-10 15:12:58 +01001189 if (v->cap < len) bc_vec_grow(v, slen);
Denys Vlasenko1ff88622018-12-06 12:06:16 +01001190 strcpy(v->v + v->len - 1, str);
Gavin Howard01055ba2018-11-03 11:00:21 -06001191
1192 v->len = len;
1193}
1194
1195static void *bc_vec_item(const BcVec *v, size_t idx)
1196{
1197 return v->v + v->size * idx;
1198}
1199
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01001200static char** bc_program_str(size_t idx)
1201{
1202 return bc_vec_item(&G.prog.strs, idx);
1203}
1204
1205static BcFunc* bc_program_func(size_t idx)
1206{
1207 return bc_vec_item(&G.prog.fns, idx);
1208}
1209
Gavin Howard01055ba2018-11-03 11:00:21 -06001210static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1211{
1212 return v->v + v->size * (v->len - idx - 1);
1213}
1214
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001215static void *bc_vec_top(const BcVec *v)
1216{
1217 return v->v + v->size * (v->len - 1);
1218}
1219
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001220static FAST_FUNC void bc_vec_free(void *vec)
Gavin Howard01055ba2018-11-03 11:00:21 -06001221{
1222 BcVec *v = (BcVec *) vec;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001223 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001224 free(v->v);
1225}
1226
Denys Vlasenkocca79a02018-12-05 21:15:46 +01001227static int bc_id_cmp(const void *e1, const void *e2)
1228{
1229 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1230}
1231
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001232static FAST_FUNC void bc_id_free(void *id)
Denys Vlasenkocca79a02018-12-05 21:15:46 +01001233{
1234 free(((BcId *) id)->name);
1235}
1236
Gavin Howard01055ba2018-11-03 11:00:21 -06001237static size_t bc_map_find(const BcVec *v, const void *ptr)
1238{
1239 size_t low = 0, high = v->len;
1240
1241 while (low < high) {
1242
1243 size_t mid = (low + high) / 2;
1244 BcId *id = bc_vec_item(v, mid);
1245 int result = bc_id_cmp(ptr, id);
1246
1247 if (result == 0)
1248 return mid;
1249 else if (result < 0)
1250 high = mid;
1251 else
1252 low = mid + 1;
1253 }
1254
1255 return low;
1256}
1257
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001258static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
Gavin Howard01055ba2018-11-03 11:00:21 -06001259{
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001260 size_t n = *i = bc_map_find(v, ptr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001261
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001262 if (n == v->len)
Gavin Howard01055ba2018-11-03 11:00:21 -06001263 bc_vec_push(v, ptr);
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001264 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1265 return 0; // "was not inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001266 else
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001267 bc_vec_pushAt(v, ptr, n);
1268 return 1; // "was inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001269}
1270
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001271#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06001272static size_t bc_map_index(const BcVec *v, const void *ptr)
1273{
1274 size_t i = bc_map_find(v, ptr);
1275 if (i >= v->len) return BC_VEC_INVALID_IDX;
1276 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1277}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001278#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06001279
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001280static int push_input_byte(BcVec *vec, char c)
1281{
1282 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1283 || c > 0x7e
1284 ) {
1285 // Bad chars on this line, ignore entire line
1286 bc_error_fmt("illegal character 0x%02x", c);
1287 return 1;
1288 }
1289 bc_vec_pushByte(vec, (char)c);
1290 return 0;
1291}
1292
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01001293static BcStatus bc_read_line(BcVec *vec)
Gavin Howard01055ba2018-11-03 11:00:21 -06001294{
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001295 BcStatus s;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001296 bool bad_chars;
Gavin Howard01055ba2018-11-03 11:00:21 -06001297
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001298 s = BC_STATUS_SUCCESS;
Denys Vlasenko00d77792018-11-30 23:13:42 +01001299 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001300 int c;
Gavin Howard01055ba2018-11-03 11:00:21 -06001301
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001302 bad_chars = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001303 bc_vec_pop_all(vec);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001304
1305 fflush_and_check();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001306
Gavin Howard01055ba2018-11-03 11:00:21 -06001307#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001308 if (G_interrupt) { // ^C was pressed
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001309 intr:
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001310 G_interrupt = 0;
Denys Vlasenkoac6ed112018-12-08 21:39:10 +01001311 // GNU bc says "interrupted execution."
1312 // GNU dc says "Interrupt!"
1313 fputs("\ninterrupted execution\n", stderr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001314 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001315# if ENABLE_FEATURE_EDITING
1316 if (G_ttyin) {
1317 int n, i;
1318# define line_buf bb_common_bufsiz1
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01001319 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001320 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1321 if (n == 0) // ^C
1322 goto intr;
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001323 s = BC_STATUS_EOF;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001324 break;
1325 }
1326 i = 0;
1327 for (;;) {
1328 c = line_buf[i++];
1329 if (!c) break;
1330 bad_chars |= push_input_byte(vec, c);
1331 }
1332# undef line_buf
1333 } else
1334# endif
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001335#endif
Denys Vlasenkoed849352018-12-06 10:26:13 +01001336 {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001337 IF_FEATURE_BC_SIGNALS(errno = 0;)
1338 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001339 c = fgetc(stdin);
1340#if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1341 // Both conditions appear simultaneously, check both just in case
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001342 if (errno == EINTR || G_interrupt) {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001343 // ^C was pressed
1344 clearerr(stdin);
1345 goto intr;
1346 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001347#endif
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001348 if (c == EOF) {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001349 if (ferror(stdin))
1350 quit(); // this emits error message
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001351 s = BC_STATUS_EOF;
Denys Vlasenkoed849352018-12-06 10:26:13 +01001352 // Note: EOF does not append '\n', therefore:
1353 // printf 'print 123\n' | bc - works
1354 // printf 'print 123' | bc - fails (syntax error)
1355 break;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001356 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001357 bad_chars |= push_input_byte(vec, c);
1358 } while (c != '\n');
Denys Vlasenkoed849352018-12-06 10:26:13 +01001359 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001360 } while (bad_chars);
Gavin Howard01055ba2018-11-03 11:00:21 -06001361
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001362 bc_vec_pushZeroByte(vec);
Gavin Howard01055ba2018-11-03 11:00:21 -06001363
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001364 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06001365}
1366
Denys Vlasenkodf515392018-12-02 19:27:48 +01001367static char* bc_read_file(const char *path)
Gavin Howard01055ba2018-11-03 11:00:21 -06001368{
Denys Vlasenkodf515392018-12-02 19:27:48 +01001369 char *buf;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001370 size_t size = ((size_t) -1);
1371 size_t i;
Gavin Howard01055ba2018-11-03 11:00:21 -06001372
Denys Vlasenko4c9455f2018-12-06 15:21:39 +01001373 // Never returns NULL (dies on errors)
1374 buf = xmalloc_xopen_read_close(path, &size);
Gavin Howard01055ba2018-11-03 11:00:21 -06001375
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001376 for (i = 0; i < size; ++i) {
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001377 char c = buf[i];
1378 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1379 || c > 0x7e
1380 ) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01001381 free(buf);
1382 buf = NULL;
1383 break;
1384 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001385 }
1386
Denys Vlasenkodf515392018-12-02 19:27:48 +01001387 return buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06001388}
1389
Gavin Howard01055ba2018-11-03 11:00:21 -06001390static void bc_num_setToZero(BcNum *n, size_t scale)
1391{
1392 n->len = 0;
1393 n->neg = false;
1394 n->rdx = scale;
1395}
1396
1397static void bc_num_zero(BcNum *n)
1398{
1399 bc_num_setToZero(n, 0);
1400}
1401
1402static void bc_num_one(BcNum *n)
1403{
1404 bc_num_setToZero(n, 0);
1405 n->len = 1;
1406 n->num[0] = 1;
1407}
1408
1409static void bc_num_ten(BcNum *n)
1410{
1411 bc_num_setToZero(n, 0);
1412 n->len = 2;
1413 n->num[0] = 0;
1414 n->num[1] = 1;
1415}
1416
Denys Vlasenko3129f702018-12-09 12:04:44 +01001417// Note: this also sets BcNum to zero
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001418static void bc_num_init(BcNum *n, size_t req)
1419{
1420 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
Denys Vlasenko3129f702018-12-09 12:04:44 +01001421 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001422 n->num = xmalloc(req);
1423 n->cap = req;
Denys Vlasenko3129f702018-12-09 12:04:44 +01001424 n->rdx = 0;
1425 n->len = 0;
1426 n->neg = false;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001427}
1428
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01001429static void bc_num_init_DEF_SIZE(BcNum *n)
1430{
1431 bc_num_init(n, BC_NUM_DEF_SIZE);
1432}
1433
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001434static void bc_num_expand(BcNum *n, size_t req)
1435{
1436 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1437 if (req > n->cap) {
1438 n->num = xrealloc(n->num, req);
1439 n->cap = req;
1440 }
1441}
1442
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001443static FAST_FUNC void bc_num_free(void *num)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001444{
1445 free(((BcNum *) num)->num);
1446}
1447
1448static void bc_num_copy(BcNum *d, BcNum *s)
1449{
1450 if (d != s) {
1451 bc_num_expand(d, s->cap);
1452 d->len = s->len;
1453 d->neg = s->neg;
1454 d->rdx = s->rdx;
1455 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1456 }
1457}
1458
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001459static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001460{
1461 size_t i;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001462 unsigned long pow, result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001463
1464 if (n->neg) return bc_error("negative number");
1465
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001466 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001467
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001468 unsigned long prev = result, powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001469
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001470 result += ((unsigned long) n->num[i]) * pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001471 pow *= 10;
1472
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001473 if (result < prev || pow < powprev)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001474 return bc_error("overflow");
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001475 prev = result;
1476 powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001477 }
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001478 *result_p = result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001479
1480 return BC_STATUS_SUCCESS;
1481}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01001482#if ERRORS_ARE_FATAL
1483# define bc_num_ulong(...) (bc_num_ulong(__VA_ARGS__), BC_STATUS_SUCCESS)
1484#endif
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001485
1486static void bc_num_ulong2num(BcNum *n, unsigned long val)
1487{
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001488 BcDig *ptr;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001489
1490 bc_num_zero(n);
1491
1492 if (val == 0) return;
1493
Denys Vlasenkob696d9e2018-12-10 12:22:15 +01001494 if (ULONG_MAX == 0xffffffffUL)
1495 bc_num_expand(n, 10); // 10 digits: 4294967295
Denys Vlasenkoc665c182018-12-10 15:15:42 +01001496 if (ULONG_MAX == 0xffffffffffffffffULL)
Denys Vlasenkob696d9e2018-12-10 12:22:15 +01001497 bc_num_expand(n, 20); // 20 digits: 18446744073709551615
Denys Vlasenkoc665c182018-12-10 15:15:42 +01001498 BUILD_BUG_ON(ULONG_MAX > 0xffffffffffffffffULL);
Denys Vlasenkob696d9e2018-12-10 12:22:15 +01001499
1500 ptr = n->num;
1501 for (;;) {
1502 n->len++;
1503 *ptr++ = val % 10;
1504 val /= 10;
1505 if (val == 0) break;
1506 }
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001507}
1508
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001509static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001510 size_t len)
1511{
1512 size_t i, j;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001513 for (i = 0; i < len; ++i) {
1514 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001515 a[i + j++] += 10;
1516 a[i + j] -= 1;
1517 }
1518 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001519}
1520
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01001521#define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1522#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1523#define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1524//#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1525static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1526{
1527 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1528}
1529//#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1530static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1531{
1532 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1533}
1534
Gavin Howard01055ba2018-11-03 11:00:21 -06001535static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1536{
1537 size_t i;
1538 int c = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001539 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
Gavin Howard01055ba2018-11-03 11:00:21 -06001540 return BC_NUM_NEG(i + 1, c < 0);
1541}
1542
1543static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1544{
1545 size_t i, min, a_int, b_int, diff;
1546 BcDig *max_num, *min_num;
1547 bool a_max, neg = false;
1548 ssize_t cmp;
1549
1550 if (a == b) return 0;
1551 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1552 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1553 if (a->neg) {
1554 if (b->neg)
1555 neg = true;
1556 else
1557 return -1;
1558 }
1559 else if (b->neg)
1560 return 1;
1561
1562 a_int = BC_NUM_INT(a);
1563 b_int = BC_NUM_INT(b);
1564 a_int -= b_int;
1565 a_max = (a->rdx > b->rdx);
1566
1567 if (a_int != 0) return (ssize_t) a_int;
1568
1569 if (a_max) {
1570 min = b->rdx;
1571 diff = a->rdx - b->rdx;
1572 max_num = a->num + diff;
1573 min_num = b->num;
1574 }
1575 else {
1576 min = a->rdx;
1577 diff = b->rdx - a->rdx;
1578 max_num = b->num + diff;
1579 min_num = a->num;
1580 }
1581
1582 cmp = bc_num_compare(max_num, min_num, b_int + min);
1583 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1584
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001585 for (max_num -= diff, i = diff - 1; i < diff; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001586 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1587 }
1588
1589 return 0;
1590}
1591
1592static void bc_num_truncate(BcNum *n, size_t places)
1593{
1594 if (places == 0) return;
1595
1596 n->rdx -= places;
1597
1598 if (n->len != 0) {
1599 n->len -= places;
1600 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1601 }
1602}
1603
1604static void bc_num_extend(BcNum *n, size_t places)
1605{
1606 size_t len = n->len + places;
1607
1608 if (places != 0) {
1609
1610 if (n->cap < len) bc_num_expand(n, len);
1611
1612 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1613 memset(n->num, 0, sizeof(BcDig) * places);
1614
1615 n->len += places;
1616 n->rdx += places;
1617 }
1618}
1619
1620static void bc_num_clean(BcNum *n)
1621{
1622 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1623 if (n->len == 0)
1624 n->neg = false;
1625 else if (n->len < n->rdx)
1626 n->len = n->rdx;
1627}
1628
1629static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1630{
1631 if (n->rdx < scale)
1632 bc_num_extend(n, scale - n->rdx);
1633 else
1634 bc_num_truncate(n, n->rdx - scale);
1635
1636 bc_num_clean(n);
1637 if (n->len != 0) n->neg = !neg1 != !neg2;
1638}
1639
1640static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1641 BcNum *restrict b)
1642{
1643 if (idx < n->len) {
1644
1645 b->len = n->len - idx;
1646 a->len = idx;
1647 a->rdx = b->rdx = 0;
1648
1649 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1650 memcpy(a->num, n->num, idx * sizeof(BcDig));
1651 }
1652 else {
1653 bc_num_zero(b);
1654 bc_num_copy(a, n);
1655 }
1656
1657 bc_num_clean(a);
1658 bc_num_clean(b);
1659}
1660
1661static BcStatus bc_num_shift(BcNum *n, size_t places)
1662{
1663 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
Denys Vlasenko64074a12018-12-07 15:50:14 +01001664
1665 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1666 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1667 if (places + n->len > BC_MAX_NUM)
1668 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1669 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001670
1671 if (n->rdx >= places)
1672 n->rdx -= places;
1673 else {
1674 bc_num_extend(n, places - n->rdx);
1675 n->rdx = 0;
1676 }
1677
1678 bc_num_clean(n);
1679
1680 return BC_STATUS_SUCCESS;
1681}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01001682#if ERRORS_ARE_FATAL
1683# define bc_num_shift(...) (bc_num_shift(__VA_ARGS__), BC_STATUS_SUCCESS)
1684#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06001685
1686static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1687{
1688 BcNum one;
1689 BcDig num[2];
1690
1691 one.cap = 2;
1692 one.num = num;
1693 bc_num_one(&one);
1694
1695 return bc_num_div(&one, a, b, scale);
1696}
1697
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001698static FAST_FUNC BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
Gavin Howard01055ba2018-11-03 11:00:21 -06001699{
1700 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1701 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1702 int carry, in;
1703
1704 // Because this function doesn't need to use scale (per the bc spec),
1705 // I am hijacking it to say whether it's doing an add or a subtract.
1706
1707 if (a->len == 0) {
1708 bc_num_copy(c, b);
1709 if (sub && c->len) c->neg = !c->neg;
1710 return BC_STATUS_SUCCESS;
1711 }
1712 else if (b->len == 0) {
1713 bc_num_copy(c, a);
1714 return BC_STATUS_SUCCESS;
1715 }
1716
1717 c->neg = a->neg;
1718 c->rdx = BC_MAX(a->rdx, b->rdx);
1719 min_rdx = BC_MIN(a->rdx, b->rdx);
1720 c->len = 0;
1721
1722 if (a->rdx > b->rdx) {
1723 diff = a->rdx - b->rdx;
1724 ptr = a->num;
1725 ptr_a = a->num + diff;
1726 ptr_b = b->num;
1727 }
1728 else {
1729 diff = b->rdx - a->rdx;
1730 ptr = b->num;
1731 ptr_a = a->num;
1732 ptr_b = b->num + diff;
1733 }
1734
1735 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1736
1737 ptr_c += diff;
1738 a_int = BC_NUM_INT(a);
1739 b_int = BC_NUM_INT(b);
1740
1741 if (a_int > b_int) {
1742 min_int = b_int;
1743 max = a_int;
1744 ptr = ptr_a;
1745 }
1746 else {
1747 min_int = a_int;
1748 max = b_int;
1749 ptr = ptr_b;
1750 }
1751
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001752 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001753 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1754 carry = in / 10;
1755 ptr_c[i] = (BcDig)(in % 10);
1756 }
1757
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001758 for (; i < max + min_rdx; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001759 in = ((int) ptr[i]) + carry;
1760 carry = in / 10;
1761 ptr_c[i] = (BcDig)(in % 10);
1762 }
1763
1764 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1765
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001766 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001767}
1768
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001769static FAST_FUNC BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
Gavin Howard01055ba2018-11-03 11:00:21 -06001770{
Gavin Howard01055ba2018-11-03 11:00:21 -06001771 ssize_t cmp;
1772 BcNum *minuend, *subtrahend;
1773 size_t start;
1774 bool aneg, bneg, neg;
1775
1776 // Because this function doesn't need to use scale (per the bc spec),
1777 // I am hijacking it to say whether it's doing an add or a subtract.
1778
1779 if (a->len == 0) {
1780 bc_num_copy(c, b);
1781 if (sub && c->len) c->neg = !c->neg;
1782 return BC_STATUS_SUCCESS;
1783 }
1784 else if (b->len == 0) {
1785 bc_num_copy(c, a);
1786 return BC_STATUS_SUCCESS;
1787 }
1788
1789 aneg = a->neg;
1790 bneg = b->neg;
1791 a->neg = b->neg = false;
1792
1793 cmp = bc_num_cmp(a, b);
1794
1795 a->neg = aneg;
1796 b->neg = bneg;
1797
1798 if (cmp == 0) {
1799 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1800 return BC_STATUS_SUCCESS;
1801 }
1802 else if (cmp > 0) {
1803 neg = a->neg;
1804 minuend = a;
1805 subtrahend = b;
1806 }
1807 else {
1808 neg = b->neg;
1809 if (sub) neg = !neg;
1810 minuend = b;
1811 subtrahend = a;
1812 }
1813
1814 bc_num_copy(c, minuend);
1815 c->neg = neg;
1816
1817 if (c->rdx < subtrahend->rdx) {
1818 bc_num_extend(c, subtrahend->rdx - c->rdx);
1819 start = 0;
1820 }
1821 else
1822 start = c->rdx - subtrahend->rdx;
1823
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001824 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001825
1826 bc_num_clean(c);
1827
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001828 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001829}
1830
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001831static FAST_FUNC BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001832 BcNum *restrict c)
1833{
1834 BcStatus s;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001835 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
Gavin Howard01055ba2018-11-03 11:00:21 -06001836 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001837 bool aone;
Gavin Howard01055ba2018-11-03 11:00:21 -06001838
Gavin Howard01055ba2018-11-03 11:00:21 -06001839 if (a->len == 0 || b->len == 0) {
1840 bc_num_zero(c);
1841 return BC_STATUS_SUCCESS;
1842 }
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001843 aone = BC_NUM_ONE(a);
1844 if (aone || BC_NUM_ONE(b)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001845 bc_num_copy(c, aone ? b : a);
1846 return BC_STATUS_SUCCESS;
1847 }
1848
1849 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1850 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1851 {
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001852 size_t i, j, len;
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001853 unsigned carry;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001854
Gavin Howard01055ba2018-11-03 11:00:21 -06001855 bc_num_expand(c, a->len + b->len + 1);
1856
1857 memset(c->num, 0, sizeof(BcDig) * c->cap);
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001858 c->len = len = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06001859
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001860 for (i = 0; i < b->len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001861
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001862 carry = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001863 for (j = 0; j < a->len; ++j) {
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001864 unsigned in = c->num[i + j];
1865 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1866 // note: compilers prefer _unsigned_ div/const
Gavin Howard01055ba2018-11-03 11:00:21 -06001867 carry = in / 10;
1868 c->num[i + j] = (BcDig)(in % 10);
1869 }
1870
1871 c->num[i + j] += (BcDig) carry;
1872 len = BC_MAX(len, i + j + !!carry);
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01001873
1874 // a=2^1000000
1875 // a*a <- without check below, this will not be interruptible
1876 if (G_interrupt) return BC_STATUS_FAILURE;
Gavin Howard01055ba2018-11-03 11:00:21 -06001877 }
1878
1879 c->len = len;
1880
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001881 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06001882 }
1883
1884 bc_num_init(&l1, max);
1885 bc_num_init(&h1, max);
1886 bc_num_init(&l2, max);
1887 bc_num_init(&h2, max);
1888 bc_num_init(&m1, max);
1889 bc_num_init(&m2, max);
1890 bc_num_init(&z0, max);
1891 bc_num_init(&z1, max);
1892 bc_num_init(&z2, max);
1893 bc_num_init(&temp, max + max);
1894
1895 bc_num_split(a, max2, &l1, &h1);
1896 bc_num_split(b, max2, &l2, &h2);
1897
1898 s = bc_num_add(&h1, &l1, &m1, 0);
1899 if (s) goto err;
1900 s = bc_num_add(&h2, &l2, &m2, 0);
1901 if (s) goto err;
1902
1903 s = bc_num_k(&h1, &h2, &z0);
1904 if (s) goto err;
1905 s = bc_num_k(&m1, &m2, &z1);
1906 if (s) goto err;
1907 s = bc_num_k(&l1, &l2, &z2);
1908 if (s) goto err;
1909
1910 s = bc_num_sub(&z1, &z0, &temp, 0);
1911 if (s) goto err;
1912 s = bc_num_sub(&temp, &z2, &z1, 0);
1913 if (s) goto err;
1914
1915 s = bc_num_shift(&z0, max2 * 2);
1916 if (s) goto err;
1917 s = bc_num_shift(&z1, max2);
1918 if (s) goto err;
1919 s = bc_num_add(&z0, &z1, &temp, 0);
1920 if (s) goto err;
1921 s = bc_num_add(&temp, &z2, c, 0);
1922
1923err:
1924 bc_num_free(&temp);
1925 bc_num_free(&z2);
1926 bc_num_free(&z1);
1927 bc_num_free(&z0);
1928 bc_num_free(&m2);
1929 bc_num_free(&m1);
1930 bc_num_free(&h2);
1931 bc_num_free(&l2);
1932 bc_num_free(&h1);
1933 bc_num_free(&l1);
1934 return s;
1935}
1936
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001937static FAST_FUNC BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06001938{
1939 BcStatus s;
1940 BcNum cpa, cpb;
1941 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1942
1943 scale = BC_MAX(scale, a->rdx);
1944 scale = BC_MAX(scale, b->rdx);
1945 scale = BC_MIN(a->rdx + b->rdx, scale);
1946 maxrdx = BC_MAX(maxrdx, scale);
1947
1948 bc_num_init(&cpa, a->len);
1949 bc_num_init(&cpb, b->len);
1950
1951 bc_num_copy(&cpa, a);
1952 bc_num_copy(&cpb, b);
1953 cpa.neg = cpb.neg = false;
1954
1955 s = bc_num_shift(&cpa, maxrdx);
1956 if (s) goto err;
1957 s = bc_num_shift(&cpb, maxrdx);
1958 if (s) goto err;
1959 s = bc_num_k(&cpa, &cpb, c);
1960 if (s) goto err;
1961
1962 maxrdx += scale;
1963 bc_num_expand(c, c->len + maxrdx);
1964
1965 if (c->len < maxrdx) {
1966 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1967 c->len += maxrdx;
1968 }
1969
1970 c->rdx = maxrdx;
1971 bc_num_retireMul(c, scale, a->neg, b->neg);
1972
1973err:
1974 bc_num_free(&cpb);
1975 bc_num_free(&cpa);
1976 return s;
1977}
1978
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01001979static FAST_FUNC BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06001980{
1981 BcStatus s = BC_STATUS_SUCCESS;
1982 BcDig *n, *p, q;
1983 size_t len, end, i;
1984 BcNum cp;
1985 bool zero = true;
1986
1987 if (b->len == 0)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001988 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001989 else if (a->len == 0) {
1990 bc_num_setToZero(c, scale);
1991 return BC_STATUS_SUCCESS;
1992 }
1993 else if (BC_NUM_ONE(b)) {
1994 bc_num_copy(c, a);
1995 bc_num_retireMul(c, scale, a->neg, b->neg);
1996 return BC_STATUS_SUCCESS;
1997 }
1998
1999 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
2000 bc_num_copy(&cp, a);
2001 len = b->len;
2002
2003 if (len > cp.len) {
2004 bc_num_expand(&cp, len + 2);
2005 bc_num_extend(&cp, len - cp.len);
2006 }
2007
2008 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
2009 cp.rdx -= b->rdx;
2010 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
2011
2012 if (b->rdx == b->len) {
2013 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
2014 len -= i - 1;
2015 }
2016
2017 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
2018
2019 // We want an extra zero in front to make things simpler.
2020 cp.num[cp.len++] = 0;
2021 end = cp.len - len;
2022
2023 bc_num_expand(c, cp.len);
2024
2025 bc_num_zero(c);
2026 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2027 c->rdx = cp.rdx;
2028 c->len = cp.len;
2029 p = b->num;
2030
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002031 for (i = end - 1; !s && i < end; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002032 n = cp.num + i;
2033 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002034 bc_num_subArrays(n, p, len);
Gavin Howard01055ba2018-11-03 11:00:21 -06002035 c->num[i] = q;
Denys Vlasenkof381a882018-12-05 19:21:34 +01002036 // a=2^100000
2037 // scale=40000
2038 // 1/a <- without check below, this will not be interruptible
2039 if (G_interrupt) {
2040 s = BC_STATUS_FAILURE;
2041 break;
2042 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002043 }
2044
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002045 bc_num_retireMul(c, scale, a->neg, b->neg);
Gavin Howard01055ba2018-11-03 11:00:21 -06002046 bc_num_free(&cp);
2047
Denys Vlasenkof381a882018-12-05 19:21:34 +01002048 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06002049}
2050
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002051static FAST_FUNC BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
Gavin Howard01055ba2018-11-03 11:00:21 -06002052 BcNum *restrict d, size_t scale, size_t ts)
2053{
2054 BcStatus s;
2055 BcNum temp;
2056 bool neg;
2057
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002058 if (b->len == 0)
2059 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06002060
2061 if (a->len == 0) {
2062 bc_num_setToZero(d, ts);
2063 return BC_STATUS_SUCCESS;
2064 }
2065
2066 bc_num_init(&temp, d->cap);
Denys Vlasenkof381a882018-12-05 19:21:34 +01002067 s = bc_num_d(a, b, c, scale);
2068 if (s) goto err;
Gavin Howard01055ba2018-11-03 11:00:21 -06002069
2070 if (scale != 0) scale = ts;
2071
2072 s = bc_num_m(c, b, &temp, scale);
2073 if (s) goto err;
2074 s = bc_num_sub(a, &temp, d, scale);
2075 if (s) goto err;
2076
2077 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2078
2079 neg = d->neg;
2080 bc_num_retireMul(d, ts, a->neg, b->neg);
2081 d->neg = neg;
2082
2083err:
2084 bc_num_free(&temp);
2085 return s;
2086}
2087
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002088static FAST_FUNC BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002089{
2090 BcStatus s;
2091 BcNum c1;
2092 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2093
2094 bc_num_init(&c1, len);
2095 s = bc_num_r(a, b, &c1, c, scale, ts);
2096 bc_num_free(&c1);
2097
2098 return s;
2099}
2100
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002101static FAST_FUNC BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002102{
2103 BcStatus s = BC_STATUS_SUCCESS;
2104 BcNum copy;
2105 unsigned long pow;
2106 size_t i, powrdx, resrdx;
2107 bool neg, zero;
2108
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002109 if (b->rdx) return bc_error("non integer number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002110
2111 if (b->len == 0) {
2112 bc_num_one(c);
2113 return BC_STATUS_SUCCESS;
2114 }
2115 else if (a->len == 0) {
2116 bc_num_setToZero(c, scale);
2117 return BC_STATUS_SUCCESS;
2118 }
2119 else if (BC_NUM_ONE(b)) {
2120 if (!b->neg)
2121 bc_num_copy(c, a);
2122 else
2123 s = bc_num_inv(a, c, scale);
2124 return s;
2125 }
2126
2127 neg = b->neg;
2128 b->neg = false;
2129
2130 s = bc_num_ulong(b, &pow);
2131 if (s) return s;
2132
2133 bc_num_init(&copy, a->len);
2134 bc_num_copy(&copy, a);
2135
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01002136 if (!neg) {
2137 if (a->rdx > scale)
2138 scale = a->rdx;
2139 if (a->rdx * pow < scale)
2140 scale = a->rdx * pow;
2141 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002142
2143 b->neg = neg;
2144
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002145 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002146 powrdx <<= 1;
2147 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2148 if (s) goto err;
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002149 // Not needed: bc_num_mul() has a check for ^C:
2150 //if (G_interrupt) {
2151 // s = BC_STATUS_FAILURE;
2152 // goto err;
2153 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002154 }
2155
Gavin Howard01055ba2018-11-03 11:00:21 -06002156 bc_num_copy(c, &copy);
2157
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002158 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002159
2160 powrdx <<= 1;
2161 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2162 if (s) goto err;
2163
2164 if (pow & 1) {
2165 resrdx += powrdx;
2166 s = bc_num_mul(c, &copy, c, resrdx);
2167 if (s) goto err;
2168 }
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002169 // Not needed: bc_num_mul() has a check for ^C:
2170 //if (G_interrupt) {
2171 // s = BC_STATUS_FAILURE;
2172 // goto err;
2173 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002174 }
2175
2176 if (neg) {
2177 s = bc_num_inv(c, c, scale);
2178 if (s) goto err;
2179 }
2180
Gavin Howard01055ba2018-11-03 11:00:21 -06002181 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2182
2183 // We can't use bc_num_clean() here.
2184 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2185 if (zero) bc_num_setToZero(c, scale);
2186
2187err:
2188 bc_num_free(&copy);
2189 return s;
2190}
2191
2192static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2193 BcNumBinaryOp op, size_t req)
2194{
2195 BcStatus s;
2196 BcNum num2, *ptr_a, *ptr_b;
2197 bool init = false;
2198
2199 if (c == a) {
2200 ptr_a = &num2;
2201 memcpy(ptr_a, c, sizeof(BcNum));
2202 init = true;
2203 }
2204 else
2205 ptr_a = a;
2206
2207 if (c == b) {
2208 ptr_b = &num2;
2209 if (c != a) {
2210 memcpy(ptr_b, c, sizeof(BcNum));
2211 init = true;
2212 }
2213 }
2214 else
2215 ptr_b = b;
2216
2217 if (init)
2218 bc_num_init(c, req);
2219 else
2220 bc_num_expand(c, req);
2221
2222 s = op(ptr_a, ptr_b, c, scale);
2223
2224 if (init) bc_num_free(&num2);
2225
2226 return s;
2227}
2228
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002229static void bc_num_printNewline(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06002230{
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002231 if (G.prog.nchars == G.prog.len - 1) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002232 bb_putchar('\\');
2233 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002234 G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06002235 }
2236}
2237
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002238#if ENABLE_DC
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002239static FAST_FUNC void bc_num_printChar(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002240{
Denys Vlasenko2a8ad482018-12-08 21:56:37 +01002241 (void) radix;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002242 bb_putchar((char) num);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002243 G.prog.nchars += width;
Gavin Howard01055ba2018-11-03 11:00:21 -06002244}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002245#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002246
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002247static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002248{
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002249 size_t exp, pow;
Gavin Howard01055ba2018-11-03 11:00:21 -06002250
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002251 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002252 bb_putchar(radix ? '.' : ' ');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002253 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06002254
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002255 bc_num_printNewline();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002256 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2257 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002258
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002259 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002260 size_t dig;
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002261 bc_num_printNewline();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002262 dig = num / pow;
2263 num -= dig * pow;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002264 bb_putchar(((char) dig) + '0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002265 }
2266}
2267
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002268static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002269{
2270 if (radix) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002271 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002272 bb_putchar('.');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002273 G.prog.nchars += 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06002274 }
2275
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002276 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002277 bb_putchar(bb_hexdigits_upcase[num]);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002278 G.prog.nchars += width;
Gavin Howard01055ba2018-11-03 11:00:21 -06002279}
2280
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002281static void bc_num_printDecimal(BcNum *n)
Gavin Howard01055ba2018-11-03 11:00:21 -06002282{
2283 size_t i, rdx = n->rdx - 1;
2284
Denys Vlasenko00d77792018-11-30 23:13:42 +01002285 if (n->neg) bb_putchar('-');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002286 G.prog.nchars += n->neg;
Gavin Howard01055ba2018-11-03 11:00:21 -06002287
2288 for (i = n->len - 1; i < n->len; --i)
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002289 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
Gavin Howard01055ba2018-11-03 11:00:21 -06002290}
2291
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002292static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width, BcNumDigitOp print)
Gavin Howard01055ba2018-11-03 11:00:21 -06002293{
2294 BcStatus s;
2295 BcVec stack;
2296 BcNum intp, fracp, digit, frac_len;
2297 unsigned long dig, *ptr;
2298 size_t i;
2299 bool radix;
2300
2301 if (n->len == 0) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002302 print(0, width, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06002303 return BC_STATUS_SUCCESS;
2304 }
2305
2306 bc_vec_init(&stack, sizeof(long), NULL);
2307 bc_num_init(&intp, n->len);
2308 bc_num_init(&fracp, n->rdx);
2309 bc_num_init(&digit, width);
2310 bc_num_init(&frac_len, BC_NUM_INT(n));
2311 bc_num_copy(&intp, n);
2312 bc_num_one(&frac_len);
2313
2314 bc_num_truncate(&intp, intp.rdx);
2315 s = bc_num_sub(n, &intp, &fracp, 0);
2316 if (s) goto err;
2317
2318 while (intp.len != 0) {
2319 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2320 if (s) goto err;
2321 s = bc_num_ulong(&digit, &dig);
2322 if (s) goto err;
2323 bc_vec_push(&stack, &dig);
2324 }
2325
2326 for (i = 0; i < stack.len; ++i) {
2327 ptr = bc_vec_item_rev(&stack, i);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002328 print(*ptr, width, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06002329 }
2330
2331 if (!n->rdx) goto err;
2332
2333 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2334 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2335 if (s) goto err;
2336 s = bc_num_ulong(&fracp, &dig);
2337 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002338 bc_num_ulong2num(&intp, dig);
Gavin Howard01055ba2018-11-03 11:00:21 -06002339 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2340 if (s) goto err;
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002341 print(dig, width, radix);
Gavin Howard01055ba2018-11-03 11:00:21 -06002342 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2343 if (s) goto err;
2344 }
2345
2346err:
2347 bc_num_free(&frac_len);
2348 bc_num_free(&digit);
2349 bc_num_free(&fracp);
2350 bc_num_free(&intp);
2351 bc_vec_free(&stack);
2352 return s;
2353}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01002354#if ERRORS_ARE_FATAL
2355# define bc_num_printNum(...) (bc_num_printNum(__VA_ARGS__), BC_STATUS_SUCCESS)
2356#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002357
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002358static BcStatus bc_num_printBase(BcNum *n)
Gavin Howard01055ba2018-11-03 11:00:21 -06002359{
2360 BcStatus s;
2361 size_t width, i;
2362 BcNumDigitOp print;
2363 bool neg = n->neg;
2364
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002365 if (neg) {
2366 bb_putchar('-');
2367 G.prog.nchars++;
2368 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002369
2370 n->neg = false;
2371
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002372 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002373 width = 1;
2374 print = bc_num_printHex;
2375 }
2376 else {
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002377 for (i = G.prog.ob_t - 1, width = 0; i != 0; i /= 10, ++width)
2378 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002379 print = bc_num_printDigits;
2380 }
2381
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002382 s = bc_num_printNum(n, &G.prog.ob, width, print);
Gavin Howard01055ba2018-11-03 11:00:21 -06002383 n->neg = neg;
2384
2385 return s;
2386}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01002387#if ERRORS_ARE_FATAL
2388# define bc_num_printBase(...) (bc_num_printBase(__VA_ARGS__), BC_STATUS_SUCCESS)
2389#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002390
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002391#if ENABLE_DC
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002392static BcStatus bc_num_stream(BcNum *n, BcNum *base)
Gavin Howard01055ba2018-11-03 11:00:21 -06002393{
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002394 return bc_num_printNum(n, base, 1, bc_num_printChar);
Gavin Howard01055ba2018-11-03 11:00:21 -06002395}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01002396#if ERRORS_ARE_FATAL
2397# define bc_num_stream(...) (bc_num_stream(__VA_ARGS__), BC_STATUS_SUCCESS)
2398#endif
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002399#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002400
Denys Vlasenko9311e012018-12-10 11:54:18 +01002401static bool bc_num_strValid(const char *val, size_t base)
2402{
2403 BcDig b;
2404 bool radix;
2405
2406 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2407 radix = false;
2408 for (;;) {
2409 BcDig c = *val++;
2410 if (c == '\0')
2411 break;
2412 if (c == '.') {
2413 if (radix) return false;
2414 radix = true;
2415 continue;
2416 }
2417 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2418 return false;
2419 }
2420 return true;
2421}
2422
2423// Note: n is already "bc_num_zero()"ed,
2424// leading zeroes in "val" are removed
2425static void bc_num_parseDecimal(BcNum *n, const char *val)
2426{
2427 size_t len, i;
2428 const char *ptr;
Denys Vlasenko9311e012018-12-10 11:54:18 +01002429
2430 len = strlen(val);
2431 if (len == 0)
2432 return;
2433
Denys Vlasenko9311e012018-12-10 11:54:18 +01002434 bc_num_expand(n, len);
2435
2436 ptr = strchr(val, '.');
2437
2438 n->rdx = 0;
2439 if (ptr != NULL)
2440 n->rdx = (size_t)((val + len) - (ptr + 1));
2441
Denys Vlasenkodafbc2c2018-12-10 15:38:52 +01002442 for (i = 0; val[i]; ++i) {
2443 if (val[i] != '0' && val[i] != '.') {
2444 // Not entirely zero value - convert it, and exit
2445 i = len - 1;
2446 for (;;) {
2447 n->num[n->len] = val[i] - '0';
2448 ++n->len;
Denys Vlasenko9311e012018-12-10 11:54:18 +01002449 skip_dot:
Denys Vlasenkodafbc2c2018-12-10 15:38:52 +01002450 if ((ssize_t)--i == (ssize_t)-1) break;
2451 if (val[i] == '.') goto skip_dot;
2452 }
2453 break;
Denys Vlasenko9311e012018-12-10 11:54:18 +01002454 }
2455 }
Denys Vlasenkodafbc2c2018-12-10 15:38:52 +01002456 // if this is reached, the value is entirely zero
Denys Vlasenko9311e012018-12-10 11:54:18 +01002457}
2458
2459// Note: n is already "bc_num_zero()"ed,
2460// leading zeroes in "val" are removed
2461static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2462{
2463 BcStatus s;
2464 BcNum temp, mult, result;
2465 BcDig c = '\0';
2466 unsigned long v;
2467 size_t i, digits;
2468
2469 for (i = 0; ; ++i) {
2470 if (val[i] == '\0')
2471 return;
2472 if (val[i] != '.' && val[i] != '0')
2473 break;
2474 }
2475
2476 bc_num_init_DEF_SIZE(&temp);
2477 bc_num_init_DEF_SIZE(&mult);
2478
2479 for (;;) {
2480 c = *val++;
2481 if (c == '\0') goto int_err;
2482 if (c == '.') break;
2483
2484 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2485
2486 s = bc_num_mul(n, base, &mult, 0);
2487 if (s) goto int_err;
2488 bc_num_ulong2num(&temp, v);
2489 s = bc_num_add(&mult, &temp, n, 0);
2490 if (s) goto int_err;
2491 }
2492
2493 bc_num_init(&result, base->len);
2494 //bc_num_zero(&result); - already is
2495 bc_num_one(&mult);
2496
2497 digits = 0;
2498 for (;;) {
2499 c = *val++;
2500 if (c == '\0') break;
2501 digits++;
2502
2503 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2504
2505 s = bc_num_mul(&result, base, &result, 0);
2506 if (s) goto err;
2507 bc_num_ulong2num(&temp, v);
2508 s = bc_num_add(&result, &temp, &result, 0);
2509 if (s) goto err;
2510 s = bc_num_mul(&mult, base, &mult, 0);
2511 if (s) goto err;
2512 }
2513
2514 s = bc_num_div(&result, &mult, &result, digits);
2515 if (s) goto err;
2516 s = bc_num_add(n, &result, n, digits);
2517 if (s) goto err;
2518
2519 if (n->len != 0) {
2520 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2521 } else
2522 bc_num_zero(n);
2523
2524err:
2525 bc_num_free(&result);
2526int_err:
2527 bc_num_free(&mult);
2528 bc_num_free(&temp);
2529}
2530
Gavin Howard01055ba2018-11-03 11:00:21 -06002531static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2532 size_t base_t)
2533{
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002534 if (!bc_num_strValid(val, base_t))
2535 return bc_error("bad number string");
Gavin Howard01055ba2018-11-03 11:00:21 -06002536
Denys Vlasenko4a024c72018-12-09 13:21:54 +01002537 bc_num_zero(n);
2538 while (*val == '0') val++;
2539
Gavin Howard01055ba2018-11-03 11:00:21 -06002540 if (base_t == 10)
2541 bc_num_parseDecimal(n, val);
2542 else
2543 bc_num_parseBase(n, val, base);
2544
2545 return BC_STATUS_SUCCESS;
2546}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01002547#if ERRORS_ARE_FATAL
2548# define bc_num_parse(...) (bc_num_parse(__VA_ARGS__), BC_STATUS_SUCCESS)
2549#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002550
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002551static BcStatus bc_num_print(BcNum *n, bool newline)
Gavin Howard01055ba2018-11-03 11:00:21 -06002552{
2553 BcStatus s = BC_STATUS_SUCCESS;
2554
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002555 bc_num_printNewline();
Gavin Howard01055ba2018-11-03 11:00:21 -06002556
2557 if (n->len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002558 bb_putchar('0');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002559 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06002560 }
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002561 else if (G.prog.ob_t == 10)
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002562 bc_num_printDecimal(n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002563 else
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002564 s = bc_num_printBase(n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002565
2566 if (newline) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002567 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002568 G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06002569 }
2570
2571 return s;
2572}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01002573#if ERRORS_ARE_FATAL
2574# define bc_num_print(...) (bc_num_print(__VA_ARGS__), BC_STATUS_SUCCESS)
2575#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002576
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002577static FAST_FUNC BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002578{
2579 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2580 (void) scale;
2581 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2582}
2583
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002584static FAST_FUNC BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002585{
2586 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2587 (void) scale;
2588 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2589}
2590
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002591static FAST_FUNC BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002592{
2593 size_t req = BC_NUM_MREQ(a, b, scale);
2594 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2595}
2596
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002597static FAST_FUNC BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002598{
2599 size_t req = BC_NUM_MREQ(a, b, scale);
2600 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2601}
2602
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002603static FAST_FUNC BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002604{
2605 size_t req = BC_NUM_MREQ(a, b, scale);
2606 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2607}
2608
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002609static FAST_FUNC BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
Gavin Howard01055ba2018-11-03 11:00:21 -06002610{
2611 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2612}
2613
2614static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2615{
2616 BcStatus s;
2617 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2618 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2619 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2620
2621 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2622 bc_num_expand(b, req);
2623
2624 if (a->len == 0) {
2625 bc_num_setToZero(b, scale);
2626 return BC_STATUS_SUCCESS;
2627 }
2628 else if (a->neg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002629 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002630 else if (BC_NUM_ONE(a)) {
2631 bc_num_one(b);
2632 bc_num_extend(b, scale);
2633 return BC_STATUS_SUCCESS;
2634 }
2635
2636 scale = BC_MAX(scale, a->rdx) + 1;
2637 len = a->len + scale;
2638
2639 bc_num_init(&num1, len);
2640 bc_num_init(&num2, len);
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01002641 bc_num_init_DEF_SIZE(&half);
Gavin Howard01055ba2018-11-03 11:00:21 -06002642
2643 bc_num_one(&half);
2644 half.num[0] = 5;
2645 half.rdx = 1;
2646
2647 bc_num_init(&f, len);
2648 bc_num_init(&fprime, len);
2649
2650 x0 = &num1;
2651 x1 = &num2;
2652
2653 bc_num_one(x0);
2654 pow = BC_NUM_INT(a);
2655
2656 if (pow) {
2657
2658 if (pow & 1)
2659 x0->num[0] = 2;
2660 else
2661 x0->num[0] = 6;
2662
2663 pow -= 2 - (pow & 1);
2664
2665 bc_num_extend(x0, pow);
2666
2667 // Make sure to move the radix back.
2668 x0->rdx -= pow;
2669 }
2670
2671 x0->rdx = digs = digs1 = 0;
2672 resrdx = scale + 2;
2673 len = BC_NUM_INT(x0) + resrdx - 1;
2674
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002675 while (cmp != 0 || digs < len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002676
2677 s = bc_num_div(a, x0, &f, resrdx);
2678 if (s) goto err;
2679 s = bc_num_add(x0, &f, &fprime, resrdx);
2680 if (s) goto err;
2681 s = bc_num_mul(&fprime, &half, x1, resrdx);
2682 if (s) goto err;
2683
2684 cmp = bc_num_cmp(x1, x0);
2685 digs = x1->len - (unsigned long long) llabs(cmp);
2686
2687 if (cmp == cmp2 && digs == digs1)
2688 times += 1;
2689 else
2690 times = 0;
2691
2692 resrdx += times > 4;
2693
2694 cmp2 = cmp1;
2695 cmp1 = cmp;
2696 digs1 = digs;
2697
2698 temp = x0;
2699 x0 = x1;
2700 x1 = temp;
2701 }
2702
Gavin Howard01055ba2018-11-03 11:00:21 -06002703 bc_num_copy(b, x0);
2704 scale -= 1;
2705 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2706
2707err:
2708 bc_num_free(&fprime);
2709 bc_num_free(&f);
2710 bc_num_free(&half);
2711 bc_num_free(&num2);
2712 bc_num_free(&num1);
2713 return s;
2714}
2715
2716static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2717 size_t scale)
2718{
2719 BcStatus s;
2720 BcNum num2, *ptr_a;
2721 bool init = false;
2722 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2723
2724 if (c == a) {
2725 memcpy(&num2, c, sizeof(BcNum));
2726 ptr_a = &num2;
2727 bc_num_init(c, len);
2728 init = true;
2729 }
2730 else {
2731 ptr_a = a;
2732 bc_num_expand(c, len);
2733 }
2734
2735 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2736
2737 if (init) bc_num_free(&num2);
2738
2739 return s;
2740}
2741
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002742#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002743static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2744{
2745 BcStatus s;
2746 BcNum base, exp, two, temp;
2747
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002748 if (c->len == 0)
2749 return bc_error("divide by zero");
2750 if (a->rdx || b->rdx || c->rdx)
2751 return bc_error("non integer number");
2752 if (b->neg)
2753 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002754
2755 bc_num_expand(d, c->len);
2756 bc_num_init(&base, c->len);
2757 bc_num_init(&exp, b->len);
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01002758 bc_num_init_DEF_SIZE(&two);
Gavin Howard01055ba2018-11-03 11:00:21 -06002759 bc_num_init(&temp, b->len);
2760
2761 bc_num_one(&two);
2762 two.num[0] = 2;
2763 bc_num_one(d);
2764
2765 s = bc_num_rem(a, c, &base, 0);
2766 if (s) goto err;
2767 bc_num_copy(&exp, b);
2768
2769 while (exp.len != 0) {
2770
2771 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2772 if (s) goto err;
2773
2774 if (BC_NUM_ONE(&temp)) {
2775 s = bc_num_mul(d, &base, &temp, 0);
2776 if (s) goto err;
2777 s = bc_num_rem(&temp, c, d, 0);
2778 if (s) goto err;
2779 }
2780
2781 s = bc_num_mul(&base, &base, &temp, 0);
2782 if (s) goto err;
2783 s = bc_num_rem(&temp, c, &base, 0);
2784 if (s) goto err;
2785 }
2786
2787err:
2788 bc_num_free(&temp);
2789 bc_num_free(&two);
2790 bc_num_free(&exp);
2791 bc_num_free(&base);
2792 return s;
2793}
2794#endif // ENABLE_DC
2795
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002796#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002797static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2798{
2799 BcId a;
2800 size_t i;
2801
2802 for (i = 0; i < f->autos.len; ++i) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002803 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2804 return bc_error("function parameter or auto var has the same name as another");
Gavin Howard01055ba2018-11-03 11:00:21 -06002805 }
2806
2807 a.idx = var;
2808 a.name = name;
2809
2810 bc_vec_push(&f->autos, &a);
2811
2812 return BC_STATUS_SUCCESS;
2813}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01002814#if ERRORS_ARE_FATAL
2815# define bc_func_insert(...) (bc_func_insert(__VA_ARGS__), BC_STATUS_SUCCESS)
2816#endif
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002817#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002818
2819static void bc_func_init(BcFunc *f)
2820{
Denys Vlasenko7d628012018-12-04 21:46:47 +01002821 bc_char_vec_init(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06002822 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2823 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2824 f->nparams = 0;
2825}
2826
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002827static FAST_FUNC void bc_func_free(void *func)
Gavin Howard01055ba2018-11-03 11:00:21 -06002828{
2829 BcFunc *f = (BcFunc *) func;
2830 bc_vec_free(&f->code);
2831 bc_vec_free(&f->autos);
2832 bc_vec_free(&f->labels);
2833}
2834
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002835static void bc_array_expand(BcVec *a, size_t len);
2836
Gavin Howard01055ba2018-11-03 11:00:21 -06002837static void bc_array_init(BcVec *a, bool nums)
2838{
2839 if (nums)
2840 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2841 else
2842 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2843 bc_array_expand(a, 1);
2844}
2845
Gavin Howard01055ba2018-11-03 11:00:21 -06002846static void bc_array_expand(BcVec *a, size_t len)
2847{
2848 BcResultData data;
2849
2850 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2851 while (len > a->len) {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01002852 bc_num_init_DEF_SIZE(&data.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002853 bc_vec_push(a, &data.n);
2854 }
2855 }
2856 else {
2857 while (len > a->len) {
2858 bc_array_init(&data.v, true);
2859 bc_vec_push(a, &data.v);
2860 }
2861 }
2862}
2863
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002864static void bc_array_copy(BcVec *d, const BcVec *s)
2865{
2866 size_t i;
2867
2868 bc_vec_pop_all(d);
2869 bc_vec_expand(d, s->cap);
2870 d->len = s->len;
2871
2872 for (i = 0; i < s->len; ++i) {
2873 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2874 bc_num_init(dnum, snum->len);
2875 bc_num_copy(dnum, snum);
2876 }
2877}
2878
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002879static FAST_FUNC void bc_string_free(void *string)
Gavin Howard01055ba2018-11-03 11:00:21 -06002880{
2881 free(*((char **) string));
2882}
2883
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002884#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002885static void bc_result_copy(BcResult *d, BcResult *src)
2886{
2887 d->t = src->t;
2888
2889 switch (d->t) {
2890
2891 case BC_RESULT_TEMP:
2892 case BC_RESULT_IBASE:
2893 case BC_RESULT_SCALE:
2894 case BC_RESULT_OBASE:
2895 {
2896 bc_num_init(&d->d.n, src->d.n.len);
2897 bc_num_copy(&d->d.n, &src->d.n);
2898 break;
2899 }
2900
2901 case BC_RESULT_VAR:
2902 case BC_RESULT_ARRAY:
2903 case BC_RESULT_ARRAY_ELEM:
2904 {
2905 d->d.id.name = xstrdup(src->d.id.name);
2906 break;
2907 }
2908
2909 case BC_RESULT_CONSTANT:
2910 case BC_RESULT_LAST:
2911 case BC_RESULT_ONE:
2912 case BC_RESULT_STR:
2913 {
2914 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2915 break;
2916 }
2917 }
2918}
2919#endif // ENABLE_DC
2920
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01002921static FAST_FUNC void bc_result_free(void *result)
Gavin Howard01055ba2018-11-03 11:00:21 -06002922{
2923 BcResult *r = (BcResult *) result;
2924
2925 switch (r->t) {
2926
2927 case BC_RESULT_TEMP:
2928 case BC_RESULT_IBASE:
2929 case BC_RESULT_SCALE:
2930 case BC_RESULT_OBASE:
2931 {
2932 bc_num_free(&r->d.n);
2933 break;
2934 }
2935
2936 case BC_RESULT_VAR:
2937 case BC_RESULT_ARRAY:
2938 case BC_RESULT_ARRAY_ELEM:
2939 {
2940 free(r->d.id.name);
2941 break;
2942 }
2943
2944 default:
2945 {
2946 // Do nothing.
2947 break;
2948 }
2949 }
2950}
2951
2952static void bc_lex_lineComment(BcLex *l)
2953{
2954 l->t.t = BC_LEX_WHITESPACE;
2955 while (l->i < l->len && l->buf[l->i++] != '\n');
2956 --l->i;
2957}
2958
2959static void bc_lex_whitespace(BcLex *l)
2960{
2961 char c;
2962 l->t.t = BC_LEX_WHITESPACE;
2963 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2964}
2965
2966static BcStatus bc_lex_number(BcLex *l, char start)
2967{
2968 const char *buf = l->buf + l->i;
2969 size_t len, hits = 0, bslashes = 0, i = 0, j;
2970 char c = buf[i];
2971 bool last_pt, pt = start == '.';
2972
2973 last_pt = pt;
2974 l->t.t = BC_LEX_NUMBER;
2975
2976 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2977 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2978 {
2979 if (c != '\\') {
2980 last_pt = c == '.';
2981 pt = pt || last_pt;
2982 }
2983 else {
2984 ++i;
2985 bslashes += 1;
2986 }
2987
2988 c = buf[++i];
2989 }
2990
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002991 len = i + !last_pt - bslashes * 2;
Denys Vlasenko64074a12018-12-07 15:50:14 +01002992 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2993 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2994 if (len > BC_MAX_NUM)
2995 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2996 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002997
Denys Vlasenko7d628012018-12-04 21:46:47 +01002998 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002999 bc_vec_expand(&l->t.v, len + 1);
3000 bc_vec_push(&l->t.v, &start);
3001
3002 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
3003
3004 c = buf[j];
3005
3006 // If we have hit a backslash, skip it. We don't have
3007 // to check for a newline because it's guaranteed.
3008 if (hits < bslashes && c == '\\') {
3009 ++hits;
3010 ++j;
3011 continue;
3012 }
3013
3014 bc_vec_push(&l->t.v, &c);
3015 }
3016
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003017 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003018 l->i += i;
3019
3020 return BC_STATUS_SUCCESS;
3021}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01003022#if ERRORS_ARE_FATAL
3023# define bc_lex_number(...) (bc_lex_number(__VA_ARGS__), BC_STATUS_SUCCESS)
3024#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06003025
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003026static void bc_lex_name(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06003027{
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003028 size_t i;
3029 const char *buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003030
3031 l->t.t = BC_LEX_NAME;
3032
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003033 i = 0;
3034 buf = l->buf + l->i - 1;
3035 for (;;) {
3036 char c = buf[i];
3037 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
3038 i++;
3039 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003040
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003041#if 0 // We do not protect against people with gigabyte-long names
Denys Vlasenko64074a12018-12-07 15:50:14 +01003042 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3043 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3044 if (i > BC_MAX_STRING)
3045 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
3046 }
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003047#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06003048 bc_vec_string(&l->t.v, i, buf);
3049
3050 // Increment the index. We minus 1 because it has already been incremented.
3051 l->i += i - 1;
3052
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003053 //return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06003054}
3055
3056static void bc_lex_init(BcLex *l, BcLexNext next)
3057{
3058 l->next = next;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003059 bc_char_vec_init(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003060}
3061
3062static void bc_lex_free(BcLex *l)
3063{
3064 bc_vec_free(&l->t.v);
3065}
3066
Denys Vlasenko0409ad32018-12-05 16:39:22 +01003067static void bc_lex_file(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06003068{
Denys Vlasenko5318f812018-12-05 17:48:01 +01003069 G.err_line = l->line = 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003070 l->newline = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06003071}
3072
3073static BcStatus bc_lex_next(BcLex *l)
3074{
3075 BcStatus s;
3076
3077 l->t.last = l->t.t;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003078 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06003079
3080 l->line += l->newline;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003081 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003082 l->t.t = BC_LEX_EOF;
3083
3084 l->newline = (l->i == l->len);
3085 if (l->newline) return BC_STATUS_SUCCESS;
3086
3087 // Loop until failure or we don't have whitespace. This
3088 // is so the parser doesn't get inundated with whitespace.
3089 do {
3090 s = l->next(l);
3091 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3092
3093 return s;
3094}
3095
3096static BcStatus bc_lex_text(BcLex *l, const char *text)
3097{
3098 l->buf = text;
3099 l->i = 0;
3100 l->len = strlen(text);
3101 l->t.t = l->t.last = BC_LEX_INVALID;
3102 return bc_lex_next(l);
3103}
3104
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003105#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06003106static BcStatus bc_lex_identifier(BcLex *l)
3107{
3108 BcStatus s;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003109 unsigned i;
Gavin Howard01055ba2018-11-03 11:00:21 -06003110 const char *buf = l->buf + l->i - 1;
3111
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003112 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3113 const char *keyword8 = bc_lex_kws[i].name8;
3114 unsigned j = 0;
3115 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3116 j++;
3117 if (j == 8) goto match;
Gavin Howard01055ba2018-11-03 11:00:21 -06003118 }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003119 if (keyword8[j] != '\0')
3120 continue;
3121 match:
3122 // buf starts with keyword bc_lex_kws[i]
3123 l->t.t = BC_LEX_KEY_1st_keyword + i;
Denys Vlasenkod00d2f92018-12-06 12:59:40 +01003124 if (!bc_lex_kws_POSIX(i)) {
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003125 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003126 if (s) return s;
3127 }
3128
3129 // We minus 1 because the index has already been incremented.
3130 l->i += j - 1;
3131 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06003132 }
3133
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003134 bc_lex_name(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003135
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003136 if (l->t.v.len > 2) {
3137 // Prevent this:
3138 // >>> qwe=1
3139 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3140 // '
3141 unsigned len = strchrnul(buf, '\n') - buf;
3142 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3143 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003144
3145 return s;
3146}
3147
3148static BcStatus bc_lex_string(BcLex *l)
3149{
3150 size_t len, nls = 0, i = l->i;
3151 char c;
3152
3153 l->t.t = BC_LEX_STR;
3154
3155 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3156
3157 if (c == '\0') {
3158 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003159 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003160 }
3161
3162 len = i - l->i;
Denys Vlasenko64074a12018-12-07 15:50:14 +01003163 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3164 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3165 if (len > BC_MAX_STRING)
3166 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3167 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003168 bc_vec_string(&l->t.v, len, l->buf + l->i);
3169
3170 l->i = i + 1;
3171 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003172 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003173
3174 return BC_STATUS_SUCCESS;
3175}
3176
3177static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3178{
3179 if (l->buf[l->i] == '=') {
3180 ++l->i;
3181 l->t.t = with;
3182 }
3183 else
3184 l->t.t = without;
3185}
3186
3187static BcStatus bc_lex_comment(BcLex *l)
3188{
3189 size_t i, nls = 0;
3190 const char *buf = l->buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003191
3192 l->t.t = BC_LEX_WHITESPACE;
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003193 i = ++l->i;
3194 for (;;) {
3195 char c = buf[i];
3196 check_star:
3197 if (c == '*') {
3198 c = buf[++i];
3199 if (c == '/')
3200 break;
3201 goto check_star;
3202 }
3203 if (c == '\0') {
Gavin Howard01055ba2018-11-03 11:00:21 -06003204 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003205 return bc_error("comment end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003206 }
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003207 nls += (c == '\n');
3208 i++;
Gavin Howard01055ba2018-11-03 11:00:21 -06003209 }
3210
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003211 l->i = i + 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003212 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003213 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003214
3215 return BC_STATUS_SUCCESS;
3216}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01003217#if ERRORS_ARE_FATAL
3218# define bc_lex_comment(...) (bc_lex_comment(__VA_ARGS__), BC_STATUS_SUCCESS)
3219#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06003220
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01003221static FAST_FUNC BcStatus bc_lex_token(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06003222{
3223 BcStatus s = BC_STATUS_SUCCESS;
3224 char c = l->buf[l->i++], c2;
3225
3226 // This is the workhorse of the lexer.
3227 switch (c) {
3228
3229 case '\0':
3230 case '\n':
3231 {
3232 l->newline = true;
3233 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3234 break;
3235 }
3236
3237 case '\t':
3238 case '\v':
3239 case '\f':
3240 case '\r':
3241 case ' ':
3242 {
3243 bc_lex_whitespace(l);
3244 break;
3245 }
3246
3247 case '!':
3248 {
3249 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3250
3251 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
Denys Vlasenko00646792018-12-05 18:12:27 +01003252 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
Gavin Howard01055ba2018-11-03 11:00:21 -06003253 if (s) return s;
3254 }
3255
3256 break;
3257 }
3258
3259 case '"':
3260 {
3261 s = bc_lex_string(l);
3262 break;
3263 }
3264
3265 case '#':
3266 {
Denys Vlasenko00646792018-12-05 18:12:27 +01003267 s = bc_POSIX_does_not_allow("'#' script comments");
Gavin Howard01055ba2018-11-03 11:00:21 -06003268 if (s) return s;
3269
3270 bc_lex_lineComment(l);
3271
3272 break;
3273 }
3274
3275 case '%':
3276 {
3277 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3278 break;
3279 }
3280
3281 case '&':
3282 {
3283 c2 = l->buf[l->i];
3284 if (c2 == '&') {
3285
Denys Vlasenko00646792018-12-05 18:12:27 +01003286 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
Gavin Howard01055ba2018-11-03 11:00:21 -06003287 if (s) return s;
3288
3289 ++l->i;
3290 l->t.t = BC_LEX_OP_BOOL_AND;
3291 }
3292 else {
3293 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003294 s = bc_error_bad_character('&');
Gavin Howard01055ba2018-11-03 11:00:21 -06003295 }
3296
3297 break;
3298 }
3299
3300 case '(':
3301 case ')':
3302 {
3303 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3304 break;
3305 }
3306
3307 case '*':
3308 {
3309 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3310 break;
3311 }
3312
3313 case '+':
3314 {
3315 c2 = l->buf[l->i];
3316 if (c2 == '+') {
3317 ++l->i;
3318 l->t.t = BC_LEX_OP_INC;
3319 }
3320 else
3321 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3322 break;
3323 }
3324
3325 case ',':
3326 {
3327 l->t.t = BC_LEX_COMMA;
3328 break;
3329 }
3330
3331 case '-':
3332 {
3333 c2 = l->buf[l->i];
3334 if (c2 == '-') {
3335 ++l->i;
3336 l->t.t = BC_LEX_OP_DEC;
3337 }
3338 else
3339 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3340 break;
3341 }
3342
3343 case '.':
3344 {
3345 if (isdigit(l->buf[l->i]))
3346 s = bc_lex_number(l, c);
3347 else {
3348 l->t.t = BC_LEX_KEY_LAST;
Denys Vlasenko00646792018-12-05 18:12:27 +01003349 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
Gavin Howard01055ba2018-11-03 11:00:21 -06003350 }
3351 break;
3352 }
3353
3354 case '/':
3355 {
3356 c2 = l->buf[l->i];
3357 if (c2 == '*')
3358 s = bc_lex_comment(l);
3359 else
3360 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3361 break;
3362 }
3363
3364 case '0':
3365 case '1':
3366 case '2':
3367 case '3':
3368 case '4':
3369 case '5':
3370 case '6':
3371 case '7':
3372 case '8':
3373 case '9':
3374 case 'A':
3375 case 'B':
3376 case 'C':
3377 case 'D':
3378 case 'E':
3379 case 'F':
3380 {
3381 s = bc_lex_number(l, c);
3382 break;
3383 }
3384
3385 case ';':
3386 {
3387 l->t.t = BC_LEX_SCOLON;
3388 break;
3389 }
3390
3391 case '<':
3392 {
3393 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3394 break;
3395 }
3396
3397 case '=':
3398 {
3399 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3400 break;
3401 }
3402
3403 case '>':
3404 {
3405 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3406 break;
3407 }
3408
3409 case '[':
3410 case ']':
3411 {
3412 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3413 break;
3414 }
3415
3416 case '\\':
3417 {
3418 if (l->buf[l->i] == '\n') {
3419 l->t.t = BC_LEX_WHITESPACE;
3420 ++l->i;
3421 }
3422 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003423 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003424 break;
3425 }
3426
3427 case '^':
3428 {
3429 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3430 break;
3431 }
3432
3433 case 'a':
3434 case 'b':
3435 case 'c':
3436 case 'd':
3437 case 'e':
3438 case 'f':
3439 case 'g':
3440 case 'h':
3441 case 'i':
3442 case 'j':
3443 case 'k':
3444 case 'l':
3445 case 'm':
3446 case 'n':
3447 case 'o':
3448 case 'p':
3449 case 'q':
3450 case 'r':
3451 case 's':
3452 case 't':
3453 case 'u':
3454 case 'v':
3455 case 'w':
3456 case 'x':
3457 case 'y':
3458 case 'z':
3459 {
3460 s = bc_lex_identifier(l);
3461 break;
3462 }
3463
3464 case '{':
3465 case '}':
3466 {
3467 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3468 break;
3469 }
3470
3471 case '|':
3472 {
3473 c2 = l->buf[l->i];
3474
3475 if (c2 == '|') {
Denys Vlasenko00646792018-12-05 18:12:27 +01003476 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
Gavin Howard01055ba2018-11-03 11:00:21 -06003477 if (s) return s;
3478
3479 ++l->i;
3480 l->t.t = BC_LEX_OP_BOOL_OR;
3481 }
3482 else {
3483 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003484 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003485 }
3486
3487 break;
3488 }
3489
3490 default:
3491 {
3492 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003493 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003494 break;
3495 }
3496 }
3497
3498 return s;
3499}
3500#endif // ENABLE_BC
3501
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003502#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06003503static BcStatus dc_lex_register(BcLex *l)
3504{
3505 BcStatus s = BC_STATUS_SUCCESS;
3506
3507 if (isspace(l->buf[l->i - 1])) {
3508 bc_lex_whitespace(l);
3509 ++l->i;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01003510 if (!G_exreg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003511 s = bc_error("extended register");
Gavin Howard01055ba2018-11-03 11:00:21 -06003512 else
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003513 bc_lex_name(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003514 }
3515 else {
Denys Vlasenko7d628012018-12-04 21:46:47 +01003516 bc_vec_pop_all(&l->t.v);
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003517 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003518 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003519 l->t.t = BC_LEX_NAME;
3520 }
3521
3522 return s;
3523}
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003524#if ERRORS_ARE_FATAL
3525# define dc_lex_register(...) (dc_lex_register(__VA_ARGS__), BC_STATUS_SUCCESS)
3526#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06003527
3528static BcStatus dc_lex_string(BcLex *l)
3529{
3530 size_t depth = 1, nls = 0, i = l->i;
3531 char c;
3532
3533 l->t.t = BC_LEX_STR;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003534 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003535
3536 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3537
3538 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3539 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3540 nls += (c == '\n');
3541
3542 if (depth) bc_vec_push(&l->t.v, &c);
3543 }
3544
3545 if (c == '\0') {
3546 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003547 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003548 }
3549
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003550 bc_vec_pushZeroByte(&l->t.v);
Denys Vlasenko64074a12018-12-07 15:50:14 +01003551 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3552 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3553 if (i - l->i > BC_MAX_STRING)
3554 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3555 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003556
3557 l->i = i;
3558 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003559 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003560
3561 return BC_STATUS_SUCCESS;
3562}
Denys Vlasenko88cfea62018-12-10 20:26:04 +01003563#if ERRORS_ARE_FATAL
3564# define dc_lex_string(...) (dc_lex_string(__VA_ARGS__), BC_STATUS_SUCCESS)
3565#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06003566
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01003567static FAST_FUNC BcStatus dc_lex_token(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06003568{
3569 BcStatus s = BC_STATUS_SUCCESS;
3570 char c = l->buf[l->i++], c2;
3571 size_t i;
3572
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003573 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3574 if (l->t.last == dc_lex_regs[i])
3575 return dc_lex_register(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003576 }
3577
3578 if (c >= '%' && c <= '~' &&
3579 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3580 {
3581 return s;
3582 }
3583
3584 // This is the workhorse of the lexer.
3585 switch (c) {
3586
3587 case '\0':
3588 {
3589 l->t.t = BC_LEX_EOF;
3590 break;
3591 }
3592
3593 case '\n':
3594 case '\t':
3595 case '\v':
3596 case '\f':
3597 case '\r':
3598 case ' ':
3599 {
3600 l->newline = (c == '\n');
3601 bc_lex_whitespace(l);
3602 break;
3603 }
3604
3605 case '!':
3606 {
3607 c2 = l->buf[l->i];
3608
3609 if (c2 == '=')
3610 l->t.t = BC_LEX_OP_REL_NE;
3611 else if (c2 == '<')
3612 l->t.t = BC_LEX_OP_REL_LE;
3613 else if (c2 == '>')
3614 l->t.t = BC_LEX_OP_REL_GE;
3615 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003616 return bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003617
3618 ++l->i;
3619 break;
3620 }
3621
3622 case '#':
3623 {
3624 bc_lex_lineComment(l);
3625 break;
3626 }
3627
3628 case '.':
3629 {
3630 if (isdigit(l->buf[l->i]))
3631 s = bc_lex_number(l, c);
3632 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003633 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003634 break;
3635 }
3636
3637 case '0':
3638 case '1':
3639 case '2':
3640 case '3':
3641 case '4':
3642 case '5':
3643 case '6':
3644 case '7':
3645 case '8':
3646 case '9':
3647 case 'A':
3648 case 'B':
3649 case 'C':
3650 case 'D':
3651 case 'E':
3652 case 'F':
3653 {
3654 s = bc_lex_number(l, c);
3655 break;
3656 }
3657
3658 case '[':
3659 {
3660 s = dc_lex_string(l);
3661 break;
3662 }
3663
3664 default:
3665 {
3666 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003667 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003668 break;
3669 }
3670 }
3671
3672 return s;
3673}
3674#endif // ENABLE_DC
3675
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003676static void bc_program_addFunc(char *name, size_t *idx);
3677
Gavin Howard01055ba2018-11-03 11:00:21 -06003678static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3679{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003680 bc_program_addFunc(name, idx);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003681 p->func = bc_program_func(p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003682}
3683
Denys Vlasenkob23ac512018-12-06 13:10:56 +01003684#define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3685
Gavin Howard01055ba2018-11-03 11:00:21 -06003686static void bc_parse_pushName(BcParse *p, char *name)
3687{
3688 size_t i = 0, len = strlen(name);
3689
3690 for (; i < len; ++i) bc_parse_push(p, name[i]);
3691 bc_parse_push(p, BC_PARSE_STREND);
3692
3693 free(name);
3694}
3695
3696static void bc_parse_pushIndex(BcParse *p, size_t idx)
3697{
3698 unsigned char amt, i, nums[sizeof(size_t)];
3699
3700 for (amt = 0; idx; ++amt) {
3701 nums[amt] = (char) idx;
3702 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3703 }
3704
3705 bc_parse_push(p, amt);
3706 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3707}
3708
3709static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3710{
3711 char *num = xstrdup(p->l.t.v.v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003712 size_t idx = G.prog.consts.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06003713
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003714 bc_vec_push(&G.prog.consts, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06003715
3716 bc_parse_push(p, BC_INST_NUM);
3717 bc_parse_pushIndex(p, idx);
3718
3719 ++(*nexs);
3720 (*prev) = BC_INST_NUM;
3721}
3722
3723static BcStatus bc_parse_text(BcParse *p, const char *text)
3724{
3725 BcStatus s;
3726
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003727 p->func = bc_program_func(p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003728
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003729 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003730 p->l.t.t = BC_LEX_INVALID;
3731 s = p->parse(p);
3732 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003733 if (!BC_PARSE_CAN_EXEC(p))
3734 return bc_error("file is not executable");
Gavin Howard01055ba2018-11-03 11:00:21 -06003735 }
3736
3737 return bc_lex_text(&p->l, text);
3738}
3739
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003740// Called when parsing or execution detects a failure,
3741// resets execution structures.
3742static void bc_program_reset(void)
3743{
3744 BcFunc *f;
3745 BcInstPtr *ip;
3746
3747 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3748 bc_vec_pop_all(&G.prog.results);
3749
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003750 f = bc_program_func(0);
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003751 ip = bc_vec_top(&G.prog.stack);
3752 ip->idx = f->code.len;
3753}
3754
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003755#define bc_parse_updateFunc(p, f) \
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003756 ((p)->func = bc_program_func((p)->fidx = (f)))
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003757
Denys Vlasenkod38af482018-12-04 19:11:02 +01003758// Called when bc/dc_parse_parse() detects a failure,
3759// resets parsing structures.
3760static void bc_parse_reset(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06003761{
3762 if (p->fidx != BC_PROG_MAIN) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003763 p->func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003764 bc_vec_pop_all(&p->func->code);
3765 bc_vec_pop_all(&p->func->autos);
3766 bc_vec_pop_all(&p->func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06003767
3768 bc_parse_updateFunc(p, BC_PROG_MAIN);
3769 }
3770
3771 p->l.i = p->l.len;
3772 p->l.t.t = BC_LEX_EOF;
3773 p->auto_part = (p->nbraces = 0);
3774
3775 bc_vec_npop(&p->flags, p->flags.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01003776 bc_vec_pop_all(&p->exits);
3777 bc_vec_pop_all(&p->conds);
3778 bc_vec_pop_all(&p->ops);
Gavin Howard01055ba2018-11-03 11:00:21 -06003779
Denys Vlasenkod38af482018-12-04 19:11:02 +01003780 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06003781}
3782
3783static void bc_parse_free(BcParse *p)
3784{
3785 bc_vec_free(&p->flags);
3786 bc_vec_free(&p->exits);
3787 bc_vec_free(&p->conds);
3788 bc_vec_free(&p->ops);
3789 bc_lex_free(&p->l);
3790}
3791
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003792static void bc_parse_create(BcParse *p, size_t func,
Gavin Howard01055ba2018-11-03 11:00:21 -06003793 BcParseParse parse, BcLexNext next)
3794{
3795 memset(p, 0, sizeof(BcParse));
3796
3797 bc_lex_init(&p->l, next);
3798 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3799 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3800 bc_vec_init(&p->conds, sizeof(size_t), NULL);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003801 bc_vec_pushZeroByte(&p->flags);
Gavin Howard01055ba2018-11-03 11:00:21 -06003802 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3803
3804 p->parse = parse;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01003805 // p->auto_part = p->nbraces = 0; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06003806 bc_parse_updateFunc(p, func);
3807}
3808
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003809#if ENABLE_BC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003810
3811#define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3812#define BC_PARSE_LEAF(p, rparen) \
3813 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3814 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3815
3816// We can calculate the conversion between tokens and exprs by subtracting the
3817// position of the first operator in the lex enum and adding the position of the
3818// first in the expr enum. Note: This only works for binary operators.
3819#define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3820
Gavin Howard01055ba2018-11-03 11:00:21 -06003821static BcStatus bc_parse_else(BcParse *p);
3822static BcStatus bc_parse_stmt(BcParse *p);
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003823static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01003824static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
Gavin Howard01055ba2018-11-03 11:00:21 -06003825
3826static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3827 size_t *nexprs, bool next)
3828{
3829 BcStatus s = BC_STATUS_SUCCESS;
3830 BcLexType t;
Denys Vlasenko65437582018-12-05 19:37:19 +01003831 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3832 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003833
3834 while (p->ops.len > start) {
3835
3836 t = BC_PARSE_TOP_OP(p);
3837 if (t == BC_LEX_LPAREN) break;
3838
Denys Vlasenko65437582018-12-05 19:37:19 +01003839 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003840 if (l >= r && (l != r || !left)) break;
3841
3842 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3843 bc_vec_pop(&p->ops);
3844 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3845 }
3846
3847 bc_vec_push(&p->ops, &type);
3848 if (next) s = bc_lex_next(&p->l);
3849
3850 return s;
3851}
3852
3853static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3854{
3855 BcLexType top;
3856
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003857 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003858 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003859 top = BC_PARSE_TOP_OP(p);
3860
3861 while (top != BC_LEX_LPAREN) {
3862
3863 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3864
3865 bc_vec_pop(&p->ops);
3866 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3867
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003868 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003869 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003870 top = BC_PARSE_TOP_OP(p);
3871 }
3872
3873 bc_vec_pop(&p->ops);
3874
3875 return bc_lex_next(&p->l);
3876}
3877
3878static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3879{
3880 BcStatus s;
3881 bool comma = false;
3882 size_t nparams;
3883
3884 s = bc_lex_next(&p->l);
3885 if (s) return s;
3886
3887 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3888
3889 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3890 s = bc_parse_expr(p, flags, bc_parse_next_param);
3891 if (s) return s;
3892
3893 comma = p->l.t.t == BC_LEX_COMMA;
3894 if (comma) {
3895 s = bc_lex_next(&p->l);
3896 if (s) return s;
3897 }
3898 }
3899
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003900 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003901 bc_parse_push(p, BC_INST_CALL);
3902 bc_parse_pushIndex(p, nparams);
3903
3904 return BC_STATUS_SUCCESS;
3905}
3906
3907static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3908{
3909 BcStatus s;
3910 BcId entry, *entry_ptr;
3911 size_t idx;
3912
3913 entry.name = name;
3914
3915 s = bc_parse_params(p, flags);
3916 if (s) goto err;
3917
3918 if (p->l.t.t != BC_LEX_RPAREN) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003919 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003920 goto err;
3921 }
3922
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003923 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003924
3925 if (idx == BC_VEC_INVALID_IDX) {
3926 name = xstrdup(entry.name);
3927 bc_parse_addFunc(p, name, &idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003928 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003929 free(entry.name);
3930 }
3931 else
3932 free(name);
3933
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003934 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003935 bc_parse_pushIndex(p, entry_ptr->idx);
3936
3937 return bc_lex_next(&p->l);
3938
3939err:
3940 free(name);
3941 return s;
3942}
3943
3944static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3945{
3946 BcStatus s;
3947 char *name;
3948
3949 name = xstrdup(p->l.t.v.v);
3950 s = bc_lex_next(&p->l);
3951 if (s) goto err;
3952
3953 if (p->l.t.t == BC_LEX_LBRACKET) {
3954
3955 s = bc_lex_next(&p->l);
3956 if (s) goto err;
3957
3958 if (p->l.t.t == BC_LEX_RBRACKET) {
3959
3960 if (!(flags & BC_PARSE_ARRAY)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003961 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003962 goto err;
3963 }
3964
3965 *type = BC_INST_ARRAY;
3966 }
3967 else {
3968
3969 *type = BC_INST_ARRAY_ELEM;
3970
3971 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3972 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3973 if (s) goto err;
3974 }
3975
3976 s = bc_lex_next(&p->l);
3977 if (s) goto err;
3978 bc_parse_push(p, *type);
3979 bc_parse_pushName(p, name);
3980 }
3981 else if (p->l.t.t == BC_LEX_LPAREN) {
3982
3983 if (flags & BC_PARSE_NOCALL) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003984 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003985 goto err;
3986 }
3987
3988 *type = BC_INST_CALL;
3989 s = bc_parse_call(p, name, flags);
3990 }
3991 else {
3992 *type = BC_INST_VAR;
3993 bc_parse_push(p, BC_INST_VAR);
3994 bc_parse_pushName(p, name);
3995 }
3996
3997 return s;
3998
3999err:
4000 free(name);
4001 return s;
4002}
4003
4004static BcStatus bc_parse_read(BcParse *p)
4005{
4006 BcStatus s;
4007
4008 s = bc_lex_next(&p->l);
4009 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004010 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004011
4012 s = bc_lex_next(&p->l);
4013 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004014 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004015
4016 bc_parse_push(p, BC_INST_READ);
4017
4018 return bc_lex_next(&p->l);
4019}
4020
4021static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
4022 BcInst *prev)
4023{
4024 BcStatus s;
4025
4026 s = bc_lex_next(&p->l);
4027 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004028 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004029
4030 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
4031
4032 s = bc_lex_next(&p->l);
4033 if (s) return s;
4034
4035 s = bc_parse_expr(p, flags, bc_parse_next_rel);
4036 if (s) return s;
4037
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004038 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004039
4040 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
4041 bc_parse_push(p, *prev);
4042
4043 return bc_lex_next(&p->l);
4044}
4045
4046static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
4047{
4048 BcStatus s;
4049
4050 s = bc_lex_next(&p->l);
4051 if (s) return s;
4052
4053 if (p->l.t.t != BC_LEX_LPAREN) {
4054 *type = BC_INST_SCALE;
4055 bc_parse_push(p, BC_INST_SCALE);
4056 return BC_STATUS_SUCCESS;
4057 }
4058
4059 *type = BC_INST_SCALE_FUNC;
4060 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
4061
4062 s = bc_lex_next(&p->l);
4063 if (s) return s;
4064
4065 s = bc_parse_expr(p, flags, bc_parse_next_rel);
4066 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004067 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004068 bc_parse_push(p, BC_INST_SCALE_FUNC);
4069
4070 return bc_lex_next(&p->l);
4071}
4072
4073static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
4074 size_t *nexprs, uint8_t flags)
4075{
4076 BcStatus s;
4077 BcLexType type;
4078 char inst;
4079 BcInst etype = *prev;
4080
4081 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4082 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4083 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4084 {
4085 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4086 bc_parse_push(p, inst);
4087 s = bc_lex_next(&p->l);
4088 }
4089 else {
4090
4091 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4092 *paren_expr = true;
4093
4094 s = bc_lex_next(&p->l);
4095 if (s) return s;
4096 type = p->l.t.t;
4097
4098 // Because we parse the next part of the expression
4099 // right here, we need to increment this.
4100 *nexprs = *nexprs + 1;
4101
4102 switch (type) {
4103
4104 case BC_LEX_NAME:
4105 {
4106 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4107 break;
4108 }
4109
4110 case BC_LEX_KEY_IBASE:
4111 case BC_LEX_KEY_LAST:
4112 case BC_LEX_KEY_OBASE:
4113 {
4114 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4115 s = bc_lex_next(&p->l);
4116 break;
4117 }
4118
4119 case BC_LEX_KEY_SCALE:
4120 {
4121 s = bc_lex_next(&p->l);
4122 if (s) return s;
4123 if (p->l.t.t == BC_LEX_LPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004124 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004125 else
4126 bc_parse_push(p, BC_INST_SCALE);
4127 break;
4128 }
4129
4130 default:
4131 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004132 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004133 break;
4134 }
4135 }
4136
4137 if (!s) bc_parse_push(p, inst);
4138 }
4139
4140 return s;
4141}
4142
4143static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4144 bool rparen, size_t *nexprs)
4145{
4146 BcStatus s;
4147 BcLexType type;
4148 BcInst etype = *prev;
4149
4150 s = bc_lex_next(&p->l);
4151 if (s) return s;
4152
4153 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4154 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4155 BC_LEX_OP_MINUS :
4156 BC_LEX_NEG;
4157 *prev = BC_PARSE_TOKEN_INST(type);
4158
4159 // We can just push onto the op stack because this is the largest
4160 // precedence operator that gets pushed. Inc/dec does not.
4161 if (type != BC_LEX_OP_MINUS)
4162 bc_vec_push(&p->ops, &type);
4163 else
4164 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4165
4166 return s;
4167}
4168
4169static BcStatus bc_parse_string(BcParse *p, char inst)
4170{
4171 char *str = xstrdup(p->l.t.v.v);
4172
4173 bc_parse_push(p, BC_INST_STR);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004174 bc_parse_pushIndex(p, G.prog.strs.len);
4175 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06004176 bc_parse_push(p, inst);
4177
4178 return bc_lex_next(&p->l);
4179}
4180
4181static BcStatus bc_parse_print(BcParse *p)
4182{
4183 BcStatus s;
4184 BcLexType type;
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004185 bool comma;
Gavin Howard01055ba2018-11-03 11:00:21 -06004186
4187 s = bc_lex_next(&p->l);
4188 if (s) return s;
4189
4190 type = p->l.t.t;
4191
4192 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004193 return bc_error("bad print statement");
Gavin Howard01055ba2018-11-03 11:00:21 -06004194
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004195 comma = false;
4196 while (type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004197
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004198 if (type == BC_LEX_STR) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004199 s = bc_parse_string(p, BC_INST_PRINT_POP);
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004200 if (s) return s;
4201 } else {
Gavin Howard01055ba2018-11-03 11:00:21 -06004202 s = bc_parse_expr(p, 0, bc_parse_next_print);
4203 if (s) return s;
4204 bc_parse_push(p, BC_INST_PRINT_POP);
4205 }
4206
Gavin Howard01055ba2018-11-03 11:00:21 -06004207 comma = p->l.t.t == BC_LEX_COMMA;
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004208 if (comma) {
4209 s = bc_lex_next(&p->l);
4210 if (s) return s;
4211 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004212 type = p->l.t.t;
4213 }
4214
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004215 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004216
4217 return bc_lex_next(&p->l);
4218}
4219
4220static BcStatus bc_parse_return(BcParse *p)
4221{
4222 BcStatus s;
4223 BcLexType t;
4224 bool paren;
4225
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004226 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004227
4228 s = bc_lex_next(&p->l);
4229 if (s) return s;
4230
4231 t = p->l.t.t;
4232 paren = t == BC_LEX_LPAREN;
4233
4234 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4235 bc_parse_push(p, BC_INST_RET0);
4236 else {
4237
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004238 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004239 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004240 bc_parse_push(p, BC_INST_RET0);
4241 s = bc_lex_next(&p->l);
Gavin Howard01055ba2018-11-03 11:00:21 -06004242 }
Denys Vlasenko452df922018-12-05 20:28:26 +01004243 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06004244
4245 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004246 s = bc_POSIX_requires("parentheses around return expressions");
Gavin Howard01055ba2018-11-03 11:00:21 -06004247 if (s) return s;
4248 }
4249
4250 bc_parse_push(p, BC_INST_RET);
4251 }
4252
4253 return s;
4254}
4255
4256static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4257{
4258 BcStatus s = BC_STATUS_SUCCESS;
4259
4260 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004261 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004262
4263 if (brace) {
4264
4265 if (p->l.t.t == BC_LEX_RBRACE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004266 if (!p->nbraces) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004267 --p->nbraces;
4268 s = bc_lex_next(&p->l);
4269 if (s) return s;
4270 }
4271 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004272 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004273 }
4274
4275 if (BC_PARSE_IF(p)) {
4276
4277 uint8_t *flag_ptr;
4278
4279 while (p->l.t.t == BC_LEX_NLINE) {
4280 s = bc_lex_next(&p->l);
4281 if (s) return s;
4282 }
4283
4284 bc_vec_pop(&p->flags);
4285
4286 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4287 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4288
4289 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4290 }
4291 else if (BC_PARSE_ELSE(p)) {
4292
4293 BcInstPtr *ip;
4294 size_t *label;
4295
4296 bc_vec_pop(&p->flags);
4297
4298 ip = bc_vec_top(&p->exits);
4299 label = bc_vec_item(&p->func->labels, ip->idx);
4300 *label = p->func->code.len;
4301
4302 bc_vec_pop(&p->exits);
4303 }
4304 else if (BC_PARSE_FUNC_INNER(p)) {
4305 bc_parse_push(p, BC_INST_RET0);
4306 bc_parse_updateFunc(p, BC_PROG_MAIN);
4307 bc_vec_pop(&p->flags);
4308 }
4309 else {
4310
4311 BcInstPtr *ip = bc_vec_top(&p->exits);
4312 size_t *label = bc_vec_top(&p->conds);
4313
4314 bc_parse_push(p, BC_INST_JUMP);
4315 bc_parse_pushIndex(p, *label);
4316
4317 label = bc_vec_item(&p->func->labels, ip->idx);
4318 *label = p->func->code.len;
4319
4320 bc_vec_pop(&p->flags);
4321 bc_vec_pop(&p->exits);
4322 bc_vec_pop(&p->conds);
4323 }
4324
4325 return s;
4326}
4327
4328static void bc_parse_startBody(BcParse *p, uint8_t flags)
4329{
4330 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4331 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4332 flags |= BC_PARSE_FLAG_BODY;
4333 bc_vec_push(&p->flags, &flags);
4334}
4335
4336static void bc_parse_noElse(BcParse *p)
4337{
4338 BcInstPtr *ip;
4339 size_t *label;
4340 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4341
4342 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4343
4344 ip = bc_vec_top(&p->exits);
4345 label = bc_vec_item(&p->func->labels, ip->idx);
4346 *label = p->func->code.len;
4347
4348 bc_vec_pop(&p->exits);
4349}
4350
4351static BcStatus bc_parse_if(BcParse *p)
4352{
4353 BcStatus s;
4354 BcInstPtr ip;
4355
4356 s = bc_lex_next(&p->l);
4357 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004358 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004359
4360 s = bc_lex_next(&p->l);
4361 if (s) return s;
4362 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4363 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004364 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004365
4366 s = bc_lex_next(&p->l);
4367 if (s) return s;
4368 bc_parse_push(p, BC_INST_JUMP_ZERO);
4369
4370 ip.idx = p->func->labels.len;
4371 ip.func = ip.len = 0;
4372
4373 bc_parse_pushIndex(p, ip.idx);
4374 bc_vec_push(&p->exits, &ip);
4375 bc_vec_push(&p->func->labels, &ip.idx);
4376 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4377
4378 return BC_STATUS_SUCCESS;
4379}
4380
4381static BcStatus bc_parse_else(BcParse *p)
4382{
4383 BcInstPtr ip;
4384
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004385 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004386
4387 ip.idx = p->func->labels.len;
4388 ip.func = ip.len = 0;
4389
4390 bc_parse_push(p, BC_INST_JUMP);
4391 bc_parse_pushIndex(p, ip.idx);
4392
4393 bc_parse_noElse(p);
4394
4395 bc_vec_push(&p->exits, &ip);
4396 bc_vec_push(&p->func->labels, &ip.idx);
4397 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4398
4399 return bc_lex_next(&p->l);
4400}
4401
4402static BcStatus bc_parse_while(BcParse *p)
4403{
4404 BcStatus s;
4405 BcInstPtr ip;
4406
4407 s = bc_lex_next(&p->l);
4408 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004409 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004410 s = bc_lex_next(&p->l);
4411 if (s) return s;
4412
4413 ip.idx = p->func->labels.len;
4414
4415 bc_vec_push(&p->func->labels, &p->func->code.len);
4416 bc_vec_push(&p->conds, &ip.idx);
4417
4418 ip.idx = p->func->labels.len;
4419 ip.func = 1;
4420 ip.len = 0;
4421
4422 bc_vec_push(&p->exits, &ip);
4423 bc_vec_push(&p->func->labels, &ip.idx);
4424
4425 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4426 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004427 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004428 s = bc_lex_next(&p->l);
4429 if (s) return s;
4430
4431 bc_parse_push(p, BC_INST_JUMP_ZERO);
4432 bc_parse_pushIndex(p, ip.idx);
4433 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4434
4435 return BC_STATUS_SUCCESS;
4436}
4437
4438static BcStatus bc_parse_for(BcParse *p)
4439{
4440 BcStatus s;
4441 BcInstPtr ip;
4442 size_t cond_idx, exit_idx, body_idx, update_idx;
4443
4444 s = bc_lex_next(&p->l);
4445 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004446 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004447 s = bc_lex_next(&p->l);
4448 if (s) return s;
4449
4450 if (p->l.t.t != BC_LEX_SCOLON)
4451 s = bc_parse_expr(p, 0, bc_parse_next_for);
4452 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004453 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
Gavin Howard01055ba2018-11-03 11:00:21 -06004454
4455 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004456 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004457 s = bc_lex_next(&p->l);
4458 if (s) return s;
4459
4460 cond_idx = p->func->labels.len;
4461 update_idx = cond_idx + 1;
4462 body_idx = update_idx + 1;
4463 exit_idx = body_idx + 1;
4464
4465 bc_vec_push(&p->func->labels, &p->func->code.len);
4466
4467 if (p->l.t.t != BC_LEX_SCOLON)
4468 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4469 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004470 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004471
4472 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004473 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004474
4475 s = bc_lex_next(&p->l);
4476 if (s) return s;
4477
4478 bc_parse_push(p, BC_INST_JUMP_ZERO);
4479 bc_parse_pushIndex(p, exit_idx);
4480 bc_parse_push(p, BC_INST_JUMP);
4481 bc_parse_pushIndex(p, body_idx);
4482
4483 ip.idx = p->func->labels.len;
4484
4485 bc_vec_push(&p->conds, &update_idx);
4486 bc_vec_push(&p->func->labels, &p->func->code.len);
4487
4488 if (p->l.t.t != BC_LEX_RPAREN)
4489 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4490 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004491 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
Gavin Howard01055ba2018-11-03 11:00:21 -06004492
4493 if (s) return s;
4494
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004495 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004496 bc_parse_push(p, BC_INST_JUMP);
4497 bc_parse_pushIndex(p, cond_idx);
4498 bc_vec_push(&p->func->labels, &p->func->code.len);
4499
4500 ip.idx = exit_idx;
4501 ip.func = 1;
4502 ip.len = 0;
4503
4504 bc_vec_push(&p->exits, &ip);
4505 bc_vec_push(&p->func->labels, &ip.idx);
4506 bc_lex_next(&p->l);
4507 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4508
4509 return BC_STATUS_SUCCESS;
4510}
4511
4512static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4513{
4514 BcStatus s;
4515 size_t i;
4516 BcInstPtr *ip;
4517
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004518 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004519
4520 if (type == BC_LEX_KEY_BREAK) {
4521
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004522 if (p->exits.len == 0) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004523
4524 i = p->exits.len - 1;
4525 ip = bc_vec_item(&p->exits, i);
4526
4527 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004528 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004529
4530 i = ip->idx;
4531 }
4532 else
4533 i = *((size_t *) bc_vec_top(&p->conds));
4534
4535 bc_parse_push(p, BC_INST_JUMP);
4536 bc_parse_pushIndex(p, i);
4537
4538 s = bc_lex_next(&p->l);
4539 if (s) return s;
4540
4541 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004542 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004543
4544 return bc_lex_next(&p->l);
4545}
4546
4547static BcStatus bc_parse_func(BcParse *p)
4548{
4549 BcStatus s;
4550 bool var, comma = false;
4551 uint8_t flags;
4552 char *name;
4553
4554 s = bc_lex_next(&p->l);
4555 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004556 if (p->l.t.t != BC_LEX_NAME)
4557 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004558
4559 name = xstrdup(p->l.t.v.v);
4560 bc_parse_addFunc(p, name, &p->fidx);
4561
4562 s = bc_lex_next(&p->l);
4563 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004564 if (p->l.t.t != BC_LEX_LPAREN)
4565 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004566 s = bc_lex_next(&p->l);
4567 if (s) return s;
4568
4569 while (p->l.t.t != BC_LEX_RPAREN) {
4570
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004571 if (p->l.t.t != BC_LEX_NAME)
4572 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004573
4574 ++p->func->nparams;
4575
4576 name = xstrdup(p->l.t.v.v);
4577 s = bc_lex_next(&p->l);
4578 if (s) goto err;
4579
4580 var = p->l.t.t != BC_LEX_LBRACKET;
4581
4582 if (!var) {
4583
4584 s = bc_lex_next(&p->l);
4585 if (s) goto err;
4586
4587 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004588 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004589 goto err;
4590 }
4591
4592 s = bc_lex_next(&p->l);
4593 if (s) goto err;
4594 }
4595
4596 comma = p->l.t.t == BC_LEX_COMMA;
4597 if (comma) {
4598 s = bc_lex_next(&p->l);
4599 if (s) goto err;
4600 }
4601
4602 s = bc_func_insert(p->func, name, var);
4603 if (s) goto err;
4604 }
4605
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004606 if (comma) return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004607
4608 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4609 bc_parse_startBody(p, flags);
4610
4611 s = bc_lex_next(&p->l);
4612 if (s) return s;
4613
4614 if (p->l.t.t != BC_LEX_LBRACE)
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004615 s = bc_POSIX_requires("the left brace be on the same line as the function header");
Gavin Howard01055ba2018-11-03 11:00:21 -06004616
4617 return s;
4618
4619err:
4620 free(name);
4621 return s;
4622}
4623
4624static BcStatus bc_parse_auto(BcParse *p)
4625{
4626 BcStatus s;
4627 bool comma, var, one;
4628 char *name;
4629
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004630 if (!p->auto_part) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004631 s = bc_lex_next(&p->l);
4632 if (s) return s;
4633
4634 p->auto_part = comma = false;
4635 one = p->l.t.t == BC_LEX_NAME;
4636
4637 while (p->l.t.t == BC_LEX_NAME) {
4638
4639 name = xstrdup(p->l.t.v.v);
4640 s = bc_lex_next(&p->l);
4641 if (s) goto err;
4642
4643 var = p->l.t.t != BC_LEX_LBRACKET;
4644 if (!var) {
4645
4646 s = bc_lex_next(&p->l);
4647 if (s) goto err;
4648
4649 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004650 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004651 goto err;
4652 }
4653
4654 s = bc_lex_next(&p->l);
4655 if (s) goto err;
4656 }
4657
4658 comma = p->l.t.t == BC_LEX_COMMA;
4659 if (comma) {
4660 s = bc_lex_next(&p->l);
4661 if (s) goto err;
4662 }
4663
4664 s = bc_func_insert(p->func, name, var);
4665 if (s) goto err;
4666 }
4667
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004668 if (comma) return bc_error("bad function definition");
Denys Vlasenkoabbc4332018-12-03 21:46:41 +01004669 if (!one) return bc_error("no auto variable found");
Gavin Howard01055ba2018-11-03 11:00:21 -06004670
4671 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004672 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004673
4674 return bc_lex_next(&p->l);
4675
4676err:
4677 free(name);
4678 return s;
4679}
4680
4681static BcStatus bc_parse_body(BcParse *p, bool brace)
4682{
4683 BcStatus s = BC_STATUS_SUCCESS;
4684 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4685
4686 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4687
4688 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4689
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004690 if (!brace) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004691 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4692
4693 if (!p->auto_part) {
4694 s = bc_parse_auto(p);
4695 if (s) return s;
4696 }
4697
4698 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4699 }
4700 else {
4701 s = bc_parse_stmt(p);
4702 if (!s && !brace) s = bc_parse_endBody(p, false);
4703 }
4704
4705 return s;
4706}
4707
4708static BcStatus bc_parse_stmt(BcParse *p)
4709{
4710 BcStatus s = BC_STATUS_SUCCESS;
4711
4712 switch (p->l.t.t) {
4713
4714 case BC_LEX_NLINE:
4715 {
4716 return bc_lex_next(&p->l);
4717 }
4718
4719 case BC_LEX_KEY_ELSE:
4720 {
4721 p->auto_part = false;
4722 break;
4723 }
4724
4725 case BC_LEX_LBRACE:
4726 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004727 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004728
4729 ++p->nbraces;
4730 s = bc_lex_next(&p->l);
4731 if (s) return s;
4732
4733 return bc_parse_body(p, true);
4734 }
4735
4736 case BC_LEX_KEY_AUTO:
4737 {
4738 return bc_parse_auto(p);
4739 }
4740
4741 default:
4742 {
4743 p->auto_part = false;
4744
4745 if (BC_PARSE_IF_END(p)) {
4746 bc_parse_noElse(p);
4747 return BC_STATUS_SUCCESS;
4748 }
4749 else if (BC_PARSE_BODY(p))
4750 return bc_parse_body(p, false);
4751
4752 break;
4753 }
4754 }
4755
4756 switch (p->l.t.t) {
4757
4758 case BC_LEX_OP_INC:
4759 case BC_LEX_OP_DEC:
4760 case BC_LEX_OP_MINUS:
4761 case BC_LEX_OP_BOOL_NOT:
4762 case BC_LEX_LPAREN:
4763 case BC_LEX_NAME:
4764 case BC_LEX_NUMBER:
4765 case BC_LEX_KEY_IBASE:
4766 case BC_LEX_KEY_LAST:
4767 case BC_LEX_KEY_LENGTH:
4768 case BC_LEX_KEY_OBASE:
4769 case BC_LEX_KEY_READ:
4770 case BC_LEX_KEY_SCALE:
4771 case BC_LEX_KEY_SQRT:
4772 {
4773 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4774 break;
4775 }
4776
4777 case BC_LEX_KEY_ELSE:
4778 {
4779 s = bc_parse_else(p);
4780 break;
4781 }
4782
4783 case BC_LEX_SCOLON:
4784 {
4785 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4786 break;
4787 }
4788
4789 case BC_LEX_RBRACE:
4790 {
4791 s = bc_parse_endBody(p, true);
4792 break;
4793 }
4794
4795 case BC_LEX_STR:
4796 {
4797 s = bc_parse_string(p, BC_INST_PRINT_STR);
4798 break;
4799 }
4800
4801 case BC_LEX_KEY_BREAK:
4802 case BC_LEX_KEY_CONTINUE:
4803 {
4804 s = bc_parse_loopExit(p, p->l.t.t);
4805 break;
4806 }
4807
4808 case BC_LEX_KEY_FOR:
4809 {
4810 s = bc_parse_for(p);
4811 break;
4812 }
4813
4814 case BC_LEX_KEY_HALT:
4815 {
4816 bc_parse_push(p, BC_INST_HALT);
4817 s = bc_lex_next(&p->l);
4818 break;
4819 }
4820
4821 case BC_LEX_KEY_IF:
4822 {
4823 s = bc_parse_if(p);
4824 break;
4825 }
4826
4827 case BC_LEX_KEY_LIMITS:
4828 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004829 // "limits" is a compile-time command,
4830 // the output is produced at _parse time_.
Gavin Howard01055ba2018-11-03 11:00:21 -06004831 s = bc_lex_next(&p->l);
4832 if (s) return s;
Denys Vlasenko64074a12018-12-07 15:50:14 +01004833 printf(
4834 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4835 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4836 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4837 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4838 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4839 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4840 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4841 "Number of vars = "BC_MAX_VARS_STR "\n"
4842 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004843 break;
4844 }
4845
4846 case BC_LEX_KEY_PRINT:
4847 {
4848 s = bc_parse_print(p);
4849 break;
4850 }
4851
4852 case BC_LEX_KEY_QUIT:
4853 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004854 // "quit" is a compile-time command. For example,
4855 // "if (0 == 1) quit" terminates when parsing the statement,
4856 // not when it is executed
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01004857 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06004858 }
4859
4860 case BC_LEX_KEY_RETURN:
4861 {
4862 s = bc_parse_return(p);
4863 break;
4864 }
4865
4866 case BC_LEX_KEY_WHILE:
4867 {
4868 s = bc_parse_while(p);
4869 break;
4870 }
4871
4872 default:
4873 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004874 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004875 break;
4876 }
4877 }
4878
4879 return s;
4880}
4881
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01004882static FAST_FUNC BcStatus bc_parse_parse(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06004883{
4884 BcStatus s;
4885
4886 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004887 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 -06004888 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004889 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004890 s = bc_parse_func(p);
4891 }
4892 else
4893 s = bc_parse_stmt(p);
4894
Denys Vlasenkod38af482018-12-04 19:11:02 +01004895 if (s || G_interrupt) {
4896 bc_parse_reset(p);
4897 s = BC_STATUS_FAILURE;
4898 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004899
4900 return s;
4901}
4902
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004903static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
Gavin Howard01055ba2018-11-03 11:00:21 -06004904{
4905 BcStatus s = BC_STATUS_SUCCESS;
4906 BcInst prev = BC_INST_PRINT;
4907 BcLexType top, t = p->l.t.t;
4908 size_t nexprs = 0, ops_bgn = p->ops.len;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01004909 unsigned nparens, nrelops;
Gavin Howard01055ba2018-11-03 11:00:21 -06004910 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4911
4912 paren_first = p->l.t.t == BC_LEX_LPAREN;
4913 nparens = nrelops = 0;
4914 paren_expr = rprn = done = get_token = assign = false;
4915 bin_last = true;
4916
Denys Vlasenkobcb62a72018-12-05 20:17:48 +01004917 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004918 switch (t) {
4919
4920 case BC_LEX_OP_INC:
4921 case BC_LEX_OP_DEC:
4922 {
4923 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4924 rprn = get_token = bin_last = false;
4925 break;
4926 }
4927
4928 case BC_LEX_OP_MINUS:
4929 {
4930 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4931 rprn = get_token = false;
4932 bin_last = prev == BC_INST_MINUS;
4933 break;
4934 }
4935
4936 case BC_LEX_OP_ASSIGN_POWER:
4937 case BC_LEX_OP_ASSIGN_MULTIPLY:
4938 case BC_LEX_OP_ASSIGN_DIVIDE:
4939 case BC_LEX_OP_ASSIGN_MODULUS:
4940 case BC_LEX_OP_ASSIGN_PLUS:
4941 case BC_LEX_OP_ASSIGN_MINUS:
4942 case BC_LEX_OP_ASSIGN:
4943 {
4944 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4945 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4946 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4947 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004948 s = bc_error("bad assignment:"
4949 " left side must be scale,"
4950 " ibase, obase, last, var,"
4951 " or array element"
4952 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004953 break;
4954 }
4955 }
4956 // Fallthrough.
4957 case BC_LEX_OP_POWER:
4958 case BC_LEX_OP_MULTIPLY:
4959 case BC_LEX_OP_DIVIDE:
4960 case BC_LEX_OP_MODULUS:
4961 case BC_LEX_OP_PLUS:
4962 case BC_LEX_OP_REL_EQ:
4963 case BC_LEX_OP_REL_LE:
4964 case BC_LEX_OP_REL_GE:
4965 case BC_LEX_OP_REL_NE:
4966 case BC_LEX_OP_REL_LT:
4967 case BC_LEX_OP_REL_GT:
4968 case BC_LEX_OP_BOOL_NOT:
4969 case BC_LEX_OP_BOOL_OR:
4970 case BC_LEX_OP_BOOL_AND:
4971 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004972 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4973 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4974 ) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004975 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004976 }
4977
4978 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4979 prev = BC_PARSE_TOKEN_INST(t);
4980 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4981 rprn = get_token = false;
4982 bin_last = t != BC_LEX_OP_BOOL_NOT;
4983
4984 break;
4985 }
4986
4987 case BC_LEX_LPAREN:
4988 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004989 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004990 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004991 ++nparens;
4992 paren_expr = rprn = bin_last = false;
4993 get_token = true;
4994 bc_vec_push(&p->ops, &t);
4995
4996 break;
4997 }
4998
4999 case BC_LEX_RPAREN:
5000 {
5001 if (bin_last || prev == BC_INST_BOOL_NOT)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005002 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005003
5004 if (nparens == 0) {
5005 s = BC_STATUS_SUCCESS;
5006 done = true;
5007 get_token = false;
5008 break;
5009 }
5010 else if (!paren_expr)
5011 return BC_STATUS_PARSE_EMPTY_EXP;
5012
5013 --nparens;
5014 paren_expr = rprn = true;
5015 get_token = bin_last = false;
5016
5017 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
5018
5019 break;
5020 }
5021
5022 case BC_LEX_NAME:
5023 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005024 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005025 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005026 paren_expr = true;
5027 rprn = get_token = bin_last = false;
5028 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
5029 ++nexprs;
5030
5031 break;
5032 }
5033
5034 case BC_LEX_NUMBER:
5035 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005036 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005037 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005038 bc_parse_number(p, &prev, &nexprs);
5039 paren_expr = get_token = true;
5040 rprn = bin_last = false;
5041
5042 break;
5043 }
5044
5045 case BC_LEX_KEY_IBASE:
5046 case BC_LEX_KEY_LAST:
5047 case BC_LEX_KEY_OBASE:
5048 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005049 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005050 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005051 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
5052 bc_parse_push(p, (char) prev);
5053
5054 paren_expr = get_token = true;
5055 rprn = bin_last = false;
5056 ++nexprs;
5057
5058 break;
5059 }
5060
5061 case BC_LEX_KEY_LENGTH:
5062 case BC_LEX_KEY_SQRT:
5063 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005064 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005065 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005066 s = bc_parse_builtin(p, t, flags, &prev);
5067 paren_expr = true;
5068 rprn = get_token = bin_last = false;
5069 ++nexprs;
5070
5071 break;
5072 }
5073
5074 case BC_LEX_KEY_READ:
5075 {
5076 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005077 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005078 else if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005079 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005080 else
5081 s = bc_parse_read(p);
5082
5083 paren_expr = true;
5084 rprn = get_token = bin_last = false;
5085 ++nexprs;
5086 prev = BC_INST_READ;
5087
5088 break;
5089 }
5090
5091 case BC_LEX_KEY_SCALE:
5092 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005093 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005094 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005095 s = bc_parse_scale(p, &prev, flags);
5096 paren_expr = true;
5097 rprn = get_token = bin_last = false;
5098 ++nexprs;
5099 prev = BC_INST_SCALE;
5100
5101 break;
5102 }
5103
5104 default:
5105 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005106 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005107 break;
5108 }
5109 }
5110
5111 if (!s && get_token) s = bc_lex_next(&p->l);
5112 }
5113
5114 if (s) return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01005115 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
Gavin Howard01055ba2018-11-03 11:00:21 -06005116
5117 while (p->ops.len > ops_bgn) {
5118
5119 top = BC_PARSE_TOP_OP(p);
5120 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5121
5122 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005123 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005124
5125 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5126
5127 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5128 bc_vec_pop(&p->ops);
5129 }
5130
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005131 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005132 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005133
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005134 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5135 for (;;) {
5136 if (t == (next & 0x7f))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005137 goto ok;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005138 if (next & 0x80) // last element?
5139 break;
5140 next >>= 8;
5141 }
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005142 return bc_error_bad_expression();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005143 ok:
Gavin Howard01055ba2018-11-03 11:00:21 -06005144
5145 if (!(flags & BC_PARSE_REL) && nrelops) {
Denys Vlasenko00646792018-12-05 18:12:27 +01005146 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
Gavin Howard01055ba2018-11-03 11:00:21 -06005147 if (s) return s;
5148 }
5149 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01005150 s = bc_POSIX_requires("exactly one comparison operator per condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06005151 if (s) return s;
5152 }
5153
5154 if (flags & BC_PARSE_PRINT) {
5155 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5156 bc_parse_push(p, BC_INST_POP);
5157 }
5158
5159 return s;
5160}
5161
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01005162static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5163{
5164 BcStatus s;
5165
5166 s = bc_parse_expr_empty_ok(p, flags, next);
5167 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5168 return bc_error("empty expression");
5169 return s;
5170}
5171
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005172static void bc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005173{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005174 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005175}
5176
5177static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5178{
5179 return bc_parse_expr(p, flags, bc_parse_next_read);
5180}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005181
Gavin Howard01055ba2018-11-03 11:00:21 -06005182#endif // ENABLE_BC
5183
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005184#if ENABLE_DC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005185
5186#define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5187
Gavin Howard01055ba2018-11-03 11:00:21 -06005188static BcStatus dc_parse_register(BcParse *p)
5189{
5190 BcStatus s;
5191 char *name;
5192
5193 s = bc_lex_next(&p->l);
5194 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005195 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005196
5197 name = xstrdup(p->l.t.v.v);
5198 bc_parse_pushName(p, name);
5199
5200 return s;
5201}
5202
5203static BcStatus dc_parse_string(BcParse *p)
5204{
5205 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005206 size_t idx, len = G.prog.strs.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005207
5208 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5209 name = xstrdup(b);
5210
5211 str = xstrdup(p->l.t.v.v);
5212 bc_parse_push(p, BC_INST_STR);
5213 bc_parse_pushIndex(p, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005214 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06005215 bc_parse_addFunc(p, name, &idx);
5216
5217 return bc_lex_next(&p->l);
5218}
5219
5220static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5221{
5222 BcStatus s;
5223
5224 bc_parse_push(p, inst);
5225 if (name) {
5226 s = dc_parse_register(p);
5227 if (s) return s;
5228 }
5229
5230 if (store) {
5231 bc_parse_push(p, BC_INST_SWAP);
5232 bc_parse_push(p, BC_INST_ASSIGN);
5233 bc_parse_push(p, BC_INST_POP);
5234 }
5235
5236 return bc_lex_next(&p->l);
5237}
5238
5239static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5240{
5241 BcStatus s;
5242
5243 bc_parse_push(p, inst);
5244 bc_parse_push(p, BC_INST_EXEC_COND);
5245
5246 s = dc_parse_register(p);
5247 if (s) return s;
5248
5249 s = bc_lex_next(&p->l);
5250 if (s) return s;
5251
5252 if (p->l.t.t == BC_LEX_ELSE) {
5253 s = dc_parse_register(p);
5254 if (s) return s;
5255 s = bc_lex_next(&p->l);
5256 }
5257 else
5258 bc_parse_push(p, BC_PARSE_STREND);
5259
5260 return s;
5261}
5262
5263static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5264{
5265 BcStatus s = BC_STATUS_SUCCESS;
5266 BcInst prev;
5267 uint8_t inst;
5268 bool assign, get_token = false;
5269
5270 switch (t) {
5271
5272 case BC_LEX_OP_REL_EQ:
5273 case BC_LEX_OP_REL_LE:
5274 case BC_LEX_OP_REL_GE:
5275 case BC_LEX_OP_REL_NE:
5276 case BC_LEX_OP_REL_LT:
5277 case BC_LEX_OP_REL_GT:
5278 {
5279 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5280 break;
5281 }
5282
5283 case BC_LEX_SCOLON:
5284 case BC_LEX_COLON:
5285 {
5286 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5287 break;
5288 }
5289
5290 case BC_LEX_STR:
5291 {
5292 s = dc_parse_string(p);
5293 break;
5294 }
5295
5296 case BC_LEX_NEG:
5297 case BC_LEX_NUMBER:
5298 {
5299 if (t == BC_LEX_NEG) {
5300 s = bc_lex_next(&p->l);
5301 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005302 if (p->l.t.t != BC_LEX_NUMBER)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005303 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005304 }
5305
5306 bc_parse_number(p, &prev, &p->nbraces);
5307
5308 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5309 get_token = true;
5310
5311 break;
5312 }
5313
5314 case BC_LEX_KEY_READ:
5315 {
5316 if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005317 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005318 else
5319 bc_parse_push(p, BC_INST_READ);
5320 get_token = true;
5321 break;
5322 }
5323
5324 case BC_LEX_OP_ASSIGN:
5325 case BC_LEX_STORE_PUSH:
5326 {
5327 assign = t == BC_LEX_OP_ASSIGN;
5328 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5329 s = dc_parse_mem(p, inst, true, assign);
5330 break;
5331 }
5332
5333 case BC_LEX_LOAD:
5334 case BC_LEX_LOAD_POP:
5335 {
5336 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5337 s = dc_parse_mem(p, inst, true, false);
5338 break;
5339 }
5340
5341 case BC_LEX_STORE_IBASE:
5342 case BC_LEX_STORE_SCALE:
5343 case BC_LEX_STORE_OBASE:
5344 {
5345 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5346 s = dc_parse_mem(p, inst, false, true);
5347 break;
5348 }
5349
5350 default:
5351 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005352 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005353 get_token = true;
5354 break;
5355 }
5356 }
5357
5358 if (!s && get_token) s = bc_lex_next(&p->l);
5359
5360 return s;
5361}
5362
5363static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5364{
5365 BcStatus s = BC_STATUS_SUCCESS;
5366 BcInst inst;
5367 BcLexType t;
5368
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005369 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005370
5371 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5372
5373 inst = dc_parse_insts[t];
5374
5375 if (inst != BC_INST_INVALID) {
5376 bc_parse_push(p, inst);
5377 s = bc_lex_next(&p->l);
5378 }
5379 else
5380 s = dc_parse_token(p, t, flags);
5381 }
5382
5383 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5384 bc_parse_push(p, BC_INST_POP_EXEC);
5385
5386 return s;
5387}
5388
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01005389static FAST_FUNC BcStatus dc_parse_parse(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06005390{
5391 BcStatus s;
5392
5393 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005394 s = bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06005395 else
5396 s = dc_parse_expr(p, 0);
5397
Denys Vlasenkod38af482018-12-04 19:11:02 +01005398 if (s || G_interrupt) {
5399 bc_parse_reset(p);
5400 s = BC_STATUS_FAILURE;
5401 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005402
5403 return s;
5404}
5405
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005406static void dc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005407{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005408 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005409}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005410
Gavin Howard01055ba2018-11-03 11:00:21 -06005411#endif // ENABLE_DC
5412
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005413static void common_parse_init(BcParse *p, size_t func)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005414{
5415 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005416 IF_BC(bc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005417 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005418 IF_DC(dc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005419 }
5420}
5421
5422static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5423{
5424 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005425 IF_BC(return bc_parse_expression(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005426 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005427 IF_DC(return dc_parse_expr(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005428 }
5429}
5430
Denys Vlasenkodf515392018-12-02 19:27:48 +01005431static BcVec* bc_program_search(char *id, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005432{
Gavin Howard01055ba2018-11-03 11:00:21 -06005433 BcId e, *ptr;
5434 BcVec *v, *map;
5435 size_t i;
5436 BcResultData data;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005437 int new;
Gavin Howard01055ba2018-11-03 11:00:21 -06005438
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005439 v = var ? &G.prog.vars : &G.prog.arrs;
5440 map = var ? &G.prog.var_map : &G.prog.arr_map;
Gavin Howard01055ba2018-11-03 11:00:21 -06005441
5442 e.name = id;
5443 e.idx = v->len;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005444 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
Gavin Howard01055ba2018-11-03 11:00:21 -06005445
5446 if (new) {
5447 bc_array_init(&data.v, var);
5448 bc_vec_push(v, &data.v);
5449 }
5450
5451 ptr = bc_vec_item(map, i);
5452 if (new) ptr->name = xstrdup(e.name);
Denys Vlasenkodf515392018-12-02 19:27:48 +01005453 return bc_vec_item(v, ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005454}
5455
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005456static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
Gavin Howard01055ba2018-11-03 11:00:21 -06005457{
Gavin Howard01055ba2018-11-03 11:00:21 -06005458 switch (r->t) {
5459
5460 case BC_RESULT_STR:
5461 case BC_RESULT_TEMP:
5462 case BC_RESULT_IBASE:
5463 case BC_RESULT_SCALE:
5464 case BC_RESULT_OBASE:
5465 {
5466 *num = &r->d.n;
5467 break;
5468 }
5469
5470 case BC_RESULT_CONSTANT:
5471 {
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005472 BcStatus s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005473 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005474 size_t base_t, len = strlen(*str);
5475 BcNum *base;
5476
5477 bc_num_init(&r->d.n, len);
5478
5479 hex = hex && len == 1;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005480 base = hex ? &G.prog.hexb : &G.prog.ib;
5481 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005482 s = bc_num_parse(&r->d.n, *str, base, base_t);
5483
5484 if (s) {
5485 bc_num_free(&r->d.n);
5486 return s;
5487 }
5488
5489 *num = &r->d.n;
5490 r->t = BC_RESULT_TEMP;
5491
5492 break;
5493 }
5494
5495 case BC_RESULT_VAR:
5496 case BC_RESULT_ARRAY:
5497 case BC_RESULT_ARRAY_ELEM:
5498 {
5499 BcVec *v;
5500
Denys Vlasenkodf515392018-12-02 19:27:48 +01005501 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
Gavin Howard01055ba2018-11-03 11:00:21 -06005502
5503 if (r->t == BC_RESULT_ARRAY_ELEM) {
5504 v = bc_vec_top(v);
5505 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5506 *num = bc_vec_item(v, r->d.id.idx);
5507 }
5508 else
5509 *num = bc_vec_top(v);
5510
5511 break;
5512 }
5513
5514 case BC_RESULT_LAST:
5515 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005516 *num = &G.prog.last;
Gavin Howard01055ba2018-11-03 11:00:21 -06005517 break;
5518 }
5519
5520 case BC_RESULT_ONE:
5521 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005522 *num = &G.prog.one;
Gavin Howard01055ba2018-11-03 11:00:21 -06005523 break;
5524 }
5525 }
5526
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005527 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06005528}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005529#if ERRORS_ARE_FATAL
5530# define bc_program_num(...) (bc_program_num(__VA_ARGS__), BC_STATUS_SUCCESS)
5531#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005532
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005533static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
Gavin Howard01055ba2018-11-03 11:00:21 -06005534 BcResult **r, BcNum **rn, bool assign)
5535{
5536 BcStatus s;
5537 bool hex;
5538 BcResultType lt, rt;
5539
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005540 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005541 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005542
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005543 *r = bc_vec_item_rev(&G.prog.results, 0);
5544 *l = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06005545
5546 lt = (*l)->t;
5547 rt = (*r)->t;
5548 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5549
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005550 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005551 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005552 s = bc_program_num(*r, rn, hex);
Gavin Howard01055ba2018-11-03 11:00:21 -06005553 if (s) return s;
5554
5555 // We run this again under these conditions in case any vector has been
5556 // reallocated out from under the BcNums or arrays we had.
5557 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005558 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005559 if (s) return s;
5560 }
5561
5562 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005563 return bc_error_variable_is_wrong_type();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005564 if (!assign && !BC_PROG_NUM((*r), (*ln)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005565 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005566
Gavin Howard01055ba2018-11-03 11:00:21 -06005567 return s;
5568}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01005569#if ERRORS_ARE_FATAL
5570# define bc_program_binOpPrep(...) (bc_program_binOpPrep(__VA_ARGS__), BC_STATUS_SUCCESS)
5571#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005572
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005573static void bc_program_binOpRetire(BcResult *r)
Gavin Howard01055ba2018-11-03 11:00:21 -06005574{
5575 r->t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005576 bc_vec_pop(&G.prog.results);
5577 bc_vec_pop(&G.prog.results);
5578 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005579}
5580
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005581static BcStatus bc_program_prep(BcResult **r, BcNum **n)
Gavin Howard01055ba2018-11-03 11:00:21 -06005582{
5583 BcStatus s;
5584
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005585 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005586 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005587 *r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005588
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005589 s = bc_program_num(*r, n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005590 if (s) return s;
5591
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005592 if (!BC_PROG_NUM((*r), (*n)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005593 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005594
5595 return s;
5596}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005597#if ERRORS_ARE_FATAL
5598# define bc_program_prep(...) (bc_program_prep(__VA_ARGS__), BC_STATUS_SUCCESS)
5599#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005600
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005601static void bc_program_retire(BcResult *r, BcResultType t)
Gavin Howard01055ba2018-11-03 11:00:21 -06005602{
5603 r->t = t;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005604 bc_vec_pop(&G.prog.results);
5605 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005606}
5607
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005608static BcStatus bc_program_op(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005609{
5610 BcStatus s;
5611 BcResult *opd1, *opd2, res;
5612 BcNum *n1, *n2 = NULL;
5613
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005614 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005615 if (s) return s;
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01005616 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06005617
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005618 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005619 if (s) goto err;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005620 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005621
5622 return s;
5623
5624err:
5625 bc_num_free(&res.d.n);
5626 return s;
5627}
5628
Denys Vlasenko785e4b32018-12-02 17:18:52 +01005629static BcStatus bc_program_read(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005630{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005631 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005632 BcStatus s;
5633 BcParse parse;
5634 BcVec buf;
5635 BcInstPtr ip;
5636 size_t i;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005637 BcFunc *f = bc_program_func(BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005638
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005639 for (i = 0; i < G.prog.stack.len; ++i) {
5640 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005641 if (ip_ptr->func == BC_PROG_READ)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005642 return bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005643 }
5644
Denys Vlasenko7d628012018-12-04 21:46:47 +01005645 bc_vec_pop_all(&f->code);
5646 bc_char_vec_init(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005647
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005648 sv_file = G.prog.file;
5649 G.prog.file = NULL;
5650
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01005651 s = bc_read_line(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005652 if (s) goto io_err;
5653
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005654 common_parse_init(&parse, BC_PROG_READ);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005655 bc_lex_file(&parse.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005656
5657 s = bc_parse_text(&parse, buf.v);
5658 if (s) goto exec_err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005659 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
Gavin Howard01055ba2018-11-03 11:00:21 -06005660 if (s) goto exec_err;
5661
5662 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005663 s = bc_error("bad read() expression");
Gavin Howard01055ba2018-11-03 11:00:21 -06005664 goto exec_err;
5665 }
5666
5667 ip.func = BC_PROG_READ;
5668 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005669 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005670
5671 // Update this pointer, just in case.
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005672 f = bc_program_func(BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005673
5674 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005675 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06005676
5677exec_err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005678 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005679 bc_parse_free(&parse);
5680io_err:
5681 bc_vec_free(&buf);
5682 return s;
5683}
5684
5685static size_t bc_program_index(char *code, size_t *bgn)
5686{
5687 char amt = code[(*bgn)++], i = 0;
5688 size_t res = 0;
5689
5690 for (; i < amt; ++i, ++(*bgn))
5691 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5692
5693 return res;
5694}
5695
5696static char *bc_program_name(char *code, size_t *bgn)
5697{
5698 size_t i;
5699 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5700
5701 s = xmalloc(ptr - str + 1);
5702 c = code[(*bgn)++];
5703
5704 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5705 s[i] = c;
5706
5707 s[i] = '\0';
5708
5709 return s;
5710}
5711
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005712static void bc_program_printString(const char *str)
Gavin Howard01055ba2018-11-03 11:00:21 -06005713{
5714 size_t i, len = strlen(str);
5715
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005716#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005717 if (len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005718 bb_putchar('\0');
Gavin Howard01055ba2018-11-03 11:00:21 -06005719 return;
5720 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005721#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005722
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005723 for (i = 0; i < len; ++i, ++G.prog.nchars) {
Gavin Howard01055ba2018-11-03 11:00:21 -06005724
5725 int c = str[i];
5726
5727 if (c != '\\' || i == len - 1)
Denys Vlasenko00d77792018-11-30 23:13:42 +01005728 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005729 else {
5730
5731 c = str[++i];
5732
5733 switch (c) {
5734
5735 case 'a':
5736 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005737 bb_putchar('\a');
Gavin Howard01055ba2018-11-03 11:00:21 -06005738 break;
5739 }
5740
5741 case 'b':
5742 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005743 bb_putchar('\b');
Gavin Howard01055ba2018-11-03 11:00:21 -06005744 break;
5745 }
5746
5747 case '\\':
5748 case 'e':
5749 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005750 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005751 break;
5752 }
5753
5754 case 'f':
5755 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005756 bb_putchar('\f');
Gavin Howard01055ba2018-11-03 11:00:21 -06005757 break;
5758 }
5759
5760 case 'n':
5761 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005762 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005763 G.prog.nchars = SIZE_MAX;
Gavin Howard01055ba2018-11-03 11:00:21 -06005764 break;
5765 }
5766
5767 case 'r':
5768 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005769 bb_putchar('\r');
Gavin Howard01055ba2018-11-03 11:00:21 -06005770 break;
5771 }
5772
5773 case 'q':
5774 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005775 bb_putchar('"');
Gavin Howard01055ba2018-11-03 11:00:21 -06005776 break;
5777 }
5778
5779 case 't':
5780 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005781 bb_putchar('\t');
Gavin Howard01055ba2018-11-03 11:00:21 -06005782 break;
5783 }
5784
5785 default:
5786 {
5787 // Just print the backslash and following character.
Denys Vlasenko00d77792018-11-30 23:13:42 +01005788 bb_putchar('\\');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005789 ++G.prog.nchars;
Denys Vlasenko00d77792018-11-30 23:13:42 +01005790 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005791 break;
5792 }
5793 }
5794 }
5795 }
5796}
5797
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005798static BcStatus bc_program_print(char inst, size_t idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005799{
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005800 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06005801 BcResult *r;
Denys Vlasenko44d79d82018-12-10 12:33:40 +01005802 BcNum *num;
Gavin Howard01055ba2018-11-03 11:00:21 -06005803 bool pop = inst != BC_INST_PRINT;
5804
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005805 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005806 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005807
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005808 r = bc_vec_item_rev(&G.prog.results, idx);
Denys Vlasenko44d79d82018-12-10 12:33:40 +01005809 num = NULL; // is this NULL necessary?
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005810 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005811 if (s) return s;
5812
5813 if (BC_PROG_NUM(r, num)) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005814 s = bc_num_print(num, !pop);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005815 if (!s) bc_num_copy(&G.prog.last, num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005816 }
5817 else {
Denys Vlasenko44d79d82018-12-10 12:33:40 +01005818 char *str;
Gavin Howard01055ba2018-11-03 11:00:21 -06005819
5820 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005821 str = *bc_program_str(idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005822
5823 if (inst == BC_INST_PRINT_STR) {
Denys Vlasenko44d79d82018-12-10 12:33:40 +01005824 for (;;) {
5825 char c = *str++;
5826 if (c == '\0') break;
Denys Vlasenko00d77792018-11-30 23:13:42 +01005827 bb_putchar(c);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005828 ++G.prog.nchars;
Denys Vlasenko44d79d82018-12-10 12:33:40 +01005829 if (c == '\n') G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06005830 }
5831 }
5832 else {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005833 bc_program_printString(str);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005834 if (inst == BC_INST_PRINT) bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005835 }
5836 }
5837
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005838 if (!s && pop) bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005839
5840 return s;
5841}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005842#if ERRORS_ARE_FATAL
5843# define bc_program_print(...) (bc_program_print(__VA_ARGS__), BC_STATUS_SUCCESS)
5844#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005845
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005846static BcStatus bc_program_negate(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005847{
5848 BcStatus s;
5849 BcResult res, *ptr;
5850 BcNum *num = NULL;
5851
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005852 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005853 if (s) return s;
5854
5855 bc_num_init(&res.d.n, num->len);
5856 bc_num_copy(&res.d.n, num);
5857 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5858
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005859 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06005860
5861 return s;
5862}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01005863#if ERRORS_ARE_FATAL
5864# define bc_program_negate(...) (bc_program_negate(__VA_ARGS__), BC_STATUS_SUCCESS)
5865#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005866
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005867static BcStatus bc_program_logical(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005868{
5869 BcStatus s;
5870 BcResult *opd1, *opd2, res;
5871 BcNum *n1, *n2;
5872 bool cond = 0;
5873 ssize_t cmp;
5874
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005875 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005876 if (s) return s;
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01005877 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06005878
5879 if (inst == BC_INST_BOOL_AND)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005880 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005881 else if (inst == BC_INST_BOOL_OR)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005882 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005883 else {
5884
5885 cmp = bc_num_cmp(n1, n2);
5886
5887 switch (inst) {
5888
5889 case BC_INST_REL_EQ:
5890 {
5891 cond = cmp == 0;
5892 break;
5893 }
5894
5895 case BC_INST_REL_LE:
5896 {
5897 cond = cmp <= 0;
5898 break;
5899 }
5900
5901 case BC_INST_REL_GE:
5902 {
5903 cond = cmp >= 0;
5904 break;
5905 }
5906
5907 case BC_INST_REL_NE:
5908 {
5909 cond = cmp != 0;
5910 break;
5911 }
5912
5913 case BC_INST_REL_LT:
5914 {
5915 cond = cmp < 0;
5916 break;
5917 }
5918
5919 case BC_INST_REL_GT:
5920 {
5921 cond = cmp > 0;
5922 break;
5923 }
5924 }
5925 }
5926
5927 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5928
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005929 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005930
5931 return s;
5932}
5933
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005934#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005935static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
Gavin Howard01055ba2018-11-03 11:00:21 -06005936 bool push)
5937{
5938 BcNum n2;
5939 BcResult res;
5940
5941 memset(&n2, 0, sizeof(BcNum));
5942 n2.rdx = res.d.id.idx = r->d.id.idx;
5943 res.t = BC_RESULT_STR;
5944
5945 if (!push) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005946 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005947 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005948 bc_vec_pop(v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005949 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005950 }
5951
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005952 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005953
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005954 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005955 bc_vec_push(v, &n2);
5956
5957 return BC_STATUS_SUCCESS;
5958}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01005959#if ERRORS_ARE_FATAL
5960# define bc_program_assignStr(...) (bc_program_assignStr(__VA_ARGS__), BC_STATUS_SUCCESS)
5961#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005962#endif // ENABLE_DC
5963
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005964static BcStatus bc_program_copyToVar(char *name, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005965{
5966 BcStatus s;
5967 BcResult *ptr, r;
5968 BcVec *v;
5969 BcNum *n;
5970
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005971 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005972 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005973
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005974 ptr = bc_vec_top(&G.prog.results);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005975 if ((ptr->t == BC_RESULT_ARRAY) != !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005976 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005977 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005978
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005979#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005980 if (ptr->t == BC_RESULT_STR && !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005981 return bc_error_variable_is_wrong_type();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005982 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005983#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005984
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005985 s = bc_program_num(ptr, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005986 if (s) return s;
5987
5988 // Do this once more to make sure that pointers were not invalidated.
Denys Vlasenkodf515392018-12-02 19:27:48 +01005989 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005990
5991 if (var) {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01005992 bc_num_init_DEF_SIZE(&r.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06005993 bc_num_copy(&r.d.n, n);
5994 }
5995 else {
5996 bc_array_init(&r.d.v, true);
5997 bc_array_copy(&r.d.v, (BcVec *) n);
5998 }
5999
6000 bc_vec_push(v, &r.d);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006001 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006002
6003 return s;
6004}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01006005#if ERRORS_ARE_FATAL
6006# define bc_program_copyToVar(...) (bc_program_copyToVar(__VA_ARGS__), BC_STATUS_SUCCESS)
6007#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006008
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006009static BcStatus bc_program_assign(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006010{
6011 BcStatus s;
6012 BcResult *left, *right, res;
6013 BcNum *l = NULL, *r = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06006014 bool assign = inst == BC_INST_ASSIGN, ib, sc;
6015
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006016 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
Gavin Howard01055ba2018-11-03 11:00:21 -06006017 if (s) return s;
6018
6019 ib = left->t == BC_RESULT_IBASE;
6020 sc = left->t == BC_RESULT_SCALE;
6021
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006022#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006023
6024 if (right->t == BC_RESULT_STR) {
6025
6026 BcVec *v;
6027
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006028 if (left->t != BC_RESULT_VAR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006029 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01006030 v = bc_program_search(left->d.id.name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006031
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006032 return bc_program_assignStr(right, v, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006033 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006034#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006035
6036 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006037 return bc_error("bad assignment:"
6038 " left side must be scale,"
6039 " ibase, obase, last, var,"
6040 " or array element"
6041 );
Gavin Howard01055ba2018-11-03 11:00:21 -06006042
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006043#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006044 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006045 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06006046
6047 if (assign)
6048 bc_num_copy(l, r);
6049 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006050 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006051
6052 if (s) return s;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006053#else
Gavin Howard01055ba2018-11-03 11:00:21 -06006054 bc_num_copy(l, r);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006055#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006056
6057 if (ib || sc || left->t == BC_RESULT_OBASE) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006058 static const char *const msg[] = {
Denys Vlasenko64074a12018-12-07 15:50:14 +01006059 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
6060 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
6061 NULL, //can't happen //BC_RESULT_LAST
6062 NULL, //can't happen //BC_RESULT_CONSTANT
6063 NULL, //can't happen //BC_RESULT_ONE
6064 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006065 };
Gavin Howard01055ba2018-11-03 11:00:21 -06006066 size_t *ptr;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01006067 unsigned long val, max;
Gavin Howard01055ba2018-11-03 11:00:21 -06006068
6069 s = bc_num_ulong(l, &val);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006070 if (s)
6071 return s;
6072 s = left->t - BC_RESULT_IBASE;
Gavin Howard01055ba2018-11-03 11:00:21 -06006073 if (sc) {
6074 max = BC_MAX_SCALE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006075 ptr = &G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006076 }
6077 else {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006078 if (val < BC_NUM_MIN_BASE)
6079 return bc_error(msg[s]);
Gavin Howard01055ba2018-11-03 11:00:21 -06006080 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006081 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006082 }
6083
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006084 if (val > max)
6085 return bc_error(msg[s]);
6086 if (!sc)
6087 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
Gavin Howard01055ba2018-11-03 11:00:21 -06006088
6089 *ptr = (size_t) val;
6090 s = BC_STATUS_SUCCESS;
6091 }
6092
6093 bc_num_init(&res.d.n, l->len);
6094 bc_num_copy(&res.d.n, l);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006095 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006096
6097 return s;
6098}
6099
Denys Vlasenko416ce762018-12-02 20:57:17 +01006100#if !ENABLE_DC
6101#define bc_program_pushVar(code, bgn, pop, copy) \
6102 bc_program_pushVar(code, bgn)
6103// for bc, 'pop' and 'copy' are always false
6104#endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006105static BcStatus bc_program_pushVar(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006106 bool pop, bool copy)
6107{
6108 BcStatus s = BC_STATUS_SUCCESS;
6109 BcResult r;
6110 char *name = bc_program_name(code, bgn);
Gavin Howard01055ba2018-11-03 11:00:21 -06006111
6112 r.t = BC_RESULT_VAR;
6113 r.d.id.name = name;
6114
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006115#if ENABLE_DC
Denys Vlasenko416ce762018-12-02 20:57:17 +01006116 {
6117 BcVec *v = bc_program_search(name, true);
6118 BcNum *num = bc_vec_top(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006119
Denys Vlasenko416ce762018-12-02 20:57:17 +01006120 if (pop || copy) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006121
Denys Vlasenko416ce762018-12-02 20:57:17 +01006122 if (!BC_PROG_STACK(v, 2 - copy)) {
6123 free(name);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006124 return bc_error_stack_has_too_few_elements();
Denys Vlasenko416ce762018-12-02 20:57:17 +01006125 }
6126
Gavin Howard01055ba2018-11-03 11:00:21 -06006127 free(name);
Denys Vlasenko416ce762018-12-02 20:57:17 +01006128 name = NULL;
6129
6130 if (!BC_PROG_STR(num)) {
6131
6132 r.t = BC_RESULT_TEMP;
6133
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006134 bc_num_init_DEF_SIZE(&r.d.n);
Denys Vlasenko416ce762018-12-02 20:57:17 +01006135 bc_num_copy(&r.d.n, num);
6136 }
6137 else {
6138 r.t = BC_RESULT_STR;
6139 r.d.id.idx = num->rdx;
6140 }
6141
6142 if (!copy) bc_vec_pop(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006143 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006144 }
6145#endif // ENABLE_DC
6146
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006147 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006148
6149 return s;
6150}
6151
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006152static BcStatus bc_program_pushArray(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006153 char inst)
6154{
6155 BcStatus s = BC_STATUS_SUCCESS;
6156 BcResult r;
6157 BcNum *num;
6158
6159 r.d.id.name = bc_program_name(code, bgn);
6160
6161 if (inst == BC_INST_ARRAY) {
6162 r.t = BC_RESULT_ARRAY;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006163 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006164 }
6165 else {
6166
6167 BcResult *operand;
6168 unsigned long temp;
6169
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006170 s = bc_program_prep(&operand, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006171 if (s) goto err;
6172 s = bc_num_ulong(num, &temp);
6173 if (s) goto err;
6174
6175 if (temp > BC_MAX_DIM) {
Denys Vlasenko64074a12018-12-07 15:50:14 +01006176 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
Gavin Howard01055ba2018-11-03 11:00:21 -06006177 goto err;
6178 }
6179
6180 r.d.id.idx = (size_t) temp;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006181 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
Gavin Howard01055ba2018-11-03 11:00:21 -06006182 }
6183
6184err:
6185 if (s) free(r.d.id.name);
6186 return s;
6187}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01006188#if ERRORS_ARE_FATAL
6189# define bc_program_pushArray(...) (bc_program_pushArray(__VA_ARGS__), BC_STATUS_SUCCESS)
6190#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006191
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006192#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006193static BcStatus bc_program_incdec(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006194{
6195 BcStatus s;
6196 BcResult *ptr, res, copy;
6197 BcNum *num = NULL;
6198 char inst2 = inst;
6199
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006200 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006201 if (s) return s;
6202
6203 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6204 copy.t = BC_RESULT_TEMP;
6205 bc_num_init(&copy.d.n, num->len);
6206 bc_num_copy(&copy.d.n, num);
6207 }
6208
6209 res.t = BC_RESULT_ONE;
6210 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6211 BC_INST_ASSIGN_PLUS :
6212 BC_INST_ASSIGN_MINUS;
6213
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006214 bc_vec_push(&G.prog.results, &res);
6215 bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006216
6217 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006218 bc_vec_pop(&G.prog.results);
6219 bc_vec_push(&G.prog.results, &copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006220 }
6221
6222 return s;
6223}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01006224#if ERRORS_ARE_FATAL
6225# define bc_program_incdec(...) (bc_program_incdec(__VA_ARGS__), BC_STATUS_SUCCESS)
6226#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006227
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006228static BcStatus bc_program_call(char *code, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006229{
Gavin Howard01055ba2018-11-03 11:00:21 -06006230 BcInstPtr ip;
6231 size_t i, nparams = bc_program_index(code, idx);
6232 BcFunc *func;
Gavin Howard01055ba2018-11-03 11:00:21 -06006233 BcId *a;
6234 BcResultData param;
6235 BcResult *arg;
6236
6237 ip.idx = 0;
6238 ip.func = bc_program_index(code, idx);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006239 func = bc_program_func(ip.func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006240
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006241 if (func->code.len == 0) {
6242 return bc_error("undefined function");
6243 }
6244 if (nparams != func->nparams) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006245 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006246 }
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006247 ip.len = G.prog.results.len - nparams;
Gavin Howard01055ba2018-11-03 11:00:21 -06006248
6249 for (i = 0; i < nparams; ++i) {
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01006250 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006251
6252 a = bc_vec_item(&func->autos, nparams - 1 - i);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006253 arg = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006254
6255 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006256 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006257
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006258 s = bc_program_copyToVar(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006259 if (s) return s;
6260 }
6261
6262 for (; i < func->autos.len; ++i) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006263 BcVec *v;
Gavin Howard01055ba2018-11-03 11:00:21 -06006264
6265 a = bc_vec_item(&func->autos, i);
Denys Vlasenkodf515392018-12-02 19:27:48 +01006266 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006267
6268 if (a->idx) {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006269 bc_num_init_DEF_SIZE(&param.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006270 bc_vec_push(v, &param.n);
6271 }
6272 else {
6273 bc_array_init(&param.v, true);
6274 bc_vec_push(v, &param.v);
6275 }
6276 }
6277
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006278 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006279
6280 return BC_STATUS_SUCCESS;
6281}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01006282#if ERRORS_ARE_FATAL
6283# define bc_program_call(...) (bc_program_call(__VA_ARGS__), BC_STATUS_SUCCESS)
6284#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006285
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006286static BcStatus bc_program_return(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006287{
Gavin Howard01055ba2018-11-03 11:00:21 -06006288 BcResult res;
6289 BcFunc *f;
6290 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006291 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006292
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006293 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006294 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006295
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006296 f = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006297 res.t = BC_RESULT_TEMP;
6298
6299 if (inst == BC_INST_RET) {
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01006300 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006301 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006302 BcResult *operand = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006303
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006304 s = bc_program_num(operand, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006305 if (s) return s;
6306 bc_num_init(&res.d.n, num->len);
6307 bc_num_copy(&res.d.n, num);
6308 }
6309 else {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006310 bc_num_init_DEF_SIZE(&res.d.n);
Denys Vlasenko3129f702018-12-09 12:04:44 +01006311 //bc_num_zero(&res.d.n); - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06006312 }
6313
6314 // We need to pop arguments as well, so this takes that into account.
6315 for (i = 0; i < f->autos.len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006316 BcVec *v;
6317 BcId *a = bc_vec_item(&f->autos, i);
6318
Denys Vlasenkodf515392018-12-02 19:27:48 +01006319 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006320 bc_vec_pop(v);
6321 }
6322
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006323 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6324 bc_vec_push(&G.prog.results, &res);
6325 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006326
6327 return BC_STATUS_SUCCESS;
6328}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01006329#if ERRORS_ARE_FATAL
6330# define bc_program_return(...) (bc_program_return(__VA_ARGS__), BC_STATUS_SUCCESS)
6331#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006332#endif // ENABLE_BC
6333
6334static unsigned long bc_program_scale(BcNum *n)
6335{
6336 return (unsigned long) n->rdx;
6337}
6338
6339static unsigned long bc_program_len(BcNum *n)
6340{
Denys Vlasenkoa7f1a362018-12-10 12:57:01 +01006341 size_t len = n->len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006342
Denys Vlasenkoa7f1a362018-12-10 12:57:01 +01006343 if (n->rdx != len) return len;
6344 for (;;) {
6345 if (len == 0) break;
6346 len--;
6347 if (n->num[len] != 0) break;
6348 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006349 return len;
6350}
6351
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006352static BcStatus bc_program_builtin(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006353{
6354 BcStatus s;
6355 BcResult *opnd;
6356 BcNum *num = NULL;
6357 BcResult res;
6358 bool len = inst == BC_INST_LENGTH;
6359
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006360 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006361 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006362 opnd = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006363
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006364 s = bc_program_num(opnd, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006365 if (s) return s;
6366
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006367#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006368 if (!BC_PROG_NUM(opnd, num) && !len)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006369 return bc_error_variable_is_wrong_type();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006370#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006371
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006372 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006373
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006374 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006375#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006376 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006377 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006378 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006379#endif
6380#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006381 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6382
6383 char **str;
6384 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6385
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006386 str = bc_program_str(idx);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006387 bc_num_ulong2num(&res.d.n, strlen(*str));
Gavin Howard01055ba2018-11-03 11:00:21 -06006388 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006389#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006390 else {
Denys Vlasenko5ba55f12018-12-10 15:37:14 +01006391 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
Gavin Howard01055ba2018-11-03 11:00:21 -06006392 }
6393
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006394 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006395
6396 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006397}
6398
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006399#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006400static BcStatus bc_program_divmod(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006401{
6402 BcStatus s;
6403 BcResult *opd1, *opd2, res, res2;
6404 BcNum *n1, *n2 = NULL;
6405
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006406 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006407 if (s) return s;
6408
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006409 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006410 bc_num_init(&res2.d.n, n2->len);
6411
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006412 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006413 if (s) goto err;
6414
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006415 bc_program_binOpRetire(&res2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006416 res.t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006417 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006418
6419 return s;
6420
6421err:
6422 bc_num_free(&res2.d.n);
6423 bc_num_free(&res.d.n);
6424 return s;
6425}
6426
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006427static BcStatus bc_program_modexp(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006428{
6429 BcStatus s;
6430 BcResult *r1, *r2, *r3, res;
6431 BcNum *n1, *n2, *n3;
6432
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006433 if (!BC_PROG_STACK(&G.prog.results, 3))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006434 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006435 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006436 if (s) return s;
6437
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006438 r1 = bc_vec_item_rev(&G.prog.results, 2);
6439 s = bc_program_num(r1, &n1, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006440 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006441 if (!BC_PROG_NUM(r1, n1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006442 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006443
6444 // Make sure that the values have their pointers updated, if necessary.
6445 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6446
6447 if (r1->t == r2->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006448 s = bc_program_num(r2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006449 if (s) return s;
6450 }
6451
6452 if (r1->t == r3->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006453 s = bc_program_num(r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006454 if (s) return s;
6455 }
6456 }
6457
6458 bc_num_init(&res.d.n, n3->len);
6459 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6460 if (s) goto err;
6461
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006462 bc_vec_pop(&G.prog.results);
6463 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006464
6465 return s;
6466
6467err:
6468 bc_num_free(&res.d.n);
6469 return s;
6470}
6471
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006472static void bc_program_stackLen(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006473{
Gavin Howard01055ba2018-11-03 11:00:21 -06006474 BcResult res;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006475 size_t len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006476
6477 res.t = BC_RESULT_TEMP;
6478
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006479 bc_num_init_DEF_SIZE(&res.d.n);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006480 bc_num_ulong2num(&res.d.n, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006481 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006482}
6483
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006484static BcStatus bc_program_asciify(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006485{
6486 BcStatus s;
6487 BcResult *r, res;
Denys Vlasenko4a024c72018-12-09 13:21:54 +01006488 BcNum *num, n;
Gavin Howard01055ba2018-11-03 11:00:21 -06006489 char *str, *str2, c;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006490 size_t len = G.prog.strs.len, idx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006491 unsigned long val;
6492
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006493 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006494 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006495 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006496
Denys Vlasenko4a024c72018-12-09 13:21:54 +01006497 num = NULL; // TODO: is this NULL needed?
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006498 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006499 if (s) return s;
6500
6501 if (BC_PROG_NUM(r, num)) {
6502
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006503 bc_num_init_DEF_SIZE(&n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006504 bc_num_copy(&n, num);
6505 bc_num_truncate(&n, n.rdx);
6506
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006507 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006508 if (s) goto num_err;
6509 s = bc_num_ulong(&n, &val);
6510 if (s) goto num_err;
6511
6512 c = (char) val;
6513
6514 bc_num_free(&n);
6515 }
6516 else {
6517 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006518 str2 = *bc_program_str(idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006519 c = str2[0];
6520 }
6521
Denys Vlasenkofa35e592018-12-10 20:17:24 +01006522 str = xzalloc(2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006523 str[0] = c;
Denys Vlasenkofa35e592018-12-10 20:17:24 +01006524 //str[1] = '\0'; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06006525
6526 str2 = xstrdup(str);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006527 bc_program_addFunc(str2, &idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006528
6529 if (idx != len + BC_PROG_REQ_FUNCS) {
6530
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006531 for (idx = 0; idx < G.prog.strs.len; ++idx) {
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006532 if (strcmp(*bc_program_str(idx), str) == 0) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006533 len = idx;
6534 break;
6535 }
6536 }
6537
6538 free(str);
6539 }
6540 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006541 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006542
6543 res.t = BC_RESULT_STR;
6544 res.d.id.idx = len;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006545 bc_vec_pop(&G.prog.results);
6546 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006547
6548 return BC_STATUS_SUCCESS;
6549
6550num_err:
6551 bc_num_free(&n);
6552 return s;
6553}
6554
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006555static BcStatus bc_program_printStream(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006556{
6557 BcStatus s;
6558 BcResult *r;
6559 BcNum *n = NULL;
6560 size_t idx;
6561 char *str;
6562
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006563 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006564 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006565 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006566
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006567 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006568 if (s) return s;
6569
6570 if (BC_PROG_NUM(r, n))
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01006571 s = bc_num_stream(n, &G.prog.strmb);
Gavin Howard01055ba2018-11-03 11:00:21 -06006572 else {
6573 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006574 str = *bc_program_str(idx);
Denys Vlasenko00d77792018-11-30 23:13:42 +01006575 printf("%s", str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006576 }
6577
6578 return s;
6579}
Denys Vlasenko628bf1b2018-12-10 20:41:05 +01006580#if ERRORS_ARE_FATAL
6581# define bc_program_printStream(...) (bc_program_printStream(__VA_ARGS__), BC_STATUS_SUCCESS)
6582#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006583
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006584static BcStatus bc_program_nquit(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006585{
6586 BcStatus s;
6587 BcResult *opnd;
6588 BcNum *num = NULL;
6589 unsigned long val;
6590
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006591 s = bc_program_prep(&opnd, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006592 if (s) return s;
6593 s = bc_num_ulong(num, &val);
6594 if (s) return s;
6595
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006596 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006597
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006598 if (G.prog.stack.len < val)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006599 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006600 if (G.prog.stack.len == val) {
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006601 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006602 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006603
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006604 bc_vec_npop(&G.prog.stack, val);
Gavin Howard01055ba2018-11-03 11:00:21 -06006605
6606 return s;
6607}
Denys Vlasenkofa35e592018-12-10 20:17:24 +01006608#if ERRORS_ARE_FATAL
6609# define bc_program_nquit(...) (bc_program_nquit(__VA_ARGS__), BC_STATUS_SUCCESS)
6610#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006611
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006612static BcStatus bc_program_execStr(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006613 bool cond)
6614{
6615 BcStatus s = BC_STATUS_SUCCESS;
6616 BcResult *r;
6617 char **str;
6618 BcFunc *f;
6619 BcParse prs;
6620 BcInstPtr ip;
6621 size_t fidx, sidx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006622
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006623 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006624 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006625
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006626 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006627
6628 if (cond) {
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006629 BcNum *n = n; // for compiler
6630 bool exec;
6631 char *name;
6632 char *then_name = bc_program_name(code, bgn);
6633 char *else_name = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06006634
6635 if (code[*bgn] == BC_PARSE_STREND)
6636 (*bgn) += 1;
6637 else
6638 else_name = bc_program_name(code, bgn);
6639
6640 exec = r->d.n.len != 0;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006641 name = then_name;
6642 if (!exec && else_name != NULL) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006643 exec = true;
6644 name = else_name;
6645 }
6646
6647 if (exec) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006648 BcVec *v;
6649 v = bc_program_search(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006650 n = bc_vec_top(v);
6651 }
6652
6653 free(then_name);
6654 free(else_name);
6655
6656 if (!exec) goto exit;
6657 if (!BC_PROG_STR(n)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006658 s = bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006659 goto exit;
6660 }
6661
6662 sidx = n->rdx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006663 } else {
6664 if (r->t == BC_RESULT_STR) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006665 sidx = r->d.id.idx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006666 } else if (r->t == BC_RESULT_VAR) {
6667 BcNum *n;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006668 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006669 if (s || !BC_PROG_STR(n)) goto exit;
6670 sidx = n->rdx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006671 } else
Gavin Howard01055ba2018-11-03 11:00:21 -06006672 goto exit;
6673 }
6674
6675 fidx = sidx + BC_PROG_REQ_FUNCS;
6676
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006677 str = bc_program_str(sidx);
6678 f = bc_program_func(fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006679
6680 if (f->code.len == 0) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006681 common_parse_init(&prs, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006682 s = bc_parse_text(&prs, *str);
6683 if (s) goto err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01006684 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006685 if (s) goto err;
6686
6687 if (prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006688 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06006689 goto err;
6690 }
6691
6692 bc_parse_free(&prs);
6693 }
6694
6695 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006696 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006697 ip.func = fidx;
6698
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006699 bc_vec_pop(&G.prog.results);
6700 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006701
6702 return BC_STATUS_SUCCESS;
6703
6704err:
6705 bc_parse_free(&prs);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006706 f = bc_program_func(fidx);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006707 bc_vec_pop_all(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06006708exit:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006709 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006710 return s;
6711}
6712#endif // ENABLE_DC
6713
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006714static void bc_program_pushGlobal(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006715{
Gavin Howard01055ba2018-11-03 11:00:21 -06006716 BcResult res;
6717 unsigned long val;
6718
6719 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6720 if (inst == BC_INST_IBASE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006721 val = (unsigned long) G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006722 else if (inst == BC_INST_SCALE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006723 val = (unsigned long) G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006724 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006725 val = (unsigned long) G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006726
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006727 bc_num_init_DEF_SIZE(&res.d.n);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006728 bc_num_ulong2num(&res.d.n, val);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006729 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006730}
6731
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006732static void bc_program_addFunc(char *name, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006733{
Gavin Howard01055ba2018-11-03 11:00:21 -06006734 BcId entry, *entry_ptr;
6735 BcFunc f;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006736 int inserted;
Gavin Howard01055ba2018-11-03 11:00:21 -06006737
6738 entry.name = name;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006739 entry.idx = G.prog.fns.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006740
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006741 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6742 if (!inserted) free(name);
Gavin Howard01055ba2018-11-03 11:00:21 -06006743
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006744 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006745 *idx = entry_ptr->idx;
6746
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006747 if (!inserted) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006748
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006749 BcFunc *func = bc_program_func(entry_ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006750
6751 // We need to reset these, so the function can be repopulated.
6752 func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01006753 bc_vec_pop_all(&func->autos);
6754 bc_vec_pop_all(&func->code);
6755 bc_vec_pop_all(&func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06006756 }
6757 else {
6758 bc_func_init(&f);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006759 bc_vec_push(&G.prog.fns, &f);
Gavin Howard01055ba2018-11-03 11:00:21 -06006760 }
6761}
6762
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006763static BcStatus bc_program_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006764{
Gavin Howard01055ba2018-11-03 11:00:21 -06006765 BcResult r, *ptr;
6766 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006767 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006768 BcFunc *func = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006769 char *code = func->code.v;
6770 bool cond = false;
6771
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006772 while (ip->idx < func->code.len) {
Denys Vlasenkofa35e592018-12-10 20:17:24 +01006773 BcStatus s = BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06006774 char inst = code[(ip->idx)++];
6775
6776 switch (inst) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006777#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006778 case BC_INST_JUMP_ZERO:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006779 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006780 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006781 cond = !bc_num_cmp(num, &G.prog.zero);
6782 bc_vec_pop(&G.prog.results);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006783 // Fallthrough.
6784 case BC_INST_JUMP: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006785 size_t *addr;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006786 size_t idx = bc_program_index(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006787 addr = bc_vec_item(&func->labels, idx);
6788 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6789 break;
6790 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006791 case BC_INST_CALL:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006792 s = bc_program_call(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006793 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006794 case BC_INST_INC_PRE:
6795 case BC_INST_DEC_PRE:
6796 case BC_INST_INC_POST:
6797 case BC_INST_DEC_POST:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006798 s = bc_program_incdec(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006799 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006800 case BC_INST_HALT:
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006801 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06006802 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006803 case BC_INST_RET:
6804 case BC_INST_RET0:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006805 s = bc_program_return(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006806 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006807 case BC_INST_BOOL_OR:
6808 case BC_INST_BOOL_AND:
6809#endif // ENABLE_BC
6810 case BC_INST_REL_EQ:
6811 case BC_INST_REL_LE:
6812 case BC_INST_REL_GE:
6813 case BC_INST_REL_NE:
6814 case BC_INST_REL_LT:
6815 case BC_INST_REL_GT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006816 s = bc_program_logical(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006817 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006818 case BC_INST_READ:
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006819 s = bc_program_read();
Gavin Howard01055ba2018-11-03 11:00:21 -06006820 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006821 case BC_INST_VAR:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006822 s = bc_program_pushVar(code, &ip->idx, false, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006823 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006824 case BC_INST_ARRAY_ELEM:
6825 case BC_INST_ARRAY:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006826 s = bc_program_pushArray(code, &ip->idx, inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006827 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006828 case BC_INST_LAST:
Gavin Howard01055ba2018-11-03 11:00:21 -06006829 r.t = BC_RESULT_LAST;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006830 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006831 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006832 case BC_INST_IBASE:
6833 case BC_INST_SCALE:
6834 case BC_INST_OBASE:
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006835 bc_program_pushGlobal(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006836 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006837 case BC_INST_SCALE_FUNC:
6838 case BC_INST_LENGTH:
6839 case BC_INST_SQRT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006840 s = bc_program_builtin(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006841 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006842 case BC_INST_NUM:
Gavin Howard01055ba2018-11-03 11:00:21 -06006843 r.t = BC_RESULT_CONSTANT;
6844 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006845 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006846 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006847 case BC_INST_POP:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006848 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006849 s = bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006850 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006851 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006852 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006853 case BC_INST_POP_EXEC:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006854 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006855 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006856 case BC_INST_PRINT:
6857 case BC_INST_PRINT_POP:
6858 case BC_INST_PRINT_STR:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006859 s = bc_program_print(inst, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006860 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006861 case BC_INST_STR:
Gavin Howard01055ba2018-11-03 11:00:21 -06006862 r.t = BC_RESULT_STR;
6863 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006864 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006865 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006866 case BC_INST_POWER:
6867 case BC_INST_MULTIPLY:
6868 case BC_INST_DIVIDE:
6869 case BC_INST_MODULUS:
6870 case BC_INST_PLUS:
6871 case BC_INST_MINUS:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006872 s = bc_program_op(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006873 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006874 case BC_INST_BOOL_NOT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006875 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006876 if (s) return s;
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006877 bc_num_init_DEF_SIZE(&r.d.n);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006878 if (!bc_num_cmp(num, &G.prog.zero))
6879 bc_num_one(&r.d.n);
Denys Vlasenko3129f702018-12-09 12:04:44 +01006880 //else bc_num_zero(&r.d.n); - already is
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006881 bc_program_retire(&r, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006882 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006883 case BC_INST_NEG:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006884 s = bc_program_negate();
Gavin Howard01055ba2018-11-03 11:00:21 -06006885 break;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006886#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006887 case BC_INST_ASSIGN_POWER:
6888 case BC_INST_ASSIGN_MULTIPLY:
6889 case BC_INST_ASSIGN_DIVIDE:
6890 case BC_INST_ASSIGN_MODULUS:
6891 case BC_INST_ASSIGN_PLUS:
6892 case BC_INST_ASSIGN_MINUS:
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006893#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006894 case BC_INST_ASSIGN:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006895 s = bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006896 break;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006897#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006898 case BC_INST_MODEXP:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006899 s = bc_program_modexp();
Gavin Howard01055ba2018-11-03 11:00:21 -06006900 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006901 case BC_INST_DIVMOD:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006902 s = bc_program_divmod();
Gavin Howard01055ba2018-11-03 11:00:21 -06006903 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006904 case BC_INST_EXECUTE:
6905 case BC_INST_EXEC_COND:
Gavin Howard01055ba2018-11-03 11:00:21 -06006906 cond = inst == BC_INST_EXEC_COND;
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006907 s = bc_program_execStr(code, &ip->idx, cond);
Gavin Howard01055ba2018-11-03 11:00:21 -06006908 break;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006909 case BC_INST_PRINT_STACK: {
6910 size_t idx;
6911 for (idx = 0; idx < G.prog.results.len; ++idx) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006912 s = bc_program_print(BC_INST_PRINT, idx);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006913 if (s) break;
6914 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006915 break;
6916 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006917 case BC_INST_CLEAR_STACK:
Denys Vlasenko7d628012018-12-04 21:46:47 +01006918 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006919 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006920 case BC_INST_STACK_LEN:
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006921 bc_program_stackLen();
Gavin Howard01055ba2018-11-03 11:00:21 -06006922 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006923 case BC_INST_DUPLICATE:
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006924 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006925 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006926 ptr = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006927 bc_result_copy(&r, ptr);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006928 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006929 break;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006930 case BC_INST_SWAP: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006931 BcResult *ptr2;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006932 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006933 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006934 ptr = bc_vec_item_rev(&G.prog.results, 0);
6935 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006936 memcpy(&r, ptr, sizeof(BcResult));
6937 memcpy(ptr, ptr2, sizeof(BcResult));
6938 memcpy(ptr2, &r, sizeof(BcResult));
Gavin Howard01055ba2018-11-03 11:00:21 -06006939 break;
6940 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006941 case BC_INST_ASCIIFY:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006942 s = bc_program_asciify();
Gavin Howard01055ba2018-11-03 11:00:21 -06006943 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006944 case BC_INST_PRINT_STREAM:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006945 s = bc_program_printStream();
Gavin Howard01055ba2018-11-03 11:00:21 -06006946 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006947 case BC_INST_LOAD:
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006948 case BC_INST_PUSH_VAR: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006949 bool copy = inst == BC_INST_LOAD;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006950 s = bc_program_pushVar(code, &ip->idx, true, copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006951 break;
6952 }
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006953 case BC_INST_PUSH_TO_VAR: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006954 char *name = bc_program_name(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006955 s = bc_program_copyToVar(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006956 free(name);
6957 break;
6958 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006959 case BC_INST_QUIT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006960 if (G.prog.stack.len <= 2)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006961 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006962 bc_vec_npop(&G.prog.stack, 2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006963 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006964 case BC_INST_NQUIT:
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006965 s = bc_program_nquit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006966 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006967#endif // ENABLE_DC
6968 }
6969
Denys Vlasenkod38af482018-12-04 19:11:02 +01006970 if (s || G_interrupt) {
6971 bc_program_reset();
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006972 return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01006973 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006974
6975 // If the stack has changed, pointers may be invalid.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006976 ip = bc_vec_top(&G.prog.stack);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006977 func = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006978 code = func->code.v;
6979 }
6980
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006981 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06006982}
6983
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006984#if ENABLE_BC
Denys Vlasenko54214c32018-12-06 09:07:06 +01006985static void bc_vm_info(void)
6986{
6987 printf("%s "BB_VER"\n"
6988 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
Denys Vlasenko54214c32018-12-06 09:07:06 +01006989 , applet_name);
6990}
6991
6992static void bc_args(char **argv)
6993{
6994 unsigned opts;
6995 int i;
6996
6997 GETOPT_RESET();
6998#if ENABLE_FEATURE_BC_LONG_OPTIONS
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006999 opts = option_mask32 |= getopt32long(argv, "wvsqli",
Denys Vlasenko54214c32018-12-06 09:07:06 +01007000 "warn\0" No_argument "w"
7001 "version\0" No_argument "v"
7002 "standard\0" No_argument "s"
7003 "quiet\0" No_argument "q"
7004 "mathlib\0" No_argument "l"
7005 "interactive\0" No_argument "i"
7006 );
7007#else
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007008 opts = option_mask32 |= getopt32(argv, "wvsqli");
Denys Vlasenko54214c32018-12-06 09:07:06 +01007009#endif
7010 if (getenv("POSIXLY_CORRECT"))
7011 option_mask32 |= BC_FLAG_S;
7012
Denys Vlasenko54214c32018-12-06 09:07:06 +01007013 if (opts & BC_FLAG_V) {
7014 bc_vm_info();
7015 exit(0);
7016 }
7017
7018 for (i = optind; argv[i]; ++i)
7019 bc_vec_push(&G.files, argv + i);
7020}
7021
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007022static void bc_vm_envArgs(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007023{
Gavin Howard01055ba2018-11-03 11:00:21 -06007024 BcVec v;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007025 char *buf;
Denys Vlasenko54214c32018-12-06 09:07:06 +01007026 char *env_args = getenv("BC_ENV_ARGS");
Gavin Howard01055ba2018-11-03 11:00:21 -06007027
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007028 if (!env_args) return;
Gavin Howard01055ba2018-11-03 11:00:21 -06007029
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007030 G.env_args = xstrdup(env_args);
7031 buf = G.env_args;
Gavin Howard01055ba2018-11-03 11:00:21 -06007032
7033 bc_vec_init(&v, sizeof(char *), NULL);
Gavin Howard01055ba2018-11-03 11:00:21 -06007034
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007035 while (*(buf = skip_whitespace(buf)) != '\0') {
7036 bc_vec_push(&v, &buf);
7037 buf = skip_non_whitespace(buf);
7038 if (!*buf)
7039 break;
7040 *buf++ = '\0';
Gavin Howard01055ba2018-11-03 11:00:21 -06007041 }
7042
Denys Vlasenko54214c32018-12-06 09:07:06 +01007043 // NULL terminate, and pass argv[] so that first arg is argv[1]
7044 if (sizeof(int) == sizeof(char*)) {
7045 bc_vec_push(&v, &const_int_0);
7046 } else {
7047 static char *const nullptr = NULL;
7048 bc_vec_push(&v, &nullptr);
7049 }
7050 bc_args(((char **)v.v) - 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06007051
7052 bc_vec_free(&v);
Gavin Howard01055ba2018-11-03 11:00:21 -06007053}
7054#endif // ENABLE_BC
7055
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007056static unsigned bc_vm_envLen(const char *var)
Gavin Howard01055ba2018-11-03 11:00:21 -06007057{
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007058 char *lenv;
7059 unsigned len;
Gavin Howard01055ba2018-11-03 11:00:21 -06007060
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007061 lenv = getenv(var);
7062 len = BC_NUM_PRINT_WIDTH;
Gavin Howard01055ba2018-11-03 11:00:21 -06007063 if (!lenv) return len;
7064
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007065 len = bb_strtou(lenv, NULL, 10) - 1;
7066 if (errno || len < 2 || len >= INT_MAX)
Gavin Howard01055ba2018-11-03 11:00:21 -06007067 len = BC_NUM_PRINT_WIDTH;
7068
7069 return len;
7070}
7071
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007072static BcStatus bc_vm_process(const char *text)
Gavin Howard01055ba2018-11-03 11:00:21 -06007073{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007074 BcStatus s = bc_parse_text(&G.prs, text);
Gavin Howard01055ba2018-11-03 11:00:21 -06007075
Gavin Howard01055ba2018-11-03 11:00:21 -06007076 if (s) return s;
7077
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007078 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007079 s = G.prs.parse(&G.prs);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01007080 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007081 }
7082
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007083 if (BC_PARSE_CAN_EXEC(&G.prs)) {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007084 s = bc_program_exec();
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01007085 fflush_and_check();
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007086 if (s)
Denys Vlasenkod38af482018-12-04 19:11:02 +01007087 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06007088 }
7089
7090 return s;
7091}
7092
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007093static BcStatus bc_vm_file(const char *file)
Gavin Howard01055ba2018-11-03 11:00:21 -06007094{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007095 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007096 char *data;
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007097 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007098 BcFunc *main_func;
7099 BcInstPtr *ip;
7100
Denys Vlasenkodf515392018-12-02 19:27:48 +01007101 data = bc_read_file(file);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007102 if (!data) return bc_error_fmt("file '%s' is not text", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007103
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007104 sv_file = G.prog.file;
7105 G.prog.file = file;
7106 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007107 s = bc_vm_process(data);
Gavin Howard01055ba2018-11-03 11:00:21 -06007108 if (s) goto err;
7109
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01007110 main_func = bc_program_func(BC_PROG_MAIN);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007111 ip = bc_vec_item(&G.prog.stack, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06007112
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007113 if (main_func->code.len < ip->idx)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007114 s = bc_error_fmt("file '%s' is not executable", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007115
7116err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007117 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007118 free(data);
7119 return s;
7120}
7121
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007122static BcStatus bc_vm_stdin(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007123{
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007124 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007125 BcVec buf, buffer;
Gavin Howard01055ba2018-11-03 11:00:21 -06007126 size_t len, i, str = 0;
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007127 bool comment = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06007128
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007129 G.prog.file = NULL;
7130 bc_lex_file(&G.prs.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06007131
Denys Vlasenko7d628012018-12-04 21:46:47 +01007132 bc_char_vec_init(&buffer);
7133 bc_char_vec_init(&buf);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01007134 bc_vec_pushZeroByte(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007135
7136 // This loop is complex because the vm tries not to send any lines that end
7137 // with a backslash to the parser. The reason for that is because the parser
7138 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7139 // case, and for strings and comments, the parser will expect more stuff.
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007140 while ((s = bc_read_line(&buf)) == BC_STATUS_SUCCESS) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007141
7142 char *string = buf.v;
7143
7144 len = buf.len - 1;
7145
7146 if (len == 1) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007147 if (str && buf.v[0] == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007148 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007149 else if (buf.v[0] == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007150 str += 1;
7151 }
7152 else if (len > 1 || comment) {
7153
7154 for (i = 0; i < len; ++i) {
7155
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007156 bool notend = len > i + 1;
7157 char c = string[i];
Gavin Howard01055ba2018-11-03 11:00:21 -06007158
7159 if (i - 1 > len || string[i - 1] != '\\') {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007160 if (G.sbgn == G.send)
7161 str ^= c == G.sbgn;
7162 else if (c == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007163 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007164 else if (c == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007165 str += 1;
7166 }
7167
7168 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7169 comment = true;
7170 break;
7171 }
7172 else if (c == '*' && notend && comment && string[i + 1] == '/')
7173 comment = false;
7174 }
7175
7176 if (str || comment || string[len - 2] == '\\') {
7177 bc_vec_concat(&buffer, buf.v);
7178 continue;
7179 }
7180 }
7181
7182 bc_vec_concat(&buffer, buf.v);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007183 s = bc_vm_process(buffer.v);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007184 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007185 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007186 // Debug config, non-interactive mode:
7187 // return all the way back to main.
7188 // Non-debug builds do not come here, they exit.
7189 break;
7190 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007191 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007192
Denys Vlasenko7d628012018-12-04 21:46:47 +01007193 bc_vec_pop_all(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007194 }
Denys Vlasenkof522dd92018-12-07 16:35:43 +01007195 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7196 s = BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06007197
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007198 if (str) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007199 s = bc_error("string end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007200 }
7201 else if (comment) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007202 s = bc_error("comment end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007203 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007204
Gavin Howard01055ba2018-11-03 11:00:21 -06007205 bc_vec_free(&buf);
7206 bc_vec_free(&buffer);
7207 return s;
7208}
7209
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007210#if ENABLE_BC
7211static const char bc_lib[] = {
7212 "scale=20"
7213"\n" "define e(x){"
7214"\n" "auto b,s,n,r,d,i,p,f,v"
7215"\n" "b=ibase"
7216"\n" "ibase=A"
7217"\n" "if(x<0){"
7218"\n" "n=1"
7219"\n" "x=-x"
7220"\n" "}"
7221"\n" "s=scale"
7222"\n" "r=6+s+0.44*x"
7223"\n" "scale=scale(x)+1"
7224"\n" "while(x>1){"
7225"\n" "d+=1"
7226"\n" "x/=2"
7227"\n" "scale+=1"
7228"\n" "}"
7229"\n" "scale=r"
7230"\n" "r=x+1"
7231"\n" "p=x"
7232"\n" "f=v=1"
7233"\n" "for(i=2;v!=0;++i){"
7234"\n" "p*=x"
7235"\n" "f*=i"
7236"\n" "v=p/f"
7237"\n" "r+=v"
7238"\n" "}"
7239"\n" "while((d--)!=0)r*=r"
7240"\n" "scale=s"
7241"\n" "ibase=b"
7242"\n" "if(n!=0)return(1/r)"
7243"\n" "return(r/1)"
7244"\n" "}"
7245"\n" "define l(x){"
7246"\n" "auto b,s,r,p,a,q,i,v"
7247"\n" "b=ibase"
7248"\n" "ibase=A"
7249"\n" "if(x<=0){"
7250"\n" "r=(1-10^scale)/1"
7251"\n" "ibase=b"
7252"\n" "return(r)"
7253"\n" "}"
7254"\n" "s=scale"
7255"\n" "scale+=6"
7256"\n" "p=2"
7257"\n" "while(x>=2){"
7258"\n" "p*=2"
7259"\n" "x=sqrt(x)"
7260"\n" "}"
7261"\n" "while(x<=0.5){"
7262"\n" "p*=2"
7263"\n" "x=sqrt(x)"
7264"\n" "}"
7265"\n" "r=a=(x-1)/(x+1)"
7266"\n" "q=a*a"
7267"\n" "v=1"
7268"\n" "for(i=3;v!=0;i+=2){"
7269"\n" "a*=q"
7270"\n" "v=a/i"
7271"\n" "r+=v"
7272"\n" "}"
7273"\n" "r*=p"
7274"\n" "scale=s"
7275"\n" "ibase=b"
7276"\n" "return(r/1)"
7277"\n" "}"
7278"\n" "define s(x){"
7279"\n" "auto b,s,r,n,a,q,i"
7280"\n" "b=ibase"
7281"\n" "ibase=A"
7282"\n" "s=scale"
7283"\n" "scale=1.1*s+2"
7284"\n" "a=a(1)"
7285"\n" "if(x<0){"
7286"\n" "n=1"
7287"\n" "x=-x"
7288"\n" "}"
7289"\n" "scale=0"
7290"\n" "q=(x/a+2)/4"
7291"\n" "x=x-4*q*a"
7292"\n" "if(q%2!=0)x=-x"
7293"\n" "scale=s+2"
7294"\n" "r=a=x"
7295"\n" "q=-x*x"
7296"\n" "for(i=3;a!=0;i+=2){"
7297"\n" "a*=q/(i*(i-1))"
7298"\n" "r+=a"
7299"\n" "}"
7300"\n" "scale=s"
7301"\n" "ibase=b"
7302"\n" "if(n!=0)return(-r/1)"
7303"\n" "return(r/1)"
7304"\n" "}"
7305"\n" "define c(x){"
7306"\n" "auto b,s"
7307"\n" "b=ibase"
7308"\n" "ibase=A"
7309"\n" "s=scale"
7310"\n" "scale*=1.2"
7311"\n" "x=s(2*a(1)+x)"
7312"\n" "scale=s"
7313"\n" "ibase=b"
7314"\n" "return(x/1)"
7315"\n" "}"
7316"\n" "define a(x){"
7317"\n" "auto b,s,r,n,a,m,t,f,i,u"
7318"\n" "b=ibase"
7319"\n" "ibase=A"
7320"\n" "n=1"
7321"\n" "if(x<0){"
7322"\n" "n=-1"
7323"\n" "x=-x"
7324"\n" "}"
7325"\n" "if(x==1){"
7326"\n" "if(scale<65){"
7327"\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7328"\n" "}"
7329"\n" "}"
7330"\n" "if(x==.2){"
7331"\n" "if(scale<65){"
7332"\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7333"\n" "}"
7334"\n" "}"
7335"\n" "s=scale"
7336"\n" "if(x>.2){"
7337"\n" "scale+=5"
7338"\n" "a=a(.2)"
7339"\n" "}"
7340"\n" "scale=s+3"
7341"\n" "while(x>.2){"
7342"\n" "m+=1"
7343"\n" "x=(x-.2)/(1+.2*x)"
7344"\n" "}"
7345"\n" "r=u=x"
7346"\n" "f=-x*x"
7347"\n" "t=1"
7348"\n" "for(i=3;t!=0;i+=2){"
7349"\n" "u*=f"
7350"\n" "t=u/i"
7351"\n" "r+=t"
7352"\n" "}"
7353"\n" "scale=s"
7354"\n" "ibase=b"
7355"\n" "return((m*a+r)/n)"
7356"\n" "}"
7357"\n" "define j(n,x){"
7358"\n" "auto b,s,o,a,i,v,f"
7359"\n" "b=ibase"
7360"\n" "ibase=A"
7361"\n" "s=scale"
7362"\n" "scale=0"
7363"\n" "n/=1"
7364"\n" "if(n<0){"
7365"\n" "n=-n"
7366"\n" "if(n%2==1)o=1"
7367"\n" "}"
7368"\n" "a=1"
7369"\n" "for(i=2;i<=n;++i)a*=i"
7370"\n" "scale=1.5*s"
7371"\n" "a=(x^n)/2^n/a"
7372"\n" "r=v=1"
7373"\n" "f=-x*x/4"
7374"\n" "scale=scale+length(a)-scale(a)"
7375"\n" "for(i=1;v!=0;++i){"
7376"\n" "v=v*f/i/(n+i)"
7377"\n" "r+=v"
7378"\n" "}"
7379"\n" "scale=s"
7380"\n" "ibase=b"
7381"\n" "if(o!=0)a=-a"
7382"\n" "return(a*r/1)"
7383"\n" "}"
7384};
7385#endif // ENABLE_BC
7386
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007387static BcStatus bc_vm_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007388{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007389 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007390 size_t i;
7391
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007392#if ENABLE_BC
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007393 if (option_mask32 & BC_FLAG_L) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007394
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007395 // We know that internal library is not buggy,
7396 // thus error checking is normally disabled.
7397# define DEBUG_LIB 0
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007398 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007399 s = bc_parse_text(&G.prs, bc_lib);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007400 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007401
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007402 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007403 s = G.prs.parse(&G.prs);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007404 if (DEBUG_LIB && s) return s;
7405 }
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007406 s = bc_program_exec();
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007407 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007408 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007409#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007410
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007411 s = BC_STATUS_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007412 for (i = 0; !s && i < G.files.len; ++i)
7413 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007414 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7415 // Debug config, non-interactive mode:
7416 // return all the way back to main.
7417 // Non-debug builds do not come here, they exit.
7418 return s;
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007419 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007420
Denys Vlasenko91cde952018-12-10 20:56:08 +01007421 if (IS_BC || (option_mask32 & BC_FLAG_I))
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007422 s = bc_vm_stdin();
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007423
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007424 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7425 s = bc_vm_process("");
Gavin Howard01055ba2018-11-03 11:00:21 -06007426
Denys Vlasenko00d77792018-11-30 23:13:42 +01007427 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007428}
7429
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007430#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007431static void bc_program_free(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007432{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007433 bc_num_free(&G.prog.ib);
7434 bc_num_free(&G.prog.ob);
7435 bc_num_free(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007436# if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007437 bc_num_free(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007438# endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007439 bc_vec_free(&G.prog.fns);
7440 bc_vec_free(&G.prog.fn_map);
7441 bc_vec_free(&G.prog.vars);
7442 bc_vec_free(&G.prog.var_map);
7443 bc_vec_free(&G.prog.arrs);
7444 bc_vec_free(&G.prog.arr_map);
7445 bc_vec_free(&G.prog.strs);
7446 bc_vec_free(&G.prog.consts);
7447 bc_vec_free(&G.prog.results);
7448 bc_vec_free(&G.prog.stack);
7449 bc_num_free(&G.prog.last);
7450 bc_num_free(&G.prog.zero);
7451 bc_num_free(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007452}
7453
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007454static void bc_vm_free(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007455{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007456 bc_vec_free(&G.files);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007457 bc_program_free();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007458 bc_parse_free(&G.prs);
7459 free(G.env_args);
Gavin Howard01055ba2018-11-03 11:00:21 -06007460}
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007461#endif
7462
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007463static void bc_program_init(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007464{
7465 size_t idx;
7466 BcInstPtr ip;
7467
7468 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7469 memset(&ip, 0, sizeof(BcInstPtr));
7470
7471 /* G.prog.nchars = G.prog.scale = 0; - already is */
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007472 bc_num_init_DEF_SIZE(&G.prog.ib);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007473 bc_num_ten(&G.prog.ib);
7474 G.prog.ib_t = 10;
7475
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007476 bc_num_init_DEF_SIZE(&G.prog.ob);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007477 bc_num_ten(&G.prog.ob);
7478 G.prog.ob_t = 10;
7479
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007480 bc_num_init_DEF_SIZE(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007481 bc_num_ten(&G.prog.hexb);
7482 G.prog.hexb.num[0] = 6;
7483
7484#if ENABLE_DC
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007485 bc_num_init_DEF_SIZE(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007486 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7487#endif
7488
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007489 bc_num_init_DEF_SIZE(&G.prog.last);
Denys Vlasenko3129f702018-12-09 12:04:44 +01007490 //bc_num_zero(&G.prog.last); - already is
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007491
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007492 bc_num_init_DEF_SIZE(&G.prog.zero);
Denys Vlasenko3129f702018-12-09 12:04:44 +01007493 //bc_num_zero(&G.prog.zero); - already is
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007494
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007495 bc_num_init_DEF_SIZE(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007496 bc_num_one(&G.prog.one);
7497
7498 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007499 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007500
Denys Vlasenko1f67e932018-12-03 00:08:59 +01007501 bc_program_addFunc(xstrdup("(main)"), &idx);
7502 bc_program_addFunc(xstrdup("(read)"), &idx);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007503
7504 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007505 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007506
7507 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007508 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007509
7510 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7511 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7512 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7513 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7514 bc_vec_push(&G.prog.stack, &ip);
7515}
Gavin Howard01055ba2018-11-03 11:00:21 -06007516
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007517static int bc_vm_init(const char *env_len)
Gavin Howard01055ba2018-11-03 11:00:21 -06007518{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007519#if ENABLE_FEATURE_EDITING
7520 G.line_input_state = new_line_input_t(DO_HISTORY);
7521#endif
7522 G.prog.len = bc_vm_envLen(env_len);
7523
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007524 bc_vec_init(&G.files, sizeof(char *), NULL);
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007525 if (IS_BC)
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007526 IF_BC(bc_vm_envArgs();)
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007527 bc_program_init();
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007528 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007529 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007530 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007531 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007532 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007533
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007534 if (isatty(0)) {
Denys Vlasenkod38af482018-12-04 19:11:02 +01007535#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007536 G_ttyin = 1;
Denys Vlasenko17c54722018-12-04 21:21:32 +01007537 // With SA_RESTART, most system calls will restart
7538 // (IOW: they won't fail with EINTR).
7539 // In particular, this means ^C won't cause
7540 // stdout to get into "error state" if SIGINT hits
7541 // within write() syscall.
7542 // The downside is that ^C while line input is taken
7543 // will only be handled after [Enter] since read()
7544 // from stdin is not interrupted by ^C either,
7545 // it restarts, thus fgetc() does not return on ^C.
7546 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7547
7548 // Without SA_RESTART, this exhibits a bug:
7549 // "while (1) print 1" and try ^C-ing it.
7550 // Intermittently, instead of returning to input line,
7551 // you'll get "output error: Interrupted system call"
7552 // and exit.
7553 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
Denys Vlasenkod38af482018-12-04 19:11:02 +01007554#endif
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007555 return 1; // "tty"
Denys Vlasenkod38af482018-12-04 19:11:02 +01007556 }
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007557 return 0; // "not a tty"
7558}
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007559
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007560static BcStatus bc_vm_run(void)
7561{
7562 BcStatus st = bc_vm_exec();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007563#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01007564 if (G_exiting) // it was actually "halt" or "quit"
7565 st = EXIT_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007566 bc_vm_free();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007567# if ENABLE_FEATURE_EDITING
7568 free_line_input_t(G.line_input_state);
7569# endif
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007570 FREE_G();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007571#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007572 return st;
7573}
7574
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007575#if ENABLE_BC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007576int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007577int bc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007578{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007579 int is_tty;
7580
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007581 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007582 G.sbgn = G.send = '"';
Gavin Howard01055ba2018-11-03 11:00:21 -06007583
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007584 is_tty = bc_vm_init("BC_LINE_LENGTH");
7585
7586 bc_args(argv);
7587
7588 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7589 bc_vm_info();
7590
7591 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007592}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007593#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007594
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007595#if ENABLE_DC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007596int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007597int dc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007598{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007599 int noscript;
7600
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007601 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007602 G.sbgn = '[';
7603 G.send = ']';
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007604 /*
7605 * TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7606 * 1 char wider than bc from the same package.
7607 * Both default width, and xC_LINE_LENGTH=N are wider:
7608 * "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7609 * 1234\
7610 * 56
7611 * "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7612 * 123\
7613 * 456
7614 * Do the same, or it's a bug?
7615 */
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007616 bc_vm_init("DC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007617
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007618 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7619 noscript = BC_FLAG_I;
7620 for (;;) {
7621 int n = getopt(argc, argv, "e:f:x");
7622 if (n <= 0)
7623 break;
7624 switch (n) {
7625 case 'e':
7626 noscript = 0;
7627 n = bc_vm_process(optarg);
7628 if (n) return n;
7629 break;
7630 case 'f':
7631 noscript = 0;
7632 bc_vm_file(optarg);
7633 break;
7634 case 'x':
7635 option_mask32 |= DC_FLAG_X;
7636 break;
7637 default:
7638 bb_show_usage();
7639 }
7640 }
7641 argv += optind;
7642
7643 while (*argv) {
7644 noscript = 0;
7645 bc_vec_push(&G.files, argv++);
7646 }
7647
7648 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7649
7650 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007651}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007652#endif
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +01007653
7654#endif // not DC_SMALL