blob: 33abe9366cd0251a4df7f2989a52af7a875f47aa [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
196typedef void (*BcVecFree)(void *);
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 Vlasenko5f1b90b2018-12-08 23:18:06 +0100224typedef void (*BcNumDigitOp)(size_t, size_t, bool);
Denys Vlasenko2a8ad482018-12-08 21:56:37 +0100225
Gavin Howard01055ba2018-11-03 11:00:21 -0600226typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
Gavin Howard01055ba2018-11-03 11:00:21 -0600227
Gavin Howard01055ba2018-11-03 11:00:21 -0600228static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
229static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
230static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
231static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
232static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
233static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
234static 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;
562typedef BcStatus (*BcLexNext)(struct BcLex *);
563
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
Gavin Howard01055ba2018-11-03 11:00:21 -0600629typedef BcStatus (*BcParseParse)(struct BcParse *);
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
705typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
706
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100707#define BC_FLAG_W (1 << 0)
708#define BC_FLAG_V (1 << 1)
709#define BC_FLAG_S (1 << 2)
710#define BC_FLAG_Q (1 << 3)
711#define BC_FLAG_L (1 << 4)
712#define BC_FLAG_I (1 << 5)
713#define DC_FLAG_X (1 << 6)
Gavin Howard01055ba2018-11-03 11:00:21 -0600714
715#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
716#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
717
Denys Vlasenko64074a12018-12-07 15:50:14 +0100718#define BC_MAX_OBASE ((unsigned) 999)
719#define BC_MAX_DIM ((unsigned) INT_MAX)
720#define BC_MAX_SCALE ((unsigned) UINT_MAX)
721#define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
722#define BC_MAX_NUM BC_MAX_STRING
723// Unused apart from "limits" message. Just show a "biggish number" there.
724//#define BC_MAX_NAME BC_MAX_STRING
725//#define BC_MAX_EXP ((unsigned long) LONG_MAX)
726//#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
727#define BC_MAX_NAME_STR "999999999"
728#define BC_MAX_EXP_STR "999999999"
729#define BC_MAX_VARS_STR "999999999"
730
731#define BC_MAX_OBASE_STR "999"
732
733#if INT_MAX == 2147483647
734# define BC_MAX_DIM_STR "2147483647"
735#elif INT_MAX == 9223372036854775807
736# define BC_MAX_DIM_STR "9223372036854775807"
737#else
738# error Strange INT_MAX
739#endif
740
741#if UINT_MAX == 4294967295
742# define BC_MAX_SCALE_STR "4294967295"
743# define BC_MAX_STRING_STR "4294967294"
744#elif UINT_MAX == 18446744073709551615
745# define BC_MAX_SCALE_STR "18446744073709551615"
746# define BC_MAX_STRING_STR "18446744073709551614"
747#else
748# error Strange UINT_MAX
749#endif
750#define BC_MAX_NUM_STR BC_MAX_STRING_STR
Gavin Howard01055ba2018-11-03 11:00:21 -0600751
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100752struct globals {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100753 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100754 IF_FEATURE_CLEAN_UP(smallint exiting;)
Gavin Howard01055ba2018-11-03 11:00:21 -0600755 char sbgn;
756 char send;
Gavin Howard01055ba2018-11-03 11:00:21 -0600757
758 BcParse prs;
759 BcProgram prog;
760
Denys Vlasenko5318f812018-12-05 17:48:01 +0100761 // For error messages. Can be set to current parsed line,
762 // or [TODO] to current executing line (can be before last parsed one)
763 unsigned err_line;
764
Gavin Howard01055ba2018-11-03 11:00:21 -0600765 BcVec files;
766
767 char *env_args;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100768
769#if ENABLE_FEATURE_EDITING
770 line_input_t *line_input_state;
771#endif
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100772} FIX_ALIASING;
773#define G (*ptr_to_globals)
774#define INIT_G() do { \
775 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
776} while (0)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100777#define FREE_G() do { \
778 FREE_PTR_TO_GLOBALS(); \
779} while (0)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100780#define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
781#define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100782#define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100783#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkob9c321d2018-12-07 12:41:42 +0100784# define G_interrupt bb_got_signal
785# define G_ttyin G.ttyin
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100786#else
Denys Vlasenkob9c321d2018-12-07 12:41:42 +0100787# define G_interrupt 0
788# define G_ttyin 0
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100789#endif
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100790#if ENABLE_FEATURE_CLEAN_UP
791# define G_exiting G.exiting
792#else
793# define G_exiting 0
794#endif
Denys Vlasenko00d77792018-11-30 23:13:42 +0100795#define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
796
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100797#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600798
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100799// This is a bit array that corresponds to token types. An entry is
Gavin Howard01055ba2018-11-03 11:00:21 -0600800// true if the token is valid in an expression, false otherwise.
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100801enum {
802 BC_PARSE_EXPRS_BITS = 0
803 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
804 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
805 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
806 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
807 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
808 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
809 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
810 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
Gavin Howard01055ba2018-11-03 11:00:21 -0600811};
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100812static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
813{
814#if ULONG_MAX > 0xffffffff
815 // 64-bit version (will not work correctly for 32-bit longs!)
816 return BC_PARSE_EXPRS_BITS & (1UL << i);
817#else
818 // 32-bit version
819 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
820 if (i >= 32) {
821 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
822 i &= 31;
823 }
824 return m & (1UL << i);
825#endif
826}
Gavin Howard01055ba2018-11-03 11:00:21 -0600827
828// This is an array of data for operators that correspond to token types.
Denys Vlasenko65437582018-12-05 19:37:19 +0100829static const uint8_t bc_parse_ops[] = {
830#define OP(p,l) ((int)(l) * 0x10 + (p))
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100831 OP(0, false), OP( 0, false ), // inc dec
832 OP(1, false), // neg
Denys Vlasenko65437582018-12-05 19:37:19 +0100833 OP(2, false),
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100834 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
835 OP(4, true ), OP( 4, true ), // mod + -
836 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
837 OP(1, false), // not
838 OP(7, true ), OP( 7, true ), // or and
839 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
840 OP(5, false), OP( 5, false ), // -= =
Denys Vlasenko65437582018-12-05 19:37:19 +0100841#undef OP
Gavin Howard01055ba2018-11-03 11:00:21 -0600842};
Denys Vlasenko65437582018-12-05 19:37:19 +0100843#define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
844#define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
Gavin Howard01055ba2018-11-03 11:00:21 -0600845
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100846// Byte array of up to 4 BC_LEX's, packed into 32-bit word
847typedef uint32_t BcParseNext;
848
Gavin Howard01055ba2018-11-03 11:00:21 -0600849// These identify what tokens can come after expressions in certain cases.
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100850enum {
851#define BC_PARSE_NEXT4(a,b,c,d) ( (a) | ((b)<<8) | ((c)<<16) | ((((d)|0x80)<<24)) )
852#define BC_PARSE_NEXT2(a,b) BC_PARSE_NEXT4(a,b,0xff,0xff)
853#define BC_PARSE_NEXT1(a) BC_PARSE_NEXT4(a,0xff,0xff,0xff)
854 bc_parse_next_expr = BC_PARSE_NEXT4(BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF),
855 bc_parse_next_param = BC_PARSE_NEXT2(BC_LEX_RPAREN, BC_LEX_COMMA),
856 bc_parse_next_print = BC_PARSE_NEXT4(BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF),
857 bc_parse_next_rel = BC_PARSE_NEXT1(BC_LEX_RPAREN),
858 bc_parse_next_elem = BC_PARSE_NEXT1(BC_LEX_RBRACKET),
859 bc_parse_next_for = BC_PARSE_NEXT1(BC_LEX_SCOLON),
860 bc_parse_next_read = BC_PARSE_NEXT2(BC_LEX_NLINE, BC_LEX_EOF),
861#undef BC_PARSE_NEXT4
862#undef BC_PARSE_NEXT2
863#undef BC_PARSE_NEXT1
864};
Gavin Howard01055ba2018-11-03 11:00:21 -0600865#endif // ENABLE_BC
866
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100867#if ENABLE_DC
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100868static const //BcLexType - should be this type, but narrower type saves size:
869uint8_t
870dc_lex_regs[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600871 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
872 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
873 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
874 BC_LEX_STORE_PUSH,
875};
876
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100877static const //BcLexType - should be this type
878uint8_t
879dc_lex_tokens[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600880 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
881 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
882 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
883 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
884 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
885 BC_LEX_INVALID, BC_LEX_INVALID,
886 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
887 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
888 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
889 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
890 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
891 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
892 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
893 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
894 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
895 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
896 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
897 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
898 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
899 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
900 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
901 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
902 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
903 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
904 BC_LEX_INVALID
905};
906
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100907static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
908int8_t
909dc_parse_insts[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600910 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
911 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
912 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
913 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
914 BC_INST_INVALID, BC_INST_INVALID,
915 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
916 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
917 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
918 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
919 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
920 BC_INST_INVALID, BC_INST_INVALID,
921 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
922 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
923 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
924 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
925 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
926 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
927 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
928 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
929 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
930 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
931 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
932 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
933};
934#endif // ENABLE_DC
935
Gavin Howard01055ba2018-11-03 11:00:21 -0600936static const BcNumBinaryOp bc_program_ops[] = {
937 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
938};
939
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100940static void fflush_and_check(void)
941{
942 fflush_all();
943 if (ferror(stdout) || ferror(stderr))
944 bb_perror_msg_and_die("output error");
945}
946
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100947#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100948#define QUIT_OR_RETURN_TO_MAIN \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100949do { \
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100950 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100951 G_exiting = 1; \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100952 return BC_STATUS_FAILURE; \
953} while (0)
954#else
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100955#define QUIT_OR_RETURN_TO_MAIN quit()
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100956#endif
957
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100958static void quit(void) NORETURN;
959static void quit(void)
960{
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100961 if (ferror(stdin))
962 bb_perror_msg_and_die("input error");
963 fflush_and_check();
964 exit(0);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100965}
966
Denys Vlasenko5318f812018-12-05 17:48:01 +0100967static void bc_verror_msg(const char *fmt, va_list p)
968{
969 const char *sv = sv; /* for compiler */
970 if (G.prog.file) {
971 sv = applet_name;
972 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
973 }
974 bb_verror_msg(fmt, p, NULL);
975 if (G.prog.file) {
976 free((char*)applet_name);
977 applet_name = sv;
978 }
979}
980
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100981static NOINLINE int bc_error_fmt(const char *fmt, ...)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100982{
983 va_list p;
984
985 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +0100986 bc_verror_msg(fmt, p);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100987 va_end(p);
Denys Vlasenko0409ad32018-12-05 16:39:22 +0100988
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100989 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100990 exit(1);
991 return BC_STATUS_FAILURE;
992}
993
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +0100994#if ENABLE_BC
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100995static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100996{
997 va_list p;
998
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100999 // Are non-POSIX constructs totally ok?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01001000 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001001 return BC_STATUS_SUCCESS; // yes
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001002
1003 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +01001004 bc_verror_msg(fmt, p);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001005 va_end(p);
1006
1007 // Do we treat non-POSIX constructs as errors?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01001008 if (!(option_mask32 & BC_FLAG_S))
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001009 return BC_STATUS_SUCCESS; // no, it's a warning
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01001010 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001011 exit(1);
1012 return BC_STATUS_FAILURE;
1013}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001014#endif
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001015
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001016// We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
1017// This idiom begs for tail-call optimization, but for it to work,
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001018// function must not have caller-cleaned parameters on stack.
1019// Unfortunately, vararg function API does exactly that on most arches.
1020// Thus, use these shims for the cases when we have no vararg PARAMS:
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001021static int bc_error(const char *msg)
1022{
1023 return bc_error_fmt("%s", msg);
1024}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001025#if ENABLE_BC
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001026static int bc_POSIX_requires(const char *msg)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001027{
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001028 return bc_posix_error_fmt("POSIX requires %s", msg);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001029}
Denys Vlasenko00646792018-12-05 18:12:27 +01001030static int bc_POSIX_does_not_allow(const char *msg)
1031{
1032 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1033}
1034static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1035{
1036 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1037}
1038static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1039{
1040 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1041}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001042#endif
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001043static int bc_error_bad_character(char c)
1044{
1045 return bc_error_fmt("bad character '%c'", c);
1046}
1047static int bc_error_bad_expression(void)
1048{
1049 return bc_error("bad expression");
1050}
1051static int bc_error_bad_token(void)
1052{
1053 return bc_error("bad token");
1054}
1055static int bc_error_stack_has_too_few_elements(void)
1056{
1057 return bc_error("stack has too few elements");
1058}
1059static int bc_error_variable_is_wrong_type(void)
1060{
1061 return bc_error("variable is wrong type");
1062}
1063static int bc_error_nested_read_call(void)
1064{
1065 return bc_error("read() call inside of a read() call");
1066}
1067
Gavin Howard01055ba2018-11-03 11:00:21 -06001068static void bc_vec_grow(BcVec *v, size_t n)
1069{
1070 size_t cap = v->cap * 2;
1071 while (cap < v->len + n) cap *= 2;
1072 v->v = xrealloc(v->v, v->size * cap);
1073 v->cap = cap;
1074}
1075
1076static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1077{
1078 v->size = esize;
1079 v->cap = BC_VEC_START_CAP;
1080 v->len = 0;
1081 v->dtor = dtor;
1082 v->v = xmalloc(esize * BC_VEC_START_CAP);
1083}
1084
Denys Vlasenko7d628012018-12-04 21:46:47 +01001085static void bc_char_vec_init(BcVec *v)
1086{
1087 bc_vec_init(v, sizeof(char), NULL);
1088}
1089
Gavin Howard01055ba2018-11-03 11:00:21 -06001090static void bc_vec_expand(BcVec *v, size_t req)
1091{
1092 if (v->cap < req) {
1093 v->v = xrealloc(v->v, v->size * req);
1094 v->cap = req;
1095 }
1096}
1097
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001098static void bc_vec_pop(BcVec *v)
1099{
1100 v->len--;
1101 if (v->dtor)
1102 v->dtor(v->v + (v->size * v->len));
1103}
Denys Vlasenko2fa11b62018-12-06 12:34:39 +01001104
Gavin Howard01055ba2018-11-03 11:00:21 -06001105static void bc_vec_npop(BcVec *v, size_t n)
1106{
1107 if (!v->dtor)
1108 v->len -= n;
1109 else {
1110 size_t len = v->len - n;
1111 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1112 }
1113}
1114
Denys Vlasenko7d628012018-12-04 21:46:47 +01001115static void bc_vec_pop_all(BcVec *v)
1116{
1117 bc_vec_npop(v, v->len);
1118}
1119
Gavin Howard01055ba2018-11-03 11:00:21 -06001120static void bc_vec_push(BcVec *v, const void *data)
1121{
1122 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1123 memmove(v->v + (v->size * v->len), data, v->size);
1124 v->len += 1;
1125}
1126
1127static void bc_vec_pushByte(BcVec *v, char data)
1128{
1129 bc_vec_push(v, &data);
1130}
1131
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001132static void bc_vec_pushZeroByte(BcVec *v)
1133{
1134 //bc_vec_pushByte(v, '\0');
1135 // better:
1136 bc_vec_push(v, &const_int_0);
1137}
1138
Gavin Howard01055ba2018-11-03 11:00:21 -06001139static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1140{
1141 if (idx == v->len)
1142 bc_vec_push(v, data);
1143 else {
1144
1145 char *ptr;
1146
1147 if (v->len == v->cap) bc_vec_grow(v, 1);
1148
1149 ptr = v->v + v->size * idx;
1150
1151 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1152 memmove(ptr, data, v->size);
1153 }
1154}
1155
1156static void bc_vec_string(BcVec *v, size_t len, const char *str)
1157{
Denys Vlasenko7d628012018-12-04 21:46:47 +01001158 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001159 bc_vec_expand(v, len + 1);
1160 memcpy(v->v, str, len);
1161 v->len = len;
1162
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001163 bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001164}
1165
1166static void bc_vec_concat(BcVec *v, const char *str)
1167{
1168 size_t len;
1169
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001170 if (v->len == 0) bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001171
1172 len = v->len + strlen(str);
1173
1174 if (v->cap < len) bc_vec_grow(v, len - v->len);
Denys Vlasenko1ff88622018-12-06 12:06:16 +01001175 strcpy(v->v + v->len - 1, str);
Gavin Howard01055ba2018-11-03 11:00:21 -06001176
1177 v->len = len;
1178}
1179
1180static void *bc_vec_item(const BcVec *v, size_t idx)
1181{
1182 return v->v + v->size * idx;
1183}
1184
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01001185static char** bc_program_str(size_t idx)
1186{
1187 return bc_vec_item(&G.prog.strs, idx);
1188}
1189
1190static BcFunc* bc_program_func(size_t idx)
1191{
1192 return bc_vec_item(&G.prog.fns, idx);
1193}
1194
Gavin Howard01055ba2018-11-03 11:00:21 -06001195static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1196{
1197 return v->v + v->size * (v->len - idx - 1);
1198}
1199
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001200static void *bc_vec_top(const BcVec *v)
1201{
1202 return v->v + v->size * (v->len - 1);
1203}
1204
Gavin Howard01055ba2018-11-03 11:00:21 -06001205static void bc_vec_free(void *vec)
1206{
1207 BcVec *v = (BcVec *) vec;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001208 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001209 free(v->v);
1210}
1211
Denys Vlasenkocca79a02018-12-05 21:15:46 +01001212static int bc_id_cmp(const void *e1, const void *e2)
1213{
1214 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1215}
1216
1217static void bc_id_free(void *id)
1218{
1219 free(((BcId *) id)->name);
1220}
1221
Gavin Howard01055ba2018-11-03 11:00:21 -06001222static size_t bc_map_find(const BcVec *v, const void *ptr)
1223{
1224 size_t low = 0, high = v->len;
1225
1226 while (low < high) {
1227
1228 size_t mid = (low + high) / 2;
1229 BcId *id = bc_vec_item(v, mid);
1230 int result = bc_id_cmp(ptr, id);
1231
1232 if (result == 0)
1233 return mid;
1234 else if (result < 0)
1235 high = mid;
1236 else
1237 low = mid + 1;
1238 }
1239
1240 return low;
1241}
1242
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001243static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
Gavin Howard01055ba2018-11-03 11:00:21 -06001244{
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001245 size_t n = *i = bc_map_find(v, ptr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001246
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001247 if (n == v->len)
Gavin Howard01055ba2018-11-03 11:00:21 -06001248 bc_vec_push(v, ptr);
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001249 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1250 return 0; // "was not inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001251 else
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001252 bc_vec_pushAt(v, ptr, n);
1253 return 1; // "was inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001254}
1255
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001256#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06001257static size_t bc_map_index(const BcVec *v, const void *ptr)
1258{
1259 size_t i = bc_map_find(v, ptr);
1260 if (i >= v->len) return BC_VEC_INVALID_IDX;
1261 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1262}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001263#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06001264
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001265static int push_input_byte(BcVec *vec, char c)
1266{
1267 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1268 || c > 0x7e
1269 ) {
1270 // Bad chars on this line, ignore entire line
1271 bc_error_fmt("illegal character 0x%02x", c);
1272 return 1;
1273 }
1274 bc_vec_pushByte(vec, (char)c);
1275 return 0;
1276}
1277
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01001278static BcStatus bc_read_line(BcVec *vec)
Gavin Howard01055ba2018-11-03 11:00:21 -06001279{
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001280 BcStatus s;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001281 bool bad_chars;
Gavin Howard01055ba2018-11-03 11:00:21 -06001282
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001283 s = BC_STATUS_SUCCESS;
Denys Vlasenko00d77792018-11-30 23:13:42 +01001284 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001285 int c;
Gavin Howard01055ba2018-11-03 11:00:21 -06001286
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001287 bad_chars = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001288 bc_vec_pop_all(vec);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001289
1290 fflush_and_check();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001291
Gavin Howard01055ba2018-11-03 11:00:21 -06001292#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001293 if (G_interrupt) { // ^C was pressed
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001294 intr:
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001295 G_interrupt = 0;
Denys Vlasenkoac6ed112018-12-08 21:39:10 +01001296 // GNU bc says "interrupted execution."
1297 // GNU dc says "Interrupt!"
1298 fputs("\ninterrupted execution\n", stderr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001299 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001300# if ENABLE_FEATURE_EDITING
1301 if (G_ttyin) {
1302 int n, i;
1303# define line_buf bb_common_bufsiz1
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01001304 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001305 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1306 if (n == 0) // ^C
1307 goto intr;
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001308 s = BC_STATUS_EOF;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001309 break;
1310 }
1311 i = 0;
1312 for (;;) {
1313 c = line_buf[i++];
1314 if (!c) break;
1315 bad_chars |= push_input_byte(vec, c);
1316 }
1317# undef line_buf
1318 } else
1319# endif
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001320#endif
Denys Vlasenkoed849352018-12-06 10:26:13 +01001321 {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001322 IF_FEATURE_BC_SIGNALS(errno = 0;)
1323 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001324 c = fgetc(stdin);
1325#if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1326 // Both conditions appear simultaneously, check both just in case
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001327 if (errno == EINTR || G_interrupt) {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001328 // ^C was pressed
1329 clearerr(stdin);
1330 goto intr;
1331 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001332#endif
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001333 if (c == EOF) {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001334 if (ferror(stdin))
1335 quit(); // this emits error message
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001336 s = BC_STATUS_EOF;
Denys Vlasenkoed849352018-12-06 10:26:13 +01001337 // Note: EOF does not append '\n', therefore:
1338 // printf 'print 123\n' | bc - works
1339 // printf 'print 123' | bc - fails (syntax error)
1340 break;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001341 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001342 bad_chars |= push_input_byte(vec, c);
1343 } while (c != '\n');
Denys Vlasenkoed849352018-12-06 10:26:13 +01001344 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001345 } while (bad_chars);
Gavin Howard01055ba2018-11-03 11:00:21 -06001346
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001347 bc_vec_pushZeroByte(vec);
Gavin Howard01055ba2018-11-03 11:00:21 -06001348
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001349 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06001350}
1351
Denys Vlasenkodf515392018-12-02 19:27:48 +01001352static char* bc_read_file(const char *path)
Gavin Howard01055ba2018-11-03 11:00:21 -06001353{
Denys Vlasenkodf515392018-12-02 19:27:48 +01001354 char *buf;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001355 size_t size = ((size_t) -1);
1356 size_t i;
Gavin Howard01055ba2018-11-03 11:00:21 -06001357
Denys Vlasenko4c9455f2018-12-06 15:21:39 +01001358 // Never returns NULL (dies on errors)
1359 buf = xmalloc_xopen_read_close(path, &size);
Gavin Howard01055ba2018-11-03 11:00:21 -06001360
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001361 for (i = 0; i < size; ++i) {
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001362 char c = buf[i];
1363 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1364 || c > 0x7e
1365 ) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01001366 free(buf);
1367 buf = NULL;
1368 break;
1369 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001370 }
1371
Denys Vlasenkodf515392018-12-02 19:27:48 +01001372 return buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06001373}
1374
Gavin Howard01055ba2018-11-03 11:00:21 -06001375static void bc_num_setToZero(BcNum *n, size_t scale)
1376{
1377 n->len = 0;
1378 n->neg = false;
1379 n->rdx = scale;
1380}
1381
1382static void bc_num_zero(BcNum *n)
1383{
1384 bc_num_setToZero(n, 0);
1385}
1386
1387static void bc_num_one(BcNum *n)
1388{
1389 bc_num_setToZero(n, 0);
1390 n->len = 1;
1391 n->num[0] = 1;
1392}
1393
1394static void bc_num_ten(BcNum *n)
1395{
1396 bc_num_setToZero(n, 0);
1397 n->len = 2;
1398 n->num[0] = 0;
1399 n->num[1] = 1;
1400}
1401
Denys Vlasenko3129f702018-12-09 12:04:44 +01001402// Note: this also sets BcNum to zero
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001403static void bc_num_init(BcNum *n, size_t req)
1404{
1405 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
Denys Vlasenko3129f702018-12-09 12:04:44 +01001406 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001407 n->num = xmalloc(req);
1408 n->cap = req;
Denys Vlasenko3129f702018-12-09 12:04:44 +01001409 n->rdx = 0;
1410 n->len = 0;
1411 n->neg = false;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001412}
1413
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01001414static void bc_num_init_DEF_SIZE(BcNum *n)
1415{
1416 bc_num_init(n, BC_NUM_DEF_SIZE);
1417}
1418
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001419static void bc_num_expand(BcNum *n, size_t req)
1420{
1421 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1422 if (req > n->cap) {
1423 n->num = xrealloc(n->num, req);
1424 n->cap = req;
1425 }
1426}
1427
1428static void bc_num_free(void *num)
1429{
1430 free(((BcNum *) num)->num);
1431}
1432
1433static void bc_num_copy(BcNum *d, BcNum *s)
1434{
1435 if (d != s) {
1436 bc_num_expand(d, s->cap);
1437 d->len = s->len;
1438 d->neg = s->neg;
1439 d->rdx = s->rdx;
1440 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1441 }
1442}
1443
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001444static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001445{
1446 size_t i;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001447 unsigned long pow, result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001448
1449 if (n->neg) return bc_error("negative number");
1450
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001451 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001452
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001453 unsigned long prev = result, powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001454
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001455 result += ((unsigned long) n->num[i]) * pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001456 pow *= 10;
1457
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001458 if (result < prev || pow < powprev)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001459 return bc_error("overflow");
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001460 prev = result;
1461 powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001462 }
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001463 *result_p = result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001464
1465 return BC_STATUS_SUCCESS;
1466}
1467
1468static void bc_num_ulong2num(BcNum *n, unsigned long val)
1469{
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001470 BcDig *ptr;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001471
1472 bc_num_zero(n);
1473
1474 if (val == 0) return;
1475
Denys Vlasenkob696d9e2018-12-10 12:22:15 +01001476 if (ULONG_MAX == 0xffffffffUL)
1477 bc_num_expand(n, 10); // 10 digits: 4294967295
1478 if (ULONG_MAX == 0xffffffffffffffffUL)
1479 bc_num_expand(n, 20); // 20 digits: 18446744073709551615
1480 BUILD_BUG_ON(ULONG_MAX > 0xffffffffffffffffUL);
1481
1482 ptr = n->num;
1483 for (;;) {
1484 n->len++;
1485 *ptr++ = val % 10;
1486 val /= 10;
1487 if (val == 0) break;
1488 }
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001489}
1490
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001491static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001492 size_t len)
1493{
1494 size_t i, j;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001495 for (i = 0; i < len; ++i) {
1496 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001497 a[i + j++] += 10;
1498 a[i + j] -= 1;
1499 }
1500 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001501}
1502
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01001503#define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1504#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1505#define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1506//#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1507static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1508{
1509 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1510}
1511//#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1512static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1513{
1514 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1515}
1516
Gavin Howard01055ba2018-11-03 11:00:21 -06001517static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1518{
1519 size_t i;
1520 int c = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001521 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
Gavin Howard01055ba2018-11-03 11:00:21 -06001522 return BC_NUM_NEG(i + 1, c < 0);
1523}
1524
1525static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1526{
1527 size_t i, min, a_int, b_int, diff;
1528 BcDig *max_num, *min_num;
1529 bool a_max, neg = false;
1530 ssize_t cmp;
1531
1532 if (a == b) return 0;
1533 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1534 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1535 if (a->neg) {
1536 if (b->neg)
1537 neg = true;
1538 else
1539 return -1;
1540 }
1541 else if (b->neg)
1542 return 1;
1543
1544 a_int = BC_NUM_INT(a);
1545 b_int = BC_NUM_INT(b);
1546 a_int -= b_int;
1547 a_max = (a->rdx > b->rdx);
1548
1549 if (a_int != 0) return (ssize_t) a_int;
1550
1551 if (a_max) {
1552 min = b->rdx;
1553 diff = a->rdx - b->rdx;
1554 max_num = a->num + diff;
1555 min_num = b->num;
1556 }
1557 else {
1558 min = a->rdx;
1559 diff = b->rdx - a->rdx;
1560 max_num = b->num + diff;
1561 min_num = a->num;
1562 }
1563
1564 cmp = bc_num_compare(max_num, min_num, b_int + min);
1565 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1566
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001567 for (max_num -= diff, i = diff - 1; i < diff; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001568 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1569 }
1570
1571 return 0;
1572}
1573
1574static void bc_num_truncate(BcNum *n, size_t places)
1575{
1576 if (places == 0) return;
1577
1578 n->rdx -= places;
1579
1580 if (n->len != 0) {
1581 n->len -= places;
1582 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1583 }
1584}
1585
1586static void bc_num_extend(BcNum *n, size_t places)
1587{
1588 size_t len = n->len + places;
1589
1590 if (places != 0) {
1591
1592 if (n->cap < len) bc_num_expand(n, len);
1593
1594 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1595 memset(n->num, 0, sizeof(BcDig) * places);
1596
1597 n->len += places;
1598 n->rdx += places;
1599 }
1600}
1601
1602static void bc_num_clean(BcNum *n)
1603{
1604 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1605 if (n->len == 0)
1606 n->neg = false;
1607 else if (n->len < n->rdx)
1608 n->len = n->rdx;
1609}
1610
1611static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1612{
1613 if (n->rdx < scale)
1614 bc_num_extend(n, scale - n->rdx);
1615 else
1616 bc_num_truncate(n, n->rdx - scale);
1617
1618 bc_num_clean(n);
1619 if (n->len != 0) n->neg = !neg1 != !neg2;
1620}
1621
1622static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1623 BcNum *restrict b)
1624{
1625 if (idx < n->len) {
1626
1627 b->len = n->len - idx;
1628 a->len = idx;
1629 a->rdx = b->rdx = 0;
1630
1631 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1632 memcpy(a->num, n->num, idx * sizeof(BcDig));
1633 }
1634 else {
1635 bc_num_zero(b);
1636 bc_num_copy(a, n);
1637 }
1638
1639 bc_num_clean(a);
1640 bc_num_clean(b);
1641}
1642
1643static BcStatus bc_num_shift(BcNum *n, size_t places)
1644{
1645 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
Denys Vlasenko64074a12018-12-07 15:50:14 +01001646
1647 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1648 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1649 if (places + n->len > BC_MAX_NUM)
1650 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1651 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001652
1653 if (n->rdx >= places)
1654 n->rdx -= places;
1655 else {
1656 bc_num_extend(n, places - n->rdx);
1657 n->rdx = 0;
1658 }
1659
1660 bc_num_clean(n);
1661
1662 return BC_STATUS_SUCCESS;
1663}
1664
1665static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1666{
1667 BcNum one;
1668 BcDig num[2];
1669
1670 one.cap = 2;
1671 one.num = num;
1672 bc_num_one(&one);
1673
1674 return bc_num_div(&one, a, b, scale);
1675}
1676
1677static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1678{
1679 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1680 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1681 int carry, in;
1682
1683 // Because this function doesn't need to use scale (per the bc spec),
1684 // I am hijacking it to say whether it's doing an add or a subtract.
1685
1686 if (a->len == 0) {
1687 bc_num_copy(c, b);
1688 if (sub && c->len) c->neg = !c->neg;
1689 return BC_STATUS_SUCCESS;
1690 }
1691 else if (b->len == 0) {
1692 bc_num_copy(c, a);
1693 return BC_STATUS_SUCCESS;
1694 }
1695
1696 c->neg = a->neg;
1697 c->rdx = BC_MAX(a->rdx, b->rdx);
1698 min_rdx = BC_MIN(a->rdx, b->rdx);
1699 c->len = 0;
1700
1701 if (a->rdx > b->rdx) {
1702 diff = a->rdx - b->rdx;
1703 ptr = a->num;
1704 ptr_a = a->num + diff;
1705 ptr_b = b->num;
1706 }
1707 else {
1708 diff = b->rdx - a->rdx;
1709 ptr = b->num;
1710 ptr_a = a->num;
1711 ptr_b = b->num + diff;
1712 }
1713
1714 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1715
1716 ptr_c += diff;
1717 a_int = BC_NUM_INT(a);
1718 b_int = BC_NUM_INT(b);
1719
1720 if (a_int > b_int) {
1721 min_int = b_int;
1722 max = a_int;
1723 ptr = ptr_a;
1724 }
1725 else {
1726 min_int = a_int;
1727 max = b_int;
1728 ptr = ptr_b;
1729 }
1730
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001731 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001732 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1733 carry = in / 10;
1734 ptr_c[i] = (BcDig)(in % 10);
1735 }
1736
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001737 for (; i < max + min_rdx; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001738 in = ((int) ptr[i]) + carry;
1739 carry = in / 10;
1740 ptr_c[i] = (BcDig)(in % 10);
1741 }
1742
1743 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1744
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001745 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001746}
1747
1748static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1749{
Gavin Howard01055ba2018-11-03 11:00:21 -06001750 ssize_t cmp;
1751 BcNum *minuend, *subtrahend;
1752 size_t start;
1753 bool aneg, bneg, neg;
1754
1755 // Because this function doesn't need to use scale (per the bc spec),
1756 // I am hijacking it to say whether it's doing an add or a subtract.
1757
1758 if (a->len == 0) {
1759 bc_num_copy(c, b);
1760 if (sub && c->len) c->neg = !c->neg;
1761 return BC_STATUS_SUCCESS;
1762 }
1763 else if (b->len == 0) {
1764 bc_num_copy(c, a);
1765 return BC_STATUS_SUCCESS;
1766 }
1767
1768 aneg = a->neg;
1769 bneg = b->neg;
1770 a->neg = b->neg = false;
1771
1772 cmp = bc_num_cmp(a, b);
1773
1774 a->neg = aneg;
1775 b->neg = bneg;
1776
1777 if (cmp == 0) {
1778 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1779 return BC_STATUS_SUCCESS;
1780 }
1781 else if (cmp > 0) {
1782 neg = a->neg;
1783 minuend = a;
1784 subtrahend = b;
1785 }
1786 else {
1787 neg = b->neg;
1788 if (sub) neg = !neg;
1789 minuend = b;
1790 subtrahend = a;
1791 }
1792
1793 bc_num_copy(c, minuend);
1794 c->neg = neg;
1795
1796 if (c->rdx < subtrahend->rdx) {
1797 bc_num_extend(c, subtrahend->rdx - c->rdx);
1798 start = 0;
1799 }
1800 else
1801 start = c->rdx - subtrahend->rdx;
1802
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001803 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001804
1805 bc_num_clean(c);
1806
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001807 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001808}
1809
1810static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1811 BcNum *restrict c)
1812{
1813 BcStatus s;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001814 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
Gavin Howard01055ba2018-11-03 11:00:21 -06001815 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001816 bool aone;
Gavin Howard01055ba2018-11-03 11:00:21 -06001817
Gavin Howard01055ba2018-11-03 11:00:21 -06001818 if (a->len == 0 || b->len == 0) {
1819 bc_num_zero(c);
1820 return BC_STATUS_SUCCESS;
1821 }
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001822 aone = BC_NUM_ONE(a);
1823 if (aone || BC_NUM_ONE(b)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001824 bc_num_copy(c, aone ? b : a);
1825 return BC_STATUS_SUCCESS;
1826 }
1827
1828 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1829 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1830 {
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001831 size_t i, j, len;
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001832 unsigned carry;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001833
Gavin Howard01055ba2018-11-03 11:00:21 -06001834 bc_num_expand(c, a->len + b->len + 1);
1835
1836 memset(c->num, 0, sizeof(BcDig) * c->cap);
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001837 c->len = len = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06001838
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001839 for (i = 0; i < b->len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001840
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001841 carry = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001842 for (j = 0; j < a->len; ++j) {
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001843 unsigned in = c->num[i + j];
1844 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1845 // note: compilers prefer _unsigned_ div/const
Gavin Howard01055ba2018-11-03 11:00:21 -06001846 carry = in / 10;
1847 c->num[i + j] = (BcDig)(in % 10);
1848 }
1849
1850 c->num[i + j] += (BcDig) carry;
1851 len = BC_MAX(len, i + j + !!carry);
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01001852
1853 // a=2^1000000
1854 // a*a <- without check below, this will not be interruptible
1855 if (G_interrupt) return BC_STATUS_FAILURE;
Gavin Howard01055ba2018-11-03 11:00:21 -06001856 }
1857
1858 c->len = len;
1859
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001860 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06001861 }
1862
1863 bc_num_init(&l1, max);
1864 bc_num_init(&h1, max);
1865 bc_num_init(&l2, max);
1866 bc_num_init(&h2, max);
1867 bc_num_init(&m1, max);
1868 bc_num_init(&m2, max);
1869 bc_num_init(&z0, max);
1870 bc_num_init(&z1, max);
1871 bc_num_init(&z2, max);
1872 bc_num_init(&temp, max + max);
1873
1874 bc_num_split(a, max2, &l1, &h1);
1875 bc_num_split(b, max2, &l2, &h2);
1876
1877 s = bc_num_add(&h1, &l1, &m1, 0);
1878 if (s) goto err;
1879 s = bc_num_add(&h2, &l2, &m2, 0);
1880 if (s) goto err;
1881
1882 s = bc_num_k(&h1, &h2, &z0);
1883 if (s) goto err;
1884 s = bc_num_k(&m1, &m2, &z1);
1885 if (s) goto err;
1886 s = bc_num_k(&l1, &l2, &z2);
1887 if (s) goto err;
1888
1889 s = bc_num_sub(&z1, &z0, &temp, 0);
1890 if (s) goto err;
1891 s = bc_num_sub(&temp, &z2, &z1, 0);
1892 if (s) goto err;
1893
1894 s = bc_num_shift(&z0, max2 * 2);
1895 if (s) goto err;
1896 s = bc_num_shift(&z1, max2);
1897 if (s) goto err;
1898 s = bc_num_add(&z0, &z1, &temp, 0);
1899 if (s) goto err;
1900 s = bc_num_add(&temp, &z2, c, 0);
1901
1902err:
1903 bc_num_free(&temp);
1904 bc_num_free(&z2);
1905 bc_num_free(&z1);
1906 bc_num_free(&z0);
1907 bc_num_free(&m2);
1908 bc_num_free(&m1);
1909 bc_num_free(&h2);
1910 bc_num_free(&l2);
1911 bc_num_free(&h1);
1912 bc_num_free(&l1);
1913 return s;
1914}
1915
1916static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1917{
1918 BcStatus s;
1919 BcNum cpa, cpb;
1920 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1921
1922 scale = BC_MAX(scale, a->rdx);
1923 scale = BC_MAX(scale, b->rdx);
1924 scale = BC_MIN(a->rdx + b->rdx, scale);
1925 maxrdx = BC_MAX(maxrdx, scale);
1926
1927 bc_num_init(&cpa, a->len);
1928 bc_num_init(&cpb, b->len);
1929
1930 bc_num_copy(&cpa, a);
1931 bc_num_copy(&cpb, b);
1932 cpa.neg = cpb.neg = false;
1933
1934 s = bc_num_shift(&cpa, maxrdx);
1935 if (s) goto err;
1936 s = bc_num_shift(&cpb, maxrdx);
1937 if (s) goto err;
1938 s = bc_num_k(&cpa, &cpb, c);
1939 if (s) goto err;
1940
1941 maxrdx += scale;
1942 bc_num_expand(c, c->len + maxrdx);
1943
1944 if (c->len < maxrdx) {
1945 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1946 c->len += maxrdx;
1947 }
1948
1949 c->rdx = maxrdx;
1950 bc_num_retireMul(c, scale, a->neg, b->neg);
1951
1952err:
1953 bc_num_free(&cpb);
1954 bc_num_free(&cpa);
1955 return s;
1956}
1957
1958static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1959{
1960 BcStatus s = BC_STATUS_SUCCESS;
1961 BcDig *n, *p, q;
1962 size_t len, end, i;
1963 BcNum cp;
1964 bool zero = true;
1965
1966 if (b->len == 0)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001967 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001968 else if (a->len == 0) {
1969 bc_num_setToZero(c, scale);
1970 return BC_STATUS_SUCCESS;
1971 }
1972 else if (BC_NUM_ONE(b)) {
1973 bc_num_copy(c, a);
1974 bc_num_retireMul(c, scale, a->neg, b->neg);
1975 return BC_STATUS_SUCCESS;
1976 }
1977
1978 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1979 bc_num_copy(&cp, a);
1980 len = b->len;
1981
1982 if (len > cp.len) {
1983 bc_num_expand(&cp, len + 2);
1984 bc_num_extend(&cp, len - cp.len);
1985 }
1986
1987 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1988 cp.rdx -= b->rdx;
1989 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1990
1991 if (b->rdx == b->len) {
1992 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1993 len -= i - 1;
1994 }
1995
1996 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1997
1998 // We want an extra zero in front to make things simpler.
1999 cp.num[cp.len++] = 0;
2000 end = cp.len - len;
2001
2002 bc_num_expand(c, cp.len);
2003
2004 bc_num_zero(c);
2005 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2006 c->rdx = cp.rdx;
2007 c->len = cp.len;
2008 p = b->num;
2009
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002010 for (i = end - 1; !s && i < end; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002011 n = cp.num + i;
2012 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002013 bc_num_subArrays(n, p, len);
Gavin Howard01055ba2018-11-03 11:00:21 -06002014 c->num[i] = q;
Denys Vlasenkof381a882018-12-05 19:21:34 +01002015 // a=2^100000
2016 // scale=40000
2017 // 1/a <- without check below, this will not be interruptible
2018 if (G_interrupt) {
2019 s = BC_STATUS_FAILURE;
2020 break;
2021 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002022 }
2023
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002024 bc_num_retireMul(c, scale, a->neg, b->neg);
Gavin Howard01055ba2018-11-03 11:00:21 -06002025 bc_num_free(&cp);
2026
Denys Vlasenkof381a882018-12-05 19:21:34 +01002027 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06002028}
2029
2030static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2031 BcNum *restrict d, size_t scale, size_t ts)
2032{
2033 BcStatus s;
2034 BcNum temp;
2035 bool neg;
2036
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002037 if (b->len == 0)
2038 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06002039
2040 if (a->len == 0) {
2041 bc_num_setToZero(d, ts);
2042 return BC_STATUS_SUCCESS;
2043 }
2044
2045 bc_num_init(&temp, d->cap);
Denys Vlasenkof381a882018-12-05 19:21:34 +01002046 s = bc_num_d(a, b, c, scale);
2047 if (s) goto err;
Gavin Howard01055ba2018-11-03 11:00:21 -06002048
2049 if (scale != 0) scale = ts;
2050
2051 s = bc_num_m(c, b, &temp, scale);
2052 if (s) goto err;
2053 s = bc_num_sub(a, &temp, d, scale);
2054 if (s) goto err;
2055
2056 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2057
2058 neg = d->neg;
2059 bc_num_retireMul(d, ts, a->neg, b->neg);
2060 d->neg = neg;
2061
2062err:
2063 bc_num_free(&temp);
2064 return s;
2065}
2066
2067static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2068{
2069 BcStatus s;
2070 BcNum c1;
2071 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2072
2073 bc_num_init(&c1, len);
2074 s = bc_num_r(a, b, &c1, c, scale, ts);
2075 bc_num_free(&c1);
2076
2077 return s;
2078}
2079
2080static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2081{
2082 BcStatus s = BC_STATUS_SUCCESS;
2083 BcNum copy;
2084 unsigned long pow;
2085 size_t i, powrdx, resrdx;
2086 bool neg, zero;
2087
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002088 if (b->rdx) return bc_error("non integer number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002089
2090 if (b->len == 0) {
2091 bc_num_one(c);
2092 return BC_STATUS_SUCCESS;
2093 }
2094 else if (a->len == 0) {
2095 bc_num_setToZero(c, scale);
2096 return BC_STATUS_SUCCESS;
2097 }
2098 else if (BC_NUM_ONE(b)) {
2099 if (!b->neg)
2100 bc_num_copy(c, a);
2101 else
2102 s = bc_num_inv(a, c, scale);
2103 return s;
2104 }
2105
2106 neg = b->neg;
2107 b->neg = false;
2108
2109 s = bc_num_ulong(b, &pow);
2110 if (s) return s;
2111
2112 bc_num_init(&copy, a->len);
2113 bc_num_copy(&copy, a);
2114
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01002115 if (!neg) {
2116 if (a->rdx > scale)
2117 scale = a->rdx;
2118 if (a->rdx * pow < scale)
2119 scale = a->rdx * pow;
2120 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002121
2122 b->neg = neg;
2123
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002124 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002125 powrdx <<= 1;
2126 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2127 if (s) goto err;
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002128 // Not needed: bc_num_mul() has a check for ^C:
2129 //if (G_interrupt) {
2130 // s = BC_STATUS_FAILURE;
2131 // goto err;
2132 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002133 }
2134
Gavin Howard01055ba2018-11-03 11:00:21 -06002135 bc_num_copy(c, &copy);
2136
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002137 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002138
2139 powrdx <<= 1;
2140 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2141 if (s) goto err;
2142
2143 if (pow & 1) {
2144 resrdx += powrdx;
2145 s = bc_num_mul(c, &copy, c, resrdx);
2146 if (s) goto err;
2147 }
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002148 // Not needed: bc_num_mul() has a check for ^C:
2149 //if (G_interrupt) {
2150 // s = BC_STATUS_FAILURE;
2151 // goto err;
2152 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002153 }
2154
2155 if (neg) {
2156 s = bc_num_inv(c, c, scale);
2157 if (s) goto err;
2158 }
2159
Gavin Howard01055ba2018-11-03 11:00:21 -06002160 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2161
2162 // We can't use bc_num_clean() here.
2163 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2164 if (zero) bc_num_setToZero(c, scale);
2165
2166err:
2167 bc_num_free(&copy);
2168 return s;
2169}
2170
2171static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2172 BcNumBinaryOp op, size_t req)
2173{
2174 BcStatus s;
2175 BcNum num2, *ptr_a, *ptr_b;
2176 bool init = false;
2177
2178 if (c == a) {
2179 ptr_a = &num2;
2180 memcpy(ptr_a, c, sizeof(BcNum));
2181 init = true;
2182 }
2183 else
2184 ptr_a = a;
2185
2186 if (c == b) {
2187 ptr_b = &num2;
2188 if (c != a) {
2189 memcpy(ptr_b, c, sizeof(BcNum));
2190 init = true;
2191 }
2192 }
2193 else
2194 ptr_b = b;
2195
2196 if (init)
2197 bc_num_init(c, req);
2198 else
2199 bc_num_expand(c, req);
2200
2201 s = op(ptr_a, ptr_b, c, scale);
2202
2203 if (init) bc_num_free(&num2);
2204
2205 return s;
2206}
2207
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002208static void bc_num_printNewline(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06002209{
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002210 if (G.prog.nchars == G.prog.len - 1) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002211 bb_putchar('\\');
2212 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002213 G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06002214 }
2215}
2216
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002217#if ENABLE_DC
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002218static void bc_num_printChar(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002219{
Denys Vlasenko2a8ad482018-12-08 21:56:37 +01002220 (void) radix;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002221 bb_putchar((char) num);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002222 G.prog.nchars += width;
Gavin Howard01055ba2018-11-03 11:00:21 -06002223}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002224#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002225
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002226static void bc_num_printDigits(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002227{
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002228 size_t exp, pow;
Gavin Howard01055ba2018-11-03 11:00:21 -06002229
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002230 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002231 bb_putchar(radix ? '.' : ' ');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002232 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06002233
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002234 bc_num_printNewline();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002235 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2236 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002237
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002238 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002239 size_t dig;
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002240 bc_num_printNewline();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002241 dig = num / pow;
2242 num -= dig * pow;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002243 bb_putchar(((char) dig) + '0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002244 }
2245}
2246
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002247static void bc_num_printHex(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002248{
2249 if (radix) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002250 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002251 bb_putchar('.');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002252 G.prog.nchars += 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06002253 }
2254
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002255 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002256 bb_putchar(bb_hexdigits_upcase[num]);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002257 G.prog.nchars += width;
Gavin Howard01055ba2018-11-03 11:00:21 -06002258}
2259
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002260static void bc_num_printDecimal(BcNum *n)
Gavin Howard01055ba2018-11-03 11:00:21 -06002261{
2262 size_t i, rdx = n->rdx - 1;
2263
Denys Vlasenko00d77792018-11-30 23:13:42 +01002264 if (n->neg) bb_putchar('-');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002265 G.prog.nchars += n->neg;
Gavin Howard01055ba2018-11-03 11:00:21 -06002266
2267 for (i = n->len - 1; i < n->len; --i)
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002268 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
Gavin Howard01055ba2018-11-03 11:00:21 -06002269}
2270
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002271static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width, BcNumDigitOp print)
Gavin Howard01055ba2018-11-03 11:00:21 -06002272{
2273 BcStatus s;
2274 BcVec stack;
2275 BcNum intp, fracp, digit, frac_len;
2276 unsigned long dig, *ptr;
2277 size_t i;
2278 bool radix;
2279
2280 if (n->len == 0) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002281 print(0, width, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06002282 return BC_STATUS_SUCCESS;
2283 }
2284
2285 bc_vec_init(&stack, sizeof(long), NULL);
2286 bc_num_init(&intp, n->len);
2287 bc_num_init(&fracp, n->rdx);
2288 bc_num_init(&digit, width);
2289 bc_num_init(&frac_len, BC_NUM_INT(n));
2290 bc_num_copy(&intp, n);
2291 bc_num_one(&frac_len);
2292
2293 bc_num_truncate(&intp, intp.rdx);
2294 s = bc_num_sub(n, &intp, &fracp, 0);
2295 if (s) goto err;
2296
2297 while (intp.len != 0) {
2298 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2299 if (s) goto err;
2300 s = bc_num_ulong(&digit, &dig);
2301 if (s) goto err;
2302 bc_vec_push(&stack, &dig);
2303 }
2304
2305 for (i = 0; i < stack.len; ++i) {
2306 ptr = bc_vec_item_rev(&stack, i);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002307 print(*ptr, width, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06002308 }
2309
2310 if (!n->rdx) goto err;
2311
2312 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2313 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2314 if (s) goto err;
2315 s = bc_num_ulong(&fracp, &dig);
2316 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002317 bc_num_ulong2num(&intp, dig);
Gavin Howard01055ba2018-11-03 11:00:21 -06002318 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2319 if (s) goto err;
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002320 print(dig, width, radix);
Gavin Howard01055ba2018-11-03 11:00:21 -06002321 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2322 if (s) goto err;
2323 }
2324
2325err:
2326 bc_num_free(&frac_len);
2327 bc_num_free(&digit);
2328 bc_num_free(&fracp);
2329 bc_num_free(&intp);
2330 bc_vec_free(&stack);
2331 return s;
2332}
2333
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002334static BcStatus bc_num_printBase(BcNum *n)
Gavin Howard01055ba2018-11-03 11:00:21 -06002335{
2336 BcStatus s;
2337 size_t width, i;
2338 BcNumDigitOp print;
2339 bool neg = n->neg;
2340
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002341 if (neg) {
2342 bb_putchar('-');
2343 G.prog.nchars++;
2344 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002345
2346 n->neg = false;
2347
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002348 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002349 width = 1;
2350 print = bc_num_printHex;
2351 }
2352 else {
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002353 for (i = G.prog.ob_t - 1, width = 0; i != 0; i /= 10, ++width)
2354 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002355 print = bc_num_printDigits;
2356 }
2357
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002358 s = bc_num_printNum(n, &G.prog.ob, width, print);
Gavin Howard01055ba2018-11-03 11:00:21 -06002359 n->neg = neg;
2360
2361 return s;
2362}
2363
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002364#if ENABLE_DC
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002365static BcStatus bc_num_stream(BcNum *n, BcNum *base)
Gavin Howard01055ba2018-11-03 11:00:21 -06002366{
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002367 return bc_num_printNum(n, base, 1, bc_num_printChar);
Gavin Howard01055ba2018-11-03 11:00:21 -06002368}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002369#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002370
Denys Vlasenko9311e012018-12-10 11:54:18 +01002371static bool bc_num_strValid(const char *val, size_t base)
2372{
2373 BcDig b;
2374 bool radix;
2375
2376 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2377 radix = false;
2378 for (;;) {
2379 BcDig c = *val++;
2380 if (c == '\0')
2381 break;
2382 if (c == '.') {
2383 if (radix) return false;
2384 radix = true;
2385 continue;
2386 }
2387 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2388 return false;
2389 }
2390 return true;
2391}
2392
2393// Note: n is already "bc_num_zero()"ed,
2394// leading zeroes in "val" are removed
2395static void bc_num_parseDecimal(BcNum *n, const char *val)
2396{
2397 size_t len, i;
2398 const char *ptr;
2399 bool zero;
2400
2401 len = strlen(val);
2402 if (len == 0)
2403 return;
2404
2405 zero = true;
2406 for (i = 0; val[i]; ++i) {
2407 if (val[i] != '0' && val[i] != '.') {
2408 zero = false;
2409 break;
2410 }
2411 }
2412 bc_num_expand(n, len);
2413
2414 ptr = strchr(val, '.');
2415
2416 n->rdx = 0;
2417 if (ptr != NULL)
2418 n->rdx = (size_t)((val + len) - (ptr + 1));
2419
2420 if (!zero) {
2421 i = len - 1;
2422 for (;;) {
2423 n->num[n->len] = val[i] - '0';
2424 ++n->len;
2425 skip_dot:
2426 if ((ssize_t)--i == (ssize_t)-1) break;
2427 if (val[i] == '.') goto skip_dot;
2428 }
2429 }
2430}
2431
2432// Note: n is already "bc_num_zero()"ed,
2433// leading zeroes in "val" are removed
2434static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2435{
2436 BcStatus s;
2437 BcNum temp, mult, result;
2438 BcDig c = '\0';
2439 unsigned long v;
2440 size_t i, digits;
2441
2442 for (i = 0; ; ++i) {
2443 if (val[i] == '\0')
2444 return;
2445 if (val[i] != '.' && val[i] != '0')
2446 break;
2447 }
2448
2449 bc_num_init_DEF_SIZE(&temp);
2450 bc_num_init_DEF_SIZE(&mult);
2451
2452 for (;;) {
2453 c = *val++;
2454 if (c == '\0') goto int_err;
2455 if (c == '.') break;
2456
2457 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2458
2459 s = bc_num_mul(n, base, &mult, 0);
2460 if (s) goto int_err;
2461 bc_num_ulong2num(&temp, v);
2462 s = bc_num_add(&mult, &temp, n, 0);
2463 if (s) goto int_err;
2464 }
2465
2466 bc_num_init(&result, base->len);
2467 //bc_num_zero(&result); - already is
2468 bc_num_one(&mult);
2469
2470 digits = 0;
2471 for (;;) {
2472 c = *val++;
2473 if (c == '\0') break;
2474 digits++;
2475
2476 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2477
2478 s = bc_num_mul(&result, base, &result, 0);
2479 if (s) goto err;
2480 bc_num_ulong2num(&temp, v);
2481 s = bc_num_add(&result, &temp, &result, 0);
2482 if (s) goto err;
2483 s = bc_num_mul(&mult, base, &mult, 0);
2484 if (s) goto err;
2485 }
2486
2487 s = bc_num_div(&result, &mult, &result, digits);
2488 if (s) goto err;
2489 s = bc_num_add(n, &result, n, digits);
2490 if (s) goto err;
2491
2492 if (n->len != 0) {
2493 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2494 } else
2495 bc_num_zero(n);
2496
2497err:
2498 bc_num_free(&result);
2499int_err:
2500 bc_num_free(&mult);
2501 bc_num_free(&temp);
2502}
2503
Gavin Howard01055ba2018-11-03 11:00:21 -06002504static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2505 size_t base_t)
2506{
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002507 if (!bc_num_strValid(val, base_t))
2508 return bc_error("bad number string");
Gavin Howard01055ba2018-11-03 11:00:21 -06002509
Denys Vlasenko4a024c72018-12-09 13:21:54 +01002510 bc_num_zero(n);
2511 while (*val == '0') val++;
2512
Gavin Howard01055ba2018-11-03 11:00:21 -06002513 if (base_t == 10)
2514 bc_num_parseDecimal(n, val);
2515 else
2516 bc_num_parseBase(n, val, base);
2517
2518 return BC_STATUS_SUCCESS;
2519}
2520
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002521static BcStatus bc_num_print(BcNum *n, bool newline)
Gavin Howard01055ba2018-11-03 11:00:21 -06002522{
2523 BcStatus s = BC_STATUS_SUCCESS;
2524
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002525 bc_num_printNewline();
Gavin Howard01055ba2018-11-03 11:00:21 -06002526
2527 if (n->len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002528 bb_putchar('0');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002529 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06002530 }
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002531 else if (G.prog.ob_t == 10)
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002532 bc_num_printDecimal(n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002533 else
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002534 s = bc_num_printBase(n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002535
2536 if (newline) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002537 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002538 G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06002539 }
2540
2541 return s;
2542}
2543
Gavin Howard01055ba2018-11-03 11:00:21 -06002544static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2545{
2546 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2547 (void) scale;
2548 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2549}
2550
2551static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2552{
2553 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2554 (void) scale;
2555 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2556}
2557
2558static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2559{
2560 size_t req = BC_NUM_MREQ(a, b, scale);
2561 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2562}
2563
2564static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2565{
2566 size_t req = BC_NUM_MREQ(a, b, scale);
2567 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2568}
2569
2570static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2571{
2572 size_t req = BC_NUM_MREQ(a, b, scale);
2573 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2574}
2575
2576static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2577{
2578 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2579}
2580
2581static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2582{
2583 BcStatus s;
2584 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2585 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2586 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2587
2588 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2589 bc_num_expand(b, req);
2590
2591 if (a->len == 0) {
2592 bc_num_setToZero(b, scale);
2593 return BC_STATUS_SUCCESS;
2594 }
2595 else if (a->neg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002596 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002597 else if (BC_NUM_ONE(a)) {
2598 bc_num_one(b);
2599 bc_num_extend(b, scale);
2600 return BC_STATUS_SUCCESS;
2601 }
2602
2603 scale = BC_MAX(scale, a->rdx) + 1;
2604 len = a->len + scale;
2605
2606 bc_num_init(&num1, len);
2607 bc_num_init(&num2, len);
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01002608 bc_num_init_DEF_SIZE(&half);
Gavin Howard01055ba2018-11-03 11:00:21 -06002609
2610 bc_num_one(&half);
2611 half.num[0] = 5;
2612 half.rdx = 1;
2613
2614 bc_num_init(&f, len);
2615 bc_num_init(&fprime, len);
2616
2617 x0 = &num1;
2618 x1 = &num2;
2619
2620 bc_num_one(x0);
2621 pow = BC_NUM_INT(a);
2622
2623 if (pow) {
2624
2625 if (pow & 1)
2626 x0->num[0] = 2;
2627 else
2628 x0->num[0] = 6;
2629
2630 pow -= 2 - (pow & 1);
2631
2632 bc_num_extend(x0, pow);
2633
2634 // Make sure to move the radix back.
2635 x0->rdx -= pow;
2636 }
2637
2638 x0->rdx = digs = digs1 = 0;
2639 resrdx = scale + 2;
2640 len = BC_NUM_INT(x0) + resrdx - 1;
2641
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002642 while (cmp != 0 || digs < len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002643
2644 s = bc_num_div(a, x0, &f, resrdx);
2645 if (s) goto err;
2646 s = bc_num_add(x0, &f, &fprime, resrdx);
2647 if (s) goto err;
2648 s = bc_num_mul(&fprime, &half, x1, resrdx);
2649 if (s) goto err;
2650
2651 cmp = bc_num_cmp(x1, x0);
2652 digs = x1->len - (unsigned long long) llabs(cmp);
2653
2654 if (cmp == cmp2 && digs == digs1)
2655 times += 1;
2656 else
2657 times = 0;
2658
2659 resrdx += times > 4;
2660
2661 cmp2 = cmp1;
2662 cmp1 = cmp;
2663 digs1 = digs;
2664
2665 temp = x0;
2666 x0 = x1;
2667 x1 = temp;
2668 }
2669
Gavin Howard01055ba2018-11-03 11:00:21 -06002670 bc_num_copy(b, x0);
2671 scale -= 1;
2672 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2673
2674err:
2675 bc_num_free(&fprime);
2676 bc_num_free(&f);
2677 bc_num_free(&half);
2678 bc_num_free(&num2);
2679 bc_num_free(&num1);
2680 return s;
2681}
2682
2683static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2684 size_t scale)
2685{
2686 BcStatus s;
2687 BcNum num2, *ptr_a;
2688 bool init = false;
2689 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2690
2691 if (c == a) {
2692 memcpy(&num2, c, sizeof(BcNum));
2693 ptr_a = &num2;
2694 bc_num_init(c, len);
2695 init = true;
2696 }
2697 else {
2698 ptr_a = a;
2699 bc_num_expand(c, len);
2700 }
2701
2702 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2703
2704 if (init) bc_num_free(&num2);
2705
2706 return s;
2707}
2708
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002709#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002710static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2711{
2712 BcStatus s;
2713 BcNum base, exp, two, temp;
2714
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002715 if (c->len == 0)
2716 return bc_error("divide by zero");
2717 if (a->rdx || b->rdx || c->rdx)
2718 return bc_error("non integer number");
2719 if (b->neg)
2720 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002721
2722 bc_num_expand(d, c->len);
2723 bc_num_init(&base, c->len);
2724 bc_num_init(&exp, b->len);
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01002725 bc_num_init_DEF_SIZE(&two);
Gavin Howard01055ba2018-11-03 11:00:21 -06002726 bc_num_init(&temp, b->len);
2727
2728 bc_num_one(&two);
2729 two.num[0] = 2;
2730 bc_num_one(d);
2731
2732 s = bc_num_rem(a, c, &base, 0);
2733 if (s) goto err;
2734 bc_num_copy(&exp, b);
2735
2736 while (exp.len != 0) {
2737
2738 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2739 if (s) goto err;
2740
2741 if (BC_NUM_ONE(&temp)) {
2742 s = bc_num_mul(d, &base, &temp, 0);
2743 if (s) goto err;
2744 s = bc_num_rem(&temp, c, d, 0);
2745 if (s) goto err;
2746 }
2747
2748 s = bc_num_mul(&base, &base, &temp, 0);
2749 if (s) goto err;
2750 s = bc_num_rem(&temp, c, &base, 0);
2751 if (s) goto err;
2752 }
2753
2754err:
2755 bc_num_free(&temp);
2756 bc_num_free(&two);
2757 bc_num_free(&exp);
2758 bc_num_free(&base);
2759 return s;
2760}
2761#endif // ENABLE_DC
2762
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002763#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002764static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2765{
2766 BcId a;
2767 size_t i;
2768
2769 for (i = 0; i < f->autos.len; ++i) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002770 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2771 return bc_error("function parameter or auto var has the same name as another");
Gavin Howard01055ba2018-11-03 11:00:21 -06002772 }
2773
2774 a.idx = var;
2775 a.name = name;
2776
2777 bc_vec_push(&f->autos, &a);
2778
2779 return BC_STATUS_SUCCESS;
2780}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002781#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002782
2783static void bc_func_init(BcFunc *f)
2784{
Denys Vlasenko7d628012018-12-04 21:46:47 +01002785 bc_char_vec_init(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06002786 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2787 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2788 f->nparams = 0;
2789}
2790
2791static void bc_func_free(void *func)
2792{
2793 BcFunc *f = (BcFunc *) func;
2794 bc_vec_free(&f->code);
2795 bc_vec_free(&f->autos);
2796 bc_vec_free(&f->labels);
2797}
2798
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002799static void bc_array_expand(BcVec *a, size_t len);
2800
Gavin Howard01055ba2018-11-03 11:00:21 -06002801static void bc_array_init(BcVec *a, bool nums)
2802{
2803 if (nums)
2804 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2805 else
2806 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2807 bc_array_expand(a, 1);
2808}
2809
Gavin Howard01055ba2018-11-03 11:00:21 -06002810static void bc_array_expand(BcVec *a, size_t len)
2811{
2812 BcResultData data;
2813
2814 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2815 while (len > a->len) {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01002816 bc_num_init_DEF_SIZE(&data.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002817 bc_vec_push(a, &data.n);
2818 }
2819 }
2820 else {
2821 while (len > a->len) {
2822 bc_array_init(&data.v, true);
2823 bc_vec_push(a, &data.v);
2824 }
2825 }
2826}
2827
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002828static void bc_array_copy(BcVec *d, const BcVec *s)
2829{
2830 size_t i;
2831
2832 bc_vec_pop_all(d);
2833 bc_vec_expand(d, s->cap);
2834 d->len = s->len;
2835
2836 for (i = 0; i < s->len; ++i) {
2837 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2838 bc_num_init(dnum, snum->len);
2839 bc_num_copy(dnum, snum);
2840 }
2841}
2842
Gavin Howard01055ba2018-11-03 11:00:21 -06002843static void bc_string_free(void *string)
2844{
2845 free(*((char **) string));
2846}
2847
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002848#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002849static void bc_result_copy(BcResult *d, BcResult *src)
2850{
2851 d->t = src->t;
2852
2853 switch (d->t) {
2854
2855 case BC_RESULT_TEMP:
2856 case BC_RESULT_IBASE:
2857 case BC_RESULT_SCALE:
2858 case BC_RESULT_OBASE:
2859 {
2860 bc_num_init(&d->d.n, src->d.n.len);
2861 bc_num_copy(&d->d.n, &src->d.n);
2862 break;
2863 }
2864
2865 case BC_RESULT_VAR:
2866 case BC_RESULT_ARRAY:
2867 case BC_RESULT_ARRAY_ELEM:
2868 {
2869 d->d.id.name = xstrdup(src->d.id.name);
2870 break;
2871 }
2872
2873 case BC_RESULT_CONSTANT:
2874 case BC_RESULT_LAST:
2875 case BC_RESULT_ONE:
2876 case BC_RESULT_STR:
2877 {
2878 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2879 break;
2880 }
2881 }
2882}
2883#endif // ENABLE_DC
2884
2885static void bc_result_free(void *result)
2886{
2887 BcResult *r = (BcResult *) result;
2888
2889 switch (r->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_free(&r->d.n);
2897 break;
2898 }
2899
2900 case BC_RESULT_VAR:
2901 case BC_RESULT_ARRAY:
2902 case BC_RESULT_ARRAY_ELEM:
2903 {
2904 free(r->d.id.name);
2905 break;
2906 }
2907
2908 default:
2909 {
2910 // Do nothing.
2911 break;
2912 }
2913 }
2914}
2915
2916static void bc_lex_lineComment(BcLex *l)
2917{
2918 l->t.t = BC_LEX_WHITESPACE;
2919 while (l->i < l->len && l->buf[l->i++] != '\n');
2920 --l->i;
2921}
2922
2923static void bc_lex_whitespace(BcLex *l)
2924{
2925 char c;
2926 l->t.t = BC_LEX_WHITESPACE;
2927 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2928}
2929
2930static BcStatus bc_lex_number(BcLex *l, char start)
2931{
2932 const char *buf = l->buf + l->i;
2933 size_t len, hits = 0, bslashes = 0, i = 0, j;
2934 char c = buf[i];
2935 bool last_pt, pt = start == '.';
2936
2937 last_pt = pt;
2938 l->t.t = BC_LEX_NUMBER;
2939
2940 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2941 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2942 {
2943 if (c != '\\') {
2944 last_pt = c == '.';
2945 pt = pt || last_pt;
2946 }
2947 else {
2948 ++i;
2949 bslashes += 1;
2950 }
2951
2952 c = buf[++i];
2953 }
2954
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002955 len = i + !last_pt - bslashes * 2;
Denys Vlasenko64074a12018-12-07 15:50:14 +01002956 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2957 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2958 if (len > BC_MAX_NUM)
2959 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2960 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002961
Denys Vlasenko7d628012018-12-04 21:46:47 +01002962 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002963 bc_vec_expand(&l->t.v, len + 1);
2964 bc_vec_push(&l->t.v, &start);
2965
2966 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2967
2968 c = buf[j];
2969
2970 // If we have hit a backslash, skip it. We don't have
2971 // to check for a newline because it's guaranteed.
2972 if (hits < bslashes && c == '\\') {
2973 ++hits;
2974 ++j;
2975 continue;
2976 }
2977
2978 bc_vec_push(&l->t.v, &c);
2979 }
2980
Denys Vlasenko08c033c2018-12-05 16:55:08 +01002981 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002982 l->i += i;
2983
2984 return BC_STATUS_SUCCESS;
2985}
2986
2987static BcStatus bc_lex_name(BcLex *l)
2988{
2989 size_t i = 0;
2990 const char *buf = l->buf + l->i - 1;
2991 char c = buf[i];
2992
2993 l->t.t = BC_LEX_NAME;
2994
2995 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2996
Denys Vlasenko64074a12018-12-07 15:50:14 +01002997 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2998 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2999 if (i > BC_MAX_STRING)
3000 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
3001 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003002 bc_vec_string(&l->t.v, i, buf);
3003
3004 // Increment the index. We minus 1 because it has already been incremented.
3005 l->i += i - 1;
3006
3007 return BC_STATUS_SUCCESS;
3008}
3009
3010static void bc_lex_init(BcLex *l, BcLexNext next)
3011{
3012 l->next = next;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003013 bc_char_vec_init(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003014}
3015
3016static void bc_lex_free(BcLex *l)
3017{
3018 bc_vec_free(&l->t.v);
3019}
3020
Denys Vlasenko0409ad32018-12-05 16:39:22 +01003021static void bc_lex_file(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06003022{
Denys Vlasenko5318f812018-12-05 17:48:01 +01003023 G.err_line = l->line = 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003024 l->newline = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06003025}
3026
3027static BcStatus bc_lex_next(BcLex *l)
3028{
3029 BcStatus s;
3030
3031 l->t.last = l->t.t;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003032 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06003033
3034 l->line += l->newline;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003035 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003036 l->t.t = BC_LEX_EOF;
3037
3038 l->newline = (l->i == l->len);
3039 if (l->newline) return BC_STATUS_SUCCESS;
3040
3041 // Loop until failure or we don't have whitespace. This
3042 // is so the parser doesn't get inundated with whitespace.
3043 do {
3044 s = l->next(l);
3045 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3046
3047 return s;
3048}
3049
3050static BcStatus bc_lex_text(BcLex *l, const char *text)
3051{
3052 l->buf = text;
3053 l->i = 0;
3054 l->len = strlen(text);
3055 l->t.t = l->t.last = BC_LEX_INVALID;
3056 return bc_lex_next(l);
3057}
3058
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003059#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06003060static BcStatus bc_lex_identifier(BcLex *l)
3061{
3062 BcStatus s;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003063 unsigned i;
Gavin Howard01055ba2018-11-03 11:00:21 -06003064 const char *buf = l->buf + l->i - 1;
3065
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003066 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3067 const char *keyword8 = bc_lex_kws[i].name8;
3068 unsigned j = 0;
3069 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3070 j++;
3071 if (j == 8) goto match;
Gavin Howard01055ba2018-11-03 11:00:21 -06003072 }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003073 if (keyword8[j] != '\0')
3074 continue;
3075 match:
3076 // buf starts with keyword bc_lex_kws[i]
3077 l->t.t = BC_LEX_KEY_1st_keyword + i;
Denys Vlasenkod00d2f92018-12-06 12:59:40 +01003078 if (!bc_lex_kws_POSIX(i)) {
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003079 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003080 if (s) return s;
3081 }
3082
3083 // We minus 1 because the index has already been incremented.
3084 l->i += j - 1;
3085 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06003086 }
3087
3088 s = bc_lex_name(l);
3089 if (s) return s;
3090
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003091 if (l->t.v.len > 2) {
3092 // Prevent this:
3093 // >>> qwe=1
3094 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3095 // '
3096 unsigned len = strchrnul(buf, '\n') - buf;
3097 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3098 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003099
3100 return s;
3101}
3102
3103static BcStatus bc_lex_string(BcLex *l)
3104{
3105 size_t len, nls = 0, i = l->i;
3106 char c;
3107
3108 l->t.t = BC_LEX_STR;
3109
3110 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3111
3112 if (c == '\0') {
3113 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003114 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003115 }
3116
3117 len = i - l->i;
Denys Vlasenko64074a12018-12-07 15:50:14 +01003118 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3119 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3120 if (len > BC_MAX_STRING)
3121 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3122 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003123 bc_vec_string(&l->t.v, len, l->buf + l->i);
3124
3125 l->i = i + 1;
3126 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003127 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003128
3129 return BC_STATUS_SUCCESS;
3130}
3131
3132static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3133{
3134 if (l->buf[l->i] == '=') {
3135 ++l->i;
3136 l->t.t = with;
3137 }
3138 else
3139 l->t.t = without;
3140}
3141
3142static BcStatus bc_lex_comment(BcLex *l)
3143{
3144 size_t i, nls = 0;
3145 const char *buf = l->buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003146
3147 l->t.t = BC_LEX_WHITESPACE;
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003148 i = ++l->i;
3149 for (;;) {
3150 char c = buf[i];
3151 check_star:
3152 if (c == '*') {
3153 c = buf[++i];
3154 if (c == '/')
3155 break;
3156 goto check_star;
3157 }
3158 if (c == '\0') {
Gavin Howard01055ba2018-11-03 11:00:21 -06003159 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003160 return bc_error("comment end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003161 }
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003162 nls += (c == '\n');
3163 i++;
Gavin Howard01055ba2018-11-03 11:00:21 -06003164 }
3165
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003166 l->i = i + 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003167 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003168 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003169
3170 return BC_STATUS_SUCCESS;
3171}
3172
3173static BcStatus bc_lex_token(BcLex *l)
3174{
3175 BcStatus s = BC_STATUS_SUCCESS;
3176 char c = l->buf[l->i++], c2;
3177
3178 // This is the workhorse of the lexer.
3179 switch (c) {
3180
3181 case '\0':
3182 case '\n':
3183 {
3184 l->newline = true;
3185 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3186 break;
3187 }
3188
3189 case '\t':
3190 case '\v':
3191 case '\f':
3192 case '\r':
3193 case ' ':
3194 {
3195 bc_lex_whitespace(l);
3196 break;
3197 }
3198
3199 case '!':
3200 {
3201 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3202
3203 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
Denys Vlasenko00646792018-12-05 18:12:27 +01003204 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
Gavin Howard01055ba2018-11-03 11:00:21 -06003205 if (s) return s;
3206 }
3207
3208 break;
3209 }
3210
3211 case '"':
3212 {
3213 s = bc_lex_string(l);
3214 break;
3215 }
3216
3217 case '#':
3218 {
Denys Vlasenko00646792018-12-05 18:12:27 +01003219 s = bc_POSIX_does_not_allow("'#' script comments");
Gavin Howard01055ba2018-11-03 11:00:21 -06003220 if (s) return s;
3221
3222 bc_lex_lineComment(l);
3223
3224 break;
3225 }
3226
3227 case '%':
3228 {
3229 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3230 break;
3231 }
3232
3233 case '&':
3234 {
3235 c2 = l->buf[l->i];
3236 if (c2 == '&') {
3237
Denys Vlasenko00646792018-12-05 18:12:27 +01003238 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
Gavin Howard01055ba2018-11-03 11:00:21 -06003239 if (s) return s;
3240
3241 ++l->i;
3242 l->t.t = BC_LEX_OP_BOOL_AND;
3243 }
3244 else {
3245 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003246 s = bc_error_bad_character('&');
Gavin Howard01055ba2018-11-03 11:00:21 -06003247 }
3248
3249 break;
3250 }
3251
3252 case '(':
3253 case ')':
3254 {
3255 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3256 break;
3257 }
3258
3259 case '*':
3260 {
3261 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3262 break;
3263 }
3264
3265 case '+':
3266 {
3267 c2 = l->buf[l->i];
3268 if (c2 == '+') {
3269 ++l->i;
3270 l->t.t = BC_LEX_OP_INC;
3271 }
3272 else
3273 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3274 break;
3275 }
3276
3277 case ',':
3278 {
3279 l->t.t = BC_LEX_COMMA;
3280 break;
3281 }
3282
3283 case '-':
3284 {
3285 c2 = l->buf[l->i];
3286 if (c2 == '-') {
3287 ++l->i;
3288 l->t.t = BC_LEX_OP_DEC;
3289 }
3290 else
3291 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3292 break;
3293 }
3294
3295 case '.':
3296 {
3297 if (isdigit(l->buf[l->i]))
3298 s = bc_lex_number(l, c);
3299 else {
3300 l->t.t = BC_LEX_KEY_LAST;
Denys Vlasenko00646792018-12-05 18:12:27 +01003301 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
Gavin Howard01055ba2018-11-03 11:00:21 -06003302 }
3303 break;
3304 }
3305
3306 case '/':
3307 {
3308 c2 = l->buf[l->i];
3309 if (c2 == '*')
3310 s = bc_lex_comment(l);
3311 else
3312 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3313 break;
3314 }
3315
3316 case '0':
3317 case '1':
3318 case '2':
3319 case '3':
3320 case '4':
3321 case '5':
3322 case '6':
3323 case '7':
3324 case '8':
3325 case '9':
3326 case 'A':
3327 case 'B':
3328 case 'C':
3329 case 'D':
3330 case 'E':
3331 case 'F':
3332 {
3333 s = bc_lex_number(l, c);
3334 break;
3335 }
3336
3337 case ';':
3338 {
3339 l->t.t = BC_LEX_SCOLON;
3340 break;
3341 }
3342
3343 case '<':
3344 {
3345 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3346 break;
3347 }
3348
3349 case '=':
3350 {
3351 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3352 break;
3353 }
3354
3355 case '>':
3356 {
3357 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3358 break;
3359 }
3360
3361 case '[':
3362 case ']':
3363 {
3364 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3365 break;
3366 }
3367
3368 case '\\':
3369 {
3370 if (l->buf[l->i] == '\n') {
3371 l->t.t = BC_LEX_WHITESPACE;
3372 ++l->i;
3373 }
3374 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003375 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003376 break;
3377 }
3378
3379 case '^':
3380 {
3381 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3382 break;
3383 }
3384
3385 case 'a':
3386 case 'b':
3387 case 'c':
3388 case 'd':
3389 case 'e':
3390 case 'f':
3391 case 'g':
3392 case 'h':
3393 case 'i':
3394 case 'j':
3395 case 'k':
3396 case 'l':
3397 case 'm':
3398 case 'n':
3399 case 'o':
3400 case 'p':
3401 case 'q':
3402 case 'r':
3403 case 's':
3404 case 't':
3405 case 'u':
3406 case 'v':
3407 case 'w':
3408 case 'x':
3409 case 'y':
3410 case 'z':
3411 {
3412 s = bc_lex_identifier(l);
3413 break;
3414 }
3415
3416 case '{':
3417 case '}':
3418 {
3419 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3420 break;
3421 }
3422
3423 case '|':
3424 {
3425 c2 = l->buf[l->i];
3426
3427 if (c2 == '|') {
Denys Vlasenko00646792018-12-05 18:12:27 +01003428 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
Gavin Howard01055ba2018-11-03 11:00:21 -06003429 if (s) return s;
3430
3431 ++l->i;
3432 l->t.t = BC_LEX_OP_BOOL_OR;
3433 }
3434 else {
3435 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003436 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003437 }
3438
3439 break;
3440 }
3441
3442 default:
3443 {
3444 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003445 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003446 break;
3447 }
3448 }
3449
3450 return s;
3451}
3452#endif // ENABLE_BC
3453
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003454#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06003455static BcStatus dc_lex_register(BcLex *l)
3456{
3457 BcStatus s = BC_STATUS_SUCCESS;
3458
3459 if (isspace(l->buf[l->i - 1])) {
3460 bc_lex_whitespace(l);
3461 ++l->i;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01003462 if (!G_exreg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003463 s = bc_error("extended register");
Gavin Howard01055ba2018-11-03 11:00:21 -06003464 else
3465 s = bc_lex_name(l);
3466 }
3467 else {
Denys Vlasenko7d628012018-12-04 21:46:47 +01003468 bc_vec_pop_all(&l->t.v);
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003469 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003470 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003471 l->t.t = BC_LEX_NAME;
3472 }
3473
3474 return s;
3475}
3476
3477static BcStatus dc_lex_string(BcLex *l)
3478{
3479 size_t depth = 1, nls = 0, i = l->i;
3480 char c;
3481
3482 l->t.t = BC_LEX_STR;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003483 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003484
3485 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3486
3487 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3488 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3489 nls += (c == '\n');
3490
3491 if (depth) bc_vec_push(&l->t.v, &c);
3492 }
3493
3494 if (c == '\0') {
3495 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003496 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003497 }
3498
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003499 bc_vec_pushZeroByte(&l->t.v);
Denys Vlasenko64074a12018-12-07 15:50:14 +01003500 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3501 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3502 if (i - l->i > BC_MAX_STRING)
3503 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3504 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003505
3506 l->i = i;
3507 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003508 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003509
3510 return BC_STATUS_SUCCESS;
3511}
3512
3513static BcStatus dc_lex_token(BcLex *l)
3514{
3515 BcStatus s = BC_STATUS_SUCCESS;
3516 char c = l->buf[l->i++], c2;
3517 size_t i;
3518
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003519 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3520 if (l->t.last == dc_lex_regs[i])
3521 return dc_lex_register(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003522 }
3523
3524 if (c >= '%' && c <= '~' &&
3525 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3526 {
3527 return s;
3528 }
3529
3530 // This is the workhorse of the lexer.
3531 switch (c) {
3532
3533 case '\0':
3534 {
3535 l->t.t = BC_LEX_EOF;
3536 break;
3537 }
3538
3539 case '\n':
3540 case '\t':
3541 case '\v':
3542 case '\f':
3543 case '\r':
3544 case ' ':
3545 {
3546 l->newline = (c == '\n');
3547 bc_lex_whitespace(l);
3548 break;
3549 }
3550
3551 case '!':
3552 {
3553 c2 = l->buf[l->i];
3554
3555 if (c2 == '=')
3556 l->t.t = BC_LEX_OP_REL_NE;
3557 else if (c2 == '<')
3558 l->t.t = BC_LEX_OP_REL_LE;
3559 else if (c2 == '>')
3560 l->t.t = BC_LEX_OP_REL_GE;
3561 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003562 return bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003563
3564 ++l->i;
3565 break;
3566 }
3567
3568 case '#':
3569 {
3570 bc_lex_lineComment(l);
3571 break;
3572 }
3573
3574 case '.':
3575 {
3576 if (isdigit(l->buf[l->i]))
3577 s = bc_lex_number(l, c);
3578 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003579 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003580 break;
3581 }
3582
3583 case '0':
3584 case '1':
3585 case '2':
3586 case '3':
3587 case '4':
3588 case '5':
3589 case '6':
3590 case '7':
3591 case '8':
3592 case '9':
3593 case 'A':
3594 case 'B':
3595 case 'C':
3596 case 'D':
3597 case 'E':
3598 case 'F':
3599 {
3600 s = bc_lex_number(l, c);
3601 break;
3602 }
3603
3604 case '[':
3605 {
3606 s = dc_lex_string(l);
3607 break;
3608 }
3609
3610 default:
3611 {
3612 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003613 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003614 break;
3615 }
3616 }
3617
3618 return s;
3619}
3620#endif // ENABLE_DC
3621
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003622static void bc_program_addFunc(char *name, size_t *idx);
3623
Gavin Howard01055ba2018-11-03 11:00:21 -06003624static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3625{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003626 bc_program_addFunc(name, idx);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003627 p->func = bc_program_func(p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003628}
3629
Denys Vlasenkob23ac512018-12-06 13:10:56 +01003630#define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3631
Gavin Howard01055ba2018-11-03 11:00:21 -06003632static void bc_parse_pushName(BcParse *p, char *name)
3633{
3634 size_t i = 0, len = strlen(name);
3635
3636 for (; i < len; ++i) bc_parse_push(p, name[i]);
3637 bc_parse_push(p, BC_PARSE_STREND);
3638
3639 free(name);
3640}
3641
3642static void bc_parse_pushIndex(BcParse *p, size_t idx)
3643{
3644 unsigned char amt, i, nums[sizeof(size_t)];
3645
3646 for (amt = 0; idx; ++amt) {
3647 nums[amt] = (char) idx;
3648 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3649 }
3650
3651 bc_parse_push(p, amt);
3652 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3653}
3654
3655static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3656{
3657 char *num = xstrdup(p->l.t.v.v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003658 size_t idx = G.prog.consts.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06003659
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003660 bc_vec_push(&G.prog.consts, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06003661
3662 bc_parse_push(p, BC_INST_NUM);
3663 bc_parse_pushIndex(p, idx);
3664
3665 ++(*nexs);
3666 (*prev) = BC_INST_NUM;
3667}
3668
3669static BcStatus bc_parse_text(BcParse *p, const char *text)
3670{
3671 BcStatus s;
3672
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003673 p->func = bc_program_func(p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003674
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003675 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003676 p->l.t.t = BC_LEX_INVALID;
3677 s = p->parse(p);
3678 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003679 if (!BC_PARSE_CAN_EXEC(p))
3680 return bc_error("file is not executable");
Gavin Howard01055ba2018-11-03 11:00:21 -06003681 }
3682
3683 return bc_lex_text(&p->l, text);
3684}
3685
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003686// Called when parsing or execution detects a failure,
3687// resets execution structures.
3688static void bc_program_reset(void)
3689{
3690 BcFunc *f;
3691 BcInstPtr *ip;
3692
3693 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3694 bc_vec_pop_all(&G.prog.results);
3695
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003696 f = bc_program_func(0);
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003697 ip = bc_vec_top(&G.prog.stack);
3698 ip->idx = f->code.len;
3699}
3700
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003701#define bc_parse_updateFunc(p, f) \
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003702 ((p)->func = bc_program_func((p)->fidx = (f)))
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003703
Denys Vlasenkod38af482018-12-04 19:11:02 +01003704// Called when bc/dc_parse_parse() detects a failure,
3705// resets parsing structures.
3706static void bc_parse_reset(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06003707{
3708 if (p->fidx != BC_PROG_MAIN) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003709 p->func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003710 bc_vec_pop_all(&p->func->code);
3711 bc_vec_pop_all(&p->func->autos);
3712 bc_vec_pop_all(&p->func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06003713
3714 bc_parse_updateFunc(p, BC_PROG_MAIN);
3715 }
3716
3717 p->l.i = p->l.len;
3718 p->l.t.t = BC_LEX_EOF;
3719 p->auto_part = (p->nbraces = 0);
3720
3721 bc_vec_npop(&p->flags, p->flags.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01003722 bc_vec_pop_all(&p->exits);
3723 bc_vec_pop_all(&p->conds);
3724 bc_vec_pop_all(&p->ops);
Gavin Howard01055ba2018-11-03 11:00:21 -06003725
Denys Vlasenkod38af482018-12-04 19:11:02 +01003726 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06003727}
3728
3729static void bc_parse_free(BcParse *p)
3730{
3731 bc_vec_free(&p->flags);
3732 bc_vec_free(&p->exits);
3733 bc_vec_free(&p->conds);
3734 bc_vec_free(&p->ops);
3735 bc_lex_free(&p->l);
3736}
3737
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003738static void bc_parse_create(BcParse *p, size_t func,
Gavin Howard01055ba2018-11-03 11:00:21 -06003739 BcParseParse parse, BcLexNext next)
3740{
3741 memset(p, 0, sizeof(BcParse));
3742
3743 bc_lex_init(&p->l, next);
3744 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3745 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3746 bc_vec_init(&p->conds, sizeof(size_t), NULL);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003747 bc_vec_pushZeroByte(&p->flags);
Gavin Howard01055ba2018-11-03 11:00:21 -06003748 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3749
3750 p->parse = parse;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01003751 // p->auto_part = p->nbraces = 0; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06003752 bc_parse_updateFunc(p, func);
3753}
3754
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003755#if ENABLE_BC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003756
3757#define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3758#define BC_PARSE_LEAF(p, rparen) \
3759 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3760 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3761
3762// We can calculate the conversion between tokens and exprs by subtracting the
3763// position of the first operator in the lex enum and adding the position of the
3764// first in the expr enum. Note: This only works for binary operators.
3765#define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3766
Gavin Howard01055ba2018-11-03 11:00:21 -06003767static BcStatus bc_parse_else(BcParse *p);
3768static BcStatus bc_parse_stmt(BcParse *p);
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003769static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01003770static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
Gavin Howard01055ba2018-11-03 11:00:21 -06003771
3772static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3773 size_t *nexprs, bool next)
3774{
3775 BcStatus s = BC_STATUS_SUCCESS;
3776 BcLexType t;
Denys Vlasenko65437582018-12-05 19:37:19 +01003777 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3778 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003779
3780 while (p->ops.len > start) {
3781
3782 t = BC_PARSE_TOP_OP(p);
3783 if (t == BC_LEX_LPAREN) break;
3784
Denys Vlasenko65437582018-12-05 19:37:19 +01003785 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003786 if (l >= r && (l != r || !left)) break;
3787
3788 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3789 bc_vec_pop(&p->ops);
3790 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3791 }
3792
3793 bc_vec_push(&p->ops, &type);
3794 if (next) s = bc_lex_next(&p->l);
3795
3796 return s;
3797}
3798
3799static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3800{
3801 BcLexType top;
3802
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003803 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003804 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003805 top = BC_PARSE_TOP_OP(p);
3806
3807 while (top != BC_LEX_LPAREN) {
3808
3809 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3810
3811 bc_vec_pop(&p->ops);
3812 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3813
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003814 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003815 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003816 top = BC_PARSE_TOP_OP(p);
3817 }
3818
3819 bc_vec_pop(&p->ops);
3820
3821 return bc_lex_next(&p->l);
3822}
3823
3824static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3825{
3826 BcStatus s;
3827 bool comma = false;
3828 size_t nparams;
3829
3830 s = bc_lex_next(&p->l);
3831 if (s) return s;
3832
3833 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3834
3835 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3836 s = bc_parse_expr(p, flags, bc_parse_next_param);
3837 if (s) return s;
3838
3839 comma = p->l.t.t == BC_LEX_COMMA;
3840 if (comma) {
3841 s = bc_lex_next(&p->l);
3842 if (s) return s;
3843 }
3844 }
3845
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003846 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003847 bc_parse_push(p, BC_INST_CALL);
3848 bc_parse_pushIndex(p, nparams);
3849
3850 return BC_STATUS_SUCCESS;
3851}
3852
3853static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3854{
3855 BcStatus s;
3856 BcId entry, *entry_ptr;
3857 size_t idx;
3858
3859 entry.name = name;
3860
3861 s = bc_parse_params(p, flags);
3862 if (s) goto err;
3863
3864 if (p->l.t.t != BC_LEX_RPAREN) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003865 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003866 goto err;
3867 }
3868
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003869 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003870
3871 if (idx == BC_VEC_INVALID_IDX) {
3872 name = xstrdup(entry.name);
3873 bc_parse_addFunc(p, name, &idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003874 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003875 free(entry.name);
3876 }
3877 else
3878 free(name);
3879
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003880 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003881 bc_parse_pushIndex(p, entry_ptr->idx);
3882
3883 return bc_lex_next(&p->l);
3884
3885err:
3886 free(name);
3887 return s;
3888}
3889
3890static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3891{
3892 BcStatus s;
3893 char *name;
3894
3895 name = xstrdup(p->l.t.v.v);
3896 s = bc_lex_next(&p->l);
3897 if (s) goto err;
3898
3899 if (p->l.t.t == BC_LEX_LBRACKET) {
3900
3901 s = bc_lex_next(&p->l);
3902 if (s) goto err;
3903
3904 if (p->l.t.t == BC_LEX_RBRACKET) {
3905
3906 if (!(flags & BC_PARSE_ARRAY)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003907 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003908 goto err;
3909 }
3910
3911 *type = BC_INST_ARRAY;
3912 }
3913 else {
3914
3915 *type = BC_INST_ARRAY_ELEM;
3916
3917 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3918 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3919 if (s) goto err;
3920 }
3921
3922 s = bc_lex_next(&p->l);
3923 if (s) goto err;
3924 bc_parse_push(p, *type);
3925 bc_parse_pushName(p, name);
3926 }
3927 else if (p->l.t.t == BC_LEX_LPAREN) {
3928
3929 if (flags & BC_PARSE_NOCALL) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003930 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003931 goto err;
3932 }
3933
3934 *type = BC_INST_CALL;
3935 s = bc_parse_call(p, name, flags);
3936 }
3937 else {
3938 *type = BC_INST_VAR;
3939 bc_parse_push(p, BC_INST_VAR);
3940 bc_parse_pushName(p, name);
3941 }
3942
3943 return s;
3944
3945err:
3946 free(name);
3947 return s;
3948}
3949
3950static BcStatus bc_parse_read(BcParse *p)
3951{
3952 BcStatus s;
3953
3954 s = bc_lex_next(&p->l);
3955 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003956 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003957
3958 s = bc_lex_next(&p->l);
3959 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003960 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003961
3962 bc_parse_push(p, BC_INST_READ);
3963
3964 return bc_lex_next(&p->l);
3965}
3966
3967static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3968 BcInst *prev)
3969{
3970 BcStatus s;
3971
3972 s = bc_lex_next(&p->l);
3973 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003974 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003975
3976 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3977
3978 s = bc_lex_next(&p->l);
3979 if (s) return s;
3980
3981 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3982 if (s) return s;
3983
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003984 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003985
3986 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3987 bc_parse_push(p, *prev);
3988
3989 return bc_lex_next(&p->l);
3990}
3991
3992static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3993{
3994 BcStatus s;
3995
3996 s = bc_lex_next(&p->l);
3997 if (s) return s;
3998
3999 if (p->l.t.t != BC_LEX_LPAREN) {
4000 *type = BC_INST_SCALE;
4001 bc_parse_push(p, BC_INST_SCALE);
4002 return BC_STATUS_SUCCESS;
4003 }
4004
4005 *type = BC_INST_SCALE_FUNC;
4006 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
4007
4008 s = bc_lex_next(&p->l);
4009 if (s) return s;
4010
4011 s = bc_parse_expr(p, flags, bc_parse_next_rel);
4012 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004013 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004014 bc_parse_push(p, BC_INST_SCALE_FUNC);
4015
4016 return bc_lex_next(&p->l);
4017}
4018
4019static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
4020 size_t *nexprs, uint8_t flags)
4021{
4022 BcStatus s;
4023 BcLexType type;
4024 char inst;
4025 BcInst etype = *prev;
4026
4027 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4028 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4029 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4030 {
4031 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4032 bc_parse_push(p, inst);
4033 s = bc_lex_next(&p->l);
4034 }
4035 else {
4036
4037 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4038 *paren_expr = true;
4039
4040 s = bc_lex_next(&p->l);
4041 if (s) return s;
4042 type = p->l.t.t;
4043
4044 // Because we parse the next part of the expression
4045 // right here, we need to increment this.
4046 *nexprs = *nexprs + 1;
4047
4048 switch (type) {
4049
4050 case BC_LEX_NAME:
4051 {
4052 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4053 break;
4054 }
4055
4056 case BC_LEX_KEY_IBASE:
4057 case BC_LEX_KEY_LAST:
4058 case BC_LEX_KEY_OBASE:
4059 {
4060 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4061 s = bc_lex_next(&p->l);
4062 break;
4063 }
4064
4065 case BC_LEX_KEY_SCALE:
4066 {
4067 s = bc_lex_next(&p->l);
4068 if (s) return s;
4069 if (p->l.t.t == BC_LEX_LPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004070 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004071 else
4072 bc_parse_push(p, BC_INST_SCALE);
4073 break;
4074 }
4075
4076 default:
4077 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004078 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004079 break;
4080 }
4081 }
4082
4083 if (!s) bc_parse_push(p, inst);
4084 }
4085
4086 return s;
4087}
4088
4089static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4090 bool rparen, size_t *nexprs)
4091{
4092 BcStatus s;
4093 BcLexType type;
4094 BcInst etype = *prev;
4095
4096 s = bc_lex_next(&p->l);
4097 if (s) return s;
4098
4099 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4100 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4101 BC_LEX_OP_MINUS :
4102 BC_LEX_NEG;
4103 *prev = BC_PARSE_TOKEN_INST(type);
4104
4105 // We can just push onto the op stack because this is the largest
4106 // precedence operator that gets pushed. Inc/dec does not.
4107 if (type != BC_LEX_OP_MINUS)
4108 bc_vec_push(&p->ops, &type);
4109 else
4110 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4111
4112 return s;
4113}
4114
4115static BcStatus bc_parse_string(BcParse *p, char inst)
4116{
4117 char *str = xstrdup(p->l.t.v.v);
4118
4119 bc_parse_push(p, BC_INST_STR);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004120 bc_parse_pushIndex(p, G.prog.strs.len);
4121 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06004122 bc_parse_push(p, inst);
4123
4124 return bc_lex_next(&p->l);
4125}
4126
4127static BcStatus bc_parse_print(BcParse *p)
4128{
4129 BcStatus s;
4130 BcLexType type;
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004131 bool comma;
Gavin Howard01055ba2018-11-03 11:00:21 -06004132
4133 s = bc_lex_next(&p->l);
4134 if (s) return s;
4135
4136 type = p->l.t.t;
4137
4138 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004139 return bc_error("bad print statement");
Gavin Howard01055ba2018-11-03 11:00:21 -06004140
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004141 comma = false;
4142 while (type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004143
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004144 if (type == BC_LEX_STR) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004145 s = bc_parse_string(p, BC_INST_PRINT_POP);
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004146 if (s) return s;
4147 } else {
Gavin Howard01055ba2018-11-03 11:00:21 -06004148 s = bc_parse_expr(p, 0, bc_parse_next_print);
4149 if (s) return s;
4150 bc_parse_push(p, BC_INST_PRINT_POP);
4151 }
4152
Gavin Howard01055ba2018-11-03 11:00:21 -06004153 comma = p->l.t.t == BC_LEX_COMMA;
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004154 if (comma) {
4155 s = bc_lex_next(&p->l);
4156 if (s) return s;
4157 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004158 type = p->l.t.t;
4159 }
4160
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004161 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004162
4163 return bc_lex_next(&p->l);
4164}
4165
4166static BcStatus bc_parse_return(BcParse *p)
4167{
4168 BcStatus s;
4169 BcLexType t;
4170 bool paren;
4171
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004172 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004173
4174 s = bc_lex_next(&p->l);
4175 if (s) return s;
4176
4177 t = p->l.t.t;
4178 paren = t == BC_LEX_LPAREN;
4179
4180 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4181 bc_parse_push(p, BC_INST_RET0);
4182 else {
4183
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004184 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004185 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004186 bc_parse_push(p, BC_INST_RET0);
4187 s = bc_lex_next(&p->l);
Gavin Howard01055ba2018-11-03 11:00:21 -06004188 }
Denys Vlasenko452df922018-12-05 20:28:26 +01004189 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06004190
4191 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004192 s = bc_POSIX_requires("parentheses around return expressions");
Gavin Howard01055ba2018-11-03 11:00:21 -06004193 if (s) return s;
4194 }
4195
4196 bc_parse_push(p, BC_INST_RET);
4197 }
4198
4199 return s;
4200}
4201
4202static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4203{
4204 BcStatus s = BC_STATUS_SUCCESS;
4205
4206 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004207 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004208
4209 if (brace) {
4210
4211 if (p->l.t.t == BC_LEX_RBRACE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004212 if (!p->nbraces) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004213 --p->nbraces;
4214 s = bc_lex_next(&p->l);
4215 if (s) return s;
4216 }
4217 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004218 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004219 }
4220
4221 if (BC_PARSE_IF(p)) {
4222
4223 uint8_t *flag_ptr;
4224
4225 while (p->l.t.t == BC_LEX_NLINE) {
4226 s = bc_lex_next(&p->l);
4227 if (s) return s;
4228 }
4229
4230 bc_vec_pop(&p->flags);
4231
4232 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4233 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4234
4235 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4236 }
4237 else if (BC_PARSE_ELSE(p)) {
4238
4239 BcInstPtr *ip;
4240 size_t *label;
4241
4242 bc_vec_pop(&p->flags);
4243
4244 ip = bc_vec_top(&p->exits);
4245 label = bc_vec_item(&p->func->labels, ip->idx);
4246 *label = p->func->code.len;
4247
4248 bc_vec_pop(&p->exits);
4249 }
4250 else if (BC_PARSE_FUNC_INNER(p)) {
4251 bc_parse_push(p, BC_INST_RET0);
4252 bc_parse_updateFunc(p, BC_PROG_MAIN);
4253 bc_vec_pop(&p->flags);
4254 }
4255 else {
4256
4257 BcInstPtr *ip = bc_vec_top(&p->exits);
4258 size_t *label = bc_vec_top(&p->conds);
4259
4260 bc_parse_push(p, BC_INST_JUMP);
4261 bc_parse_pushIndex(p, *label);
4262
4263 label = bc_vec_item(&p->func->labels, ip->idx);
4264 *label = p->func->code.len;
4265
4266 bc_vec_pop(&p->flags);
4267 bc_vec_pop(&p->exits);
4268 bc_vec_pop(&p->conds);
4269 }
4270
4271 return s;
4272}
4273
4274static void bc_parse_startBody(BcParse *p, uint8_t flags)
4275{
4276 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4277 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4278 flags |= BC_PARSE_FLAG_BODY;
4279 bc_vec_push(&p->flags, &flags);
4280}
4281
4282static void bc_parse_noElse(BcParse *p)
4283{
4284 BcInstPtr *ip;
4285 size_t *label;
4286 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4287
4288 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4289
4290 ip = bc_vec_top(&p->exits);
4291 label = bc_vec_item(&p->func->labels, ip->idx);
4292 *label = p->func->code.len;
4293
4294 bc_vec_pop(&p->exits);
4295}
4296
4297static BcStatus bc_parse_if(BcParse *p)
4298{
4299 BcStatus s;
4300 BcInstPtr ip;
4301
4302 s = bc_lex_next(&p->l);
4303 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004304 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004305
4306 s = bc_lex_next(&p->l);
4307 if (s) return s;
4308 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4309 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004310 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004311
4312 s = bc_lex_next(&p->l);
4313 if (s) return s;
4314 bc_parse_push(p, BC_INST_JUMP_ZERO);
4315
4316 ip.idx = p->func->labels.len;
4317 ip.func = ip.len = 0;
4318
4319 bc_parse_pushIndex(p, ip.idx);
4320 bc_vec_push(&p->exits, &ip);
4321 bc_vec_push(&p->func->labels, &ip.idx);
4322 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4323
4324 return BC_STATUS_SUCCESS;
4325}
4326
4327static BcStatus bc_parse_else(BcParse *p)
4328{
4329 BcInstPtr ip;
4330
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004331 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004332
4333 ip.idx = p->func->labels.len;
4334 ip.func = ip.len = 0;
4335
4336 bc_parse_push(p, BC_INST_JUMP);
4337 bc_parse_pushIndex(p, ip.idx);
4338
4339 bc_parse_noElse(p);
4340
4341 bc_vec_push(&p->exits, &ip);
4342 bc_vec_push(&p->func->labels, &ip.idx);
4343 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4344
4345 return bc_lex_next(&p->l);
4346}
4347
4348static BcStatus bc_parse_while(BcParse *p)
4349{
4350 BcStatus s;
4351 BcInstPtr ip;
4352
4353 s = bc_lex_next(&p->l);
4354 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004355 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004356 s = bc_lex_next(&p->l);
4357 if (s) return s;
4358
4359 ip.idx = p->func->labels.len;
4360
4361 bc_vec_push(&p->func->labels, &p->func->code.len);
4362 bc_vec_push(&p->conds, &ip.idx);
4363
4364 ip.idx = p->func->labels.len;
4365 ip.func = 1;
4366 ip.len = 0;
4367
4368 bc_vec_push(&p->exits, &ip);
4369 bc_vec_push(&p->func->labels, &ip.idx);
4370
4371 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4372 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004373 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004374 s = bc_lex_next(&p->l);
4375 if (s) return s;
4376
4377 bc_parse_push(p, BC_INST_JUMP_ZERO);
4378 bc_parse_pushIndex(p, ip.idx);
4379 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4380
4381 return BC_STATUS_SUCCESS;
4382}
4383
4384static BcStatus bc_parse_for(BcParse *p)
4385{
4386 BcStatus s;
4387 BcInstPtr ip;
4388 size_t cond_idx, exit_idx, body_idx, update_idx;
4389
4390 s = bc_lex_next(&p->l);
4391 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004392 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004393 s = bc_lex_next(&p->l);
4394 if (s) return s;
4395
4396 if (p->l.t.t != BC_LEX_SCOLON)
4397 s = bc_parse_expr(p, 0, bc_parse_next_for);
4398 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004399 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
Gavin Howard01055ba2018-11-03 11:00:21 -06004400
4401 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004402 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004403 s = bc_lex_next(&p->l);
4404 if (s) return s;
4405
4406 cond_idx = p->func->labels.len;
4407 update_idx = cond_idx + 1;
4408 body_idx = update_idx + 1;
4409 exit_idx = body_idx + 1;
4410
4411 bc_vec_push(&p->func->labels, &p->func->code.len);
4412
4413 if (p->l.t.t != BC_LEX_SCOLON)
4414 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4415 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004416 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004417
4418 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004419 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004420
4421 s = bc_lex_next(&p->l);
4422 if (s) return s;
4423
4424 bc_parse_push(p, BC_INST_JUMP_ZERO);
4425 bc_parse_pushIndex(p, exit_idx);
4426 bc_parse_push(p, BC_INST_JUMP);
4427 bc_parse_pushIndex(p, body_idx);
4428
4429 ip.idx = p->func->labels.len;
4430
4431 bc_vec_push(&p->conds, &update_idx);
4432 bc_vec_push(&p->func->labels, &p->func->code.len);
4433
4434 if (p->l.t.t != BC_LEX_RPAREN)
4435 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4436 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004437 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
Gavin Howard01055ba2018-11-03 11:00:21 -06004438
4439 if (s) return s;
4440
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004441 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004442 bc_parse_push(p, BC_INST_JUMP);
4443 bc_parse_pushIndex(p, cond_idx);
4444 bc_vec_push(&p->func->labels, &p->func->code.len);
4445
4446 ip.idx = exit_idx;
4447 ip.func = 1;
4448 ip.len = 0;
4449
4450 bc_vec_push(&p->exits, &ip);
4451 bc_vec_push(&p->func->labels, &ip.idx);
4452 bc_lex_next(&p->l);
4453 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4454
4455 return BC_STATUS_SUCCESS;
4456}
4457
4458static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4459{
4460 BcStatus s;
4461 size_t i;
4462 BcInstPtr *ip;
4463
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004464 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004465
4466 if (type == BC_LEX_KEY_BREAK) {
4467
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004468 if (p->exits.len == 0) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004469
4470 i = p->exits.len - 1;
4471 ip = bc_vec_item(&p->exits, i);
4472
4473 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004474 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004475
4476 i = ip->idx;
4477 }
4478 else
4479 i = *((size_t *) bc_vec_top(&p->conds));
4480
4481 bc_parse_push(p, BC_INST_JUMP);
4482 bc_parse_pushIndex(p, i);
4483
4484 s = bc_lex_next(&p->l);
4485 if (s) return s;
4486
4487 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004488 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004489
4490 return bc_lex_next(&p->l);
4491}
4492
4493static BcStatus bc_parse_func(BcParse *p)
4494{
4495 BcStatus s;
4496 bool var, comma = false;
4497 uint8_t flags;
4498 char *name;
4499
4500 s = bc_lex_next(&p->l);
4501 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004502 if (p->l.t.t != BC_LEX_NAME)
4503 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004504
4505 name = xstrdup(p->l.t.v.v);
4506 bc_parse_addFunc(p, name, &p->fidx);
4507
4508 s = bc_lex_next(&p->l);
4509 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004510 if (p->l.t.t != BC_LEX_LPAREN)
4511 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004512 s = bc_lex_next(&p->l);
4513 if (s) return s;
4514
4515 while (p->l.t.t != BC_LEX_RPAREN) {
4516
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004517 if (p->l.t.t != BC_LEX_NAME)
4518 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004519
4520 ++p->func->nparams;
4521
4522 name = xstrdup(p->l.t.v.v);
4523 s = bc_lex_next(&p->l);
4524 if (s) goto err;
4525
4526 var = p->l.t.t != BC_LEX_LBRACKET;
4527
4528 if (!var) {
4529
4530 s = bc_lex_next(&p->l);
4531 if (s) goto err;
4532
4533 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004534 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004535 goto err;
4536 }
4537
4538 s = bc_lex_next(&p->l);
4539 if (s) goto err;
4540 }
4541
4542 comma = p->l.t.t == BC_LEX_COMMA;
4543 if (comma) {
4544 s = bc_lex_next(&p->l);
4545 if (s) goto err;
4546 }
4547
4548 s = bc_func_insert(p->func, name, var);
4549 if (s) goto err;
4550 }
4551
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004552 if (comma) return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004553
4554 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4555 bc_parse_startBody(p, flags);
4556
4557 s = bc_lex_next(&p->l);
4558 if (s) return s;
4559
4560 if (p->l.t.t != BC_LEX_LBRACE)
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004561 s = bc_POSIX_requires("the left brace be on the same line as the function header");
Gavin Howard01055ba2018-11-03 11:00:21 -06004562
4563 return s;
4564
4565err:
4566 free(name);
4567 return s;
4568}
4569
4570static BcStatus bc_parse_auto(BcParse *p)
4571{
4572 BcStatus s;
4573 bool comma, var, one;
4574 char *name;
4575
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004576 if (!p->auto_part) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004577 s = bc_lex_next(&p->l);
4578 if (s) return s;
4579
4580 p->auto_part = comma = false;
4581 one = p->l.t.t == BC_LEX_NAME;
4582
4583 while (p->l.t.t == BC_LEX_NAME) {
4584
4585 name = xstrdup(p->l.t.v.v);
4586 s = bc_lex_next(&p->l);
4587 if (s) goto err;
4588
4589 var = p->l.t.t != BC_LEX_LBRACKET;
4590 if (!var) {
4591
4592 s = bc_lex_next(&p->l);
4593 if (s) goto err;
4594
4595 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004596 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004597 goto err;
4598 }
4599
4600 s = bc_lex_next(&p->l);
4601 if (s) goto err;
4602 }
4603
4604 comma = p->l.t.t == BC_LEX_COMMA;
4605 if (comma) {
4606 s = bc_lex_next(&p->l);
4607 if (s) goto err;
4608 }
4609
4610 s = bc_func_insert(p->func, name, var);
4611 if (s) goto err;
4612 }
4613
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004614 if (comma) return bc_error("bad function definition");
Denys Vlasenkoabbc4332018-12-03 21:46:41 +01004615 if (!one) return bc_error("no auto variable found");
Gavin Howard01055ba2018-11-03 11:00:21 -06004616
4617 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004618 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004619
4620 return bc_lex_next(&p->l);
4621
4622err:
4623 free(name);
4624 return s;
4625}
4626
4627static BcStatus bc_parse_body(BcParse *p, bool brace)
4628{
4629 BcStatus s = BC_STATUS_SUCCESS;
4630 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4631
4632 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4633
4634 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4635
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004636 if (!brace) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004637 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4638
4639 if (!p->auto_part) {
4640 s = bc_parse_auto(p);
4641 if (s) return s;
4642 }
4643
4644 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4645 }
4646 else {
4647 s = bc_parse_stmt(p);
4648 if (!s && !brace) s = bc_parse_endBody(p, false);
4649 }
4650
4651 return s;
4652}
4653
4654static BcStatus bc_parse_stmt(BcParse *p)
4655{
4656 BcStatus s = BC_STATUS_SUCCESS;
4657
4658 switch (p->l.t.t) {
4659
4660 case BC_LEX_NLINE:
4661 {
4662 return bc_lex_next(&p->l);
4663 }
4664
4665 case BC_LEX_KEY_ELSE:
4666 {
4667 p->auto_part = false;
4668 break;
4669 }
4670
4671 case BC_LEX_LBRACE:
4672 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004673 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004674
4675 ++p->nbraces;
4676 s = bc_lex_next(&p->l);
4677 if (s) return s;
4678
4679 return bc_parse_body(p, true);
4680 }
4681
4682 case BC_LEX_KEY_AUTO:
4683 {
4684 return bc_parse_auto(p);
4685 }
4686
4687 default:
4688 {
4689 p->auto_part = false;
4690
4691 if (BC_PARSE_IF_END(p)) {
4692 bc_parse_noElse(p);
4693 return BC_STATUS_SUCCESS;
4694 }
4695 else if (BC_PARSE_BODY(p))
4696 return bc_parse_body(p, false);
4697
4698 break;
4699 }
4700 }
4701
4702 switch (p->l.t.t) {
4703
4704 case BC_LEX_OP_INC:
4705 case BC_LEX_OP_DEC:
4706 case BC_LEX_OP_MINUS:
4707 case BC_LEX_OP_BOOL_NOT:
4708 case BC_LEX_LPAREN:
4709 case BC_LEX_NAME:
4710 case BC_LEX_NUMBER:
4711 case BC_LEX_KEY_IBASE:
4712 case BC_LEX_KEY_LAST:
4713 case BC_LEX_KEY_LENGTH:
4714 case BC_LEX_KEY_OBASE:
4715 case BC_LEX_KEY_READ:
4716 case BC_LEX_KEY_SCALE:
4717 case BC_LEX_KEY_SQRT:
4718 {
4719 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4720 break;
4721 }
4722
4723 case BC_LEX_KEY_ELSE:
4724 {
4725 s = bc_parse_else(p);
4726 break;
4727 }
4728
4729 case BC_LEX_SCOLON:
4730 {
4731 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4732 break;
4733 }
4734
4735 case BC_LEX_RBRACE:
4736 {
4737 s = bc_parse_endBody(p, true);
4738 break;
4739 }
4740
4741 case BC_LEX_STR:
4742 {
4743 s = bc_parse_string(p, BC_INST_PRINT_STR);
4744 break;
4745 }
4746
4747 case BC_LEX_KEY_BREAK:
4748 case BC_LEX_KEY_CONTINUE:
4749 {
4750 s = bc_parse_loopExit(p, p->l.t.t);
4751 break;
4752 }
4753
4754 case BC_LEX_KEY_FOR:
4755 {
4756 s = bc_parse_for(p);
4757 break;
4758 }
4759
4760 case BC_LEX_KEY_HALT:
4761 {
4762 bc_parse_push(p, BC_INST_HALT);
4763 s = bc_lex_next(&p->l);
4764 break;
4765 }
4766
4767 case BC_LEX_KEY_IF:
4768 {
4769 s = bc_parse_if(p);
4770 break;
4771 }
4772
4773 case BC_LEX_KEY_LIMITS:
4774 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004775 // "limits" is a compile-time command,
4776 // the output is produced at _parse time_.
Gavin Howard01055ba2018-11-03 11:00:21 -06004777 s = bc_lex_next(&p->l);
4778 if (s) return s;
Denys Vlasenko64074a12018-12-07 15:50:14 +01004779 printf(
4780 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4781 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4782 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4783 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4784 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4785 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4786 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4787 "Number of vars = "BC_MAX_VARS_STR "\n"
4788 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004789 break;
4790 }
4791
4792 case BC_LEX_KEY_PRINT:
4793 {
4794 s = bc_parse_print(p);
4795 break;
4796 }
4797
4798 case BC_LEX_KEY_QUIT:
4799 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004800 // "quit" is a compile-time command. For example,
4801 // "if (0 == 1) quit" terminates when parsing the statement,
4802 // not when it is executed
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01004803 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06004804 }
4805
4806 case BC_LEX_KEY_RETURN:
4807 {
4808 s = bc_parse_return(p);
4809 break;
4810 }
4811
4812 case BC_LEX_KEY_WHILE:
4813 {
4814 s = bc_parse_while(p);
4815 break;
4816 }
4817
4818 default:
4819 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004820 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004821 break;
4822 }
4823 }
4824
4825 return s;
4826}
4827
4828static BcStatus bc_parse_parse(BcParse *p)
4829{
4830 BcStatus s;
4831
4832 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004833 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 -06004834 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004835 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004836 s = bc_parse_func(p);
4837 }
4838 else
4839 s = bc_parse_stmt(p);
4840
Denys Vlasenkod38af482018-12-04 19:11:02 +01004841 if (s || G_interrupt) {
4842 bc_parse_reset(p);
4843 s = BC_STATUS_FAILURE;
4844 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004845
4846 return s;
4847}
4848
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004849static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
Gavin Howard01055ba2018-11-03 11:00:21 -06004850{
4851 BcStatus s = BC_STATUS_SUCCESS;
4852 BcInst prev = BC_INST_PRINT;
4853 BcLexType top, t = p->l.t.t;
4854 size_t nexprs = 0, ops_bgn = p->ops.len;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01004855 unsigned nparens, nrelops;
Gavin Howard01055ba2018-11-03 11:00:21 -06004856 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4857
4858 paren_first = p->l.t.t == BC_LEX_LPAREN;
4859 nparens = nrelops = 0;
4860 paren_expr = rprn = done = get_token = assign = false;
4861 bin_last = true;
4862
Denys Vlasenkobcb62a72018-12-05 20:17:48 +01004863 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004864 switch (t) {
4865
4866 case BC_LEX_OP_INC:
4867 case BC_LEX_OP_DEC:
4868 {
4869 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4870 rprn = get_token = bin_last = false;
4871 break;
4872 }
4873
4874 case BC_LEX_OP_MINUS:
4875 {
4876 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4877 rprn = get_token = false;
4878 bin_last = prev == BC_INST_MINUS;
4879 break;
4880 }
4881
4882 case BC_LEX_OP_ASSIGN_POWER:
4883 case BC_LEX_OP_ASSIGN_MULTIPLY:
4884 case BC_LEX_OP_ASSIGN_DIVIDE:
4885 case BC_LEX_OP_ASSIGN_MODULUS:
4886 case BC_LEX_OP_ASSIGN_PLUS:
4887 case BC_LEX_OP_ASSIGN_MINUS:
4888 case BC_LEX_OP_ASSIGN:
4889 {
4890 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4891 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4892 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4893 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004894 s = bc_error("bad assignment:"
4895 " left side must be scale,"
4896 " ibase, obase, last, var,"
4897 " or array element"
4898 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004899 break;
4900 }
4901 }
4902 // Fallthrough.
4903 case BC_LEX_OP_POWER:
4904 case BC_LEX_OP_MULTIPLY:
4905 case BC_LEX_OP_DIVIDE:
4906 case BC_LEX_OP_MODULUS:
4907 case BC_LEX_OP_PLUS:
4908 case BC_LEX_OP_REL_EQ:
4909 case BC_LEX_OP_REL_LE:
4910 case BC_LEX_OP_REL_GE:
4911 case BC_LEX_OP_REL_NE:
4912 case BC_LEX_OP_REL_LT:
4913 case BC_LEX_OP_REL_GT:
4914 case BC_LEX_OP_BOOL_NOT:
4915 case BC_LEX_OP_BOOL_OR:
4916 case BC_LEX_OP_BOOL_AND:
4917 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004918 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4919 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4920 ) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004921 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004922 }
4923
4924 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4925 prev = BC_PARSE_TOKEN_INST(t);
4926 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4927 rprn = get_token = false;
4928 bin_last = t != BC_LEX_OP_BOOL_NOT;
4929
4930 break;
4931 }
4932
4933 case BC_LEX_LPAREN:
4934 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004935 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004936 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004937 ++nparens;
4938 paren_expr = rprn = bin_last = false;
4939 get_token = true;
4940 bc_vec_push(&p->ops, &t);
4941
4942 break;
4943 }
4944
4945 case BC_LEX_RPAREN:
4946 {
4947 if (bin_last || prev == BC_INST_BOOL_NOT)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004948 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004949
4950 if (nparens == 0) {
4951 s = BC_STATUS_SUCCESS;
4952 done = true;
4953 get_token = false;
4954 break;
4955 }
4956 else if (!paren_expr)
4957 return BC_STATUS_PARSE_EMPTY_EXP;
4958
4959 --nparens;
4960 paren_expr = rprn = true;
4961 get_token = bin_last = false;
4962
4963 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4964
4965 break;
4966 }
4967
4968 case BC_LEX_NAME:
4969 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004970 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004971 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004972 paren_expr = true;
4973 rprn = get_token = bin_last = false;
4974 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4975 ++nexprs;
4976
4977 break;
4978 }
4979
4980 case BC_LEX_NUMBER:
4981 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004982 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004983 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004984 bc_parse_number(p, &prev, &nexprs);
4985 paren_expr = get_token = true;
4986 rprn = bin_last = false;
4987
4988 break;
4989 }
4990
4991 case BC_LEX_KEY_IBASE:
4992 case BC_LEX_KEY_LAST:
4993 case BC_LEX_KEY_OBASE:
4994 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004995 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004996 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004997 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4998 bc_parse_push(p, (char) prev);
4999
5000 paren_expr = get_token = true;
5001 rprn = bin_last = false;
5002 ++nexprs;
5003
5004 break;
5005 }
5006
5007 case BC_LEX_KEY_LENGTH:
5008 case BC_LEX_KEY_SQRT:
5009 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005010 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005011 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005012 s = bc_parse_builtin(p, t, flags, &prev);
5013 paren_expr = true;
5014 rprn = get_token = bin_last = false;
5015 ++nexprs;
5016
5017 break;
5018 }
5019
5020 case BC_LEX_KEY_READ:
5021 {
5022 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005023 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005024 else if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005025 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005026 else
5027 s = bc_parse_read(p);
5028
5029 paren_expr = true;
5030 rprn = get_token = bin_last = false;
5031 ++nexprs;
5032 prev = BC_INST_READ;
5033
5034 break;
5035 }
5036
5037 case BC_LEX_KEY_SCALE:
5038 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005039 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005040 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005041 s = bc_parse_scale(p, &prev, flags);
5042 paren_expr = true;
5043 rprn = get_token = bin_last = false;
5044 ++nexprs;
5045 prev = BC_INST_SCALE;
5046
5047 break;
5048 }
5049
5050 default:
5051 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005052 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005053 break;
5054 }
5055 }
5056
5057 if (!s && get_token) s = bc_lex_next(&p->l);
5058 }
5059
5060 if (s) return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01005061 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
Gavin Howard01055ba2018-11-03 11:00:21 -06005062
5063 while (p->ops.len > ops_bgn) {
5064
5065 top = BC_PARSE_TOP_OP(p);
5066 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5067
5068 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005069 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005070
5071 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5072
5073 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5074 bc_vec_pop(&p->ops);
5075 }
5076
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005077 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005078 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005079
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005080 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5081 for (;;) {
5082 if (t == (next & 0x7f))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005083 goto ok;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005084 if (next & 0x80) // last element?
5085 break;
5086 next >>= 8;
5087 }
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005088 return bc_error_bad_expression();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005089 ok:
Gavin Howard01055ba2018-11-03 11:00:21 -06005090
5091 if (!(flags & BC_PARSE_REL) && nrelops) {
Denys Vlasenko00646792018-12-05 18:12:27 +01005092 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
Gavin Howard01055ba2018-11-03 11:00:21 -06005093 if (s) return s;
5094 }
5095 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01005096 s = bc_POSIX_requires("exactly one comparison operator per condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06005097 if (s) return s;
5098 }
5099
5100 if (flags & BC_PARSE_PRINT) {
5101 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5102 bc_parse_push(p, BC_INST_POP);
5103 }
5104
5105 return s;
5106}
5107
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01005108static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5109{
5110 BcStatus s;
5111
5112 s = bc_parse_expr_empty_ok(p, flags, next);
5113 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5114 return bc_error("empty expression");
5115 return s;
5116}
5117
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005118static void bc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005119{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005120 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005121}
5122
5123static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5124{
5125 return bc_parse_expr(p, flags, bc_parse_next_read);
5126}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005127
Gavin Howard01055ba2018-11-03 11:00:21 -06005128#endif // ENABLE_BC
5129
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005130#if ENABLE_DC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005131
5132#define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5133
Gavin Howard01055ba2018-11-03 11:00:21 -06005134static BcStatus dc_parse_register(BcParse *p)
5135{
5136 BcStatus s;
5137 char *name;
5138
5139 s = bc_lex_next(&p->l);
5140 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005141 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005142
5143 name = xstrdup(p->l.t.v.v);
5144 bc_parse_pushName(p, name);
5145
5146 return s;
5147}
5148
5149static BcStatus dc_parse_string(BcParse *p)
5150{
5151 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005152 size_t idx, len = G.prog.strs.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005153
5154 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5155 name = xstrdup(b);
5156
5157 str = xstrdup(p->l.t.v.v);
5158 bc_parse_push(p, BC_INST_STR);
5159 bc_parse_pushIndex(p, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005160 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06005161 bc_parse_addFunc(p, name, &idx);
5162
5163 return bc_lex_next(&p->l);
5164}
5165
5166static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5167{
5168 BcStatus s;
5169
5170 bc_parse_push(p, inst);
5171 if (name) {
5172 s = dc_parse_register(p);
5173 if (s) return s;
5174 }
5175
5176 if (store) {
5177 bc_parse_push(p, BC_INST_SWAP);
5178 bc_parse_push(p, BC_INST_ASSIGN);
5179 bc_parse_push(p, BC_INST_POP);
5180 }
5181
5182 return bc_lex_next(&p->l);
5183}
5184
5185static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5186{
5187 BcStatus s;
5188
5189 bc_parse_push(p, inst);
5190 bc_parse_push(p, BC_INST_EXEC_COND);
5191
5192 s = dc_parse_register(p);
5193 if (s) return s;
5194
5195 s = bc_lex_next(&p->l);
5196 if (s) return s;
5197
5198 if (p->l.t.t == BC_LEX_ELSE) {
5199 s = dc_parse_register(p);
5200 if (s) return s;
5201 s = bc_lex_next(&p->l);
5202 }
5203 else
5204 bc_parse_push(p, BC_PARSE_STREND);
5205
5206 return s;
5207}
5208
5209static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5210{
5211 BcStatus s = BC_STATUS_SUCCESS;
5212 BcInst prev;
5213 uint8_t inst;
5214 bool assign, get_token = false;
5215
5216 switch (t) {
5217
5218 case BC_LEX_OP_REL_EQ:
5219 case BC_LEX_OP_REL_LE:
5220 case BC_LEX_OP_REL_GE:
5221 case BC_LEX_OP_REL_NE:
5222 case BC_LEX_OP_REL_LT:
5223 case BC_LEX_OP_REL_GT:
5224 {
5225 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5226 break;
5227 }
5228
5229 case BC_LEX_SCOLON:
5230 case BC_LEX_COLON:
5231 {
5232 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5233 break;
5234 }
5235
5236 case BC_LEX_STR:
5237 {
5238 s = dc_parse_string(p);
5239 break;
5240 }
5241
5242 case BC_LEX_NEG:
5243 case BC_LEX_NUMBER:
5244 {
5245 if (t == BC_LEX_NEG) {
5246 s = bc_lex_next(&p->l);
5247 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005248 if (p->l.t.t != BC_LEX_NUMBER)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005249 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005250 }
5251
5252 bc_parse_number(p, &prev, &p->nbraces);
5253
5254 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5255 get_token = true;
5256
5257 break;
5258 }
5259
5260 case BC_LEX_KEY_READ:
5261 {
5262 if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005263 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005264 else
5265 bc_parse_push(p, BC_INST_READ);
5266 get_token = true;
5267 break;
5268 }
5269
5270 case BC_LEX_OP_ASSIGN:
5271 case BC_LEX_STORE_PUSH:
5272 {
5273 assign = t == BC_LEX_OP_ASSIGN;
5274 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5275 s = dc_parse_mem(p, inst, true, assign);
5276 break;
5277 }
5278
5279 case BC_LEX_LOAD:
5280 case BC_LEX_LOAD_POP:
5281 {
5282 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5283 s = dc_parse_mem(p, inst, true, false);
5284 break;
5285 }
5286
5287 case BC_LEX_STORE_IBASE:
5288 case BC_LEX_STORE_SCALE:
5289 case BC_LEX_STORE_OBASE:
5290 {
5291 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5292 s = dc_parse_mem(p, inst, false, true);
5293 break;
5294 }
5295
5296 default:
5297 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005298 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005299 get_token = true;
5300 break;
5301 }
5302 }
5303
5304 if (!s && get_token) s = bc_lex_next(&p->l);
5305
5306 return s;
5307}
5308
5309static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5310{
5311 BcStatus s = BC_STATUS_SUCCESS;
5312 BcInst inst;
5313 BcLexType t;
5314
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005315 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005316
5317 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5318
5319 inst = dc_parse_insts[t];
5320
5321 if (inst != BC_INST_INVALID) {
5322 bc_parse_push(p, inst);
5323 s = bc_lex_next(&p->l);
5324 }
5325 else
5326 s = dc_parse_token(p, t, flags);
5327 }
5328
5329 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5330 bc_parse_push(p, BC_INST_POP_EXEC);
5331
5332 return s;
5333}
5334
5335static BcStatus dc_parse_parse(BcParse *p)
5336{
5337 BcStatus s;
5338
5339 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005340 s = bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06005341 else
5342 s = dc_parse_expr(p, 0);
5343
Denys Vlasenkod38af482018-12-04 19:11:02 +01005344 if (s || G_interrupt) {
5345 bc_parse_reset(p);
5346 s = BC_STATUS_FAILURE;
5347 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005348
5349 return s;
5350}
5351
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005352static void dc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005353{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005354 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005355}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005356
Gavin Howard01055ba2018-11-03 11:00:21 -06005357#endif // ENABLE_DC
5358
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005359static void common_parse_init(BcParse *p, size_t func)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005360{
5361 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005362 IF_BC(bc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005363 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005364 IF_DC(dc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005365 }
5366}
5367
5368static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5369{
5370 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005371 IF_BC(return bc_parse_expression(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005372 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005373 IF_DC(return dc_parse_expr(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005374 }
5375}
5376
Denys Vlasenkodf515392018-12-02 19:27:48 +01005377static BcVec* bc_program_search(char *id, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005378{
Gavin Howard01055ba2018-11-03 11:00:21 -06005379 BcId e, *ptr;
5380 BcVec *v, *map;
5381 size_t i;
5382 BcResultData data;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005383 int new;
Gavin Howard01055ba2018-11-03 11:00:21 -06005384
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005385 v = var ? &G.prog.vars : &G.prog.arrs;
5386 map = var ? &G.prog.var_map : &G.prog.arr_map;
Gavin Howard01055ba2018-11-03 11:00:21 -06005387
5388 e.name = id;
5389 e.idx = v->len;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005390 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
Gavin Howard01055ba2018-11-03 11:00:21 -06005391
5392 if (new) {
5393 bc_array_init(&data.v, var);
5394 bc_vec_push(v, &data.v);
5395 }
5396
5397 ptr = bc_vec_item(map, i);
5398 if (new) ptr->name = xstrdup(e.name);
Denys Vlasenkodf515392018-12-02 19:27:48 +01005399 return bc_vec_item(v, ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005400}
5401
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005402static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
Gavin Howard01055ba2018-11-03 11:00:21 -06005403{
5404 BcStatus s = BC_STATUS_SUCCESS;
5405
5406 switch (r->t) {
5407
5408 case BC_RESULT_STR:
5409 case BC_RESULT_TEMP:
5410 case BC_RESULT_IBASE:
5411 case BC_RESULT_SCALE:
5412 case BC_RESULT_OBASE:
5413 {
5414 *num = &r->d.n;
5415 break;
5416 }
5417
5418 case BC_RESULT_CONSTANT:
5419 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005420 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005421 size_t base_t, len = strlen(*str);
5422 BcNum *base;
5423
5424 bc_num_init(&r->d.n, len);
5425
5426 hex = hex && len == 1;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005427 base = hex ? &G.prog.hexb : &G.prog.ib;
5428 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005429 s = bc_num_parse(&r->d.n, *str, base, base_t);
5430
5431 if (s) {
5432 bc_num_free(&r->d.n);
5433 return s;
5434 }
5435
5436 *num = &r->d.n;
5437 r->t = BC_RESULT_TEMP;
5438
5439 break;
5440 }
5441
5442 case BC_RESULT_VAR:
5443 case BC_RESULT_ARRAY:
5444 case BC_RESULT_ARRAY_ELEM:
5445 {
5446 BcVec *v;
5447
Denys Vlasenkodf515392018-12-02 19:27:48 +01005448 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
Gavin Howard01055ba2018-11-03 11:00:21 -06005449
5450 if (r->t == BC_RESULT_ARRAY_ELEM) {
5451 v = bc_vec_top(v);
5452 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5453 *num = bc_vec_item(v, r->d.id.idx);
5454 }
5455 else
5456 *num = bc_vec_top(v);
5457
5458 break;
5459 }
5460
5461 case BC_RESULT_LAST:
5462 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005463 *num = &G.prog.last;
Gavin Howard01055ba2018-11-03 11:00:21 -06005464 break;
5465 }
5466
5467 case BC_RESULT_ONE:
5468 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005469 *num = &G.prog.one;
Gavin Howard01055ba2018-11-03 11:00:21 -06005470 break;
5471 }
5472 }
5473
5474 return s;
5475}
5476
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005477static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
Gavin Howard01055ba2018-11-03 11:00:21 -06005478 BcResult **r, BcNum **rn, bool assign)
5479{
5480 BcStatus s;
5481 bool hex;
5482 BcResultType lt, rt;
5483
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005484 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005485 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005486
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005487 *r = bc_vec_item_rev(&G.prog.results, 0);
5488 *l = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06005489
5490 lt = (*l)->t;
5491 rt = (*r)->t;
5492 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5493
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005494 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005495 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005496 s = bc_program_num(*r, rn, hex);
Gavin Howard01055ba2018-11-03 11:00:21 -06005497 if (s) return s;
5498
5499 // We run this again under these conditions in case any vector has been
5500 // reallocated out from under the BcNums or arrays we had.
5501 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005502 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005503 if (s) return s;
5504 }
5505
5506 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005507 return bc_error_variable_is_wrong_type();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005508 if (!assign && !BC_PROG_NUM((*r), (*ln)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005509 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005510
Gavin Howard01055ba2018-11-03 11:00:21 -06005511 return s;
5512}
5513
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005514static void bc_program_binOpRetire(BcResult *r)
Gavin Howard01055ba2018-11-03 11:00:21 -06005515{
5516 r->t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005517 bc_vec_pop(&G.prog.results);
5518 bc_vec_pop(&G.prog.results);
5519 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005520}
5521
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005522static BcStatus bc_program_prep(BcResult **r, BcNum **n)
Gavin Howard01055ba2018-11-03 11:00:21 -06005523{
5524 BcStatus s;
5525
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005526 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005527 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005528 *r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005529
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005530 s = bc_program_num(*r, n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005531 if (s) return s;
5532
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005533 if (!BC_PROG_NUM((*r), (*n)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005534 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005535
5536 return s;
5537}
5538
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005539static void bc_program_retire(BcResult *r, BcResultType t)
Gavin Howard01055ba2018-11-03 11:00:21 -06005540{
5541 r->t = t;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005542 bc_vec_pop(&G.prog.results);
5543 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005544}
5545
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005546static BcStatus bc_program_op(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005547{
5548 BcStatus s;
5549 BcResult *opd1, *opd2, res;
5550 BcNum *n1, *n2 = NULL;
5551
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005552 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005553 if (s) return s;
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01005554 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06005555
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005556 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005557 if (s) goto err;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005558 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005559
5560 return s;
5561
5562err:
5563 bc_num_free(&res.d.n);
5564 return s;
5565}
5566
Denys Vlasenko785e4b32018-12-02 17:18:52 +01005567static BcStatus bc_program_read(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005568{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005569 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005570 BcStatus s;
5571 BcParse parse;
5572 BcVec buf;
5573 BcInstPtr ip;
5574 size_t i;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005575 BcFunc *f = bc_program_func(BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005576
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005577 for (i = 0; i < G.prog.stack.len; ++i) {
5578 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005579 if (ip_ptr->func == BC_PROG_READ)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005580 return bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005581 }
5582
Denys Vlasenko7d628012018-12-04 21:46:47 +01005583 bc_vec_pop_all(&f->code);
5584 bc_char_vec_init(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005585
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005586 sv_file = G.prog.file;
5587 G.prog.file = NULL;
5588
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01005589 s = bc_read_line(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005590 if (s) goto io_err;
5591
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005592 common_parse_init(&parse, BC_PROG_READ);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005593 bc_lex_file(&parse.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005594
5595 s = bc_parse_text(&parse, buf.v);
5596 if (s) goto exec_err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005597 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
Gavin Howard01055ba2018-11-03 11:00:21 -06005598 if (s) goto exec_err;
5599
5600 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005601 s = bc_error("bad read() expression");
Gavin Howard01055ba2018-11-03 11:00:21 -06005602 goto exec_err;
5603 }
5604
5605 ip.func = BC_PROG_READ;
5606 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005607 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005608
5609 // Update this pointer, just in case.
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005610 f = bc_program_func(BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005611
5612 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005613 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06005614
5615exec_err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005616 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005617 bc_parse_free(&parse);
5618io_err:
5619 bc_vec_free(&buf);
5620 return s;
5621}
5622
5623static size_t bc_program_index(char *code, size_t *bgn)
5624{
5625 char amt = code[(*bgn)++], i = 0;
5626 size_t res = 0;
5627
5628 for (; i < amt; ++i, ++(*bgn))
5629 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5630
5631 return res;
5632}
5633
5634static char *bc_program_name(char *code, size_t *bgn)
5635{
5636 size_t i;
5637 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5638
5639 s = xmalloc(ptr - str + 1);
5640 c = code[(*bgn)++];
5641
5642 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5643 s[i] = c;
5644
5645 s[i] = '\0';
5646
5647 return s;
5648}
5649
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005650static void bc_program_printString(const char *str)
Gavin Howard01055ba2018-11-03 11:00:21 -06005651{
5652 size_t i, len = strlen(str);
5653
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005654#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005655 if (len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005656 bb_putchar('\0');
Gavin Howard01055ba2018-11-03 11:00:21 -06005657 return;
5658 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005659#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005660
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005661 for (i = 0; i < len; ++i, ++G.prog.nchars) {
Gavin Howard01055ba2018-11-03 11:00:21 -06005662
5663 int c = str[i];
5664
5665 if (c != '\\' || i == len - 1)
Denys Vlasenko00d77792018-11-30 23:13:42 +01005666 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005667 else {
5668
5669 c = str[++i];
5670
5671 switch (c) {
5672
5673 case 'a':
5674 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005675 bb_putchar('\a');
Gavin Howard01055ba2018-11-03 11:00:21 -06005676 break;
5677 }
5678
5679 case 'b':
5680 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005681 bb_putchar('\b');
Gavin Howard01055ba2018-11-03 11:00:21 -06005682 break;
5683 }
5684
5685 case '\\':
5686 case 'e':
5687 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005688 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005689 break;
5690 }
5691
5692 case 'f':
5693 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005694 bb_putchar('\f');
Gavin Howard01055ba2018-11-03 11:00:21 -06005695 break;
5696 }
5697
5698 case 'n':
5699 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005700 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005701 G.prog.nchars = SIZE_MAX;
Gavin Howard01055ba2018-11-03 11:00:21 -06005702 break;
5703 }
5704
5705 case 'r':
5706 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005707 bb_putchar('\r');
Gavin Howard01055ba2018-11-03 11:00:21 -06005708 break;
5709 }
5710
5711 case 'q':
5712 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005713 bb_putchar('"');
Gavin Howard01055ba2018-11-03 11:00:21 -06005714 break;
5715 }
5716
5717 case 't':
5718 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005719 bb_putchar('\t');
Gavin Howard01055ba2018-11-03 11:00:21 -06005720 break;
5721 }
5722
5723 default:
5724 {
5725 // Just print the backslash and following character.
Denys Vlasenko00d77792018-11-30 23:13:42 +01005726 bb_putchar('\\');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005727 ++G.prog.nchars;
Denys Vlasenko00d77792018-11-30 23:13:42 +01005728 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005729 break;
5730 }
5731 }
5732 }
5733 }
5734}
5735
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005736static BcStatus bc_program_print(char inst, size_t idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005737{
5738 BcStatus s = BC_STATUS_SUCCESS;
5739 BcResult *r;
5740 size_t len, i;
5741 char *str;
5742 BcNum *num = NULL;
5743 bool pop = inst != BC_INST_PRINT;
5744
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005745 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005746 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005747
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005748 r = bc_vec_item_rev(&G.prog.results, idx);
5749 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005750 if (s) return s;
5751
5752 if (BC_PROG_NUM(r, num)) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005753 s = bc_num_print(num, !pop);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005754 if (!s) bc_num_copy(&G.prog.last, num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005755 }
5756 else {
5757
5758 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005759 str = *bc_program_str(idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005760
5761 if (inst == BC_INST_PRINT_STR) {
5762 for (i = 0, len = strlen(str); i < len; ++i) {
5763 char c = str[i];
Denys Vlasenko00d77792018-11-30 23:13:42 +01005764 bb_putchar(c);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005765 if (c == '\n') G.prog.nchars = SIZE_MAX;
5766 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06005767 }
5768 }
5769 else {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005770 bc_program_printString(str);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005771 if (inst == BC_INST_PRINT) bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005772 }
5773 }
5774
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005775 if (!s && pop) bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005776
5777 return s;
5778}
5779
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005780static BcStatus bc_program_negate(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005781{
5782 BcStatus s;
5783 BcResult res, *ptr;
5784 BcNum *num = NULL;
5785
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005786 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005787 if (s) return s;
5788
5789 bc_num_init(&res.d.n, num->len);
5790 bc_num_copy(&res.d.n, num);
5791 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5792
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005793 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06005794
5795 return s;
5796}
5797
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005798static BcStatus bc_program_logical(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005799{
5800 BcStatus s;
5801 BcResult *opd1, *opd2, res;
5802 BcNum *n1, *n2;
5803 bool cond = 0;
5804 ssize_t cmp;
5805
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005806 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005807 if (s) return s;
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01005808 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06005809
5810 if (inst == BC_INST_BOOL_AND)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005811 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005812 else if (inst == BC_INST_BOOL_OR)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005813 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005814 else {
5815
5816 cmp = bc_num_cmp(n1, n2);
5817
5818 switch (inst) {
5819
5820 case BC_INST_REL_EQ:
5821 {
5822 cond = cmp == 0;
5823 break;
5824 }
5825
5826 case BC_INST_REL_LE:
5827 {
5828 cond = cmp <= 0;
5829 break;
5830 }
5831
5832 case BC_INST_REL_GE:
5833 {
5834 cond = cmp >= 0;
5835 break;
5836 }
5837
5838 case BC_INST_REL_NE:
5839 {
5840 cond = cmp != 0;
5841 break;
5842 }
5843
5844 case BC_INST_REL_LT:
5845 {
5846 cond = cmp < 0;
5847 break;
5848 }
5849
5850 case BC_INST_REL_GT:
5851 {
5852 cond = cmp > 0;
5853 break;
5854 }
5855 }
5856 }
5857
5858 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5859
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005860 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005861
5862 return s;
5863}
5864
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005865#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005866static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
Gavin Howard01055ba2018-11-03 11:00:21 -06005867 bool push)
5868{
5869 BcNum n2;
5870 BcResult res;
5871
5872 memset(&n2, 0, sizeof(BcNum));
5873 n2.rdx = res.d.id.idx = r->d.id.idx;
5874 res.t = BC_RESULT_STR;
5875
5876 if (!push) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005877 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005878 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005879 bc_vec_pop(v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005880 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005881 }
5882
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005883 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005884
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005885 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005886 bc_vec_push(v, &n2);
5887
5888 return BC_STATUS_SUCCESS;
5889}
5890#endif // ENABLE_DC
5891
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005892static BcStatus bc_program_copyToVar(char *name, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005893{
5894 BcStatus s;
5895 BcResult *ptr, r;
5896 BcVec *v;
5897 BcNum *n;
5898
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005899 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005900 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005901
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005902 ptr = bc_vec_top(&G.prog.results);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005903 if ((ptr->t == BC_RESULT_ARRAY) != !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005904 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005905 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005906
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005907#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005908 if (ptr->t == BC_RESULT_STR && !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005909 return bc_error_variable_is_wrong_type();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005910 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005911#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005912
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005913 s = bc_program_num(ptr, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005914 if (s) return s;
5915
5916 // Do this once more to make sure that pointers were not invalidated.
Denys Vlasenkodf515392018-12-02 19:27:48 +01005917 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005918
5919 if (var) {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01005920 bc_num_init_DEF_SIZE(&r.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06005921 bc_num_copy(&r.d.n, n);
5922 }
5923 else {
5924 bc_array_init(&r.d.v, true);
5925 bc_array_copy(&r.d.v, (BcVec *) n);
5926 }
5927
5928 bc_vec_push(v, &r.d);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005929 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005930
5931 return s;
5932}
5933
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005934static BcStatus bc_program_assign(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005935{
5936 BcStatus s;
5937 BcResult *left, *right, res;
5938 BcNum *l = NULL, *r = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06005939 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5940
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005941 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
Gavin Howard01055ba2018-11-03 11:00:21 -06005942 if (s) return s;
5943
5944 ib = left->t == BC_RESULT_IBASE;
5945 sc = left->t == BC_RESULT_SCALE;
5946
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005947#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005948
5949 if (right->t == BC_RESULT_STR) {
5950
5951 BcVec *v;
5952
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005953 if (left->t != BC_RESULT_VAR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005954 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005955 v = bc_program_search(left->d.id.name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06005956
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005957 return bc_program_assignStr(right, v, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005958 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005959#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005960
5961 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005962 return bc_error("bad assignment:"
5963 " left side must be scale,"
5964 " ibase, obase, last, var,"
5965 " or array element"
5966 );
Gavin Howard01055ba2018-11-03 11:00:21 -06005967
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005968#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005969 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005970 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06005971
5972 if (assign)
5973 bc_num_copy(l, r);
5974 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005975 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005976
5977 if (s) return s;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005978#else
Gavin Howard01055ba2018-11-03 11:00:21 -06005979 bc_num_copy(l, r);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005980#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005981
5982 if (ib || sc || left->t == BC_RESULT_OBASE) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005983 static const char *const msg[] = {
Denys Vlasenko64074a12018-12-07 15:50:14 +01005984 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5985 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5986 NULL, //can't happen //BC_RESULT_LAST
5987 NULL, //can't happen //BC_RESULT_CONSTANT
5988 NULL, //can't happen //BC_RESULT_ONE
5989 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005990 };
Gavin Howard01055ba2018-11-03 11:00:21 -06005991 size_t *ptr;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01005992 unsigned long val, max;
Gavin Howard01055ba2018-11-03 11:00:21 -06005993
5994 s = bc_num_ulong(l, &val);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005995 if (s)
5996 return s;
5997 s = left->t - BC_RESULT_IBASE;
Gavin Howard01055ba2018-11-03 11:00:21 -06005998 if (sc) {
5999 max = BC_MAX_SCALE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006000 ptr = &G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006001 }
6002 else {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006003 if (val < BC_NUM_MIN_BASE)
6004 return bc_error(msg[s]);
Gavin Howard01055ba2018-11-03 11:00:21 -06006005 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006006 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006007 }
6008
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006009 if (val > max)
6010 return bc_error(msg[s]);
6011 if (!sc)
6012 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
Gavin Howard01055ba2018-11-03 11:00:21 -06006013
6014 *ptr = (size_t) val;
6015 s = BC_STATUS_SUCCESS;
6016 }
6017
6018 bc_num_init(&res.d.n, l->len);
6019 bc_num_copy(&res.d.n, l);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006020 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006021
6022 return s;
6023}
6024
Denys Vlasenko416ce762018-12-02 20:57:17 +01006025#if !ENABLE_DC
6026#define bc_program_pushVar(code, bgn, pop, copy) \
6027 bc_program_pushVar(code, bgn)
6028// for bc, 'pop' and 'copy' are always false
6029#endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006030static BcStatus bc_program_pushVar(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006031 bool pop, bool copy)
6032{
6033 BcStatus s = BC_STATUS_SUCCESS;
6034 BcResult r;
6035 char *name = bc_program_name(code, bgn);
Gavin Howard01055ba2018-11-03 11:00:21 -06006036
6037 r.t = BC_RESULT_VAR;
6038 r.d.id.name = name;
6039
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006040#if ENABLE_DC
Denys Vlasenko416ce762018-12-02 20:57:17 +01006041 {
6042 BcVec *v = bc_program_search(name, true);
6043 BcNum *num = bc_vec_top(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006044
Denys Vlasenko416ce762018-12-02 20:57:17 +01006045 if (pop || copy) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006046
Denys Vlasenko416ce762018-12-02 20:57:17 +01006047 if (!BC_PROG_STACK(v, 2 - copy)) {
6048 free(name);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006049 return bc_error_stack_has_too_few_elements();
Denys Vlasenko416ce762018-12-02 20:57:17 +01006050 }
6051
Gavin Howard01055ba2018-11-03 11:00:21 -06006052 free(name);
Denys Vlasenko416ce762018-12-02 20:57:17 +01006053 name = NULL;
6054
6055 if (!BC_PROG_STR(num)) {
6056
6057 r.t = BC_RESULT_TEMP;
6058
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006059 bc_num_init_DEF_SIZE(&r.d.n);
Denys Vlasenko416ce762018-12-02 20:57:17 +01006060 bc_num_copy(&r.d.n, num);
6061 }
6062 else {
6063 r.t = BC_RESULT_STR;
6064 r.d.id.idx = num->rdx;
6065 }
6066
6067 if (!copy) bc_vec_pop(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006068 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006069 }
6070#endif // ENABLE_DC
6071
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006072 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006073
6074 return s;
6075}
6076
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006077static BcStatus bc_program_pushArray(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006078 char inst)
6079{
6080 BcStatus s = BC_STATUS_SUCCESS;
6081 BcResult r;
6082 BcNum *num;
6083
6084 r.d.id.name = bc_program_name(code, bgn);
6085
6086 if (inst == BC_INST_ARRAY) {
6087 r.t = BC_RESULT_ARRAY;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006088 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006089 }
6090 else {
6091
6092 BcResult *operand;
6093 unsigned long temp;
6094
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006095 s = bc_program_prep(&operand, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006096 if (s) goto err;
6097 s = bc_num_ulong(num, &temp);
6098 if (s) goto err;
6099
6100 if (temp > BC_MAX_DIM) {
Denys Vlasenko64074a12018-12-07 15:50:14 +01006101 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
Gavin Howard01055ba2018-11-03 11:00:21 -06006102 goto err;
6103 }
6104
6105 r.d.id.idx = (size_t) temp;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006106 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
Gavin Howard01055ba2018-11-03 11:00:21 -06006107 }
6108
6109err:
6110 if (s) free(r.d.id.name);
6111 return s;
6112}
6113
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006114#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006115static BcStatus bc_program_incdec(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006116{
6117 BcStatus s;
6118 BcResult *ptr, res, copy;
6119 BcNum *num = NULL;
6120 char inst2 = inst;
6121
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006122 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006123 if (s) return s;
6124
6125 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6126 copy.t = BC_RESULT_TEMP;
6127 bc_num_init(&copy.d.n, num->len);
6128 bc_num_copy(&copy.d.n, num);
6129 }
6130
6131 res.t = BC_RESULT_ONE;
6132 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6133 BC_INST_ASSIGN_PLUS :
6134 BC_INST_ASSIGN_MINUS;
6135
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006136 bc_vec_push(&G.prog.results, &res);
6137 bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006138
6139 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006140 bc_vec_pop(&G.prog.results);
6141 bc_vec_push(&G.prog.results, &copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006142 }
6143
6144 return s;
6145}
6146
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006147static BcStatus bc_program_call(char *code, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006148{
6149 BcStatus s = BC_STATUS_SUCCESS;
6150 BcInstPtr ip;
6151 size_t i, nparams = bc_program_index(code, idx);
6152 BcFunc *func;
Gavin Howard01055ba2018-11-03 11:00:21 -06006153 BcId *a;
6154 BcResultData param;
6155 BcResult *arg;
6156
6157 ip.idx = 0;
6158 ip.func = bc_program_index(code, idx);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006159 func = bc_program_func(ip.func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006160
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006161 if (func->code.len == 0) {
6162 return bc_error("undefined function");
6163 }
6164 if (nparams != func->nparams) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006165 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006166 }
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006167 ip.len = G.prog.results.len - nparams;
Gavin Howard01055ba2018-11-03 11:00:21 -06006168
6169 for (i = 0; i < nparams; ++i) {
6170
6171 a = bc_vec_item(&func->autos, nparams - 1 - i);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006172 arg = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006173
6174 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006175 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006176
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006177 s = bc_program_copyToVar(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006178 if (s) return s;
6179 }
6180
6181 for (; i < func->autos.len; ++i) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006182 BcVec *v;
Gavin Howard01055ba2018-11-03 11:00:21 -06006183
6184 a = bc_vec_item(&func->autos, i);
Denys Vlasenkodf515392018-12-02 19:27:48 +01006185 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006186
6187 if (a->idx) {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006188 bc_num_init_DEF_SIZE(&param.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006189 bc_vec_push(v, &param.n);
6190 }
6191 else {
6192 bc_array_init(&param.v, true);
6193 bc_vec_push(v, &param.v);
6194 }
6195 }
6196
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006197 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006198
6199 return BC_STATUS_SUCCESS;
6200}
6201
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006202static BcStatus bc_program_return(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006203{
6204 BcStatus s;
6205 BcResult res;
6206 BcFunc *f;
6207 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006208 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006209
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006210 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006211 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006212
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006213 f = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006214 res.t = BC_RESULT_TEMP;
6215
6216 if (inst == BC_INST_RET) {
6217
6218 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006219 BcResult *operand = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006220
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006221 s = bc_program_num(operand, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006222 if (s) return s;
6223 bc_num_init(&res.d.n, num->len);
6224 bc_num_copy(&res.d.n, num);
6225 }
6226 else {
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006227 bc_num_init_DEF_SIZE(&res.d.n);
Denys Vlasenko3129f702018-12-09 12:04:44 +01006228 //bc_num_zero(&res.d.n); - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06006229 }
6230
6231 // We need to pop arguments as well, so this takes that into account.
6232 for (i = 0; i < f->autos.len; ++i) {
6233
6234 BcVec *v;
6235 BcId *a = bc_vec_item(&f->autos, i);
6236
Denys Vlasenkodf515392018-12-02 19:27:48 +01006237 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006238 bc_vec_pop(v);
6239 }
6240
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006241 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6242 bc_vec_push(&G.prog.results, &res);
6243 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006244
6245 return BC_STATUS_SUCCESS;
6246}
6247#endif // ENABLE_BC
6248
6249static unsigned long bc_program_scale(BcNum *n)
6250{
6251 return (unsigned long) n->rdx;
6252}
6253
6254static unsigned long bc_program_len(BcNum *n)
6255{
6256 unsigned long len = n->len;
6257 size_t i;
6258
6259 if (n->rdx != n->len) return len;
6260 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6261
6262 return len;
6263}
6264
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006265static BcStatus bc_program_builtin(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006266{
6267 BcStatus s;
6268 BcResult *opnd;
6269 BcNum *num = NULL;
6270 BcResult res;
6271 bool len = inst == BC_INST_LENGTH;
6272
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006273 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006274 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006275 opnd = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006276
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006277 s = bc_program_num(opnd, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006278 if (s) return s;
6279
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006280#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006281 if (!BC_PROG_NUM(opnd, num) && !len)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006282 return bc_error_variable_is_wrong_type();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006283#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006284
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006285 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006286
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006287 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006288#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006289 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006290 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006291 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006292#endif
6293#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006294 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6295
6296 char **str;
6297 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6298
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006299 str = bc_program_str(idx);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006300 bc_num_ulong2num(&res.d.n, strlen(*str));
Gavin Howard01055ba2018-11-03 11:00:21 -06006301 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006302#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006303 else {
6304 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006305 bc_num_ulong2num(&res.d.n, f(num));
Gavin Howard01055ba2018-11-03 11:00:21 -06006306 }
6307
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006308 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006309
6310 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006311}
6312
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006313#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006314static BcStatus bc_program_divmod(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006315{
6316 BcStatus s;
6317 BcResult *opd1, *opd2, res, res2;
6318 BcNum *n1, *n2 = NULL;
6319
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006320 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006321 if (s) return s;
6322
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006323 bc_num_init_DEF_SIZE(&res.d.n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006324 bc_num_init(&res2.d.n, n2->len);
6325
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006326 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006327 if (s) goto err;
6328
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006329 bc_program_binOpRetire(&res2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006330 res.t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006331 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006332
6333 return s;
6334
6335err:
6336 bc_num_free(&res2.d.n);
6337 bc_num_free(&res.d.n);
6338 return s;
6339}
6340
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006341static BcStatus bc_program_modexp(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006342{
6343 BcStatus s;
6344 BcResult *r1, *r2, *r3, res;
6345 BcNum *n1, *n2, *n3;
6346
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006347 if (!BC_PROG_STACK(&G.prog.results, 3))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006348 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006349 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006350 if (s) return s;
6351
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006352 r1 = bc_vec_item_rev(&G.prog.results, 2);
6353 s = bc_program_num(r1, &n1, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006354 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006355 if (!BC_PROG_NUM(r1, n1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006356 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006357
6358 // Make sure that the values have their pointers updated, if necessary.
6359 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6360
6361 if (r1->t == r2->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006362 s = bc_program_num(r2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006363 if (s) return s;
6364 }
6365
6366 if (r1->t == r3->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006367 s = bc_program_num(r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006368 if (s) return s;
6369 }
6370 }
6371
6372 bc_num_init(&res.d.n, n3->len);
6373 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6374 if (s) goto err;
6375
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006376 bc_vec_pop(&G.prog.results);
6377 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006378
6379 return s;
6380
6381err:
6382 bc_num_free(&res.d.n);
6383 return s;
6384}
6385
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006386static void bc_program_stackLen(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006387{
Gavin Howard01055ba2018-11-03 11:00:21 -06006388 BcResult res;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006389 size_t len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006390
6391 res.t = BC_RESULT_TEMP;
6392
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006393 bc_num_init_DEF_SIZE(&res.d.n);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006394 bc_num_ulong2num(&res.d.n, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006395 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006396}
6397
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006398static BcStatus bc_program_asciify(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006399{
6400 BcStatus s;
6401 BcResult *r, res;
Denys Vlasenko4a024c72018-12-09 13:21:54 +01006402 BcNum *num, n;
Gavin Howard01055ba2018-11-03 11:00:21 -06006403 char *str, *str2, c;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006404 size_t len = G.prog.strs.len, idx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006405 unsigned long val;
6406
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006407 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006408 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006409 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006410
Denys Vlasenko4a024c72018-12-09 13:21:54 +01006411 num = NULL; // TODO: is this NULL needed?
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006412 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006413 if (s) return s;
6414
6415 if (BC_PROG_NUM(r, num)) {
6416
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006417 bc_num_init_DEF_SIZE(&n);
Gavin Howard01055ba2018-11-03 11:00:21 -06006418 bc_num_copy(&n, num);
6419 bc_num_truncate(&n, n.rdx);
6420
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006421 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006422 if (s) goto num_err;
6423 s = bc_num_ulong(&n, &val);
6424 if (s) goto num_err;
6425
6426 c = (char) val;
6427
6428 bc_num_free(&n);
6429 }
6430 else {
6431 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006432 str2 = *bc_program_str(idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006433 c = str2[0];
6434 }
6435
6436 str = xmalloc(2);
6437 str[0] = c;
6438 str[1] = '\0';
6439
6440 str2 = xstrdup(str);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006441 bc_program_addFunc(str2, &idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006442
6443 if (idx != len + BC_PROG_REQ_FUNCS) {
6444
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006445 for (idx = 0; idx < G.prog.strs.len; ++idx) {
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006446 if (strcmp(*bc_program_str(idx), str) == 0) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006447 len = idx;
6448 break;
6449 }
6450 }
6451
6452 free(str);
6453 }
6454 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006455 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006456
6457 res.t = BC_RESULT_STR;
6458 res.d.id.idx = len;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006459 bc_vec_pop(&G.prog.results);
6460 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006461
6462 return BC_STATUS_SUCCESS;
6463
6464num_err:
6465 bc_num_free(&n);
6466 return s;
6467}
6468
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006469static BcStatus bc_program_printStream(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006470{
6471 BcStatus s;
6472 BcResult *r;
6473 BcNum *n = NULL;
6474 size_t idx;
6475 char *str;
6476
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006477 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006478 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006479 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006480
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006481 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006482 if (s) return s;
6483
6484 if (BC_PROG_NUM(r, n))
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01006485 s = bc_num_stream(n, &G.prog.strmb);
Gavin Howard01055ba2018-11-03 11:00:21 -06006486 else {
6487 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006488 str = *bc_program_str(idx);
Denys Vlasenko00d77792018-11-30 23:13:42 +01006489 printf("%s", str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006490 }
6491
6492 return s;
6493}
6494
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006495static BcStatus bc_program_nquit(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006496{
6497 BcStatus s;
6498 BcResult *opnd;
6499 BcNum *num = NULL;
6500 unsigned long val;
6501
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006502 s = bc_program_prep(&opnd, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006503 if (s) return s;
6504 s = bc_num_ulong(num, &val);
6505 if (s) return s;
6506
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006507 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006508
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006509 if (G.prog.stack.len < val)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006510 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006511 if (G.prog.stack.len == val) {
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006512 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006513 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006514
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006515 bc_vec_npop(&G.prog.stack, val);
Gavin Howard01055ba2018-11-03 11:00:21 -06006516
6517 return s;
6518}
6519
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006520static BcStatus bc_program_execStr(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006521 bool cond)
6522{
6523 BcStatus s = BC_STATUS_SUCCESS;
6524 BcResult *r;
6525 char **str;
6526 BcFunc *f;
6527 BcParse prs;
6528 BcInstPtr ip;
6529 size_t fidx, sidx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006530
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006531 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006532 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006533
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006534 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006535
6536 if (cond) {
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006537 BcNum *n = n; // for compiler
6538 bool exec;
6539 char *name;
6540 char *then_name = bc_program_name(code, bgn);
6541 char *else_name = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06006542
6543 if (code[*bgn] == BC_PARSE_STREND)
6544 (*bgn) += 1;
6545 else
6546 else_name = bc_program_name(code, bgn);
6547
6548 exec = r->d.n.len != 0;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006549 name = then_name;
6550 if (!exec && else_name != NULL) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006551 exec = true;
6552 name = else_name;
6553 }
6554
6555 if (exec) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006556 BcVec *v;
6557 v = bc_program_search(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006558 n = bc_vec_top(v);
6559 }
6560
6561 free(then_name);
6562 free(else_name);
6563
6564 if (!exec) goto exit;
6565 if (!BC_PROG_STR(n)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006566 s = bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006567 goto exit;
6568 }
6569
6570 sidx = n->rdx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006571 } else {
6572 if (r->t == BC_RESULT_STR) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006573 sidx = r->d.id.idx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006574 } else if (r->t == BC_RESULT_VAR) {
6575 BcNum *n;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006576 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006577 if (s || !BC_PROG_STR(n)) goto exit;
6578 sidx = n->rdx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006579 } else
Gavin Howard01055ba2018-11-03 11:00:21 -06006580 goto exit;
6581 }
6582
6583 fidx = sidx + BC_PROG_REQ_FUNCS;
6584
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006585 str = bc_program_str(sidx);
6586 f = bc_program_func(fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006587
6588 if (f->code.len == 0) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006589 common_parse_init(&prs, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006590 s = bc_parse_text(&prs, *str);
6591 if (s) goto err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01006592 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006593 if (s) goto err;
6594
6595 if (prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006596 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06006597 goto err;
6598 }
6599
6600 bc_parse_free(&prs);
6601 }
6602
6603 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006604 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006605 ip.func = fidx;
6606
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006607 bc_vec_pop(&G.prog.results);
6608 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006609
6610 return BC_STATUS_SUCCESS;
6611
6612err:
6613 bc_parse_free(&prs);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006614 f = bc_program_func(fidx);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006615 bc_vec_pop_all(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06006616exit:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006617 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006618 return s;
6619}
6620#endif // ENABLE_DC
6621
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006622static void bc_program_pushGlobal(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006623{
Gavin Howard01055ba2018-11-03 11:00:21 -06006624 BcResult res;
6625 unsigned long val;
6626
6627 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6628 if (inst == BC_INST_IBASE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006629 val = (unsigned long) G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006630 else if (inst == BC_INST_SCALE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006631 val = (unsigned long) G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006632 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006633 val = (unsigned long) G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006634
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006635 bc_num_init_DEF_SIZE(&res.d.n);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006636 bc_num_ulong2num(&res.d.n, val);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006637 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006638}
6639
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006640static void bc_program_addFunc(char *name, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006641{
Gavin Howard01055ba2018-11-03 11:00:21 -06006642 BcId entry, *entry_ptr;
6643 BcFunc f;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006644 int inserted;
Gavin Howard01055ba2018-11-03 11:00:21 -06006645
6646 entry.name = name;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006647 entry.idx = G.prog.fns.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006648
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006649 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6650 if (!inserted) free(name);
Gavin Howard01055ba2018-11-03 11:00:21 -06006651
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006652 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006653 *idx = entry_ptr->idx;
6654
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006655 if (!inserted) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006656
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006657 BcFunc *func = bc_program_func(entry_ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006658
6659 // We need to reset these, so the function can be repopulated.
6660 func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01006661 bc_vec_pop_all(&func->autos);
6662 bc_vec_pop_all(&func->code);
6663 bc_vec_pop_all(&func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06006664 }
6665 else {
6666 bc_func_init(&f);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006667 bc_vec_push(&G.prog.fns, &f);
Gavin Howard01055ba2018-11-03 11:00:21 -06006668 }
6669}
6670
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006671static BcStatus bc_program_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006672{
Gavin Howard01055ba2018-11-03 11:00:21 -06006673 BcResult r, *ptr;
6674 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006675 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006676 BcFunc *func = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006677 char *code = func->code.v;
6678 bool cond = false;
6679
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006680 while (ip->idx < func->code.len) {
6681 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006682 char inst = code[(ip->idx)++];
6683
6684 switch (inst) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006685#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006686 case BC_INST_JUMP_ZERO:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006687 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006688 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006689 cond = !bc_num_cmp(num, &G.prog.zero);
6690 bc_vec_pop(&G.prog.results);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006691 // Fallthrough.
6692 case BC_INST_JUMP: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006693 size_t *addr;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006694 size_t idx = bc_program_index(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006695 addr = bc_vec_item(&func->labels, idx);
6696 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6697 break;
6698 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006699 case BC_INST_CALL:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006700 s = bc_program_call(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006701 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006702 case BC_INST_INC_PRE:
6703 case BC_INST_DEC_PRE:
6704 case BC_INST_INC_POST:
6705 case BC_INST_DEC_POST:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006706 s = bc_program_incdec(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006707 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006708 case BC_INST_HALT:
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006709 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06006710 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006711 case BC_INST_RET:
6712 case BC_INST_RET0:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006713 s = bc_program_return(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006714 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006715 case BC_INST_BOOL_OR:
6716 case BC_INST_BOOL_AND:
6717#endif // ENABLE_BC
6718 case BC_INST_REL_EQ:
6719 case BC_INST_REL_LE:
6720 case BC_INST_REL_GE:
6721 case BC_INST_REL_NE:
6722 case BC_INST_REL_LT:
6723 case BC_INST_REL_GT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006724 s = bc_program_logical(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006725 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006726 case BC_INST_READ:
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006727 s = bc_program_read();
Gavin Howard01055ba2018-11-03 11:00:21 -06006728 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006729 case BC_INST_VAR:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006730 s = bc_program_pushVar(code, &ip->idx, false, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006731 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006732 case BC_INST_ARRAY_ELEM:
6733 case BC_INST_ARRAY:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006734 s = bc_program_pushArray(code, &ip->idx, inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006735 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006736 case BC_INST_LAST:
Gavin Howard01055ba2018-11-03 11:00:21 -06006737 r.t = BC_RESULT_LAST;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006738 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006739 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006740 case BC_INST_IBASE:
6741 case BC_INST_SCALE:
6742 case BC_INST_OBASE:
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006743 bc_program_pushGlobal(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006744 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006745 case BC_INST_SCALE_FUNC:
6746 case BC_INST_LENGTH:
6747 case BC_INST_SQRT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006748 s = bc_program_builtin(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006749 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006750 case BC_INST_NUM:
Gavin Howard01055ba2018-11-03 11:00:21 -06006751 r.t = BC_RESULT_CONSTANT;
6752 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006753 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006754 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006755 case BC_INST_POP:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006756 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006757 s = bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006758 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006759 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006760 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006761 case BC_INST_POP_EXEC:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006762 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006763 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006764 case BC_INST_PRINT:
6765 case BC_INST_PRINT_POP:
6766 case BC_INST_PRINT_STR:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006767 s = bc_program_print(inst, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006768 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006769 case BC_INST_STR:
Gavin Howard01055ba2018-11-03 11:00:21 -06006770 r.t = BC_RESULT_STR;
6771 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006772 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006773 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006774 case BC_INST_POWER:
6775 case BC_INST_MULTIPLY:
6776 case BC_INST_DIVIDE:
6777 case BC_INST_MODULUS:
6778 case BC_INST_PLUS:
6779 case BC_INST_MINUS:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006780 s = bc_program_op(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006781 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006782 case BC_INST_BOOL_NOT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006783 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006784 if (s) return s;
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01006785 bc_num_init_DEF_SIZE(&r.d.n);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006786 if (!bc_num_cmp(num, &G.prog.zero))
6787 bc_num_one(&r.d.n);
Denys Vlasenko3129f702018-12-09 12:04:44 +01006788 //else bc_num_zero(&r.d.n); - already is
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006789 bc_program_retire(&r, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006790 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006791 case BC_INST_NEG:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006792 s = bc_program_negate();
Gavin Howard01055ba2018-11-03 11:00:21 -06006793 break;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006794#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006795 case BC_INST_ASSIGN_POWER:
6796 case BC_INST_ASSIGN_MULTIPLY:
6797 case BC_INST_ASSIGN_DIVIDE:
6798 case BC_INST_ASSIGN_MODULUS:
6799 case BC_INST_ASSIGN_PLUS:
6800 case BC_INST_ASSIGN_MINUS:
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006801#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006802 case BC_INST_ASSIGN:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006803 s = bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006804 break;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006805#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006806 case BC_INST_MODEXP:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006807 s = bc_program_modexp();
Gavin Howard01055ba2018-11-03 11:00:21 -06006808 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006809 case BC_INST_DIVMOD:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006810 s = bc_program_divmod();
Gavin Howard01055ba2018-11-03 11:00:21 -06006811 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006812 case BC_INST_EXECUTE:
6813 case BC_INST_EXEC_COND:
Gavin Howard01055ba2018-11-03 11:00:21 -06006814 cond = inst == BC_INST_EXEC_COND;
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006815 s = bc_program_execStr(code, &ip->idx, cond);
Gavin Howard01055ba2018-11-03 11:00:21 -06006816 break;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006817 case BC_INST_PRINT_STACK: {
6818 size_t idx;
6819 for (idx = 0; idx < G.prog.results.len; ++idx) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006820 s = bc_program_print(BC_INST_PRINT, idx);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006821 if (s) break;
6822 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006823 break;
6824 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006825 case BC_INST_CLEAR_STACK:
Denys Vlasenko7d628012018-12-04 21:46:47 +01006826 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006827 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006828 case BC_INST_STACK_LEN:
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006829 bc_program_stackLen();
Gavin Howard01055ba2018-11-03 11:00:21 -06006830 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006831 case BC_INST_DUPLICATE:
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006832 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006833 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006834 ptr = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006835 bc_result_copy(&r, ptr);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006836 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006837 break;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006838 case BC_INST_SWAP: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006839 BcResult *ptr2;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006840 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006841 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006842 ptr = bc_vec_item_rev(&G.prog.results, 0);
6843 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006844 memcpy(&r, ptr, sizeof(BcResult));
6845 memcpy(ptr, ptr2, sizeof(BcResult));
6846 memcpy(ptr2, &r, sizeof(BcResult));
Gavin Howard01055ba2018-11-03 11:00:21 -06006847 break;
6848 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006849 case BC_INST_ASCIIFY:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006850 s = bc_program_asciify();
Gavin Howard01055ba2018-11-03 11:00:21 -06006851 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006852 case BC_INST_PRINT_STREAM:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006853 s = bc_program_printStream();
Gavin Howard01055ba2018-11-03 11:00:21 -06006854 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006855 case BC_INST_LOAD:
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006856 case BC_INST_PUSH_VAR: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006857 bool copy = inst == BC_INST_LOAD;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006858 s = bc_program_pushVar(code, &ip->idx, true, copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006859 break;
6860 }
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006861 case BC_INST_PUSH_TO_VAR: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006862 char *name = bc_program_name(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006863 s = bc_program_copyToVar(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006864 free(name);
6865 break;
6866 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006867 case BC_INST_QUIT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006868 if (G.prog.stack.len <= 2)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006869 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006870 bc_vec_npop(&G.prog.stack, 2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006871 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006872 case BC_INST_NQUIT:
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006873 s = bc_program_nquit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006874 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006875#endif // ENABLE_DC
6876 }
6877
Denys Vlasenkod38af482018-12-04 19:11:02 +01006878 if (s || G_interrupt) {
6879 bc_program_reset();
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006880 return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01006881 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006882
6883 // If the stack has changed, pointers may be invalid.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006884 ip = bc_vec_top(&G.prog.stack);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006885 func = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006886 code = func->code.v;
6887 }
6888
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006889 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06006890}
6891
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006892#if ENABLE_BC
Denys Vlasenko54214c32018-12-06 09:07:06 +01006893static void bc_vm_info(void)
6894{
6895 printf("%s "BB_VER"\n"
6896 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
Denys Vlasenko54214c32018-12-06 09:07:06 +01006897 , applet_name);
6898}
6899
6900static void bc_args(char **argv)
6901{
6902 unsigned opts;
6903 int i;
6904
6905 GETOPT_RESET();
6906#if ENABLE_FEATURE_BC_LONG_OPTIONS
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006907 opts = option_mask32 |= getopt32long(argv, "wvsqli",
Denys Vlasenko54214c32018-12-06 09:07:06 +01006908 "warn\0" No_argument "w"
6909 "version\0" No_argument "v"
6910 "standard\0" No_argument "s"
6911 "quiet\0" No_argument "q"
6912 "mathlib\0" No_argument "l"
6913 "interactive\0" No_argument "i"
6914 );
6915#else
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006916 opts = option_mask32 |= getopt32(argv, "wvsqli");
Denys Vlasenko54214c32018-12-06 09:07:06 +01006917#endif
6918 if (getenv("POSIXLY_CORRECT"))
6919 option_mask32 |= BC_FLAG_S;
6920
Denys Vlasenko54214c32018-12-06 09:07:06 +01006921 if (opts & BC_FLAG_V) {
6922 bc_vm_info();
6923 exit(0);
6924 }
6925
6926 for (i = optind; argv[i]; ++i)
6927 bc_vec_push(&G.files, argv + i);
6928}
6929
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006930static void bc_vm_envArgs(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006931{
Gavin Howard01055ba2018-11-03 11:00:21 -06006932 BcVec v;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006933 char *buf;
Denys Vlasenko54214c32018-12-06 09:07:06 +01006934 char *env_args = getenv("BC_ENV_ARGS");
Gavin Howard01055ba2018-11-03 11:00:21 -06006935
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01006936 if (!env_args) return;
Gavin Howard01055ba2018-11-03 11:00:21 -06006937
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006938 G.env_args = xstrdup(env_args);
6939 buf = G.env_args;
Gavin Howard01055ba2018-11-03 11:00:21 -06006940
6941 bc_vec_init(&v, sizeof(char *), NULL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006942
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006943 while (*(buf = skip_whitespace(buf)) != '\0') {
6944 bc_vec_push(&v, &buf);
6945 buf = skip_non_whitespace(buf);
6946 if (!*buf)
6947 break;
6948 *buf++ = '\0';
Gavin Howard01055ba2018-11-03 11:00:21 -06006949 }
6950
Denys Vlasenko54214c32018-12-06 09:07:06 +01006951 // NULL terminate, and pass argv[] so that first arg is argv[1]
6952 if (sizeof(int) == sizeof(char*)) {
6953 bc_vec_push(&v, &const_int_0);
6954 } else {
6955 static char *const nullptr = NULL;
6956 bc_vec_push(&v, &nullptr);
6957 }
6958 bc_args(((char **)v.v) - 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006959
6960 bc_vec_free(&v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006961}
6962#endif // ENABLE_BC
6963
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006964static unsigned bc_vm_envLen(const char *var)
Gavin Howard01055ba2018-11-03 11:00:21 -06006965{
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006966 char *lenv;
6967 unsigned len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006968
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006969 lenv = getenv(var);
6970 len = BC_NUM_PRINT_WIDTH;
Gavin Howard01055ba2018-11-03 11:00:21 -06006971 if (!lenv) return len;
6972
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006973 len = bb_strtou(lenv, NULL, 10) - 1;
6974 if (errno || len < 2 || len >= INT_MAX)
Gavin Howard01055ba2018-11-03 11:00:21 -06006975 len = BC_NUM_PRINT_WIDTH;
6976
6977 return len;
6978}
6979
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006980static BcStatus bc_vm_process(const char *text)
Gavin Howard01055ba2018-11-03 11:00:21 -06006981{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006982 BcStatus s = bc_parse_text(&G.prs, text);
Gavin Howard01055ba2018-11-03 11:00:21 -06006983
Gavin Howard01055ba2018-11-03 11:00:21 -06006984 if (s) return s;
6985
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006986 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006987 s = G.prs.parse(&G.prs);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006988 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006989 }
6990
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006991 if (BC_PARSE_CAN_EXEC(&G.prs)) {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006992 s = bc_program_exec();
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01006993 fflush_and_check();
Denys Vlasenko9b70f192018-12-04 20:51:40 +01006994 if (s)
Denys Vlasenkod38af482018-12-04 19:11:02 +01006995 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06006996 }
6997
6998 return s;
6999}
7000
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007001static BcStatus bc_vm_file(const char *file)
Gavin Howard01055ba2018-11-03 11:00:21 -06007002{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007003 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007004 char *data;
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007005 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007006 BcFunc *main_func;
7007 BcInstPtr *ip;
7008
Denys Vlasenkodf515392018-12-02 19:27:48 +01007009 data = bc_read_file(file);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007010 if (!data) return bc_error_fmt("file '%s' is not text", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007011
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007012 sv_file = G.prog.file;
7013 G.prog.file = file;
7014 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007015 s = bc_vm_process(data);
Gavin Howard01055ba2018-11-03 11:00:21 -06007016 if (s) goto err;
7017
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01007018 main_func = bc_program_func(BC_PROG_MAIN);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007019 ip = bc_vec_item(&G.prog.stack, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06007020
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007021 if (main_func->code.len < ip->idx)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007022 s = bc_error_fmt("file '%s' is not executable", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007023
7024err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007025 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007026 free(data);
7027 return s;
7028}
7029
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007030static BcStatus bc_vm_stdin(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007031{
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007032 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007033 BcVec buf, buffer;
Gavin Howard01055ba2018-11-03 11:00:21 -06007034 size_t len, i, str = 0;
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007035 bool comment = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06007036
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007037 G.prog.file = NULL;
7038 bc_lex_file(&G.prs.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06007039
Denys Vlasenko7d628012018-12-04 21:46:47 +01007040 bc_char_vec_init(&buffer);
7041 bc_char_vec_init(&buf);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01007042 bc_vec_pushZeroByte(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007043
7044 // This loop is complex because the vm tries not to send any lines that end
7045 // with a backslash to the parser. The reason for that is because the parser
7046 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7047 // case, and for strings and comments, the parser will expect more stuff.
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007048 while ((s = bc_read_line(&buf)) == BC_STATUS_SUCCESS) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007049
7050 char *string = buf.v;
7051
7052 len = buf.len - 1;
7053
7054 if (len == 1) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007055 if (str && buf.v[0] == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007056 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007057 else if (buf.v[0] == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007058 str += 1;
7059 }
7060 else if (len > 1 || comment) {
7061
7062 for (i = 0; i < len; ++i) {
7063
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007064 bool notend = len > i + 1;
7065 char c = string[i];
Gavin Howard01055ba2018-11-03 11:00:21 -06007066
7067 if (i - 1 > len || string[i - 1] != '\\') {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007068 if (G.sbgn == G.send)
7069 str ^= c == G.sbgn;
7070 else if (c == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007071 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007072 else if (c == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007073 str += 1;
7074 }
7075
7076 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7077 comment = true;
7078 break;
7079 }
7080 else if (c == '*' && notend && comment && string[i + 1] == '/')
7081 comment = false;
7082 }
7083
7084 if (str || comment || string[len - 2] == '\\') {
7085 bc_vec_concat(&buffer, buf.v);
7086 continue;
7087 }
7088 }
7089
7090 bc_vec_concat(&buffer, buf.v);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007091 s = bc_vm_process(buffer.v);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007092 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007093 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007094 // Debug config, non-interactive mode:
7095 // return all the way back to main.
7096 // Non-debug builds do not come here, they exit.
7097 break;
7098 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007099 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007100
Denys Vlasenko7d628012018-12-04 21:46:47 +01007101 bc_vec_pop_all(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007102 }
Denys Vlasenkof522dd92018-12-07 16:35:43 +01007103 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7104 s = BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06007105
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007106 if (str) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007107 s = bc_error("string end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007108 }
7109 else if (comment) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007110 s = bc_error("comment end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007111 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007112
Gavin Howard01055ba2018-11-03 11:00:21 -06007113 bc_vec_free(&buf);
7114 bc_vec_free(&buffer);
7115 return s;
7116}
7117
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007118#if ENABLE_BC
7119static const char bc_lib[] = {
7120 "scale=20"
7121"\n" "define e(x){"
7122"\n" "auto b,s,n,r,d,i,p,f,v"
7123"\n" "b=ibase"
7124"\n" "ibase=A"
7125"\n" "if(x<0){"
7126"\n" "n=1"
7127"\n" "x=-x"
7128"\n" "}"
7129"\n" "s=scale"
7130"\n" "r=6+s+0.44*x"
7131"\n" "scale=scale(x)+1"
7132"\n" "while(x>1){"
7133"\n" "d+=1"
7134"\n" "x/=2"
7135"\n" "scale+=1"
7136"\n" "}"
7137"\n" "scale=r"
7138"\n" "r=x+1"
7139"\n" "p=x"
7140"\n" "f=v=1"
7141"\n" "for(i=2;v!=0;++i){"
7142"\n" "p*=x"
7143"\n" "f*=i"
7144"\n" "v=p/f"
7145"\n" "r+=v"
7146"\n" "}"
7147"\n" "while((d--)!=0)r*=r"
7148"\n" "scale=s"
7149"\n" "ibase=b"
7150"\n" "if(n!=0)return(1/r)"
7151"\n" "return(r/1)"
7152"\n" "}"
7153"\n" "define l(x){"
7154"\n" "auto b,s,r,p,a,q,i,v"
7155"\n" "b=ibase"
7156"\n" "ibase=A"
7157"\n" "if(x<=0){"
7158"\n" "r=(1-10^scale)/1"
7159"\n" "ibase=b"
7160"\n" "return(r)"
7161"\n" "}"
7162"\n" "s=scale"
7163"\n" "scale+=6"
7164"\n" "p=2"
7165"\n" "while(x>=2){"
7166"\n" "p*=2"
7167"\n" "x=sqrt(x)"
7168"\n" "}"
7169"\n" "while(x<=0.5){"
7170"\n" "p*=2"
7171"\n" "x=sqrt(x)"
7172"\n" "}"
7173"\n" "r=a=(x-1)/(x+1)"
7174"\n" "q=a*a"
7175"\n" "v=1"
7176"\n" "for(i=3;v!=0;i+=2){"
7177"\n" "a*=q"
7178"\n" "v=a/i"
7179"\n" "r+=v"
7180"\n" "}"
7181"\n" "r*=p"
7182"\n" "scale=s"
7183"\n" "ibase=b"
7184"\n" "return(r/1)"
7185"\n" "}"
7186"\n" "define s(x){"
7187"\n" "auto b,s,r,n,a,q,i"
7188"\n" "b=ibase"
7189"\n" "ibase=A"
7190"\n" "s=scale"
7191"\n" "scale=1.1*s+2"
7192"\n" "a=a(1)"
7193"\n" "if(x<0){"
7194"\n" "n=1"
7195"\n" "x=-x"
7196"\n" "}"
7197"\n" "scale=0"
7198"\n" "q=(x/a+2)/4"
7199"\n" "x=x-4*q*a"
7200"\n" "if(q%2!=0)x=-x"
7201"\n" "scale=s+2"
7202"\n" "r=a=x"
7203"\n" "q=-x*x"
7204"\n" "for(i=3;a!=0;i+=2){"
7205"\n" "a*=q/(i*(i-1))"
7206"\n" "r+=a"
7207"\n" "}"
7208"\n" "scale=s"
7209"\n" "ibase=b"
7210"\n" "if(n!=0)return(-r/1)"
7211"\n" "return(r/1)"
7212"\n" "}"
7213"\n" "define c(x){"
7214"\n" "auto b,s"
7215"\n" "b=ibase"
7216"\n" "ibase=A"
7217"\n" "s=scale"
7218"\n" "scale*=1.2"
7219"\n" "x=s(2*a(1)+x)"
7220"\n" "scale=s"
7221"\n" "ibase=b"
7222"\n" "return(x/1)"
7223"\n" "}"
7224"\n" "define a(x){"
7225"\n" "auto b,s,r,n,a,m,t,f,i,u"
7226"\n" "b=ibase"
7227"\n" "ibase=A"
7228"\n" "n=1"
7229"\n" "if(x<0){"
7230"\n" "n=-1"
7231"\n" "x=-x"
7232"\n" "}"
7233"\n" "if(x==1){"
7234"\n" "if(scale<65){"
7235"\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7236"\n" "}"
7237"\n" "}"
7238"\n" "if(x==.2){"
7239"\n" "if(scale<65){"
7240"\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7241"\n" "}"
7242"\n" "}"
7243"\n" "s=scale"
7244"\n" "if(x>.2){"
7245"\n" "scale+=5"
7246"\n" "a=a(.2)"
7247"\n" "}"
7248"\n" "scale=s+3"
7249"\n" "while(x>.2){"
7250"\n" "m+=1"
7251"\n" "x=(x-.2)/(1+.2*x)"
7252"\n" "}"
7253"\n" "r=u=x"
7254"\n" "f=-x*x"
7255"\n" "t=1"
7256"\n" "for(i=3;t!=0;i+=2){"
7257"\n" "u*=f"
7258"\n" "t=u/i"
7259"\n" "r+=t"
7260"\n" "}"
7261"\n" "scale=s"
7262"\n" "ibase=b"
7263"\n" "return((m*a+r)/n)"
7264"\n" "}"
7265"\n" "define j(n,x){"
7266"\n" "auto b,s,o,a,i,v,f"
7267"\n" "b=ibase"
7268"\n" "ibase=A"
7269"\n" "s=scale"
7270"\n" "scale=0"
7271"\n" "n/=1"
7272"\n" "if(n<0){"
7273"\n" "n=-n"
7274"\n" "if(n%2==1)o=1"
7275"\n" "}"
7276"\n" "a=1"
7277"\n" "for(i=2;i<=n;++i)a*=i"
7278"\n" "scale=1.5*s"
7279"\n" "a=(x^n)/2^n/a"
7280"\n" "r=v=1"
7281"\n" "f=-x*x/4"
7282"\n" "scale=scale+length(a)-scale(a)"
7283"\n" "for(i=1;v!=0;++i){"
7284"\n" "v=v*f/i/(n+i)"
7285"\n" "r+=v"
7286"\n" "}"
7287"\n" "scale=s"
7288"\n" "ibase=b"
7289"\n" "if(o!=0)a=-a"
7290"\n" "return(a*r/1)"
7291"\n" "}"
7292};
7293#endif // ENABLE_BC
7294
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007295static BcStatus bc_vm_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007296{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007297 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007298 size_t i;
7299
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007300#if ENABLE_BC
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007301 if (option_mask32 & BC_FLAG_L) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007302
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007303 // We know that internal library is not buggy,
7304 // thus error checking is normally disabled.
7305# define DEBUG_LIB 0
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007306 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007307 s = bc_parse_text(&G.prs, bc_lib);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007308 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007309
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007310 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007311 s = G.prs.parse(&G.prs);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007312 if (DEBUG_LIB && s) return s;
7313 }
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007314 s = bc_program_exec();
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007315 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007316 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007317#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007318
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007319 s = BC_STATUS_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007320 for (i = 0; !s && i < G.files.len; ++i)
7321 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007322 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7323 // Debug config, non-interactive mode:
7324 // return all the way back to main.
7325 // Non-debug builds do not come here, they exit.
7326 return s;
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007327 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007328
Denys Vlasenkoac6ed112018-12-08 21:39:10 +01007329 if (IS_BC || (option_mask32 & BC_FLAG_I))
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007330 s = bc_vm_stdin();
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007331
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007332 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7333 s = bc_vm_process("");
Gavin Howard01055ba2018-11-03 11:00:21 -06007334
Denys Vlasenko00d77792018-11-30 23:13:42 +01007335 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007336}
7337
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007338#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007339static void bc_program_free(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007340{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007341 bc_num_free(&G.prog.ib);
7342 bc_num_free(&G.prog.ob);
7343 bc_num_free(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007344# if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007345 bc_num_free(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007346# endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007347 bc_vec_free(&G.prog.fns);
7348 bc_vec_free(&G.prog.fn_map);
7349 bc_vec_free(&G.prog.vars);
7350 bc_vec_free(&G.prog.var_map);
7351 bc_vec_free(&G.prog.arrs);
7352 bc_vec_free(&G.prog.arr_map);
7353 bc_vec_free(&G.prog.strs);
7354 bc_vec_free(&G.prog.consts);
7355 bc_vec_free(&G.prog.results);
7356 bc_vec_free(&G.prog.stack);
7357 bc_num_free(&G.prog.last);
7358 bc_num_free(&G.prog.zero);
7359 bc_num_free(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007360}
7361
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007362static void bc_vm_free(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007363{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007364 bc_vec_free(&G.files);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007365 bc_program_free();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007366 bc_parse_free(&G.prs);
7367 free(G.env_args);
Gavin Howard01055ba2018-11-03 11:00:21 -06007368}
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007369#endif
7370
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007371static void bc_program_init(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007372{
7373 size_t idx;
7374 BcInstPtr ip;
7375
7376 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7377 memset(&ip, 0, sizeof(BcInstPtr));
7378
7379 /* G.prog.nchars = G.prog.scale = 0; - already is */
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007380 bc_num_init_DEF_SIZE(&G.prog.ib);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007381 bc_num_ten(&G.prog.ib);
7382 G.prog.ib_t = 10;
7383
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007384 bc_num_init_DEF_SIZE(&G.prog.ob);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007385 bc_num_ten(&G.prog.ob);
7386 G.prog.ob_t = 10;
7387
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007388 bc_num_init_DEF_SIZE(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007389 bc_num_ten(&G.prog.hexb);
7390 G.prog.hexb.num[0] = 6;
7391
7392#if ENABLE_DC
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007393 bc_num_init_DEF_SIZE(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007394 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7395#endif
7396
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007397 bc_num_init_DEF_SIZE(&G.prog.last);
Denys Vlasenko3129f702018-12-09 12:04:44 +01007398 //bc_num_zero(&G.prog.last); - already is
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007399
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007400 bc_num_init_DEF_SIZE(&G.prog.zero);
Denys Vlasenko3129f702018-12-09 12:04:44 +01007401 //bc_num_zero(&G.prog.zero); - already is
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007402
Denys Vlasenkoe20e00d2018-12-09 11:44:20 +01007403 bc_num_init_DEF_SIZE(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007404 bc_num_one(&G.prog.one);
7405
7406 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007407 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007408
Denys Vlasenko1f67e932018-12-03 00:08:59 +01007409 bc_program_addFunc(xstrdup("(main)"), &idx);
7410 bc_program_addFunc(xstrdup("(read)"), &idx);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007411
7412 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007413 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007414
7415 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007416 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007417
7418 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7419 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7420 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7421 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7422 bc_vec_push(&G.prog.stack, &ip);
7423}
Gavin Howard01055ba2018-11-03 11:00:21 -06007424
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007425static int bc_vm_init(const char *env_len)
Gavin Howard01055ba2018-11-03 11:00:21 -06007426{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007427#if ENABLE_FEATURE_EDITING
7428 G.line_input_state = new_line_input_t(DO_HISTORY);
7429#endif
7430 G.prog.len = bc_vm_envLen(env_len);
7431
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007432 bc_vec_init(&G.files, sizeof(char *), NULL);
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007433 if (IS_BC)
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007434 IF_BC(bc_vm_envArgs();)
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007435 bc_program_init();
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007436 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007437 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007438 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007439 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007440 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007441
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007442 if (isatty(0)) {
Denys Vlasenkod38af482018-12-04 19:11:02 +01007443#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007444 G_ttyin = 1;
Denys Vlasenko17c54722018-12-04 21:21:32 +01007445 // With SA_RESTART, most system calls will restart
7446 // (IOW: they won't fail with EINTR).
7447 // In particular, this means ^C won't cause
7448 // stdout to get into "error state" if SIGINT hits
7449 // within write() syscall.
7450 // The downside is that ^C while line input is taken
7451 // will only be handled after [Enter] since read()
7452 // from stdin is not interrupted by ^C either,
7453 // it restarts, thus fgetc() does not return on ^C.
7454 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7455
7456 // Without SA_RESTART, this exhibits a bug:
7457 // "while (1) print 1" and try ^C-ing it.
7458 // Intermittently, instead of returning to input line,
7459 // you'll get "output error: Interrupted system call"
7460 // and exit.
7461 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
Denys Vlasenkod38af482018-12-04 19:11:02 +01007462#endif
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007463 return 1; // "tty"
Denys Vlasenkod38af482018-12-04 19:11:02 +01007464 }
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007465 return 0; // "not a tty"
7466}
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007467
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007468static BcStatus bc_vm_run(void)
7469{
7470 BcStatus st = bc_vm_exec();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007471#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01007472 if (G_exiting) // it was actually "halt" or "quit"
7473 st = EXIT_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007474 bc_vm_free();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007475# if ENABLE_FEATURE_EDITING
7476 free_line_input_t(G.line_input_state);
7477# endif
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007478 FREE_G();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007479#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007480 return st;
7481}
7482
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007483#if ENABLE_BC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007484int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007485int bc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007486{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007487 int is_tty;
7488
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007489 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007490 G.sbgn = G.send = '"';
Gavin Howard01055ba2018-11-03 11:00:21 -06007491
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007492 is_tty = bc_vm_init("BC_LINE_LENGTH");
7493
7494 bc_args(argv);
7495
7496 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7497 bc_vm_info();
7498
7499 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007500}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007501#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007502
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007503#if ENABLE_DC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007504int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007505int dc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007506{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007507 int noscript;
7508
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007509 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007510 G.sbgn = '[';
7511 G.send = ']';
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007512 /*
7513 * TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7514 * 1 char wider than bc from the same package.
7515 * Both default width, and xC_LINE_LENGTH=N are wider:
7516 * "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7517 * 1234\
7518 * 56
7519 * "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7520 * 123\
7521 * 456
7522 * Do the same, or it's a bug?
7523 */
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007524 bc_vm_init("DC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007525
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007526 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7527 noscript = BC_FLAG_I;
7528 for (;;) {
7529 int n = getopt(argc, argv, "e:f:x");
7530 if (n <= 0)
7531 break;
7532 switch (n) {
7533 case 'e':
7534 noscript = 0;
7535 n = bc_vm_process(optarg);
7536 if (n) return n;
7537 break;
7538 case 'f':
7539 noscript = 0;
7540 bc_vm_file(optarg);
7541 break;
7542 case 'x':
7543 option_mask32 |= DC_FLAG_X;
7544 break;
7545 default:
7546 bb_show_usage();
7547 }
7548 }
7549 argv += optind;
7550
7551 while (*argv) {
7552 noscript = 0;
7553 bc_vec_push(&G.files, argv++);
7554 }
7555
7556 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7557
7558 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007559}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007560#endif
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +01007561
7562#endif // not DC_SMALL