blob: 0dc3f843c39b260b8ffc9fb71c4ceae4e445afe5 [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 Vlasenkob0e37612018-12-05 21:03:16 +01001402static void bc_num_init(BcNum *n, size_t req)
1403{
1404 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1405 memset(n, 0, sizeof(BcNum));
1406 n->num = xmalloc(req);
1407 n->cap = req;
1408}
1409
1410static void bc_num_expand(BcNum *n, size_t req)
1411{
1412 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1413 if (req > n->cap) {
1414 n->num = xrealloc(n->num, req);
1415 n->cap = req;
1416 }
1417}
1418
1419static void bc_num_free(void *num)
1420{
1421 free(((BcNum *) num)->num);
1422}
1423
1424static void bc_num_copy(BcNum *d, BcNum *s)
1425{
1426 if (d != s) {
1427 bc_num_expand(d, s->cap);
1428 d->len = s->len;
1429 d->neg = s->neg;
1430 d->rdx = s->rdx;
1431 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1432 }
1433}
1434
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001435static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001436{
1437 size_t i;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001438 unsigned long pow, result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001439
1440 if (n->neg) return bc_error("negative number");
1441
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001442 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001443
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001444 unsigned long prev = result, powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001445
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001446 result += ((unsigned long) n->num[i]) * pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001447 pow *= 10;
1448
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001449 if (result < prev || pow < powprev)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001450 return bc_error("overflow");
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001451 prev = result;
1452 powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001453 }
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001454 *result_p = result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001455
1456 return BC_STATUS_SUCCESS;
1457}
1458
1459static void bc_num_ulong2num(BcNum *n, unsigned long val)
1460{
1461 size_t len;
1462 BcDig *ptr;
1463 unsigned long i;
1464
1465 bc_num_zero(n);
1466
1467 if (val == 0) return;
1468
1469 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1470 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1471}
1472
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001473static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001474 size_t len)
1475{
1476 size_t i, j;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001477 for (i = 0; i < len; ++i) {
1478 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001479 a[i + j++] += 10;
1480 a[i + j] -= 1;
1481 }
1482 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001483}
1484
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01001485#define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1486#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1487#define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1488//#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1489static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1490{
1491 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1492}
1493//#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1494static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1495{
1496 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1497}
1498
Gavin Howard01055ba2018-11-03 11:00:21 -06001499static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1500{
1501 size_t i;
1502 int c = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001503 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
Gavin Howard01055ba2018-11-03 11:00:21 -06001504 return BC_NUM_NEG(i + 1, c < 0);
1505}
1506
1507static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1508{
1509 size_t i, min, a_int, b_int, diff;
1510 BcDig *max_num, *min_num;
1511 bool a_max, neg = false;
1512 ssize_t cmp;
1513
1514 if (a == b) return 0;
1515 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1516 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1517 if (a->neg) {
1518 if (b->neg)
1519 neg = true;
1520 else
1521 return -1;
1522 }
1523 else if (b->neg)
1524 return 1;
1525
1526 a_int = BC_NUM_INT(a);
1527 b_int = BC_NUM_INT(b);
1528 a_int -= b_int;
1529 a_max = (a->rdx > b->rdx);
1530
1531 if (a_int != 0) return (ssize_t) a_int;
1532
1533 if (a_max) {
1534 min = b->rdx;
1535 diff = a->rdx - b->rdx;
1536 max_num = a->num + diff;
1537 min_num = b->num;
1538 }
1539 else {
1540 min = a->rdx;
1541 diff = b->rdx - a->rdx;
1542 max_num = b->num + diff;
1543 min_num = a->num;
1544 }
1545
1546 cmp = bc_num_compare(max_num, min_num, b_int + min);
1547 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1548
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001549 for (max_num -= diff, i = diff - 1; i < diff; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001550 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1551 }
1552
1553 return 0;
1554}
1555
1556static void bc_num_truncate(BcNum *n, size_t places)
1557{
1558 if (places == 0) return;
1559
1560 n->rdx -= places;
1561
1562 if (n->len != 0) {
1563 n->len -= places;
1564 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1565 }
1566}
1567
1568static void bc_num_extend(BcNum *n, size_t places)
1569{
1570 size_t len = n->len + places;
1571
1572 if (places != 0) {
1573
1574 if (n->cap < len) bc_num_expand(n, len);
1575
1576 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1577 memset(n->num, 0, sizeof(BcDig) * places);
1578
1579 n->len += places;
1580 n->rdx += places;
1581 }
1582}
1583
1584static void bc_num_clean(BcNum *n)
1585{
1586 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1587 if (n->len == 0)
1588 n->neg = false;
1589 else if (n->len < n->rdx)
1590 n->len = n->rdx;
1591}
1592
1593static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1594{
1595 if (n->rdx < scale)
1596 bc_num_extend(n, scale - n->rdx);
1597 else
1598 bc_num_truncate(n, n->rdx - scale);
1599
1600 bc_num_clean(n);
1601 if (n->len != 0) n->neg = !neg1 != !neg2;
1602}
1603
1604static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1605 BcNum *restrict b)
1606{
1607 if (idx < n->len) {
1608
1609 b->len = n->len - idx;
1610 a->len = idx;
1611 a->rdx = b->rdx = 0;
1612
1613 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1614 memcpy(a->num, n->num, idx * sizeof(BcDig));
1615 }
1616 else {
1617 bc_num_zero(b);
1618 bc_num_copy(a, n);
1619 }
1620
1621 bc_num_clean(a);
1622 bc_num_clean(b);
1623}
1624
1625static BcStatus bc_num_shift(BcNum *n, size_t places)
1626{
1627 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
Denys Vlasenko64074a12018-12-07 15:50:14 +01001628
1629 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1630 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1631 if (places + n->len > BC_MAX_NUM)
1632 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1633 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001634
1635 if (n->rdx >= places)
1636 n->rdx -= places;
1637 else {
1638 bc_num_extend(n, places - n->rdx);
1639 n->rdx = 0;
1640 }
1641
1642 bc_num_clean(n);
1643
1644 return BC_STATUS_SUCCESS;
1645}
1646
1647static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1648{
1649 BcNum one;
1650 BcDig num[2];
1651
1652 one.cap = 2;
1653 one.num = num;
1654 bc_num_one(&one);
1655
1656 return bc_num_div(&one, a, b, scale);
1657}
1658
1659static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1660{
1661 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1662 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1663 int carry, in;
1664
1665 // Because this function doesn't need to use scale (per the bc spec),
1666 // I am hijacking it to say whether it's doing an add or a subtract.
1667
1668 if (a->len == 0) {
1669 bc_num_copy(c, b);
1670 if (sub && c->len) c->neg = !c->neg;
1671 return BC_STATUS_SUCCESS;
1672 }
1673 else if (b->len == 0) {
1674 bc_num_copy(c, a);
1675 return BC_STATUS_SUCCESS;
1676 }
1677
1678 c->neg = a->neg;
1679 c->rdx = BC_MAX(a->rdx, b->rdx);
1680 min_rdx = BC_MIN(a->rdx, b->rdx);
1681 c->len = 0;
1682
1683 if (a->rdx > b->rdx) {
1684 diff = a->rdx - b->rdx;
1685 ptr = a->num;
1686 ptr_a = a->num + diff;
1687 ptr_b = b->num;
1688 }
1689 else {
1690 diff = b->rdx - a->rdx;
1691 ptr = b->num;
1692 ptr_a = a->num;
1693 ptr_b = b->num + diff;
1694 }
1695
1696 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1697
1698 ptr_c += diff;
1699 a_int = BC_NUM_INT(a);
1700 b_int = BC_NUM_INT(b);
1701
1702 if (a_int > b_int) {
1703 min_int = b_int;
1704 max = a_int;
1705 ptr = ptr_a;
1706 }
1707 else {
1708 min_int = a_int;
1709 max = b_int;
1710 ptr = ptr_b;
1711 }
1712
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001713 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001714 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1715 carry = in / 10;
1716 ptr_c[i] = (BcDig)(in % 10);
1717 }
1718
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001719 for (; i < max + min_rdx; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001720 in = ((int) ptr[i]) + carry;
1721 carry = in / 10;
1722 ptr_c[i] = (BcDig)(in % 10);
1723 }
1724
1725 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1726
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001727 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001728}
1729
1730static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1731{
Gavin Howard01055ba2018-11-03 11:00:21 -06001732 ssize_t cmp;
1733 BcNum *minuend, *subtrahend;
1734 size_t start;
1735 bool aneg, bneg, neg;
1736
1737 // Because this function doesn't need to use scale (per the bc spec),
1738 // I am hijacking it to say whether it's doing an add or a subtract.
1739
1740 if (a->len == 0) {
1741 bc_num_copy(c, b);
1742 if (sub && c->len) c->neg = !c->neg;
1743 return BC_STATUS_SUCCESS;
1744 }
1745 else if (b->len == 0) {
1746 bc_num_copy(c, a);
1747 return BC_STATUS_SUCCESS;
1748 }
1749
1750 aneg = a->neg;
1751 bneg = b->neg;
1752 a->neg = b->neg = false;
1753
1754 cmp = bc_num_cmp(a, b);
1755
1756 a->neg = aneg;
1757 b->neg = bneg;
1758
1759 if (cmp == 0) {
1760 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1761 return BC_STATUS_SUCCESS;
1762 }
1763 else if (cmp > 0) {
1764 neg = a->neg;
1765 minuend = a;
1766 subtrahend = b;
1767 }
1768 else {
1769 neg = b->neg;
1770 if (sub) neg = !neg;
1771 minuend = b;
1772 subtrahend = a;
1773 }
1774
1775 bc_num_copy(c, minuend);
1776 c->neg = neg;
1777
1778 if (c->rdx < subtrahend->rdx) {
1779 bc_num_extend(c, subtrahend->rdx - c->rdx);
1780 start = 0;
1781 }
1782 else
1783 start = c->rdx - subtrahend->rdx;
1784
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001785 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001786
1787 bc_num_clean(c);
1788
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001789 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001790}
1791
1792static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1793 BcNum *restrict c)
1794{
1795 BcStatus s;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001796 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
Gavin Howard01055ba2018-11-03 11:00:21 -06001797 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001798 bool aone;
Gavin Howard01055ba2018-11-03 11:00:21 -06001799
Gavin Howard01055ba2018-11-03 11:00:21 -06001800 if (a->len == 0 || b->len == 0) {
1801 bc_num_zero(c);
1802 return BC_STATUS_SUCCESS;
1803 }
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001804 aone = BC_NUM_ONE(a);
1805 if (aone || BC_NUM_ONE(b)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001806 bc_num_copy(c, aone ? b : a);
1807 return BC_STATUS_SUCCESS;
1808 }
1809
1810 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1811 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1812 {
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001813 size_t i, j, len;
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001814 unsigned carry;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001815
Gavin Howard01055ba2018-11-03 11:00:21 -06001816 bc_num_expand(c, a->len + b->len + 1);
1817
1818 memset(c->num, 0, sizeof(BcDig) * c->cap);
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001819 c->len = len = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06001820
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001821 for (i = 0; i < b->len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001822
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001823 carry = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001824 for (j = 0; j < a->len; ++j) {
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001825 unsigned in = c->num[i + j];
1826 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1827 // note: compilers prefer _unsigned_ div/const
Gavin Howard01055ba2018-11-03 11:00:21 -06001828 carry = in / 10;
1829 c->num[i + j] = (BcDig)(in % 10);
1830 }
1831
1832 c->num[i + j] += (BcDig) carry;
1833 len = BC_MAX(len, i + j + !!carry);
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01001834
1835 // a=2^1000000
1836 // a*a <- without check below, this will not be interruptible
1837 if (G_interrupt) return BC_STATUS_FAILURE;
Gavin Howard01055ba2018-11-03 11:00:21 -06001838 }
1839
1840 c->len = len;
1841
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001842 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06001843 }
1844
1845 bc_num_init(&l1, max);
1846 bc_num_init(&h1, max);
1847 bc_num_init(&l2, max);
1848 bc_num_init(&h2, max);
1849 bc_num_init(&m1, max);
1850 bc_num_init(&m2, max);
1851 bc_num_init(&z0, max);
1852 bc_num_init(&z1, max);
1853 bc_num_init(&z2, max);
1854 bc_num_init(&temp, max + max);
1855
1856 bc_num_split(a, max2, &l1, &h1);
1857 bc_num_split(b, max2, &l2, &h2);
1858
1859 s = bc_num_add(&h1, &l1, &m1, 0);
1860 if (s) goto err;
1861 s = bc_num_add(&h2, &l2, &m2, 0);
1862 if (s) goto err;
1863
1864 s = bc_num_k(&h1, &h2, &z0);
1865 if (s) goto err;
1866 s = bc_num_k(&m1, &m2, &z1);
1867 if (s) goto err;
1868 s = bc_num_k(&l1, &l2, &z2);
1869 if (s) goto err;
1870
1871 s = bc_num_sub(&z1, &z0, &temp, 0);
1872 if (s) goto err;
1873 s = bc_num_sub(&temp, &z2, &z1, 0);
1874 if (s) goto err;
1875
1876 s = bc_num_shift(&z0, max2 * 2);
1877 if (s) goto err;
1878 s = bc_num_shift(&z1, max2);
1879 if (s) goto err;
1880 s = bc_num_add(&z0, &z1, &temp, 0);
1881 if (s) goto err;
1882 s = bc_num_add(&temp, &z2, c, 0);
1883
1884err:
1885 bc_num_free(&temp);
1886 bc_num_free(&z2);
1887 bc_num_free(&z1);
1888 bc_num_free(&z0);
1889 bc_num_free(&m2);
1890 bc_num_free(&m1);
1891 bc_num_free(&h2);
1892 bc_num_free(&l2);
1893 bc_num_free(&h1);
1894 bc_num_free(&l1);
1895 return s;
1896}
1897
1898static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1899{
1900 BcStatus s;
1901 BcNum cpa, cpb;
1902 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1903
1904 scale = BC_MAX(scale, a->rdx);
1905 scale = BC_MAX(scale, b->rdx);
1906 scale = BC_MIN(a->rdx + b->rdx, scale);
1907 maxrdx = BC_MAX(maxrdx, scale);
1908
1909 bc_num_init(&cpa, a->len);
1910 bc_num_init(&cpb, b->len);
1911
1912 bc_num_copy(&cpa, a);
1913 bc_num_copy(&cpb, b);
1914 cpa.neg = cpb.neg = false;
1915
1916 s = bc_num_shift(&cpa, maxrdx);
1917 if (s) goto err;
1918 s = bc_num_shift(&cpb, maxrdx);
1919 if (s) goto err;
1920 s = bc_num_k(&cpa, &cpb, c);
1921 if (s) goto err;
1922
1923 maxrdx += scale;
1924 bc_num_expand(c, c->len + maxrdx);
1925
1926 if (c->len < maxrdx) {
1927 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1928 c->len += maxrdx;
1929 }
1930
1931 c->rdx = maxrdx;
1932 bc_num_retireMul(c, scale, a->neg, b->neg);
1933
1934err:
1935 bc_num_free(&cpb);
1936 bc_num_free(&cpa);
1937 return s;
1938}
1939
1940static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1941{
1942 BcStatus s = BC_STATUS_SUCCESS;
1943 BcDig *n, *p, q;
1944 size_t len, end, i;
1945 BcNum cp;
1946 bool zero = true;
1947
1948 if (b->len == 0)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001949 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001950 else if (a->len == 0) {
1951 bc_num_setToZero(c, scale);
1952 return BC_STATUS_SUCCESS;
1953 }
1954 else if (BC_NUM_ONE(b)) {
1955 bc_num_copy(c, a);
1956 bc_num_retireMul(c, scale, a->neg, b->neg);
1957 return BC_STATUS_SUCCESS;
1958 }
1959
1960 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1961 bc_num_copy(&cp, a);
1962 len = b->len;
1963
1964 if (len > cp.len) {
1965 bc_num_expand(&cp, len + 2);
1966 bc_num_extend(&cp, len - cp.len);
1967 }
1968
1969 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1970 cp.rdx -= b->rdx;
1971 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1972
1973 if (b->rdx == b->len) {
1974 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1975 len -= i - 1;
1976 }
1977
1978 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1979
1980 // We want an extra zero in front to make things simpler.
1981 cp.num[cp.len++] = 0;
1982 end = cp.len - len;
1983
1984 bc_num_expand(c, cp.len);
1985
1986 bc_num_zero(c);
1987 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1988 c->rdx = cp.rdx;
1989 c->len = cp.len;
1990 p = b->num;
1991
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001992 for (i = end - 1; !s && i < end; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001993 n = cp.num + i;
1994 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001995 bc_num_subArrays(n, p, len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001996 c->num[i] = q;
Denys Vlasenkof381a882018-12-05 19:21:34 +01001997 // a=2^100000
1998 // scale=40000
1999 // 1/a <- without check below, this will not be interruptible
2000 if (G_interrupt) {
2001 s = BC_STATUS_FAILURE;
2002 break;
2003 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002004 }
2005
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002006 bc_num_retireMul(c, scale, a->neg, b->neg);
Gavin Howard01055ba2018-11-03 11:00:21 -06002007 bc_num_free(&cp);
2008
Denys Vlasenkof381a882018-12-05 19:21:34 +01002009 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06002010}
2011
2012static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2013 BcNum *restrict d, size_t scale, size_t ts)
2014{
2015 BcStatus s;
2016 BcNum temp;
2017 bool neg;
2018
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002019 if (b->len == 0)
2020 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06002021
2022 if (a->len == 0) {
2023 bc_num_setToZero(d, ts);
2024 return BC_STATUS_SUCCESS;
2025 }
2026
2027 bc_num_init(&temp, d->cap);
Denys Vlasenkof381a882018-12-05 19:21:34 +01002028 s = bc_num_d(a, b, c, scale);
2029 if (s) goto err;
Gavin Howard01055ba2018-11-03 11:00:21 -06002030
2031 if (scale != 0) scale = ts;
2032
2033 s = bc_num_m(c, b, &temp, scale);
2034 if (s) goto err;
2035 s = bc_num_sub(a, &temp, d, scale);
2036 if (s) goto err;
2037
2038 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2039
2040 neg = d->neg;
2041 bc_num_retireMul(d, ts, a->neg, b->neg);
2042 d->neg = neg;
2043
2044err:
2045 bc_num_free(&temp);
2046 return s;
2047}
2048
2049static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2050{
2051 BcStatus s;
2052 BcNum c1;
2053 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2054
2055 bc_num_init(&c1, len);
2056 s = bc_num_r(a, b, &c1, c, scale, ts);
2057 bc_num_free(&c1);
2058
2059 return s;
2060}
2061
2062static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2063{
2064 BcStatus s = BC_STATUS_SUCCESS;
2065 BcNum copy;
2066 unsigned long pow;
2067 size_t i, powrdx, resrdx;
2068 bool neg, zero;
2069
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002070 if (b->rdx) return bc_error("non integer number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002071
2072 if (b->len == 0) {
2073 bc_num_one(c);
2074 return BC_STATUS_SUCCESS;
2075 }
2076 else if (a->len == 0) {
2077 bc_num_setToZero(c, scale);
2078 return BC_STATUS_SUCCESS;
2079 }
2080 else if (BC_NUM_ONE(b)) {
2081 if (!b->neg)
2082 bc_num_copy(c, a);
2083 else
2084 s = bc_num_inv(a, c, scale);
2085 return s;
2086 }
2087
2088 neg = b->neg;
2089 b->neg = false;
2090
2091 s = bc_num_ulong(b, &pow);
2092 if (s) return s;
2093
2094 bc_num_init(&copy, a->len);
2095 bc_num_copy(&copy, a);
2096
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01002097 if (!neg) {
2098 if (a->rdx > scale)
2099 scale = a->rdx;
2100 if (a->rdx * pow < scale)
2101 scale = a->rdx * pow;
2102 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002103
2104 b->neg = neg;
2105
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002106 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002107 powrdx <<= 1;
2108 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2109 if (s) goto err;
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002110 // Not needed: bc_num_mul() has a check for ^C:
2111 //if (G_interrupt) {
2112 // s = BC_STATUS_FAILURE;
2113 // goto err;
2114 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002115 }
2116
Gavin Howard01055ba2018-11-03 11:00:21 -06002117 bc_num_copy(c, &copy);
2118
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002119 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002120
2121 powrdx <<= 1;
2122 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2123 if (s) goto err;
2124
2125 if (pow & 1) {
2126 resrdx += powrdx;
2127 s = bc_num_mul(c, &copy, c, resrdx);
2128 if (s) goto err;
2129 }
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002130 // Not needed: bc_num_mul() has a check for ^C:
2131 //if (G_interrupt) {
2132 // s = BC_STATUS_FAILURE;
2133 // goto err;
2134 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002135 }
2136
2137 if (neg) {
2138 s = bc_num_inv(c, c, scale);
2139 if (s) goto err;
2140 }
2141
Gavin Howard01055ba2018-11-03 11:00:21 -06002142 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2143
2144 // We can't use bc_num_clean() here.
2145 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2146 if (zero) bc_num_setToZero(c, scale);
2147
2148err:
2149 bc_num_free(&copy);
2150 return s;
2151}
2152
2153static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2154 BcNumBinaryOp op, size_t req)
2155{
2156 BcStatus s;
2157 BcNum num2, *ptr_a, *ptr_b;
2158 bool init = false;
2159
2160 if (c == a) {
2161 ptr_a = &num2;
2162 memcpy(ptr_a, c, sizeof(BcNum));
2163 init = true;
2164 }
2165 else
2166 ptr_a = a;
2167
2168 if (c == b) {
2169 ptr_b = &num2;
2170 if (c != a) {
2171 memcpy(ptr_b, c, sizeof(BcNum));
2172 init = true;
2173 }
2174 }
2175 else
2176 ptr_b = b;
2177
2178 if (init)
2179 bc_num_init(c, req);
2180 else
2181 bc_num_expand(c, req);
2182
2183 s = op(ptr_a, ptr_b, c, scale);
2184
2185 if (init) bc_num_free(&num2);
2186
2187 return s;
2188}
2189
2190static bool bc_num_strValid(const char *val, size_t base)
2191{
2192 BcDig b;
2193 bool small, radix = false;
2194 size_t i, len = strlen(val);
2195
2196 if (!len) return true;
2197
2198 small = base <= 10;
2199 b = (BcDig)(small ? base + '0' : base - 10 + 'A');
2200
2201 for (i = 0; i < len; ++i) {
2202
2203 BcDig c = val[i];
2204
2205 if (c == '.') {
2206
2207 if (radix) return false;
2208
2209 radix = true;
2210 continue;
2211 }
2212
2213 if (c < '0' || (small && c >= b) || (c > '9' && (c < 'A' || c >= b)))
2214 return false;
2215 }
2216
2217 return true;
2218}
2219
2220static void bc_num_parseDecimal(BcNum *n, const char *val)
2221{
2222 size_t len, i;
2223 const char *ptr;
2224 bool zero = true;
2225
2226 for (i = 0; val[i] == '0'; ++i);
2227
2228 val += i;
2229 len = strlen(val);
2230 bc_num_zero(n);
2231
2232 if (len != 0) {
2233 for (i = 0; zero && i < len; ++i) zero = val[i] == '0' || val[i] == '.';
2234 bc_num_expand(n, len);
2235 }
2236
2237 ptr = strchr(val, '.');
2238
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002239 n->rdx = 0;
2240 if (ptr != NULL)
2241 n->rdx = (size_t)((val + len) - (ptr + 1));
Gavin Howard01055ba2018-11-03 11:00:21 -06002242
2243 if (!zero) {
2244 for (i = len - 1; i < len; ++n->len, i -= 1 + (i && val[i - 1] == '.'))
2245 n->num[n->len] = val[i] - '0';
2246 }
2247}
2248
2249static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2250{
2251 BcStatus s;
2252 BcNum temp, mult, result;
2253 BcDig c = '\0';
2254 bool zero = true;
2255 unsigned long v;
2256 size_t i, digits, len = strlen(val);
2257
2258 bc_num_zero(n);
2259
2260 for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
2261 if (zero) return;
2262
2263 bc_num_init(&temp, BC_NUM_DEF_SIZE);
2264 bc_num_init(&mult, BC_NUM_DEF_SIZE);
2265
2266 for (i = 0; i < len; ++i) {
2267
2268 c = val[i];
2269 if (c == '.') break;
2270
2271 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2272
2273 s = bc_num_mul(n, base, &mult, 0);
2274 if (s) goto int_err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002275 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002276 s = bc_num_add(&mult, &temp, n, 0);
2277 if (s) goto int_err;
2278 }
2279
2280 if (i == len) {
2281 c = val[i];
2282 if (c == 0) goto int_err;
2283 }
2284
2285 bc_num_init(&result, base->len);
2286 bc_num_zero(&result);
2287 bc_num_one(&mult);
2288
2289 for (i += 1, digits = 0; i < len; ++i, ++digits) {
2290
2291 c = val[i];
2292 if (c == 0) break;
2293
2294 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2295
2296 s = bc_num_mul(&result, base, &result, 0);
2297 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002298 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002299 s = bc_num_add(&result, &temp, &result, 0);
2300 if (s) goto err;
2301 s = bc_num_mul(&mult, base, &mult, 0);
2302 if (s) goto err;
2303 }
2304
2305 s = bc_num_div(&result, &mult, &result, digits);
2306 if (s) goto err;
2307 s = bc_num_add(n, &result, n, digits);
2308 if (s) goto err;
2309
2310 if (n->len != 0) {
2311 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2312 }
2313 else
2314 bc_num_zero(n);
2315
2316err:
2317 bc_num_free(&result);
2318int_err:
2319 bc_num_free(&mult);
2320 bc_num_free(&temp);
2321}
2322
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002323static void bc_num_printNewline(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06002324{
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002325 if (G.prog.nchars == G.prog.len - 1) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002326 bb_putchar('\\');
2327 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002328 G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06002329 }
2330}
2331
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002332#if ENABLE_DC
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002333static void bc_num_printChar(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002334{
Denys Vlasenko2a8ad482018-12-08 21:56:37 +01002335 (void) radix;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002336 bb_putchar((char) num);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002337 G.prog.nchars += width;
Gavin Howard01055ba2018-11-03 11:00:21 -06002338}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002339#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002340
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002341static void bc_num_printDigits(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002342{
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002343 size_t exp, pow;
Gavin Howard01055ba2018-11-03 11:00:21 -06002344
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002345 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002346 bb_putchar(radix ? '.' : ' ');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002347 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06002348
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002349 bc_num_printNewline();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002350 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2351 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002352
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002353 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002354 size_t dig;
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002355 bc_num_printNewline();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002356 dig = num / pow;
2357 num -= dig * pow;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002358 bb_putchar(((char) dig) + '0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002359 }
2360}
2361
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002362static void bc_num_printHex(size_t num, size_t width, bool radix)
Gavin Howard01055ba2018-11-03 11:00:21 -06002363{
2364 if (radix) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002365 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002366 bb_putchar('.');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002367 G.prog.nchars += 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06002368 }
2369
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002370 bc_num_printNewline();
Denys Vlasenko00d77792018-11-30 23:13:42 +01002371 bb_putchar(bb_hexdigits_upcase[num]);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002372 G.prog.nchars += width;
Gavin Howard01055ba2018-11-03 11:00:21 -06002373}
2374
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002375static void bc_num_printDecimal(BcNum *n)
Gavin Howard01055ba2018-11-03 11:00:21 -06002376{
2377 size_t i, rdx = n->rdx - 1;
2378
Denys Vlasenko00d77792018-11-30 23:13:42 +01002379 if (n->neg) bb_putchar('-');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002380 G.prog.nchars += n->neg;
Gavin Howard01055ba2018-11-03 11:00:21 -06002381
2382 for (i = n->len - 1; i < n->len; --i)
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002383 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
Gavin Howard01055ba2018-11-03 11:00:21 -06002384}
2385
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002386static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width, BcNumDigitOp print)
Gavin Howard01055ba2018-11-03 11:00:21 -06002387{
2388 BcStatus s;
2389 BcVec stack;
2390 BcNum intp, fracp, digit, frac_len;
2391 unsigned long dig, *ptr;
2392 size_t i;
2393 bool radix;
2394
2395 if (n->len == 0) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002396 print(0, width, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06002397 return BC_STATUS_SUCCESS;
2398 }
2399
2400 bc_vec_init(&stack, sizeof(long), NULL);
2401 bc_num_init(&intp, n->len);
2402 bc_num_init(&fracp, n->rdx);
2403 bc_num_init(&digit, width);
2404 bc_num_init(&frac_len, BC_NUM_INT(n));
2405 bc_num_copy(&intp, n);
2406 bc_num_one(&frac_len);
2407
2408 bc_num_truncate(&intp, intp.rdx);
2409 s = bc_num_sub(n, &intp, &fracp, 0);
2410 if (s) goto err;
2411
2412 while (intp.len != 0) {
2413 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2414 if (s) goto err;
2415 s = bc_num_ulong(&digit, &dig);
2416 if (s) goto err;
2417 bc_vec_push(&stack, &dig);
2418 }
2419
2420 for (i = 0; i < stack.len; ++i) {
2421 ptr = bc_vec_item_rev(&stack, i);
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002422 print(*ptr, width, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06002423 }
2424
2425 if (!n->rdx) goto err;
2426
2427 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2428 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2429 if (s) goto err;
2430 s = bc_num_ulong(&fracp, &dig);
2431 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002432 bc_num_ulong2num(&intp, dig);
Gavin Howard01055ba2018-11-03 11:00:21 -06002433 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2434 if (s) goto err;
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002435 print(dig, width, radix);
Gavin Howard01055ba2018-11-03 11:00:21 -06002436 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2437 if (s) goto err;
2438 }
2439
2440err:
2441 bc_num_free(&frac_len);
2442 bc_num_free(&digit);
2443 bc_num_free(&fracp);
2444 bc_num_free(&intp);
2445 bc_vec_free(&stack);
2446 return s;
2447}
2448
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002449static BcStatus bc_num_printBase(BcNum *n)
Gavin Howard01055ba2018-11-03 11:00:21 -06002450{
2451 BcStatus s;
2452 size_t width, i;
2453 BcNumDigitOp print;
2454 bool neg = n->neg;
2455
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002456 if (neg) {
2457 bb_putchar('-');
2458 G.prog.nchars++;
2459 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002460
2461 n->neg = false;
2462
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002463 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002464 width = 1;
2465 print = bc_num_printHex;
2466 }
2467 else {
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002468 for (i = G.prog.ob_t - 1, width = 0; i != 0; i /= 10, ++width)
2469 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002470 print = bc_num_printDigits;
2471 }
2472
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002473 s = bc_num_printNum(n, &G.prog.ob, width, print);
Gavin Howard01055ba2018-11-03 11:00:21 -06002474 n->neg = neg;
2475
2476 return s;
2477}
2478
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002479#if ENABLE_DC
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002480static BcStatus bc_num_stream(BcNum *n, BcNum *base)
Gavin Howard01055ba2018-11-03 11:00:21 -06002481{
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002482 return bc_num_printNum(n, base, 1, bc_num_printChar);
Gavin Howard01055ba2018-11-03 11:00:21 -06002483}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002484#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002485
Gavin Howard01055ba2018-11-03 11:00:21 -06002486static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2487 size_t base_t)
2488{
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002489 if (!bc_num_strValid(val, base_t))
2490 return bc_error("bad number string");
Gavin Howard01055ba2018-11-03 11:00:21 -06002491
2492 if (base_t == 10)
2493 bc_num_parseDecimal(n, val);
2494 else
2495 bc_num_parseBase(n, val, base);
2496
2497 return BC_STATUS_SUCCESS;
2498}
2499
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002500static BcStatus bc_num_print(BcNum *n, bool newline)
Gavin Howard01055ba2018-11-03 11:00:21 -06002501{
2502 BcStatus s = BC_STATUS_SUCCESS;
2503
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002504 bc_num_printNewline();
Gavin Howard01055ba2018-11-03 11:00:21 -06002505
2506 if (n->len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002507 bb_putchar('0');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002508 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06002509 }
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002510 else if (G.prog.ob_t == 10)
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002511 bc_num_printDecimal(n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002512 else
Denys Vlasenko0f37b322018-12-08 23:48:53 +01002513 s = bc_num_printBase(n);
Gavin Howard01055ba2018-11-03 11:00:21 -06002514
2515 if (newline) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002516 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01002517 G.prog.nchars = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06002518 }
2519
2520 return s;
2521}
2522
Gavin Howard01055ba2018-11-03 11:00:21 -06002523static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2524{
2525 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2526 (void) scale;
2527 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2528}
2529
2530static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2531{
2532 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2533 (void) scale;
2534 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2535}
2536
2537static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2538{
2539 size_t req = BC_NUM_MREQ(a, b, scale);
2540 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2541}
2542
2543static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2544{
2545 size_t req = BC_NUM_MREQ(a, b, scale);
2546 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2547}
2548
2549static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2550{
2551 size_t req = BC_NUM_MREQ(a, b, scale);
2552 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2553}
2554
2555static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2556{
2557 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2558}
2559
2560static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2561{
2562 BcStatus s;
2563 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2564 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2565 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2566
2567 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2568 bc_num_expand(b, req);
2569
2570 if (a->len == 0) {
2571 bc_num_setToZero(b, scale);
2572 return BC_STATUS_SUCCESS;
2573 }
2574 else if (a->neg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002575 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002576 else if (BC_NUM_ONE(a)) {
2577 bc_num_one(b);
2578 bc_num_extend(b, scale);
2579 return BC_STATUS_SUCCESS;
2580 }
2581
2582 scale = BC_MAX(scale, a->rdx) + 1;
2583 len = a->len + scale;
2584
2585 bc_num_init(&num1, len);
2586 bc_num_init(&num2, len);
2587 bc_num_init(&half, BC_NUM_DEF_SIZE);
2588
2589 bc_num_one(&half);
2590 half.num[0] = 5;
2591 half.rdx = 1;
2592
2593 bc_num_init(&f, len);
2594 bc_num_init(&fprime, len);
2595
2596 x0 = &num1;
2597 x1 = &num2;
2598
2599 bc_num_one(x0);
2600 pow = BC_NUM_INT(a);
2601
2602 if (pow) {
2603
2604 if (pow & 1)
2605 x0->num[0] = 2;
2606 else
2607 x0->num[0] = 6;
2608
2609 pow -= 2 - (pow & 1);
2610
2611 bc_num_extend(x0, pow);
2612
2613 // Make sure to move the radix back.
2614 x0->rdx -= pow;
2615 }
2616
2617 x0->rdx = digs = digs1 = 0;
2618 resrdx = scale + 2;
2619 len = BC_NUM_INT(x0) + resrdx - 1;
2620
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002621 while (cmp != 0 || digs < len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002622
2623 s = bc_num_div(a, x0, &f, resrdx);
2624 if (s) goto err;
2625 s = bc_num_add(x0, &f, &fprime, resrdx);
2626 if (s) goto err;
2627 s = bc_num_mul(&fprime, &half, x1, resrdx);
2628 if (s) goto err;
2629
2630 cmp = bc_num_cmp(x1, x0);
2631 digs = x1->len - (unsigned long long) llabs(cmp);
2632
2633 if (cmp == cmp2 && digs == digs1)
2634 times += 1;
2635 else
2636 times = 0;
2637
2638 resrdx += times > 4;
2639
2640 cmp2 = cmp1;
2641 cmp1 = cmp;
2642 digs1 = digs;
2643
2644 temp = x0;
2645 x0 = x1;
2646 x1 = temp;
2647 }
2648
Gavin Howard01055ba2018-11-03 11:00:21 -06002649 bc_num_copy(b, x0);
2650 scale -= 1;
2651 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2652
2653err:
2654 bc_num_free(&fprime);
2655 bc_num_free(&f);
2656 bc_num_free(&half);
2657 bc_num_free(&num2);
2658 bc_num_free(&num1);
2659 return s;
2660}
2661
2662static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2663 size_t scale)
2664{
2665 BcStatus s;
2666 BcNum num2, *ptr_a;
2667 bool init = false;
2668 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2669
2670 if (c == a) {
2671 memcpy(&num2, c, sizeof(BcNum));
2672 ptr_a = &num2;
2673 bc_num_init(c, len);
2674 init = true;
2675 }
2676 else {
2677 ptr_a = a;
2678 bc_num_expand(c, len);
2679 }
2680
2681 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2682
2683 if (init) bc_num_free(&num2);
2684
2685 return s;
2686}
2687
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002688#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002689static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2690{
2691 BcStatus s;
2692 BcNum base, exp, two, temp;
2693
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002694 if (c->len == 0)
2695 return bc_error("divide by zero");
2696 if (a->rdx || b->rdx || c->rdx)
2697 return bc_error("non integer number");
2698 if (b->neg)
2699 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002700
2701 bc_num_expand(d, c->len);
2702 bc_num_init(&base, c->len);
2703 bc_num_init(&exp, b->len);
2704 bc_num_init(&two, BC_NUM_DEF_SIZE);
2705 bc_num_init(&temp, b->len);
2706
2707 bc_num_one(&two);
2708 two.num[0] = 2;
2709 bc_num_one(d);
2710
2711 s = bc_num_rem(a, c, &base, 0);
2712 if (s) goto err;
2713 bc_num_copy(&exp, b);
2714
2715 while (exp.len != 0) {
2716
2717 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2718 if (s) goto err;
2719
2720 if (BC_NUM_ONE(&temp)) {
2721 s = bc_num_mul(d, &base, &temp, 0);
2722 if (s) goto err;
2723 s = bc_num_rem(&temp, c, d, 0);
2724 if (s) goto err;
2725 }
2726
2727 s = bc_num_mul(&base, &base, &temp, 0);
2728 if (s) goto err;
2729 s = bc_num_rem(&temp, c, &base, 0);
2730 if (s) goto err;
2731 }
2732
2733err:
2734 bc_num_free(&temp);
2735 bc_num_free(&two);
2736 bc_num_free(&exp);
2737 bc_num_free(&base);
2738 return s;
2739}
2740#endif // ENABLE_DC
2741
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002742#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002743static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2744{
2745 BcId a;
2746 size_t i;
2747
2748 for (i = 0; i < f->autos.len; ++i) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002749 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2750 return bc_error("function parameter or auto var has the same name as another");
Gavin Howard01055ba2018-11-03 11:00:21 -06002751 }
2752
2753 a.idx = var;
2754 a.name = name;
2755
2756 bc_vec_push(&f->autos, &a);
2757
2758 return BC_STATUS_SUCCESS;
2759}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002760#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002761
2762static void bc_func_init(BcFunc *f)
2763{
Denys Vlasenko7d628012018-12-04 21:46:47 +01002764 bc_char_vec_init(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06002765 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2766 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2767 f->nparams = 0;
2768}
2769
2770static void bc_func_free(void *func)
2771{
2772 BcFunc *f = (BcFunc *) func;
2773 bc_vec_free(&f->code);
2774 bc_vec_free(&f->autos);
2775 bc_vec_free(&f->labels);
2776}
2777
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002778static void bc_array_expand(BcVec *a, size_t len);
2779
Gavin Howard01055ba2018-11-03 11:00:21 -06002780static void bc_array_init(BcVec *a, bool nums)
2781{
2782 if (nums)
2783 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2784 else
2785 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2786 bc_array_expand(a, 1);
2787}
2788
Gavin Howard01055ba2018-11-03 11:00:21 -06002789static void bc_array_expand(BcVec *a, size_t len)
2790{
2791 BcResultData data;
2792
2793 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2794 while (len > a->len) {
2795 bc_num_init(&data.n, BC_NUM_DEF_SIZE);
2796 bc_vec_push(a, &data.n);
2797 }
2798 }
2799 else {
2800 while (len > a->len) {
2801 bc_array_init(&data.v, true);
2802 bc_vec_push(a, &data.v);
2803 }
2804 }
2805}
2806
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002807static void bc_array_copy(BcVec *d, const BcVec *s)
2808{
2809 size_t i;
2810
2811 bc_vec_pop_all(d);
2812 bc_vec_expand(d, s->cap);
2813 d->len = s->len;
2814
2815 for (i = 0; i < s->len; ++i) {
2816 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2817 bc_num_init(dnum, snum->len);
2818 bc_num_copy(dnum, snum);
2819 }
2820}
2821
Gavin Howard01055ba2018-11-03 11:00:21 -06002822static void bc_string_free(void *string)
2823{
2824 free(*((char **) string));
2825}
2826
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002827#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002828static void bc_result_copy(BcResult *d, BcResult *src)
2829{
2830 d->t = src->t;
2831
2832 switch (d->t) {
2833
2834 case BC_RESULT_TEMP:
2835 case BC_RESULT_IBASE:
2836 case BC_RESULT_SCALE:
2837 case BC_RESULT_OBASE:
2838 {
2839 bc_num_init(&d->d.n, src->d.n.len);
2840 bc_num_copy(&d->d.n, &src->d.n);
2841 break;
2842 }
2843
2844 case BC_RESULT_VAR:
2845 case BC_RESULT_ARRAY:
2846 case BC_RESULT_ARRAY_ELEM:
2847 {
2848 d->d.id.name = xstrdup(src->d.id.name);
2849 break;
2850 }
2851
2852 case BC_RESULT_CONSTANT:
2853 case BC_RESULT_LAST:
2854 case BC_RESULT_ONE:
2855 case BC_RESULT_STR:
2856 {
2857 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2858 break;
2859 }
2860 }
2861}
2862#endif // ENABLE_DC
2863
2864static void bc_result_free(void *result)
2865{
2866 BcResult *r = (BcResult *) result;
2867
2868 switch (r->t) {
2869
2870 case BC_RESULT_TEMP:
2871 case BC_RESULT_IBASE:
2872 case BC_RESULT_SCALE:
2873 case BC_RESULT_OBASE:
2874 {
2875 bc_num_free(&r->d.n);
2876 break;
2877 }
2878
2879 case BC_RESULT_VAR:
2880 case BC_RESULT_ARRAY:
2881 case BC_RESULT_ARRAY_ELEM:
2882 {
2883 free(r->d.id.name);
2884 break;
2885 }
2886
2887 default:
2888 {
2889 // Do nothing.
2890 break;
2891 }
2892 }
2893}
2894
2895static void bc_lex_lineComment(BcLex *l)
2896{
2897 l->t.t = BC_LEX_WHITESPACE;
2898 while (l->i < l->len && l->buf[l->i++] != '\n');
2899 --l->i;
2900}
2901
2902static void bc_lex_whitespace(BcLex *l)
2903{
2904 char c;
2905 l->t.t = BC_LEX_WHITESPACE;
2906 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2907}
2908
2909static BcStatus bc_lex_number(BcLex *l, char start)
2910{
2911 const char *buf = l->buf + l->i;
2912 size_t len, hits = 0, bslashes = 0, i = 0, j;
2913 char c = buf[i];
2914 bool last_pt, pt = start == '.';
2915
2916 last_pt = pt;
2917 l->t.t = BC_LEX_NUMBER;
2918
2919 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2920 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2921 {
2922 if (c != '\\') {
2923 last_pt = c == '.';
2924 pt = pt || last_pt;
2925 }
2926 else {
2927 ++i;
2928 bslashes += 1;
2929 }
2930
2931 c = buf[++i];
2932 }
2933
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002934 len = i + !last_pt - bslashes * 2;
Denys Vlasenko64074a12018-12-07 15:50:14 +01002935 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2936 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2937 if (len > BC_MAX_NUM)
2938 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2939 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002940
Denys Vlasenko7d628012018-12-04 21:46:47 +01002941 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002942 bc_vec_expand(&l->t.v, len + 1);
2943 bc_vec_push(&l->t.v, &start);
2944
2945 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2946
2947 c = buf[j];
2948
2949 // If we have hit a backslash, skip it. We don't have
2950 // to check for a newline because it's guaranteed.
2951 if (hits < bslashes && c == '\\') {
2952 ++hits;
2953 ++j;
2954 continue;
2955 }
2956
2957 bc_vec_push(&l->t.v, &c);
2958 }
2959
Denys Vlasenko08c033c2018-12-05 16:55:08 +01002960 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002961 l->i += i;
2962
2963 return BC_STATUS_SUCCESS;
2964}
2965
2966static BcStatus bc_lex_name(BcLex *l)
2967{
2968 size_t i = 0;
2969 const char *buf = l->buf + l->i - 1;
2970 char c = buf[i];
2971
2972 l->t.t = BC_LEX_NAME;
2973
2974 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2975
Denys Vlasenko64074a12018-12-07 15:50:14 +01002976 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2977 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2978 if (i > BC_MAX_STRING)
2979 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2980 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002981 bc_vec_string(&l->t.v, i, buf);
2982
2983 // Increment the index. We minus 1 because it has already been incremented.
2984 l->i += i - 1;
2985
2986 return BC_STATUS_SUCCESS;
2987}
2988
2989static void bc_lex_init(BcLex *l, BcLexNext next)
2990{
2991 l->next = next;
Denys Vlasenko7d628012018-12-04 21:46:47 +01002992 bc_char_vec_init(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002993}
2994
2995static void bc_lex_free(BcLex *l)
2996{
2997 bc_vec_free(&l->t.v);
2998}
2999
Denys Vlasenko0409ad32018-12-05 16:39:22 +01003000static void bc_lex_file(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06003001{
Denys Vlasenko5318f812018-12-05 17:48:01 +01003002 G.err_line = l->line = 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003003 l->newline = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06003004}
3005
3006static BcStatus bc_lex_next(BcLex *l)
3007{
3008 BcStatus s;
3009
3010 l->t.last = l->t.t;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003011 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06003012
3013 l->line += l->newline;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003014 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003015 l->t.t = BC_LEX_EOF;
3016
3017 l->newline = (l->i == l->len);
3018 if (l->newline) return BC_STATUS_SUCCESS;
3019
3020 // Loop until failure or we don't have whitespace. This
3021 // is so the parser doesn't get inundated with whitespace.
3022 do {
3023 s = l->next(l);
3024 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3025
3026 return s;
3027}
3028
3029static BcStatus bc_lex_text(BcLex *l, const char *text)
3030{
3031 l->buf = text;
3032 l->i = 0;
3033 l->len = strlen(text);
3034 l->t.t = l->t.last = BC_LEX_INVALID;
3035 return bc_lex_next(l);
3036}
3037
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003038#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06003039static BcStatus bc_lex_identifier(BcLex *l)
3040{
3041 BcStatus s;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003042 unsigned i;
Gavin Howard01055ba2018-11-03 11:00:21 -06003043 const char *buf = l->buf + l->i - 1;
3044
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003045 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3046 const char *keyword8 = bc_lex_kws[i].name8;
3047 unsigned j = 0;
3048 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3049 j++;
3050 if (j == 8) goto match;
Gavin Howard01055ba2018-11-03 11:00:21 -06003051 }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003052 if (keyword8[j] != '\0')
3053 continue;
3054 match:
3055 // buf starts with keyword bc_lex_kws[i]
3056 l->t.t = BC_LEX_KEY_1st_keyword + i;
Denys Vlasenkod00d2f92018-12-06 12:59:40 +01003057 if (!bc_lex_kws_POSIX(i)) {
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003058 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003059 if (s) return s;
3060 }
3061
3062 // We minus 1 because the index has already been incremented.
3063 l->i += j - 1;
3064 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06003065 }
3066
3067 s = bc_lex_name(l);
3068 if (s) return s;
3069
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003070 if (l->t.v.len > 2) {
3071 // Prevent this:
3072 // >>> qwe=1
3073 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3074 // '
3075 unsigned len = strchrnul(buf, '\n') - buf;
3076 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3077 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003078
3079 return s;
3080}
3081
3082static BcStatus bc_lex_string(BcLex *l)
3083{
3084 size_t len, nls = 0, i = l->i;
3085 char c;
3086
3087 l->t.t = BC_LEX_STR;
3088
3089 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3090
3091 if (c == '\0') {
3092 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003093 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003094 }
3095
3096 len = i - l->i;
Denys Vlasenko64074a12018-12-07 15:50:14 +01003097 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3098 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3099 if (len > BC_MAX_STRING)
3100 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3101 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003102 bc_vec_string(&l->t.v, len, l->buf + l->i);
3103
3104 l->i = i + 1;
3105 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003106 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003107
3108 return BC_STATUS_SUCCESS;
3109}
3110
3111static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3112{
3113 if (l->buf[l->i] == '=') {
3114 ++l->i;
3115 l->t.t = with;
3116 }
3117 else
3118 l->t.t = without;
3119}
3120
3121static BcStatus bc_lex_comment(BcLex *l)
3122{
3123 size_t i, nls = 0;
3124 const char *buf = l->buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003125
3126 l->t.t = BC_LEX_WHITESPACE;
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003127 i = ++l->i;
3128 for (;;) {
3129 char c = buf[i];
3130 check_star:
3131 if (c == '*') {
3132 c = buf[++i];
3133 if (c == '/')
3134 break;
3135 goto check_star;
3136 }
3137 if (c == '\0') {
Gavin Howard01055ba2018-11-03 11:00:21 -06003138 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003139 return bc_error("comment end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003140 }
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003141 nls += (c == '\n');
3142 i++;
Gavin Howard01055ba2018-11-03 11:00:21 -06003143 }
3144
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003145 l->i = i + 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003146 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003147 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003148
3149 return BC_STATUS_SUCCESS;
3150}
3151
3152static BcStatus bc_lex_token(BcLex *l)
3153{
3154 BcStatus s = BC_STATUS_SUCCESS;
3155 char c = l->buf[l->i++], c2;
3156
3157 // This is the workhorse of the lexer.
3158 switch (c) {
3159
3160 case '\0':
3161 case '\n':
3162 {
3163 l->newline = true;
3164 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3165 break;
3166 }
3167
3168 case '\t':
3169 case '\v':
3170 case '\f':
3171 case '\r':
3172 case ' ':
3173 {
3174 bc_lex_whitespace(l);
3175 break;
3176 }
3177
3178 case '!':
3179 {
3180 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3181
3182 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
Denys Vlasenko00646792018-12-05 18:12:27 +01003183 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
Gavin Howard01055ba2018-11-03 11:00:21 -06003184 if (s) return s;
3185 }
3186
3187 break;
3188 }
3189
3190 case '"':
3191 {
3192 s = bc_lex_string(l);
3193 break;
3194 }
3195
3196 case '#':
3197 {
Denys Vlasenko00646792018-12-05 18:12:27 +01003198 s = bc_POSIX_does_not_allow("'#' script comments");
Gavin Howard01055ba2018-11-03 11:00:21 -06003199 if (s) return s;
3200
3201 bc_lex_lineComment(l);
3202
3203 break;
3204 }
3205
3206 case '%':
3207 {
3208 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3209 break;
3210 }
3211
3212 case '&':
3213 {
3214 c2 = l->buf[l->i];
3215 if (c2 == '&') {
3216
Denys Vlasenko00646792018-12-05 18:12:27 +01003217 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
Gavin Howard01055ba2018-11-03 11:00:21 -06003218 if (s) return s;
3219
3220 ++l->i;
3221 l->t.t = BC_LEX_OP_BOOL_AND;
3222 }
3223 else {
3224 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003225 s = bc_error_bad_character('&');
Gavin Howard01055ba2018-11-03 11:00:21 -06003226 }
3227
3228 break;
3229 }
3230
3231 case '(':
3232 case ')':
3233 {
3234 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3235 break;
3236 }
3237
3238 case '*':
3239 {
3240 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3241 break;
3242 }
3243
3244 case '+':
3245 {
3246 c2 = l->buf[l->i];
3247 if (c2 == '+') {
3248 ++l->i;
3249 l->t.t = BC_LEX_OP_INC;
3250 }
3251 else
3252 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3253 break;
3254 }
3255
3256 case ',':
3257 {
3258 l->t.t = BC_LEX_COMMA;
3259 break;
3260 }
3261
3262 case '-':
3263 {
3264 c2 = l->buf[l->i];
3265 if (c2 == '-') {
3266 ++l->i;
3267 l->t.t = BC_LEX_OP_DEC;
3268 }
3269 else
3270 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3271 break;
3272 }
3273
3274 case '.':
3275 {
3276 if (isdigit(l->buf[l->i]))
3277 s = bc_lex_number(l, c);
3278 else {
3279 l->t.t = BC_LEX_KEY_LAST;
Denys Vlasenko00646792018-12-05 18:12:27 +01003280 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
Gavin Howard01055ba2018-11-03 11:00:21 -06003281 }
3282 break;
3283 }
3284
3285 case '/':
3286 {
3287 c2 = l->buf[l->i];
3288 if (c2 == '*')
3289 s = bc_lex_comment(l);
3290 else
3291 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3292 break;
3293 }
3294
3295 case '0':
3296 case '1':
3297 case '2':
3298 case '3':
3299 case '4':
3300 case '5':
3301 case '6':
3302 case '7':
3303 case '8':
3304 case '9':
3305 case 'A':
3306 case 'B':
3307 case 'C':
3308 case 'D':
3309 case 'E':
3310 case 'F':
3311 {
3312 s = bc_lex_number(l, c);
3313 break;
3314 }
3315
3316 case ';':
3317 {
3318 l->t.t = BC_LEX_SCOLON;
3319 break;
3320 }
3321
3322 case '<':
3323 {
3324 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3325 break;
3326 }
3327
3328 case '=':
3329 {
3330 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3331 break;
3332 }
3333
3334 case '>':
3335 {
3336 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3337 break;
3338 }
3339
3340 case '[':
3341 case ']':
3342 {
3343 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3344 break;
3345 }
3346
3347 case '\\':
3348 {
3349 if (l->buf[l->i] == '\n') {
3350 l->t.t = BC_LEX_WHITESPACE;
3351 ++l->i;
3352 }
3353 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003354 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003355 break;
3356 }
3357
3358 case '^':
3359 {
3360 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3361 break;
3362 }
3363
3364 case 'a':
3365 case 'b':
3366 case 'c':
3367 case 'd':
3368 case 'e':
3369 case 'f':
3370 case 'g':
3371 case 'h':
3372 case 'i':
3373 case 'j':
3374 case 'k':
3375 case 'l':
3376 case 'm':
3377 case 'n':
3378 case 'o':
3379 case 'p':
3380 case 'q':
3381 case 'r':
3382 case 's':
3383 case 't':
3384 case 'u':
3385 case 'v':
3386 case 'w':
3387 case 'x':
3388 case 'y':
3389 case 'z':
3390 {
3391 s = bc_lex_identifier(l);
3392 break;
3393 }
3394
3395 case '{':
3396 case '}':
3397 {
3398 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3399 break;
3400 }
3401
3402 case '|':
3403 {
3404 c2 = l->buf[l->i];
3405
3406 if (c2 == '|') {
Denys Vlasenko00646792018-12-05 18:12:27 +01003407 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
Gavin Howard01055ba2018-11-03 11:00:21 -06003408 if (s) return s;
3409
3410 ++l->i;
3411 l->t.t = BC_LEX_OP_BOOL_OR;
3412 }
3413 else {
3414 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003415 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003416 }
3417
3418 break;
3419 }
3420
3421 default:
3422 {
3423 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003424 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003425 break;
3426 }
3427 }
3428
3429 return s;
3430}
3431#endif // ENABLE_BC
3432
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003433#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06003434static BcStatus dc_lex_register(BcLex *l)
3435{
3436 BcStatus s = BC_STATUS_SUCCESS;
3437
3438 if (isspace(l->buf[l->i - 1])) {
3439 bc_lex_whitespace(l);
3440 ++l->i;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01003441 if (!G_exreg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003442 s = bc_error("extended register");
Gavin Howard01055ba2018-11-03 11:00:21 -06003443 else
3444 s = bc_lex_name(l);
3445 }
3446 else {
Denys Vlasenko7d628012018-12-04 21:46:47 +01003447 bc_vec_pop_all(&l->t.v);
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003448 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003449 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003450 l->t.t = BC_LEX_NAME;
3451 }
3452
3453 return s;
3454}
3455
3456static BcStatus dc_lex_string(BcLex *l)
3457{
3458 size_t depth = 1, nls = 0, i = l->i;
3459 char c;
3460
3461 l->t.t = BC_LEX_STR;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003462 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003463
3464 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3465
3466 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3467 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3468 nls += (c == '\n');
3469
3470 if (depth) bc_vec_push(&l->t.v, &c);
3471 }
3472
3473 if (c == '\0') {
3474 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003475 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003476 }
3477
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003478 bc_vec_pushZeroByte(&l->t.v);
Denys Vlasenko64074a12018-12-07 15:50:14 +01003479 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3480 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3481 if (i - l->i > BC_MAX_STRING)
3482 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3483 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003484
3485 l->i = i;
3486 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003487 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003488
3489 return BC_STATUS_SUCCESS;
3490}
3491
3492static BcStatus dc_lex_token(BcLex *l)
3493{
3494 BcStatus s = BC_STATUS_SUCCESS;
3495 char c = l->buf[l->i++], c2;
3496 size_t i;
3497
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003498 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3499 if (l->t.last == dc_lex_regs[i])
3500 return dc_lex_register(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003501 }
3502
3503 if (c >= '%' && c <= '~' &&
3504 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3505 {
3506 return s;
3507 }
3508
3509 // This is the workhorse of the lexer.
3510 switch (c) {
3511
3512 case '\0':
3513 {
3514 l->t.t = BC_LEX_EOF;
3515 break;
3516 }
3517
3518 case '\n':
3519 case '\t':
3520 case '\v':
3521 case '\f':
3522 case '\r':
3523 case ' ':
3524 {
3525 l->newline = (c == '\n');
3526 bc_lex_whitespace(l);
3527 break;
3528 }
3529
3530 case '!':
3531 {
3532 c2 = l->buf[l->i];
3533
3534 if (c2 == '=')
3535 l->t.t = BC_LEX_OP_REL_NE;
3536 else if (c2 == '<')
3537 l->t.t = BC_LEX_OP_REL_LE;
3538 else if (c2 == '>')
3539 l->t.t = BC_LEX_OP_REL_GE;
3540 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003541 return bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003542
3543 ++l->i;
3544 break;
3545 }
3546
3547 case '#':
3548 {
3549 bc_lex_lineComment(l);
3550 break;
3551 }
3552
3553 case '.':
3554 {
3555 if (isdigit(l->buf[l->i]))
3556 s = bc_lex_number(l, c);
3557 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003558 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003559 break;
3560 }
3561
3562 case '0':
3563 case '1':
3564 case '2':
3565 case '3':
3566 case '4':
3567 case '5':
3568 case '6':
3569 case '7':
3570 case '8':
3571 case '9':
3572 case 'A':
3573 case 'B':
3574 case 'C':
3575 case 'D':
3576 case 'E':
3577 case 'F':
3578 {
3579 s = bc_lex_number(l, c);
3580 break;
3581 }
3582
3583 case '[':
3584 {
3585 s = dc_lex_string(l);
3586 break;
3587 }
3588
3589 default:
3590 {
3591 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003592 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003593 break;
3594 }
3595 }
3596
3597 return s;
3598}
3599#endif // ENABLE_DC
3600
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003601static void bc_program_addFunc(char *name, size_t *idx);
3602
Gavin Howard01055ba2018-11-03 11:00:21 -06003603static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3604{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003605 bc_program_addFunc(name, idx);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003606 p->func = bc_program_func(p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003607}
3608
Denys Vlasenkob23ac512018-12-06 13:10:56 +01003609#define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3610
Gavin Howard01055ba2018-11-03 11:00:21 -06003611static void bc_parse_pushName(BcParse *p, char *name)
3612{
3613 size_t i = 0, len = strlen(name);
3614
3615 for (; i < len; ++i) bc_parse_push(p, name[i]);
3616 bc_parse_push(p, BC_PARSE_STREND);
3617
3618 free(name);
3619}
3620
3621static void bc_parse_pushIndex(BcParse *p, size_t idx)
3622{
3623 unsigned char amt, i, nums[sizeof(size_t)];
3624
3625 for (amt = 0; idx; ++amt) {
3626 nums[amt] = (char) idx;
3627 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3628 }
3629
3630 bc_parse_push(p, amt);
3631 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3632}
3633
3634static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3635{
3636 char *num = xstrdup(p->l.t.v.v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003637 size_t idx = G.prog.consts.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06003638
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003639 bc_vec_push(&G.prog.consts, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06003640
3641 bc_parse_push(p, BC_INST_NUM);
3642 bc_parse_pushIndex(p, idx);
3643
3644 ++(*nexs);
3645 (*prev) = BC_INST_NUM;
3646}
3647
3648static BcStatus bc_parse_text(BcParse *p, const char *text)
3649{
3650 BcStatus s;
3651
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003652 p->func = bc_program_func(p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003653
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003654 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003655 p->l.t.t = BC_LEX_INVALID;
3656 s = p->parse(p);
3657 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003658 if (!BC_PARSE_CAN_EXEC(p))
3659 return bc_error("file is not executable");
Gavin Howard01055ba2018-11-03 11:00:21 -06003660 }
3661
3662 return bc_lex_text(&p->l, text);
3663}
3664
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003665// Called when parsing or execution detects a failure,
3666// resets execution structures.
3667static void bc_program_reset(void)
3668{
3669 BcFunc *f;
3670 BcInstPtr *ip;
3671
3672 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3673 bc_vec_pop_all(&G.prog.results);
3674
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003675 f = bc_program_func(0);
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003676 ip = bc_vec_top(&G.prog.stack);
3677 ip->idx = f->code.len;
3678}
3679
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003680#define bc_parse_updateFunc(p, f) \
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01003681 ((p)->func = bc_program_func((p)->fidx = (f)))
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003682
Denys Vlasenkod38af482018-12-04 19:11:02 +01003683// Called when bc/dc_parse_parse() detects a failure,
3684// resets parsing structures.
3685static void bc_parse_reset(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06003686{
3687 if (p->fidx != BC_PROG_MAIN) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003688 p->func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003689 bc_vec_pop_all(&p->func->code);
3690 bc_vec_pop_all(&p->func->autos);
3691 bc_vec_pop_all(&p->func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06003692
3693 bc_parse_updateFunc(p, BC_PROG_MAIN);
3694 }
3695
3696 p->l.i = p->l.len;
3697 p->l.t.t = BC_LEX_EOF;
3698 p->auto_part = (p->nbraces = 0);
3699
3700 bc_vec_npop(&p->flags, p->flags.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01003701 bc_vec_pop_all(&p->exits);
3702 bc_vec_pop_all(&p->conds);
3703 bc_vec_pop_all(&p->ops);
Gavin Howard01055ba2018-11-03 11:00:21 -06003704
Denys Vlasenkod38af482018-12-04 19:11:02 +01003705 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06003706}
3707
3708static void bc_parse_free(BcParse *p)
3709{
3710 bc_vec_free(&p->flags);
3711 bc_vec_free(&p->exits);
3712 bc_vec_free(&p->conds);
3713 bc_vec_free(&p->ops);
3714 bc_lex_free(&p->l);
3715}
3716
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003717static void bc_parse_create(BcParse *p, size_t func,
Gavin Howard01055ba2018-11-03 11:00:21 -06003718 BcParseParse parse, BcLexNext next)
3719{
3720 memset(p, 0, sizeof(BcParse));
3721
3722 bc_lex_init(&p->l, next);
3723 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3724 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3725 bc_vec_init(&p->conds, sizeof(size_t), NULL);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003726 bc_vec_pushZeroByte(&p->flags);
Gavin Howard01055ba2018-11-03 11:00:21 -06003727 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3728
3729 p->parse = parse;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01003730 // p->auto_part = p->nbraces = 0; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06003731 bc_parse_updateFunc(p, func);
3732}
3733
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003734#if ENABLE_BC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003735
3736#define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3737#define BC_PARSE_LEAF(p, rparen) \
3738 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3739 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3740
3741// We can calculate the conversion between tokens and exprs by subtracting the
3742// position of the first operator in the lex enum and adding the position of the
3743// first in the expr enum. Note: This only works for binary operators.
3744#define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3745
Gavin Howard01055ba2018-11-03 11:00:21 -06003746static BcStatus bc_parse_else(BcParse *p);
3747static BcStatus bc_parse_stmt(BcParse *p);
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003748static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01003749static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
Gavin Howard01055ba2018-11-03 11:00:21 -06003750
3751static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3752 size_t *nexprs, bool next)
3753{
3754 BcStatus s = BC_STATUS_SUCCESS;
3755 BcLexType t;
Denys Vlasenko65437582018-12-05 19:37:19 +01003756 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3757 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003758
3759 while (p->ops.len > start) {
3760
3761 t = BC_PARSE_TOP_OP(p);
3762 if (t == BC_LEX_LPAREN) break;
3763
Denys Vlasenko65437582018-12-05 19:37:19 +01003764 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003765 if (l >= r && (l != r || !left)) break;
3766
3767 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3768 bc_vec_pop(&p->ops);
3769 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3770 }
3771
3772 bc_vec_push(&p->ops, &type);
3773 if (next) s = bc_lex_next(&p->l);
3774
3775 return s;
3776}
3777
3778static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3779{
3780 BcLexType top;
3781
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003782 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003783 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003784 top = BC_PARSE_TOP_OP(p);
3785
3786 while (top != BC_LEX_LPAREN) {
3787
3788 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3789
3790 bc_vec_pop(&p->ops);
3791 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3792
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003793 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003794 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003795 top = BC_PARSE_TOP_OP(p);
3796 }
3797
3798 bc_vec_pop(&p->ops);
3799
3800 return bc_lex_next(&p->l);
3801}
3802
3803static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3804{
3805 BcStatus s;
3806 bool comma = false;
3807 size_t nparams;
3808
3809 s = bc_lex_next(&p->l);
3810 if (s) return s;
3811
3812 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3813
3814 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3815 s = bc_parse_expr(p, flags, bc_parse_next_param);
3816 if (s) return s;
3817
3818 comma = p->l.t.t == BC_LEX_COMMA;
3819 if (comma) {
3820 s = bc_lex_next(&p->l);
3821 if (s) return s;
3822 }
3823 }
3824
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003825 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003826 bc_parse_push(p, BC_INST_CALL);
3827 bc_parse_pushIndex(p, nparams);
3828
3829 return BC_STATUS_SUCCESS;
3830}
3831
3832static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3833{
3834 BcStatus s;
3835 BcId entry, *entry_ptr;
3836 size_t idx;
3837
3838 entry.name = name;
3839
3840 s = bc_parse_params(p, flags);
3841 if (s) goto err;
3842
3843 if (p->l.t.t != BC_LEX_RPAREN) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003844 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003845 goto err;
3846 }
3847
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003848 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003849
3850 if (idx == BC_VEC_INVALID_IDX) {
3851 name = xstrdup(entry.name);
3852 bc_parse_addFunc(p, name, &idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003853 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003854 free(entry.name);
3855 }
3856 else
3857 free(name);
3858
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003859 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003860 bc_parse_pushIndex(p, entry_ptr->idx);
3861
3862 return bc_lex_next(&p->l);
3863
3864err:
3865 free(name);
3866 return s;
3867}
3868
3869static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3870{
3871 BcStatus s;
3872 char *name;
3873
3874 name = xstrdup(p->l.t.v.v);
3875 s = bc_lex_next(&p->l);
3876 if (s) goto err;
3877
3878 if (p->l.t.t == BC_LEX_LBRACKET) {
3879
3880 s = bc_lex_next(&p->l);
3881 if (s) goto err;
3882
3883 if (p->l.t.t == BC_LEX_RBRACKET) {
3884
3885 if (!(flags & BC_PARSE_ARRAY)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003886 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003887 goto err;
3888 }
3889
3890 *type = BC_INST_ARRAY;
3891 }
3892 else {
3893
3894 *type = BC_INST_ARRAY_ELEM;
3895
3896 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3897 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3898 if (s) goto err;
3899 }
3900
3901 s = bc_lex_next(&p->l);
3902 if (s) goto err;
3903 bc_parse_push(p, *type);
3904 bc_parse_pushName(p, name);
3905 }
3906 else if (p->l.t.t == BC_LEX_LPAREN) {
3907
3908 if (flags & BC_PARSE_NOCALL) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003909 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003910 goto err;
3911 }
3912
3913 *type = BC_INST_CALL;
3914 s = bc_parse_call(p, name, flags);
3915 }
3916 else {
3917 *type = BC_INST_VAR;
3918 bc_parse_push(p, BC_INST_VAR);
3919 bc_parse_pushName(p, name);
3920 }
3921
3922 return s;
3923
3924err:
3925 free(name);
3926 return s;
3927}
3928
3929static BcStatus bc_parse_read(BcParse *p)
3930{
3931 BcStatus s;
3932
3933 s = bc_lex_next(&p->l);
3934 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003935 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003936
3937 s = bc_lex_next(&p->l);
3938 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003939 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003940
3941 bc_parse_push(p, BC_INST_READ);
3942
3943 return bc_lex_next(&p->l);
3944}
3945
3946static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3947 BcInst *prev)
3948{
3949 BcStatus s;
3950
3951 s = bc_lex_next(&p->l);
3952 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003953 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003954
3955 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3956
3957 s = bc_lex_next(&p->l);
3958 if (s) return s;
3959
3960 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3961 if (s) return s;
3962
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003963 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003964
3965 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3966 bc_parse_push(p, *prev);
3967
3968 return bc_lex_next(&p->l);
3969}
3970
3971static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3972{
3973 BcStatus s;
3974
3975 s = bc_lex_next(&p->l);
3976 if (s) return s;
3977
3978 if (p->l.t.t != BC_LEX_LPAREN) {
3979 *type = BC_INST_SCALE;
3980 bc_parse_push(p, BC_INST_SCALE);
3981 return BC_STATUS_SUCCESS;
3982 }
3983
3984 *type = BC_INST_SCALE_FUNC;
3985 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3986
3987 s = bc_lex_next(&p->l);
3988 if (s) return s;
3989
3990 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3991 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003992 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003993 bc_parse_push(p, BC_INST_SCALE_FUNC);
3994
3995 return bc_lex_next(&p->l);
3996}
3997
3998static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3999 size_t *nexprs, uint8_t flags)
4000{
4001 BcStatus s;
4002 BcLexType type;
4003 char inst;
4004 BcInst etype = *prev;
4005
4006 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4007 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4008 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4009 {
4010 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4011 bc_parse_push(p, inst);
4012 s = bc_lex_next(&p->l);
4013 }
4014 else {
4015
4016 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4017 *paren_expr = true;
4018
4019 s = bc_lex_next(&p->l);
4020 if (s) return s;
4021 type = p->l.t.t;
4022
4023 // Because we parse the next part of the expression
4024 // right here, we need to increment this.
4025 *nexprs = *nexprs + 1;
4026
4027 switch (type) {
4028
4029 case BC_LEX_NAME:
4030 {
4031 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4032 break;
4033 }
4034
4035 case BC_LEX_KEY_IBASE:
4036 case BC_LEX_KEY_LAST:
4037 case BC_LEX_KEY_OBASE:
4038 {
4039 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4040 s = bc_lex_next(&p->l);
4041 break;
4042 }
4043
4044 case BC_LEX_KEY_SCALE:
4045 {
4046 s = bc_lex_next(&p->l);
4047 if (s) return s;
4048 if (p->l.t.t == BC_LEX_LPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004049 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004050 else
4051 bc_parse_push(p, BC_INST_SCALE);
4052 break;
4053 }
4054
4055 default:
4056 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004057 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004058 break;
4059 }
4060 }
4061
4062 if (!s) bc_parse_push(p, inst);
4063 }
4064
4065 return s;
4066}
4067
4068static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4069 bool rparen, size_t *nexprs)
4070{
4071 BcStatus s;
4072 BcLexType type;
4073 BcInst etype = *prev;
4074
4075 s = bc_lex_next(&p->l);
4076 if (s) return s;
4077
4078 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4079 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4080 BC_LEX_OP_MINUS :
4081 BC_LEX_NEG;
4082 *prev = BC_PARSE_TOKEN_INST(type);
4083
4084 // We can just push onto the op stack because this is the largest
4085 // precedence operator that gets pushed. Inc/dec does not.
4086 if (type != BC_LEX_OP_MINUS)
4087 bc_vec_push(&p->ops, &type);
4088 else
4089 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4090
4091 return s;
4092}
4093
4094static BcStatus bc_parse_string(BcParse *p, char inst)
4095{
4096 char *str = xstrdup(p->l.t.v.v);
4097
4098 bc_parse_push(p, BC_INST_STR);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004099 bc_parse_pushIndex(p, G.prog.strs.len);
4100 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06004101 bc_parse_push(p, inst);
4102
4103 return bc_lex_next(&p->l);
4104}
4105
4106static BcStatus bc_parse_print(BcParse *p)
4107{
4108 BcStatus s;
4109 BcLexType type;
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004110 bool comma;
Gavin Howard01055ba2018-11-03 11:00:21 -06004111
4112 s = bc_lex_next(&p->l);
4113 if (s) return s;
4114
4115 type = p->l.t.t;
4116
4117 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004118 return bc_error("bad print statement");
Gavin Howard01055ba2018-11-03 11:00:21 -06004119
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004120 comma = false;
4121 while (type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004122
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004123 if (type == BC_LEX_STR) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004124 s = bc_parse_string(p, BC_INST_PRINT_POP);
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004125 if (s) return s;
4126 } else {
Gavin Howard01055ba2018-11-03 11:00:21 -06004127 s = bc_parse_expr(p, 0, bc_parse_next_print);
4128 if (s) return s;
4129 bc_parse_push(p, BC_INST_PRINT_POP);
4130 }
4131
Gavin Howard01055ba2018-11-03 11:00:21 -06004132 comma = p->l.t.t == BC_LEX_COMMA;
Denys Vlasenkoebc41c92018-12-08 23:36:28 +01004133 if (comma) {
4134 s = bc_lex_next(&p->l);
4135 if (s) return s;
4136 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004137 type = p->l.t.t;
4138 }
4139
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004140 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004141
4142 return bc_lex_next(&p->l);
4143}
4144
4145static BcStatus bc_parse_return(BcParse *p)
4146{
4147 BcStatus s;
4148 BcLexType t;
4149 bool paren;
4150
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004151 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004152
4153 s = bc_lex_next(&p->l);
4154 if (s) return s;
4155
4156 t = p->l.t.t;
4157 paren = t == BC_LEX_LPAREN;
4158
4159 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4160 bc_parse_push(p, BC_INST_RET0);
4161 else {
4162
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004163 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004164 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004165 bc_parse_push(p, BC_INST_RET0);
4166 s = bc_lex_next(&p->l);
Gavin Howard01055ba2018-11-03 11:00:21 -06004167 }
Denys Vlasenko452df922018-12-05 20:28:26 +01004168 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06004169
4170 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004171 s = bc_POSIX_requires("parentheses around return expressions");
Gavin Howard01055ba2018-11-03 11:00:21 -06004172 if (s) return s;
4173 }
4174
4175 bc_parse_push(p, BC_INST_RET);
4176 }
4177
4178 return s;
4179}
4180
4181static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4182{
4183 BcStatus s = BC_STATUS_SUCCESS;
4184
4185 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004186 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004187
4188 if (brace) {
4189
4190 if (p->l.t.t == BC_LEX_RBRACE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004191 if (!p->nbraces) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004192 --p->nbraces;
4193 s = bc_lex_next(&p->l);
4194 if (s) return s;
4195 }
4196 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004197 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004198 }
4199
4200 if (BC_PARSE_IF(p)) {
4201
4202 uint8_t *flag_ptr;
4203
4204 while (p->l.t.t == BC_LEX_NLINE) {
4205 s = bc_lex_next(&p->l);
4206 if (s) return s;
4207 }
4208
4209 bc_vec_pop(&p->flags);
4210
4211 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4212 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4213
4214 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4215 }
4216 else if (BC_PARSE_ELSE(p)) {
4217
4218 BcInstPtr *ip;
4219 size_t *label;
4220
4221 bc_vec_pop(&p->flags);
4222
4223 ip = bc_vec_top(&p->exits);
4224 label = bc_vec_item(&p->func->labels, ip->idx);
4225 *label = p->func->code.len;
4226
4227 bc_vec_pop(&p->exits);
4228 }
4229 else if (BC_PARSE_FUNC_INNER(p)) {
4230 bc_parse_push(p, BC_INST_RET0);
4231 bc_parse_updateFunc(p, BC_PROG_MAIN);
4232 bc_vec_pop(&p->flags);
4233 }
4234 else {
4235
4236 BcInstPtr *ip = bc_vec_top(&p->exits);
4237 size_t *label = bc_vec_top(&p->conds);
4238
4239 bc_parse_push(p, BC_INST_JUMP);
4240 bc_parse_pushIndex(p, *label);
4241
4242 label = bc_vec_item(&p->func->labels, ip->idx);
4243 *label = p->func->code.len;
4244
4245 bc_vec_pop(&p->flags);
4246 bc_vec_pop(&p->exits);
4247 bc_vec_pop(&p->conds);
4248 }
4249
4250 return s;
4251}
4252
4253static void bc_parse_startBody(BcParse *p, uint8_t flags)
4254{
4255 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4256 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4257 flags |= BC_PARSE_FLAG_BODY;
4258 bc_vec_push(&p->flags, &flags);
4259}
4260
4261static void bc_parse_noElse(BcParse *p)
4262{
4263 BcInstPtr *ip;
4264 size_t *label;
4265 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4266
4267 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4268
4269 ip = bc_vec_top(&p->exits);
4270 label = bc_vec_item(&p->func->labels, ip->idx);
4271 *label = p->func->code.len;
4272
4273 bc_vec_pop(&p->exits);
4274}
4275
4276static BcStatus bc_parse_if(BcParse *p)
4277{
4278 BcStatus s;
4279 BcInstPtr ip;
4280
4281 s = bc_lex_next(&p->l);
4282 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004283 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004284
4285 s = bc_lex_next(&p->l);
4286 if (s) return s;
4287 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4288 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004289 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004290
4291 s = bc_lex_next(&p->l);
4292 if (s) return s;
4293 bc_parse_push(p, BC_INST_JUMP_ZERO);
4294
4295 ip.idx = p->func->labels.len;
4296 ip.func = ip.len = 0;
4297
4298 bc_parse_pushIndex(p, ip.idx);
4299 bc_vec_push(&p->exits, &ip);
4300 bc_vec_push(&p->func->labels, &ip.idx);
4301 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4302
4303 return BC_STATUS_SUCCESS;
4304}
4305
4306static BcStatus bc_parse_else(BcParse *p)
4307{
4308 BcInstPtr ip;
4309
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004310 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004311
4312 ip.idx = p->func->labels.len;
4313 ip.func = ip.len = 0;
4314
4315 bc_parse_push(p, BC_INST_JUMP);
4316 bc_parse_pushIndex(p, ip.idx);
4317
4318 bc_parse_noElse(p);
4319
4320 bc_vec_push(&p->exits, &ip);
4321 bc_vec_push(&p->func->labels, &ip.idx);
4322 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4323
4324 return bc_lex_next(&p->l);
4325}
4326
4327static BcStatus bc_parse_while(BcParse *p)
4328{
4329 BcStatus s;
4330 BcInstPtr ip;
4331
4332 s = bc_lex_next(&p->l);
4333 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004334 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004335 s = bc_lex_next(&p->l);
4336 if (s) return s;
4337
4338 ip.idx = p->func->labels.len;
4339
4340 bc_vec_push(&p->func->labels, &p->func->code.len);
4341 bc_vec_push(&p->conds, &ip.idx);
4342
4343 ip.idx = p->func->labels.len;
4344 ip.func = 1;
4345 ip.len = 0;
4346
4347 bc_vec_push(&p->exits, &ip);
4348 bc_vec_push(&p->func->labels, &ip.idx);
4349
4350 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4351 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004352 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004353 s = bc_lex_next(&p->l);
4354 if (s) return s;
4355
4356 bc_parse_push(p, BC_INST_JUMP_ZERO);
4357 bc_parse_pushIndex(p, ip.idx);
4358 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4359
4360 return BC_STATUS_SUCCESS;
4361}
4362
4363static BcStatus bc_parse_for(BcParse *p)
4364{
4365 BcStatus s;
4366 BcInstPtr ip;
4367 size_t cond_idx, exit_idx, body_idx, update_idx;
4368
4369 s = bc_lex_next(&p->l);
4370 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004371 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004372 s = bc_lex_next(&p->l);
4373 if (s) return s;
4374
4375 if (p->l.t.t != BC_LEX_SCOLON)
4376 s = bc_parse_expr(p, 0, bc_parse_next_for);
4377 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004378 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
Gavin Howard01055ba2018-11-03 11:00:21 -06004379
4380 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004381 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004382 s = bc_lex_next(&p->l);
4383 if (s) return s;
4384
4385 cond_idx = p->func->labels.len;
4386 update_idx = cond_idx + 1;
4387 body_idx = update_idx + 1;
4388 exit_idx = body_idx + 1;
4389
4390 bc_vec_push(&p->func->labels, &p->func->code.len);
4391
4392 if (p->l.t.t != BC_LEX_SCOLON)
4393 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4394 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004395 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004396
4397 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004398 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004399
4400 s = bc_lex_next(&p->l);
4401 if (s) return s;
4402
4403 bc_parse_push(p, BC_INST_JUMP_ZERO);
4404 bc_parse_pushIndex(p, exit_idx);
4405 bc_parse_push(p, BC_INST_JUMP);
4406 bc_parse_pushIndex(p, body_idx);
4407
4408 ip.idx = p->func->labels.len;
4409
4410 bc_vec_push(&p->conds, &update_idx);
4411 bc_vec_push(&p->func->labels, &p->func->code.len);
4412
4413 if (p->l.t.t != BC_LEX_RPAREN)
4414 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4415 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004416 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
Gavin Howard01055ba2018-11-03 11:00:21 -06004417
4418 if (s) return s;
4419
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004420 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004421 bc_parse_push(p, BC_INST_JUMP);
4422 bc_parse_pushIndex(p, cond_idx);
4423 bc_vec_push(&p->func->labels, &p->func->code.len);
4424
4425 ip.idx = exit_idx;
4426 ip.func = 1;
4427 ip.len = 0;
4428
4429 bc_vec_push(&p->exits, &ip);
4430 bc_vec_push(&p->func->labels, &ip.idx);
4431 bc_lex_next(&p->l);
4432 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4433
4434 return BC_STATUS_SUCCESS;
4435}
4436
4437static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4438{
4439 BcStatus s;
4440 size_t i;
4441 BcInstPtr *ip;
4442
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004443 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004444
4445 if (type == BC_LEX_KEY_BREAK) {
4446
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004447 if (p->exits.len == 0) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004448
4449 i = p->exits.len - 1;
4450 ip = bc_vec_item(&p->exits, i);
4451
4452 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004453 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004454
4455 i = ip->idx;
4456 }
4457 else
4458 i = *((size_t *) bc_vec_top(&p->conds));
4459
4460 bc_parse_push(p, BC_INST_JUMP);
4461 bc_parse_pushIndex(p, i);
4462
4463 s = bc_lex_next(&p->l);
4464 if (s) return s;
4465
4466 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004467 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004468
4469 return bc_lex_next(&p->l);
4470}
4471
4472static BcStatus bc_parse_func(BcParse *p)
4473{
4474 BcStatus s;
4475 bool var, comma = false;
4476 uint8_t flags;
4477 char *name;
4478
4479 s = bc_lex_next(&p->l);
4480 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004481 if (p->l.t.t != BC_LEX_NAME)
4482 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004483
4484 name = xstrdup(p->l.t.v.v);
4485 bc_parse_addFunc(p, name, &p->fidx);
4486
4487 s = bc_lex_next(&p->l);
4488 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004489 if (p->l.t.t != BC_LEX_LPAREN)
4490 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004491 s = bc_lex_next(&p->l);
4492 if (s) return s;
4493
4494 while (p->l.t.t != BC_LEX_RPAREN) {
4495
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004496 if (p->l.t.t != BC_LEX_NAME)
4497 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004498
4499 ++p->func->nparams;
4500
4501 name = xstrdup(p->l.t.v.v);
4502 s = bc_lex_next(&p->l);
4503 if (s) goto err;
4504
4505 var = p->l.t.t != BC_LEX_LBRACKET;
4506
4507 if (!var) {
4508
4509 s = bc_lex_next(&p->l);
4510 if (s) goto err;
4511
4512 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004513 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004514 goto err;
4515 }
4516
4517 s = bc_lex_next(&p->l);
4518 if (s) goto err;
4519 }
4520
4521 comma = p->l.t.t == BC_LEX_COMMA;
4522 if (comma) {
4523 s = bc_lex_next(&p->l);
4524 if (s) goto err;
4525 }
4526
4527 s = bc_func_insert(p->func, name, var);
4528 if (s) goto err;
4529 }
4530
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004531 if (comma) return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004532
4533 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4534 bc_parse_startBody(p, flags);
4535
4536 s = bc_lex_next(&p->l);
4537 if (s) return s;
4538
4539 if (p->l.t.t != BC_LEX_LBRACE)
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004540 s = bc_POSIX_requires("the left brace be on the same line as the function header");
Gavin Howard01055ba2018-11-03 11:00:21 -06004541
4542 return s;
4543
4544err:
4545 free(name);
4546 return s;
4547}
4548
4549static BcStatus bc_parse_auto(BcParse *p)
4550{
4551 BcStatus s;
4552 bool comma, var, one;
4553 char *name;
4554
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004555 if (!p->auto_part) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004556 s = bc_lex_next(&p->l);
4557 if (s) return s;
4558
4559 p->auto_part = comma = false;
4560 one = p->l.t.t == BC_LEX_NAME;
4561
4562 while (p->l.t.t == BC_LEX_NAME) {
4563
4564 name = xstrdup(p->l.t.v.v);
4565 s = bc_lex_next(&p->l);
4566 if (s) goto err;
4567
4568 var = p->l.t.t != BC_LEX_LBRACKET;
4569 if (!var) {
4570
4571 s = bc_lex_next(&p->l);
4572 if (s) goto err;
4573
4574 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004575 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004576 goto err;
4577 }
4578
4579 s = bc_lex_next(&p->l);
4580 if (s) goto err;
4581 }
4582
4583 comma = p->l.t.t == BC_LEX_COMMA;
4584 if (comma) {
4585 s = bc_lex_next(&p->l);
4586 if (s) goto err;
4587 }
4588
4589 s = bc_func_insert(p->func, name, var);
4590 if (s) goto err;
4591 }
4592
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004593 if (comma) return bc_error("bad function definition");
Denys Vlasenkoabbc4332018-12-03 21:46:41 +01004594 if (!one) return bc_error("no auto variable found");
Gavin Howard01055ba2018-11-03 11:00:21 -06004595
4596 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004597 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004598
4599 return bc_lex_next(&p->l);
4600
4601err:
4602 free(name);
4603 return s;
4604}
4605
4606static BcStatus bc_parse_body(BcParse *p, bool brace)
4607{
4608 BcStatus s = BC_STATUS_SUCCESS;
4609 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4610
4611 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4612
4613 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4614
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004615 if (!brace) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004616 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4617
4618 if (!p->auto_part) {
4619 s = bc_parse_auto(p);
4620 if (s) return s;
4621 }
4622
4623 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4624 }
4625 else {
4626 s = bc_parse_stmt(p);
4627 if (!s && !brace) s = bc_parse_endBody(p, false);
4628 }
4629
4630 return s;
4631}
4632
4633static BcStatus bc_parse_stmt(BcParse *p)
4634{
4635 BcStatus s = BC_STATUS_SUCCESS;
4636
4637 switch (p->l.t.t) {
4638
4639 case BC_LEX_NLINE:
4640 {
4641 return bc_lex_next(&p->l);
4642 }
4643
4644 case BC_LEX_KEY_ELSE:
4645 {
4646 p->auto_part = false;
4647 break;
4648 }
4649
4650 case BC_LEX_LBRACE:
4651 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004652 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004653
4654 ++p->nbraces;
4655 s = bc_lex_next(&p->l);
4656 if (s) return s;
4657
4658 return bc_parse_body(p, true);
4659 }
4660
4661 case BC_LEX_KEY_AUTO:
4662 {
4663 return bc_parse_auto(p);
4664 }
4665
4666 default:
4667 {
4668 p->auto_part = false;
4669
4670 if (BC_PARSE_IF_END(p)) {
4671 bc_parse_noElse(p);
4672 return BC_STATUS_SUCCESS;
4673 }
4674 else if (BC_PARSE_BODY(p))
4675 return bc_parse_body(p, false);
4676
4677 break;
4678 }
4679 }
4680
4681 switch (p->l.t.t) {
4682
4683 case BC_LEX_OP_INC:
4684 case BC_LEX_OP_DEC:
4685 case BC_LEX_OP_MINUS:
4686 case BC_LEX_OP_BOOL_NOT:
4687 case BC_LEX_LPAREN:
4688 case BC_LEX_NAME:
4689 case BC_LEX_NUMBER:
4690 case BC_LEX_KEY_IBASE:
4691 case BC_LEX_KEY_LAST:
4692 case BC_LEX_KEY_LENGTH:
4693 case BC_LEX_KEY_OBASE:
4694 case BC_LEX_KEY_READ:
4695 case BC_LEX_KEY_SCALE:
4696 case BC_LEX_KEY_SQRT:
4697 {
4698 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4699 break;
4700 }
4701
4702 case BC_LEX_KEY_ELSE:
4703 {
4704 s = bc_parse_else(p);
4705 break;
4706 }
4707
4708 case BC_LEX_SCOLON:
4709 {
4710 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4711 break;
4712 }
4713
4714 case BC_LEX_RBRACE:
4715 {
4716 s = bc_parse_endBody(p, true);
4717 break;
4718 }
4719
4720 case BC_LEX_STR:
4721 {
4722 s = bc_parse_string(p, BC_INST_PRINT_STR);
4723 break;
4724 }
4725
4726 case BC_LEX_KEY_BREAK:
4727 case BC_LEX_KEY_CONTINUE:
4728 {
4729 s = bc_parse_loopExit(p, p->l.t.t);
4730 break;
4731 }
4732
4733 case BC_LEX_KEY_FOR:
4734 {
4735 s = bc_parse_for(p);
4736 break;
4737 }
4738
4739 case BC_LEX_KEY_HALT:
4740 {
4741 bc_parse_push(p, BC_INST_HALT);
4742 s = bc_lex_next(&p->l);
4743 break;
4744 }
4745
4746 case BC_LEX_KEY_IF:
4747 {
4748 s = bc_parse_if(p);
4749 break;
4750 }
4751
4752 case BC_LEX_KEY_LIMITS:
4753 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004754 // "limits" is a compile-time command,
4755 // the output is produced at _parse time_.
Gavin Howard01055ba2018-11-03 11:00:21 -06004756 s = bc_lex_next(&p->l);
4757 if (s) return s;
Denys Vlasenko64074a12018-12-07 15:50:14 +01004758 printf(
4759 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4760 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4761 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4762 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4763 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4764 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4765 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4766 "Number of vars = "BC_MAX_VARS_STR "\n"
4767 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004768 break;
4769 }
4770
4771 case BC_LEX_KEY_PRINT:
4772 {
4773 s = bc_parse_print(p);
4774 break;
4775 }
4776
4777 case BC_LEX_KEY_QUIT:
4778 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004779 // "quit" is a compile-time command. For example,
4780 // "if (0 == 1) quit" terminates when parsing the statement,
4781 // not when it is executed
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01004782 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06004783 }
4784
4785 case BC_LEX_KEY_RETURN:
4786 {
4787 s = bc_parse_return(p);
4788 break;
4789 }
4790
4791 case BC_LEX_KEY_WHILE:
4792 {
4793 s = bc_parse_while(p);
4794 break;
4795 }
4796
4797 default:
4798 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004799 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004800 break;
4801 }
4802 }
4803
4804 return s;
4805}
4806
4807static BcStatus bc_parse_parse(BcParse *p)
4808{
4809 BcStatus s;
4810
4811 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004812 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 -06004813 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004814 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004815 s = bc_parse_func(p);
4816 }
4817 else
4818 s = bc_parse_stmt(p);
4819
Denys Vlasenkod38af482018-12-04 19:11:02 +01004820 if (s || G_interrupt) {
4821 bc_parse_reset(p);
4822 s = BC_STATUS_FAILURE;
4823 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004824
4825 return s;
4826}
4827
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004828static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
Gavin Howard01055ba2018-11-03 11:00:21 -06004829{
4830 BcStatus s = BC_STATUS_SUCCESS;
4831 BcInst prev = BC_INST_PRINT;
4832 BcLexType top, t = p->l.t.t;
4833 size_t nexprs = 0, ops_bgn = p->ops.len;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01004834 unsigned nparens, nrelops;
Gavin Howard01055ba2018-11-03 11:00:21 -06004835 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4836
4837 paren_first = p->l.t.t == BC_LEX_LPAREN;
4838 nparens = nrelops = 0;
4839 paren_expr = rprn = done = get_token = assign = false;
4840 bin_last = true;
4841
Denys Vlasenkobcb62a72018-12-05 20:17:48 +01004842 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004843 switch (t) {
4844
4845 case BC_LEX_OP_INC:
4846 case BC_LEX_OP_DEC:
4847 {
4848 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4849 rprn = get_token = bin_last = false;
4850 break;
4851 }
4852
4853 case BC_LEX_OP_MINUS:
4854 {
4855 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4856 rprn = get_token = false;
4857 bin_last = prev == BC_INST_MINUS;
4858 break;
4859 }
4860
4861 case BC_LEX_OP_ASSIGN_POWER:
4862 case BC_LEX_OP_ASSIGN_MULTIPLY:
4863 case BC_LEX_OP_ASSIGN_DIVIDE:
4864 case BC_LEX_OP_ASSIGN_MODULUS:
4865 case BC_LEX_OP_ASSIGN_PLUS:
4866 case BC_LEX_OP_ASSIGN_MINUS:
4867 case BC_LEX_OP_ASSIGN:
4868 {
4869 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4870 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4871 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4872 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004873 s = bc_error("bad assignment:"
4874 " left side must be scale,"
4875 " ibase, obase, last, var,"
4876 " or array element"
4877 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004878 break;
4879 }
4880 }
4881 // Fallthrough.
4882 case BC_LEX_OP_POWER:
4883 case BC_LEX_OP_MULTIPLY:
4884 case BC_LEX_OP_DIVIDE:
4885 case BC_LEX_OP_MODULUS:
4886 case BC_LEX_OP_PLUS:
4887 case BC_LEX_OP_REL_EQ:
4888 case BC_LEX_OP_REL_LE:
4889 case BC_LEX_OP_REL_GE:
4890 case BC_LEX_OP_REL_NE:
4891 case BC_LEX_OP_REL_LT:
4892 case BC_LEX_OP_REL_GT:
4893 case BC_LEX_OP_BOOL_NOT:
4894 case BC_LEX_OP_BOOL_OR:
4895 case BC_LEX_OP_BOOL_AND:
4896 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004897 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4898 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4899 ) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004900 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004901 }
4902
4903 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4904 prev = BC_PARSE_TOKEN_INST(t);
4905 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4906 rprn = get_token = false;
4907 bin_last = t != BC_LEX_OP_BOOL_NOT;
4908
4909 break;
4910 }
4911
4912 case BC_LEX_LPAREN:
4913 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004914 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004915 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004916 ++nparens;
4917 paren_expr = rprn = bin_last = false;
4918 get_token = true;
4919 bc_vec_push(&p->ops, &t);
4920
4921 break;
4922 }
4923
4924 case BC_LEX_RPAREN:
4925 {
4926 if (bin_last || prev == BC_INST_BOOL_NOT)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004927 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004928
4929 if (nparens == 0) {
4930 s = BC_STATUS_SUCCESS;
4931 done = true;
4932 get_token = false;
4933 break;
4934 }
4935 else if (!paren_expr)
4936 return BC_STATUS_PARSE_EMPTY_EXP;
4937
4938 --nparens;
4939 paren_expr = rprn = true;
4940 get_token = bin_last = false;
4941
4942 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4943
4944 break;
4945 }
4946
4947 case BC_LEX_NAME:
4948 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004949 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004950 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004951 paren_expr = true;
4952 rprn = get_token = bin_last = false;
4953 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4954 ++nexprs;
4955
4956 break;
4957 }
4958
4959 case BC_LEX_NUMBER:
4960 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004961 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004962 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004963 bc_parse_number(p, &prev, &nexprs);
4964 paren_expr = get_token = true;
4965 rprn = bin_last = false;
4966
4967 break;
4968 }
4969
4970 case BC_LEX_KEY_IBASE:
4971 case BC_LEX_KEY_LAST:
4972 case BC_LEX_KEY_OBASE:
4973 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004974 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004975 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004976 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4977 bc_parse_push(p, (char) prev);
4978
4979 paren_expr = get_token = true;
4980 rprn = bin_last = false;
4981 ++nexprs;
4982
4983 break;
4984 }
4985
4986 case BC_LEX_KEY_LENGTH:
4987 case BC_LEX_KEY_SQRT:
4988 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004989 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004990 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004991 s = bc_parse_builtin(p, t, flags, &prev);
4992 paren_expr = true;
4993 rprn = get_token = bin_last = false;
4994 ++nexprs;
4995
4996 break;
4997 }
4998
4999 case BC_LEX_KEY_READ:
5000 {
5001 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005002 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005003 else if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005004 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005005 else
5006 s = bc_parse_read(p);
5007
5008 paren_expr = true;
5009 rprn = get_token = bin_last = false;
5010 ++nexprs;
5011 prev = BC_INST_READ;
5012
5013 break;
5014 }
5015
5016 case BC_LEX_KEY_SCALE:
5017 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005018 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005019 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005020 s = bc_parse_scale(p, &prev, flags);
5021 paren_expr = true;
5022 rprn = get_token = bin_last = false;
5023 ++nexprs;
5024 prev = BC_INST_SCALE;
5025
5026 break;
5027 }
5028
5029 default:
5030 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005031 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005032 break;
5033 }
5034 }
5035
5036 if (!s && get_token) s = bc_lex_next(&p->l);
5037 }
5038
5039 if (s) return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01005040 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
Gavin Howard01055ba2018-11-03 11:00:21 -06005041
5042 while (p->ops.len > ops_bgn) {
5043
5044 top = BC_PARSE_TOP_OP(p);
5045 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5046
5047 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005048 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005049
5050 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5051
5052 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5053 bc_vec_pop(&p->ops);
5054 }
5055
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005056 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005057 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005058
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005059 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5060 for (;;) {
5061 if (t == (next & 0x7f))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005062 goto ok;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005063 if (next & 0x80) // last element?
5064 break;
5065 next >>= 8;
5066 }
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005067 return bc_error_bad_expression();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005068 ok:
Gavin Howard01055ba2018-11-03 11:00:21 -06005069
5070 if (!(flags & BC_PARSE_REL) && nrelops) {
Denys Vlasenko00646792018-12-05 18:12:27 +01005071 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
Gavin Howard01055ba2018-11-03 11:00:21 -06005072 if (s) return s;
5073 }
5074 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01005075 s = bc_POSIX_requires("exactly one comparison operator per condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06005076 if (s) return s;
5077 }
5078
5079 if (flags & BC_PARSE_PRINT) {
5080 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5081 bc_parse_push(p, BC_INST_POP);
5082 }
5083
5084 return s;
5085}
5086
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01005087static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5088{
5089 BcStatus s;
5090
5091 s = bc_parse_expr_empty_ok(p, flags, next);
5092 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5093 return bc_error("empty expression");
5094 return s;
5095}
5096
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005097static void bc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005098{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005099 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005100}
5101
5102static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5103{
5104 return bc_parse_expr(p, flags, bc_parse_next_read);
5105}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005106
Gavin Howard01055ba2018-11-03 11:00:21 -06005107#endif // ENABLE_BC
5108
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005109#if ENABLE_DC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005110
5111#define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5112
Gavin Howard01055ba2018-11-03 11:00:21 -06005113static BcStatus dc_parse_register(BcParse *p)
5114{
5115 BcStatus s;
5116 char *name;
5117
5118 s = bc_lex_next(&p->l);
5119 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005120 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005121
5122 name = xstrdup(p->l.t.v.v);
5123 bc_parse_pushName(p, name);
5124
5125 return s;
5126}
5127
5128static BcStatus dc_parse_string(BcParse *p)
5129{
5130 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005131 size_t idx, len = G.prog.strs.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005132
5133 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5134 name = xstrdup(b);
5135
5136 str = xstrdup(p->l.t.v.v);
5137 bc_parse_push(p, BC_INST_STR);
5138 bc_parse_pushIndex(p, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005139 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06005140 bc_parse_addFunc(p, name, &idx);
5141
5142 return bc_lex_next(&p->l);
5143}
5144
5145static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5146{
5147 BcStatus s;
5148
5149 bc_parse_push(p, inst);
5150 if (name) {
5151 s = dc_parse_register(p);
5152 if (s) return s;
5153 }
5154
5155 if (store) {
5156 bc_parse_push(p, BC_INST_SWAP);
5157 bc_parse_push(p, BC_INST_ASSIGN);
5158 bc_parse_push(p, BC_INST_POP);
5159 }
5160
5161 return bc_lex_next(&p->l);
5162}
5163
5164static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5165{
5166 BcStatus s;
5167
5168 bc_parse_push(p, inst);
5169 bc_parse_push(p, BC_INST_EXEC_COND);
5170
5171 s = dc_parse_register(p);
5172 if (s) return s;
5173
5174 s = bc_lex_next(&p->l);
5175 if (s) return s;
5176
5177 if (p->l.t.t == BC_LEX_ELSE) {
5178 s = dc_parse_register(p);
5179 if (s) return s;
5180 s = bc_lex_next(&p->l);
5181 }
5182 else
5183 bc_parse_push(p, BC_PARSE_STREND);
5184
5185 return s;
5186}
5187
5188static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5189{
5190 BcStatus s = BC_STATUS_SUCCESS;
5191 BcInst prev;
5192 uint8_t inst;
5193 bool assign, get_token = false;
5194
5195 switch (t) {
5196
5197 case BC_LEX_OP_REL_EQ:
5198 case BC_LEX_OP_REL_LE:
5199 case BC_LEX_OP_REL_GE:
5200 case BC_LEX_OP_REL_NE:
5201 case BC_LEX_OP_REL_LT:
5202 case BC_LEX_OP_REL_GT:
5203 {
5204 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5205 break;
5206 }
5207
5208 case BC_LEX_SCOLON:
5209 case BC_LEX_COLON:
5210 {
5211 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5212 break;
5213 }
5214
5215 case BC_LEX_STR:
5216 {
5217 s = dc_parse_string(p);
5218 break;
5219 }
5220
5221 case BC_LEX_NEG:
5222 case BC_LEX_NUMBER:
5223 {
5224 if (t == BC_LEX_NEG) {
5225 s = bc_lex_next(&p->l);
5226 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005227 if (p->l.t.t != BC_LEX_NUMBER)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005228 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005229 }
5230
5231 bc_parse_number(p, &prev, &p->nbraces);
5232
5233 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5234 get_token = true;
5235
5236 break;
5237 }
5238
5239 case BC_LEX_KEY_READ:
5240 {
5241 if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005242 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005243 else
5244 bc_parse_push(p, BC_INST_READ);
5245 get_token = true;
5246 break;
5247 }
5248
5249 case BC_LEX_OP_ASSIGN:
5250 case BC_LEX_STORE_PUSH:
5251 {
5252 assign = t == BC_LEX_OP_ASSIGN;
5253 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5254 s = dc_parse_mem(p, inst, true, assign);
5255 break;
5256 }
5257
5258 case BC_LEX_LOAD:
5259 case BC_LEX_LOAD_POP:
5260 {
5261 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5262 s = dc_parse_mem(p, inst, true, false);
5263 break;
5264 }
5265
5266 case BC_LEX_STORE_IBASE:
5267 case BC_LEX_STORE_SCALE:
5268 case BC_LEX_STORE_OBASE:
5269 {
5270 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5271 s = dc_parse_mem(p, inst, false, true);
5272 break;
5273 }
5274
5275 default:
5276 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005277 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005278 get_token = true;
5279 break;
5280 }
5281 }
5282
5283 if (!s && get_token) s = bc_lex_next(&p->l);
5284
5285 return s;
5286}
5287
5288static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5289{
5290 BcStatus s = BC_STATUS_SUCCESS;
5291 BcInst inst;
5292 BcLexType t;
5293
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005294 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005295
5296 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5297
5298 inst = dc_parse_insts[t];
5299
5300 if (inst != BC_INST_INVALID) {
5301 bc_parse_push(p, inst);
5302 s = bc_lex_next(&p->l);
5303 }
5304 else
5305 s = dc_parse_token(p, t, flags);
5306 }
5307
5308 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5309 bc_parse_push(p, BC_INST_POP_EXEC);
5310
5311 return s;
5312}
5313
5314static BcStatus dc_parse_parse(BcParse *p)
5315{
5316 BcStatus s;
5317
5318 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005319 s = bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06005320 else
5321 s = dc_parse_expr(p, 0);
5322
Denys Vlasenkod38af482018-12-04 19:11:02 +01005323 if (s || G_interrupt) {
5324 bc_parse_reset(p);
5325 s = BC_STATUS_FAILURE;
5326 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005327
5328 return s;
5329}
5330
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005331static void dc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005332{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005333 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005334}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005335
Gavin Howard01055ba2018-11-03 11:00:21 -06005336#endif // ENABLE_DC
5337
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005338static void common_parse_init(BcParse *p, size_t func)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005339{
5340 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005341 IF_BC(bc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005342 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005343 IF_DC(dc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005344 }
5345}
5346
5347static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5348{
5349 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005350 IF_BC(return bc_parse_expression(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005351 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005352 IF_DC(return dc_parse_expr(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005353 }
5354}
5355
Denys Vlasenkodf515392018-12-02 19:27:48 +01005356static BcVec* bc_program_search(char *id, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005357{
Gavin Howard01055ba2018-11-03 11:00:21 -06005358 BcId e, *ptr;
5359 BcVec *v, *map;
5360 size_t i;
5361 BcResultData data;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005362 int new;
Gavin Howard01055ba2018-11-03 11:00:21 -06005363
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005364 v = var ? &G.prog.vars : &G.prog.arrs;
5365 map = var ? &G.prog.var_map : &G.prog.arr_map;
Gavin Howard01055ba2018-11-03 11:00:21 -06005366
5367 e.name = id;
5368 e.idx = v->len;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005369 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
Gavin Howard01055ba2018-11-03 11:00:21 -06005370
5371 if (new) {
5372 bc_array_init(&data.v, var);
5373 bc_vec_push(v, &data.v);
5374 }
5375
5376 ptr = bc_vec_item(map, i);
5377 if (new) ptr->name = xstrdup(e.name);
Denys Vlasenkodf515392018-12-02 19:27:48 +01005378 return bc_vec_item(v, ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005379}
5380
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005381static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
Gavin Howard01055ba2018-11-03 11:00:21 -06005382{
5383 BcStatus s = BC_STATUS_SUCCESS;
5384
5385 switch (r->t) {
5386
5387 case BC_RESULT_STR:
5388 case BC_RESULT_TEMP:
5389 case BC_RESULT_IBASE:
5390 case BC_RESULT_SCALE:
5391 case BC_RESULT_OBASE:
5392 {
5393 *num = &r->d.n;
5394 break;
5395 }
5396
5397 case BC_RESULT_CONSTANT:
5398 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005399 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005400 size_t base_t, len = strlen(*str);
5401 BcNum *base;
5402
5403 bc_num_init(&r->d.n, len);
5404
5405 hex = hex && len == 1;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005406 base = hex ? &G.prog.hexb : &G.prog.ib;
5407 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005408 s = bc_num_parse(&r->d.n, *str, base, base_t);
5409
5410 if (s) {
5411 bc_num_free(&r->d.n);
5412 return s;
5413 }
5414
5415 *num = &r->d.n;
5416 r->t = BC_RESULT_TEMP;
5417
5418 break;
5419 }
5420
5421 case BC_RESULT_VAR:
5422 case BC_RESULT_ARRAY:
5423 case BC_RESULT_ARRAY_ELEM:
5424 {
5425 BcVec *v;
5426
Denys Vlasenkodf515392018-12-02 19:27:48 +01005427 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
Gavin Howard01055ba2018-11-03 11:00:21 -06005428
5429 if (r->t == BC_RESULT_ARRAY_ELEM) {
5430 v = bc_vec_top(v);
5431 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5432 *num = bc_vec_item(v, r->d.id.idx);
5433 }
5434 else
5435 *num = bc_vec_top(v);
5436
5437 break;
5438 }
5439
5440 case BC_RESULT_LAST:
5441 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005442 *num = &G.prog.last;
Gavin Howard01055ba2018-11-03 11:00:21 -06005443 break;
5444 }
5445
5446 case BC_RESULT_ONE:
5447 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005448 *num = &G.prog.one;
Gavin Howard01055ba2018-11-03 11:00:21 -06005449 break;
5450 }
5451 }
5452
5453 return s;
5454}
5455
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005456static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
Gavin Howard01055ba2018-11-03 11:00:21 -06005457 BcResult **r, BcNum **rn, bool assign)
5458{
5459 BcStatus s;
5460 bool hex;
5461 BcResultType lt, rt;
5462
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005463 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005464 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005465
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005466 *r = bc_vec_item_rev(&G.prog.results, 0);
5467 *l = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06005468
5469 lt = (*l)->t;
5470 rt = (*r)->t;
5471 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5472
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005473 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005474 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005475 s = bc_program_num(*r, rn, hex);
Gavin Howard01055ba2018-11-03 11:00:21 -06005476 if (s) return s;
5477
5478 // We run this again under these conditions in case any vector has been
5479 // reallocated out from under the BcNums or arrays we had.
5480 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005481 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005482 if (s) return s;
5483 }
5484
5485 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005486 return bc_error_variable_is_wrong_type();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005487 if (!assign && !BC_PROG_NUM((*r), (*ln)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005488 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005489
Gavin Howard01055ba2018-11-03 11:00:21 -06005490 return s;
5491}
5492
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005493static void bc_program_binOpRetire(BcResult *r)
Gavin Howard01055ba2018-11-03 11:00:21 -06005494{
5495 r->t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005496 bc_vec_pop(&G.prog.results);
5497 bc_vec_pop(&G.prog.results);
5498 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005499}
5500
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005501static BcStatus bc_program_prep(BcResult **r, BcNum **n)
Gavin Howard01055ba2018-11-03 11:00:21 -06005502{
5503 BcStatus s;
5504
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005505 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005506 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005507 *r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005508
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005509 s = bc_program_num(*r, n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005510 if (s) return s;
5511
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005512 if (!BC_PROG_NUM((*r), (*n)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005513 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005514
5515 return s;
5516}
5517
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005518static void bc_program_retire(BcResult *r, BcResultType t)
Gavin Howard01055ba2018-11-03 11:00:21 -06005519{
5520 r->t = t;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005521 bc_vec_pop(&G.prog.results);
5522 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005523}
5524
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005525static BcStatus bc_program_op(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005526{
5527 BcStatus s;
5528 BcResult *opd1, *opd2, res;
5529 BcNum *n1, *n2 = NULL;
5530
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005531 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005532 if (s) return s;
5533 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5534
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005535 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005536 if (s) goto err;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005537 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005538
5539 return s;
5540
5541err:
5542 bc_num_free(&res.d.n);
5543 return s;
5544}
5545
Denys Vlasenko785e4b32018-12-02 17:18:52 +01005546static BcStatus bc_program_read(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005547{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005548 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005549 BcStatus s;
5550 BcParse parse;
5551 BcVec buf;
5552 BcInstPtr ip;
5553 size_t i;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005554 BcFunc *f = bc_program_func(BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005555
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005556 for (i = 0; i < G.prog.stack.len; ++i) {
5557 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005558 if (ip_ptr->func == BC_PROG_READ)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005559 return bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005560 }
5561
Denys Vlasenko7d628012018-12-04 21:46:47 +01005562 bc_vec_pop_all(&f->code);
5563 bc_char_vec_init(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005564
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005565 sv_file = G.prog.file;
5566 G.prog.file = NULL;
5567
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01005568 s = bc_read_line(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005569 if (s) goto io_err;
5570
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005571 common_parse_init(&parse, BC_PROG_READ);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005572 bc_lex_file(&parse.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005573
5574 s = bc_parse_text(&parse, buf.v);
5575 if (s) goto exec_err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005576 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
Gavin Howard01055ba2018-11-03 11:00:21 -06005577 if (s) goto exec_err;
5578
5579 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005580 s = bc_error("bad read() expression");
Gavin Howard01055ba2018-11-03 11:00:21 -06005581 goto exec_err;
5582 }
5583
5584 ip.func = BC_PROG_READ;
5585 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005586 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005587
5588 // Update this pointer, just in case.
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005589 f = bc_program_func(BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005590
5591 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005592 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06005593
5594exec_err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005595 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005596 bc_parse_free(&parse);
5597io_err:
5598 bc_vec_free(&buf);
5599 return s;
5600}
5601
5602static size_t bc_program_index(char *code, size_t *bgn)
5603{
5604 char amt = code[(*bgn)++], i = 0;
5605 size_t res = 0;
5606
5607 for (; i < amt; ++i, ++(*bgn))
5608 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5609
5610 return res;
5611}
5612
5613static char *bc_program_name(char *code, size_t *bgn)
5614{
5615 size_t i;
5616 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5617
5618 s = xmalloc(ptr - str + 1);
5619 c = code[(*bgn)++];
5620
5621 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5622 s[i] = c;
5623
5624 s[i] = '\0';
5625
5626 return s;
5627}
5628
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005629static void bc_program_printString(const char *str)
Gavin Howard01055ba2018-11-03 11:00:21 -06005630{
5631 size_t i, len = strlen(str);
5632
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005633#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005634 if (len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005635 bb_putchar('\0');
Gavin Howard01055ba2018-11-03 11:00:21 -06005636 return;
5637 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005638#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005639
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005640 for (i = 0; i < len; ++i, ++G.prog.nchars) {
Gavin Howard01055ba2018-11-03 11:00:21 -06005641
5642 int c = str[i];
5643
5644 if (c != '\\' || i == len - 1)
Denys Vlasenko00d77792018-11-30 23:13:42 +01005645 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005646 else {
5647
5648 c = str[++i];
5649
5650 switch (c) {
5651
5652 case 'a':
5653 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005654 bb_putchar('\a');
Gavin Howard01055ba2018-11-03 11:00:21 -06005655 break;
5656 }
5657
5658 case 'b':
5659 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005660 bb_putchar('\b');
Gavin Howard01055ba2018-11-03 11:00:21 -06005661 break;
5662 }
5663
5664 case '\\':
5665 case 'e':
5666 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005667 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005668 break;
5669 }
5670
5671 case 'f':
5672 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005673 bb_putchar('\f');
Gavin Howard01055ba2018-11-03 11:00:21 -06005674 break;
5675 }
5676
5677 case 'n':
5678 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005679 bb_putchar('\n');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005680 G.prog.nchars = SIZE_MAX;
Gavin Howard01055ba2018-11-03 11:00:21 -06005681 break;
5682 }
5683
5684 case 'r':
5685 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005686 bb_putchar('\r');
Gavin Howard01055ba2018-11-03 11:00:21 -06005687 break;
5688 }
5689
5690 case 'q':
5691 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005692 bb_putchar('"');
Gavin Howard01055ba2018-11-03 11:00:21 -06005693 break;
5694 }
5695
5696 case 't':
5697 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005698 bb_putchar('\t');
Gavin Howard01055ba2018-11-03 11:00:21 -06005699 break;
5700 }
5701
5702 default:
5703 {
5704 // Just print the backslash and following character.
Denys Vlasenko00d77792018-11-30 23:13:42 +01005705 bb_putchar('\\');
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005706 ++G.prog.nchars;
Denys Vlasenko00d77792018-11-30 23:13:42 +01005707 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005708 break;
5709 }
5710 }
5711 }
5712 }
5713}
5714
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005715static BcStatus bc_program_print(char inst, size_t idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005716{
5717 BcStatus s = BC_STATUS_SUCCESS;
5718 BcResult *r;
5719 size_t len, i;
5720 char *str;
5721 BcNum *num = NULL;
5722 bool pop = inst != BC_INST_PRINT;
5723
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005724 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005725 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005726
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005727 r = bc_vec_item_rev(&G.prog.results, idx);
5728 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005729 if (s) return s;
5730
5731 if (BC_PROG_NUM(r, num)) {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005732 s = bc_num_print(num, !pop);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005733 if (!s) bc_num_copy(&G.prog.last, num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005734 }
5735 else {
5736
5737 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01005738 str = *bc_program_str(idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005739
5740 if (inst == BC_INST_PRINT_STR) {
5741 for (i = 0, len = strlen(str); i < len; ++i) {
5742 char c = str[i];
Denys Vlasenko00d77792018-11-30 23:13:42 +01005743 bb_putchar(c);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005744 if (c == '\n') G.prog.nchars = SIZE_MAX;
5745 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06005746 }
5747 }
5748 else {
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01005749 bc_program_printString(str);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005750 if (inst == BC_INST_PRINT) bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005751 }
5752 }
5753
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005754 if (!s && pop) bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005755
5756 return s;
5757}
5758
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005759static BcStatus bc_program_negate(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005760{
5761 BcStatus s;
5762 BcResult res, *ptr;
5763 BcNum *num = NULL;
5764
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005765 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005766 if (s) return s;
5767
5768 bc_num_init(&res.d.n, num->len);
5769 bc_num_copy(&res.d.n, num);
5770 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5771
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005772 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06005773
5774 return s;
5775}
5776
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005777static BcStatus bc_program_logical(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005778{
5779 BcStatus s;
5780 BcResult *opd1, *opd2, res;
5781 BcNum *n1, *n2;
5782 bool cond = 0;
5783 ssize_t cmp;
5784
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005785 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005786 if (s) return s;
5787 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5788
5789 if (inst == BC_INST_BOOL_AND)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005790 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005791 else if (inst == BC_INST_BOOL_OR)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005792 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005793 else {
5794
5795 cmp = bc_num_cmp(n1, n2);
5796
5797 switch (inst) {
5798
5799 case BC_INST_REL_EQ:
5800 {
5801 cond = cmp == 0;
5802 break;
5803 }
5804
5805 case BC_INST_REL_LE:
5806 {
5807 cond = cmp <= 0;
5808 break;
5809 }
5810
5811 case BC_INST_REL_GE:
5812 {
5813 cond = cmp >= 0;
5814 break;
5815 }
5816
5817 case BC_INST_REL_NE:
5818 {
5819 cond = cmp != 0;
5820 break;
5821 }
5822
5823 case BC_INST_REL_LT:
5824 {
5825 cond = cmp < 0;
5826 break;
5827 }
5828
5829 case BC_INST_REL_GT:
5830 {
5831 cond = cmp > 0;
5832 break;
5833 }
5834 }
5835 }
5836
5837 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5838
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005839 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005840
5841 return s;
5842}
5843
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005844#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005845static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
Gavin Howard01055ba2018-11-03 11:00:21 -06005846 bool push)
5847{
5848 BcNum n2;
5849 BcResult res;
5850
5851 memset(&n2, 0, sizeof(BcNum));
5852 n2.rdx = res.d.id.idx = r->d.id.idx;
5853 res.t = BC_RESULT_STR;
5854
5855 if (!push) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005856 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005857 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005858 bc_vec_pop(v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005859 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005860 }
5861
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005862 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005863
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005864 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005865 bc_vec_push(v, &n2);
5866
5867 return BC_STATUS_SUCCESS;
5868}
5869#endif // ENABLE_DC
5870
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005871static BcStatus bc_program_copyToVar(char *name, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005872{
5873 BcStatus s;
5874 BcResult *ptr, r;
5875 BcVec *v;
5876 BcNum *n;
5877
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005878 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005879 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005880
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005881 ptr = bc_vec_top(&G.prog.results);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005882 if ((ptr->t == BC_RESULT_ARRAY) != !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005883 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005884 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005885
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005886#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005887 if (ptr->t == BC_RESULT_STR && !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005888 return bc_error_variable_is_wrong_type();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005889 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005890#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005891
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005892 s = bc_program_num(ptr, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005893 if (s) return s;
5894
5895 // Do this once more to make sure that pointers were not invalidated.
Denys Vlasenkodf515392018-12-02 19:27:48 +01005896 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005897
5898 if (var) {
5899 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5900 bc_num_copy(&r.d.n, n);
5901 }
5902 else {
5903 bc_array_init(&r.d.v, true);
5904 bc_array_copy(&r.d.v, (BcVec *) n);
5905 }
5906
5907 bc_vec_push(v, &r.d);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005908 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005909
5910 return s;
5911}
5912
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005913static BcStatus bc_program_assign(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005914{
5915 BcStatus s;
5916 BcResult *left, *right, res;
5917 BcNum *l = NULL, *r = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06005918 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5919
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005920 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
Gavin Howard01055ba2018-11-03 11:00:21 -06005921 if (s) return s;
5922
5923 ib = left->t == BC_RESULT_IBASE;
5924 sc = left->t == BC_RESULT_SCALE;
5925
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005926#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005927
5928 if (right->t == BC_RESULT_STR) {
5929
5930 BcVec *v;
5931
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005932 if (left->t != BC_RESULT_VAR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005933 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005934 v = bc_program_search(left->d.id.name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06005935
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005936 return bc_program_assignStr(right, v, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005937 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005938#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005939
5940 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005941 return bc_error("bad assignment:"
5942 " left side must be scale,"
5943 " ibase, obase, last, var,"
5944 " or array element"
5945 );
Gavin Howard01055ba2018-11-03 11:00:21 -06005946
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005947#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005948 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005949 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06005950
5951 if (assign)
5952 bc_num_copy(l, r);
5953 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005954 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005955
5956 if (s) return s;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005957#else
Gavin Howard01055ba2018-11-03 11:00:21 -06005958 bc_num_copy(l, r);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005959#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005960
5961 if (ib || sc || left->t == BC_RESULT_OBASE) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005962 static const char *const msg[] = {
Denys Vlasenko64074a12018-12-07 15:50:14 +01005963 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5964 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5965 NULL, //can't happen //BC_RESULT_LAST
5966 NULL, //can't happen //BC_RESULT_CONSTANT
5967 NULL, //can't happen //BC_RESULT_ONE
5968 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005969 };
Gavin Howard01055ba2018-11-03 11:00:21 -06005970 size_t *ptr;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01005971 unsigned long val, max;
Gavin Howard01055ba2018-11-03 11:00:21 -06005972
5973 s = bc_num_ulong(l, &val);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005974 if (s)
5975 return s;
5976 s = left->t - BC_RESULT_IBASE;
Gavin Howard01055ba2018-11-03 11:00:21 -06005977 if (sc) {
5978 max = BC_MAX_SCALE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005979 ptr = &G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06005980 }
5981 else {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005982 if (val < BC_NUM_MIN_BASE)
5983 return bc_error(msg[s]);
Gavin Howard01055ba2018-11-03 11:00:21 -06005984 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005985 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005986 }
5987
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005988 if (val > max)
5989 return bc_error(msg[s]);
5990 if (!sc)
5991 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005992
5993 *ptr = (size_t) val;
5994 s = BC_STATUS_SUCCESS;
5995 }
5996
5997 bc_num_init(&res.d.n, l->len);
5998 bc_num_copy(&res.d.n, l);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005999 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006000
6001 return s;
6002}
6003
Denys Vlasenko416ce762018-12-02 20:57:17 +01006004#if !ENABLE_DC
6005#define bc_program_pushVar(code, bgn, pop, copy) \
6006 bc_program_pushVar(code, bgn)
6007// for bc, 'pop' and 'copy' are always false
6008#endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006009static BcStatus bc_program_pushVar(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006010 bool pop, bool copy)
6011{
6012 BcStatus s = BC_STATUS_SUCCESS;
6013 BcResult r;
6014 char *name = bc_program_name(code, bgn);
Gavin Howard01055ba2018-11-03 11:00:21 -06006015
6016 r.t = BC_RESULT_VAR;
6017 r.d.id.name = name;
6018
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006019#if ENABLE_DC
Denys Vlasenko416ce762018-12-02 20:57:17 +01006020 {
6021 BcVec *v = bc_program_search(name, true);
6022 BcNum *num = bc_vec_top(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006023
Denys Vlasenko416ce762018-12-02 20:57:17 +01006024 if (pop || copy) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006025
Denys Vlasenko416ce762018-12-02 20:57:17 +01006026 if (!BC_PROG_STACK(v, 2 - copy)) {
6027 free(name);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006028 return bc_error_stack_has_too_few_elements();
Denys Vlasenko416ce762018-12-02 20:57:17 +01006029 }
6030
Gavin Howard01055ba2018-11-03 11:00:21 -06006031 free(name);
Denys Vlasenko416ce762018-12-02 20:57:17 +01006032 name = NULL;
6033
6034 if (!BC_PROG_STR(num)) {
6035
6036 r.t = BC_RESULT_TEMP;
6037
6038 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
6039 bc_num_copy(&r.d.n, num);
6040 }
6041 else {
6042 r.t = BC_RESULT_STR;
6043 r.d.id.idx = num->rdx;
6044 }
6045
6046 if (!copy) bc_vec_pop(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006047 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006048 }
6049#endif // ENABLE_DC
6050
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006051 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006052
6053 return s;
6054}
6055
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006056static BcStatus bc_program_pushArray(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006057 char inst)
6058{
6059 BcStatus s = BC_STATUS_SUCCESS;
6060 BcResult r;
6061 BcNum *num;
6062
6063 r.d.id.name = bc_program_name(code, bgn);
6064
6065 if (inst == BC_INST_ARRAY) {
6066 r.t = BC_RESULT_ARRAY;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006067 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006068 }
6069 else {
6070
6071 BcResult *operand;
6072 unsigned long temp;
6073
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006074 s = bc_program_prep(&operand, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006075 if (s) goto err;
6076 s = bc_num_ulong(num, &temp);
6077 if (s) goto err;
6078
6079 if (temp > BC_MAX_DIM) {
Denys Vlasenko64074a12018-12-07 15:50:14 +01006080 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
Gavin Howard01055ba2018-11-03 11:00:21 -06006081 goto err;
6082 }
6083
6084 r.d.id.idx = (size_t) temp;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006085 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
Gavin Howard01055ba2018-11-03 11:00:21 -06006086 }
6087
6088err:
6089 if (s) free(r.d.id.name);
6090 return s;
6091}
6092
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006093#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006094static BcStatus bc_program_incdec(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006095{
6096 BcStatus s;
6097 BcResult *ptr, res, copy;
6098 BcNum *num = NULL;
6099 char inst2 = inst;
6100
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006101 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006102 if (s) return s;
6103
6104 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6105 copy.t = BC_RESULT_TEMP;
6106 bc_num_init(&copy.d.n, num->len);
6107 bc_num_copy(&copy.d.n, num);
6108 }
6109
6110 res.t = BC_RESULT_ONE;
6111 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6112 BC_INST_ASSIGN_PLUS :
6113 BC_INST_ASSIGN_MINUS;
6114
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006115 bc_vec_push(&G.prog.results, &res);
6116 bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006117
6118 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006119 bc_vec_pop(&G.prog.results);
6120 bc_vec_push(&G.prog.results, &copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006121 }
6122
6123 return s;
6124}
6125
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006126static BcStatus bc_program_call(char *code, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006127{
6128 BcStatus s = BC_STATUS_SUCCESS;
6129 BcInstPtr ip;
6130 size_t i, nparams = bc_program_index(code, idx);
6131 BcFunc *func;
Gavin Howard01055ba2018-11-03 11:00:21 -06006132 BcId *a;
6133 BcResultData param;
6134 BcResult *arg;
6135
6136 ip.idx = 0;
6137 ip.func = bc_program_index(code, idx);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006138 func = bc_program_func(ip.func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006139
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006140 if (func->code.len == 0) {
6141 return bc_error("undefined function");
6142 }
6143 if (nparams != func->nparams) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006144 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006145 }
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006146 ip.len = G.prog.results.len - nparams;
Gavin Howard01055ba2018-11-03 11:00:21 -06006147
6148 for (i = 0; i < nparams; ++i) {
6149
6150 a = bc_vec_item(&func->autos, nparams - 1 - i);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006151 arg = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006152
6153 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006154 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006155
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006156 s = bc_program_copyToVar(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006157 if (s) return s;
6158 }
6159
6160 for (; i < func->autos.len; ++i) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006161 BcVec *v;
Gavin Howard01055ba2018-11-03 11:00:21 -06006162
6163 a = bc_vec_item(&func->autos, i);
Denys Vlasenkodf515392018-12-02 19:27:48 +01006164 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006165
6166 if (a->idx) {
6167 bc_num_init(&param.n, BC_NUM_DEF_SIZE);
6168 bc_vec_push(v, &param.n);
6169 }
6170 else {
6171 bc_array_init(&param.v, true);
6172 bc_vec_push(v, &param.v);
6173 }
6174 }
6175
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006176 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006177
6178 return BC_STATUS_SUCCESS;
6179}
6180
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006181static BcStatus bc_program_return(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006182{
6183 BcStatus s;
6184 BcResult res;
6185 BcFunc *f;
6186 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006187 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006188
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006189 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006190 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006191
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006192 f = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006193 res.t = BC_RESULT_TEMP;
6194
6195 if (inst == BC_INST_RET) {
6196
6197 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006198 BcResult *operand = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006199
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006200 s = bc_program_num(operand, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006201 if (s) return s;
6202 bc_num_init(&res.d.n, num->len);
6203 bc_num_copy(&res.d.n, num);
6204 }
6205 else {
6206 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6207 bc_num_zero(&res.d.n);
6208 }
6209
6210 // We need to pop arguments as well, so this takes that into account.
6211 for (i = 0; i < f->autos.len; ++i) {
6212
6213 BcVec *v;
6214 BcId *a = bc_vec_item(&f->autos, i);
6215
Denys Vlasenkodf515392018-12-02 19:27:48 +01006216 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006217 bc_vec_pop(v);
6218 }
6219
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006220 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6221 bc_vec_push(&G.prog.results, &res);
6222 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006223
6224 return BC_STATUS_SUCCESS;
6225}
6226#endif // ENABLE_BC
6227
6228static unsigned long bc_program_scale(BcNum *n)
6229{
6230 return (unsigned long) n->rdx;
6231}
6232
6233static unsigned long bc_program_len(BcNum *n)
6234{
6235 unsigned long len = n->len;
6236 size_t i;
6237
6238 if (n->rdx != n->len) return len;
6239 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6240
6241 return len;
6242}
6243
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006244static BcStatus bc_program_builtin(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006245{
6246 BcStatus s;
6247 BcResult *opnd;
6248 BcNum *num = NULL;
6249 BcResult res;
6250 bool len = inst == BC_INST_LENGTH;
6251
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006252 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006253 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006254 opnd = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006255
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006256 s = bc_program_num(opnd, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006257 if (s) return s;
6258
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006259#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006260 if (!BC_PROG_NUM(opnd, num) && !len)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006261 return bc_error_variable_is_wrong_type();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006262#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006263
6264 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6265
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006266 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006267#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006268 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006269 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006270 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006271#endif
6272#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006273 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6274
6275 char **str;
6276 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6277
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006278 str = bc_program_str(idx);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006279 bc_num_ulong2num(&res.d.n, strlen(*str));
Gavin Howard01055ba2018-11-03 11:00:21 -06006280 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006281#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006282 else {
6283 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006284 bc_num_ulong2num(&res.d.n, f(num));
Gavin Howard01055ba2018-11-03 11:00:21 -06006285 }
6286
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006287 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006288
6289 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006290}
6291
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006292#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006293static BcStatus bc_program_divmod(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006294{
6295 BcStatus s;
6296 BcResult *opd1, *opd2, res, res2;
6297 BcNum *n1, *n2 = NULL;
6298
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006299 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006300 if (s) return s;
6301
6302 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6303 bc_num_init(&res2.d.n, n2->len);
6304
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006305 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006306 if (s) goto err;
6307
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006308 bc_program_binOpRetire(&res2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006309 res.t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006310 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006311
6312 return s;
6313
6314err:
6315 bc_num_free(&res2.d.n);
6316 bc_num_free(&res.d.n);
6317 return s;
6318}
6319
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006320static BcStatus bc_program_modexp(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006321{
6322 BcStatus s;
6323 BcResult *r1, *r2, *r3, res;
6324 BcNum *n1, *n2, *n3;
6325
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006326 if (!BC_PROG_STACK(&G.prog.results, 3))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006327 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006328 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006329 if (s) return s;
6330
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006331 r1 = bc_vec_item_rev(&G.prog.results, 2);
6332 s = bc_program_num(r1, &n1, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006333 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006334 if (!BC_PROG_NUM(r1, n1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006335 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006336
6337 // Make sure that the values have their pointers updated, if necessary.
6338 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6339
6340 if (r1->t == r2->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006341 s = bc_program_num(r2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006342 if (s) return s;
6343 }
6344
6345 if (r1->t == r3->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006346 s = bc_program_num(r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006347 if (s) return s;
6348 }
6349 }
6350
6351 bc_num_init(&res.d.n, n3->len);
6352 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6353 if (s) goto err;
6354
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006355 bc_vec_pop(&G.prog.results);
6356 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006357
6358 return s;
6359
6360err:
6361 bc_num_free(&res.d.n);
6362 return s;
6363}
6364
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006365static void bc_program_stackLen(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006366{
Gavin Howard01055ba2018-11-03 11:00:21 -06006367 BcResult res;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006368 size_t len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006369
6370 res.t = BC_RESULT_TEMP;
6371
6372 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006373 bc_num_ulong2num(&res.d.n, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006374 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006375}
6376
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006377static BcStatus bc_program_asciify(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006378{
6379 BcStatus s;
6380 BcResult *r, res;
6381 BcNum *num = NULL, n;
6382 char *str, *str2, c;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006383 size_t len = G.prog.strs.len, idx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006384 unsigned long val;
6385
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006386 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006387 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006388 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006389
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006390 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006391 if (s) return s;
6392
6393 if (BC_PROG_NUM(r, num)) {
6394
6395 bc_num_init(&n, BC_NUM_DEF_SIZE);
6396 bc_num_copy(&n, num);
6397 bc_num_truncate(&n, n.rdx);
6398
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006399 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006400 if (s) goto num_err;
6401 s = bc_num_ulong(&n, &val);
6402 if (s) goto num_err;
6403
6404 c = (char) val;
6405
6406 bc_num_free(&n);
6407 }
6408 else {
6409 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006410 str2 = *bc_program_str(idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006411 c = str2[0];
6412 }
6413
6414 str = xmalloc(2);
6415 str[0] = c;
6416 str[1] = '\0';
6417
6418 str2 = xstrdup(str);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006419 bc_program_addFunc(str2, &idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006420
6421 if (idx != len + BC_PROG_REQ_FUNCS) {
6422
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006423 for (idx = 0; idx < G.prog.strs.len; ++idx) {
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006424 if (strcmp(*bc_program_str(idx), str) == 0) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006425 len = idx;
6426 break;
6427 }
6428 }
6429
6430 free(str);
6431 }
6432 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006433 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006434
6435 res.t = BC_RESULT_STR;
6436 res.d.id.idx = len;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006437 bc_vec_pop(&G.prog.results);
6438 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006439
6440 return BC_STATUS_SUCCESS;
6441
6442num_err:
6443 bc_num_free(&n);
6444 return s;
6445}
6446
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006447static BcStatus bc_program_printStream(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006448{
6449 BcStatus s;
6450 BcResult *r;
6451 BcNum *n = NULL;
6452 size_t idx;
6453 char *str;
6454
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006455 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006456 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006457 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006458
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006459 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006460 if (s) return s;
6461
6462 if (BC_PROG_NUM(r, n))
Denys Vlasenko5f1b90b2018-12-08 23:18:06 +01006463 s = bc_num_stream(n, &G.prog.strmb);
Gavin Howard01055ba2018-11-03 11:00:21 -06006464 else {
6465 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006466 str = *bc_program_str(idx);
Denys Vlasenko00d77792018-11-30 23:13:42 +01006467 printf("%s", str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006468 }
6469
6470 return s;
6471}
6472
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006473static BcStatus bc_program_nquit(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006474{
6475 BcStatus s;
6476 BcResult *opnd;
6477 BcNum *num = NULL;
6478 unsigned long val;
6479
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006480 s = bc_program_prep(&opnd, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006481 if (s) return s;
6482 s = bc_num_ulong(num, &val);
6483 if (s) return s;
6484
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006485 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006486
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006487 if (G.prog.stack.len < val)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006488 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006489 if (G.prog.stack.len == val) {
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006490 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006491 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006492
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006493 bc_vec_npop(&G.prog.stack, val);
Gavin Howard01055ba2018-11-03 11:00:21 -06006494
6495 return s;
6496}
6497
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006498static BcStatus bc_program_execStr(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006499 bool cond)
6500{
6501 BcStatus s = BC_STATUS_SUCCESS;
6502 BcResult *r;
6503 char **str;
6504 BcFunc *f;
6505 BcParse prs;
6506 BcInstPtr ip;
6507 size_t fidx, sidx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006508
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006509 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006510 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006511
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006512 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006513
6514 if (cond) {
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006515 BcNum *n = n; // for compiler
6516 bool exec;
6517 char *name;
6518 char *then_name = bc_program_name(code, bgn);
6519 char *else_name = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06006520
6521 if (code[*bgn] == BC_PARSE_STREND)
6522 (*bgn) += 1;
6523 else
6524 else_name = bc_program_name(code, bgn);
6525
6526 exec = r->d.n.len != 0;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006527 name = then_name;
6528 if (!exec && else_name != NULL) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006529 exec = true;
6530 name = else_name;
6531 }
6532
6533 if (exec) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006534 BcVec *v;
6535 v = bc_program_search(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006536 n = bc_vec_top(v);
6537 }
6538
6539 free(then_name);
6540 free(else_name);
6541
6542 if (!exec) goto exit;
6543 if (!BC_PROG_STR(n)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006544 s = bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006545 goto exit;
6546 }
6547
6548 sidx = n->rdx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006549 } else {
6550 if (r->t == BC_RESULT_STR) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006551 sidx = r->d.id.idx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006552 } else if (r->t == BC_RESULT_VAR) {
6553 BcNum *n;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006554 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006555 if (s || !BC_PROG_STR(n)) goto exit;
6556 sidx = n->rdx;
Denys Vlasenko5ec4b492018-12-09 02:54:06 +01006557 } else
Gavin Howard01055ba2018-11-03 11:00:21 -06006558 goto exit;
6559 }
6560
6561 fidx = sidx + BC_PROG_REQ_FUNCS;
6562
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006563 str = bc_program_str(sidx);
6564 f = bc_program_func(fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006565
6566 if (f->code.len == 0) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006567 common_parse_init(&prs, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006568 s = bc_parse_text(&prs, *str);
6569 if (s) goto err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01006570 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006571 if (s) goto err;
6572
6573 if (prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006574 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06006575 goto err;
6576 }
6577
6578 bc_parse_free(&prs);
6579 }
6580
6581 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006582 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006583 ip.func = fidx;
6584
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006585 bc_vec_pop(&G.prog.results);
6586 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006587
6588 return BC_STATUS_SUCCESS;
6589
6590err:
6591 bc_parse_free(&prs);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006592 f = bc_program_func(fidx);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006593 bc_vec_pop_all(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06006594exit:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006595 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006596 return s;
6597}
6598#endif // ENABLE_DC
6599
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006600static void bc_program_pushGlobal(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006601{
Gavin Howard01055ba2018-11-03 11:00:21 -06006602 BcResult res;
6603 unsigned long val;
6604
6605 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6606 if (inst == BC_INST_IBASE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006607 val = (unsigned long) G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006608 else if (inst == BC_INST_SCALE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006609 val = (unsigned long) G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006610 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006611 val = (unsigned long) G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006612
6613 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006614 bc_num_ulong2num(&res.d.n, val);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006615 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006616}
6617
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006618static void bc_program_addFunc(char *name, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006619{
Gavin Howard01055ba2018-11-03 11:00:21 -06006620 BcId entry, *entry_ptr;
6621 BcFunc f;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006622 int inserted;
Gavin Howard01055ba2018-11-03 11:00:21 -06006623
6624 entry.name = name;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006625 entry.idx = G.prog.fns.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006626
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006627 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6628 if (!inserted) free(name);
Gavin Howard01055ba2018-11-03 11:00:21 -06006629
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006630 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006631 *idx = entry_ptr->idx;
6632
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006633 if (!inserted) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006634
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006635 BcFunc *func = bc_program_func(entry_ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006636
6637 // We need to reset these, so the function can be repopulated.
6638 func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01006639 bc_vec_pop_all(&func->autos);
6640 bc_vec_pop_all(&func->code);
6641 bc_vec_pop_all(&func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06006642 }
6643 else {
6644 bc_func_init(&f);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006645 bc_vec_push(&G.prog.fns, &f);
Gavin Howard01055ba2018-11-03 11:00:21 -06006646 }
6647}
6648
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006649static BcStatus bc_program_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006650{
Gavin Howard01055ba2018-11-03 11:00:21 -06006651 BcResult r, *ptr;
6652 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006653 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006654 BcFunc *func = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006655 char *code = func->code.v;
6656 bool cond = false;
6657
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006658 while (ip->idx < func->code.len) {
6659 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006660 char inst = code[(ip->idx)++];
6661
6662 switch (inst) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006663#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006664 case BC_INST_JUMP_ZERO:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006665 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006666 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006667 cond = !bc_num_cmp(num, &G.prog.zero);
6668 bc_vec_pop(&G.prog.results);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006669 // Fallthrough.
6670 case BC_INST_JUMP: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006671 size_t *addr;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006672 size_t idx = bc_program_index(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006673 addr = bc_vec_item(&func->labels, idx);
6674 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6675 break;
6676 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006677 case BC_INST_CALL:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006678 s = bc_program_call(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006679 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006680 case BC_INST_INC_PRE:
6681 case BC_INST_DEC_PRE:
6682 case BC_INST_INC_POST:
6683 case BC_INST_DEC_POST:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006684 s = bc_program_incdec(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006685 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006686 case BC_INST_HALT:
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006687 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06006688 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006689 case BC_INST_RET:
6690 case BC_INST_RET0:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006691 s = bc_program_return(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006692 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006693 case BC_INST_BOOL_OR:
6694 case BC_INST_BOOL_AND:
6695#endif // ENABLE_BC
6696 case BC_INST_REL_EQ:
6697 case BC_INST_REL_LE:
6698 case BC_INST_REL_GE:
6699 case BC_INST_REL_NE:
6700 case BC_INST_REL_LT:
6701 case BC_INST_REL_GT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006702 s = bc_program_logical(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006703 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006704 case BC_INST_READ:
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006705 s = bc_program_read();
Gavin Howard01055ba2018-11-03 11:00:21 -06006706 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006707 case BC_INST_VAR:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006708 s = bc_program_pushVar(code, &ip->idx, false, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006709 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006710 case BC_INST_ARRAY_ELEM:
6711 case BC_INST_ARRAY:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006712 s = bc_program_pushArray(code, &ip->idx, inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006713 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006714 case BC_INST_LAST:
Gavin Howard01055ba2018-11-03 11:00:21 -06006715 r.t = BC_RESULT_LAST;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006716 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006717 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006718 case BC_INST_IBASE:
6719 case BC_INST_SCALE:
6720 case BC_INST_OBASE:
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006721 bc_program_pushGlobal(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006722 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006723 case BC_INST_SCALE_FUNC:
6724 case BC_INST_LENGTH:
6725 case BC_INST_SQRT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006726 s = bc_program_builtin(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006727 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006728 case BC_INST_NUM:
Gavin Howard01055ba2018-11-03 11:00:21 -06006729 r.t = BC_RESULT_CONSTANT;
6730 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006731 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006732 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006733 case BC_INST_POP:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006734 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006735 s = bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006736 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006737 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006738 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006739 case BC_INST_POP_EXEC:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006740 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006741 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006742 case BC_INST_PRINT:
6743 case BC_INST_PRINT_POP:
6744 case BC_INST_PRINT_STR:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006745 s = bc_program_print(inst, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006746 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006747 case BC_INST_STR:
Gavin Howard01055ba2018-11-03 11:00:21 -06006748 r.t = BC_RESULT_STR;
6749 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006750 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006751 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006752 case BC_INST_POWER:
6753 case BC_INST_MULTIPLY:
6754 case BC_INST_DIVIDE:
6755 case BC_INST_MODULUS:
6756 case BC_INST_PLUS:
6757 case BC_INST_MINUS:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006758 s = bc_program_op(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006759 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006760 case BC_INST_BOOL_NOT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006761 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006762 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006763 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006764 if (!bc_num_cmp(num, &G.prog.zero))
6765 bc_num_one(&r.d.n);
6766 else
6767 bc_num_zero(&r.d.n);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006768 bc_program_retire(&r, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006769 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006770 case BC_INST_NEG:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006771 s = bc_program_negate();
Gavin Howard01055ba2018-11-03 11:00:21 -06006772 break;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006773#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006774 case BC_INST_ASSIGN_POWER:
6775 case BC_INST_ASSIGN_MULTIPLY:
6776 case BC_INST_ASSIGN_DIVIDE:
6777 case BC_INST_ASSIGN_MODULUS:
6778 case BC_INST_ASSIGN_PLUS:
6779 case BC_INST_ASSIGN_MINUS:
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006780#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006781 case BC_INST_ASSIGN:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006782 s = bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006783 break;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006784#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006785 case BC_INST_MODEXP:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006786 s = bc_program_modexp();
Gavin Howard01055ba2018-11-03 11:00:21 -06006787 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006788 case BC_INST_DIVMOD:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006789 s = bc_program_divmod();
Gavin Howard01055ba2018-11-03 11:00:21 -06006790 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006791 case BC_INST_EXECUTE:
6792 case BC_INST_EXEC_COND:
Gavin Howard01055ba2018-11-03 11:00:21 -06006793 cond = inst == BC_INST_EXEC_COND;
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006794 s = bc_program_execStr(code, &ip->idx, cond);
Gavin Howard01055ba2018-11-03 11:00:21 -06006795 break;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006796 case BC_INST_PRINT_STACK: {
6797 size_t idx;
6798 for (idx = 0; idx < G.prog.results.len; ++idx) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006799 s = bc_program_print(BC_INST_PRINT, idx);
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006800 if (s) break;
6801 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006802 break;
6803 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006804 case BC_INST_CLEAR_STACK:
Denys Vlasenko7d628012018-12-04 21:46:47 +01006805 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006806 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006807 case BC_INST_STACK_LEN:
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006808 bc_program_stackLen();
Gavin Howard01055ba2018-11-03 11:00:21 -06006809 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006810 case BC_INST_DUPLICATE:
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006811 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006812 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006813 ptr = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006814 bc_result_copy(&r, ptr);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006815 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006816 break;
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006817 case BC_INST_SWAP: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006818 BcResult *ptr2;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006819 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006820 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006821 ptr = bc_vec_item_rev(&G.prog.results, 0);
6822 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006823 memcpy(&r, ptr, sizeof(BcResult));
6824 memcpy(ptr, ptr2, sizeof(BcResult));
6825 memcpy(ptr2, &r, sizeof(BcResult));
Gavin Howard01055ba2018-11-03 11:00:21 -06006826 break;
6827 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006828 case BC_INST_ASCIIFY:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006829 s = bc_program_asciify();
Gavin Howard01055ba2018-11-03 11:00:21 -06006830 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006831 case BC_INST_PRINT_STREAM:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006832 s = bc_program_printStream();
Gavin Howard01055ba2018-11-03 11:00:21 -06006833 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006834 case BC_INST_LOAD:
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006835 case BC_INST_PUSH_VAR: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006836 bool copy = inst == BC_INST_LOAD;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006837 s = bc_program_pushVar(code, &ip->idx, true, copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006838 break;
6839 }
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006840 case BC_INST_PUSH_TO_VAR: {
Gavin Howard01055ba2018-11-03 11:00:21 -06006841 char *name = bc_program_name(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006842 s = bc_program_copyToVar(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006843 free(name);
6844 break;
6845 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006846 case BC_INST_QUIT:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006847 if (G.prog.stack.len <= 2)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006848 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006849 bc_vec_npop(&G.prog.stack, 2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006850 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006851 case BC_INST_NQUIT:
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006852 s = bc_program_nquit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006853 break;
Gavin Howard01055ba2018-11-03 11:00:21 -06006854#endif // ENABLE_DC
6855 }
6856
Denys Vlasenkod38af482018-12-04 19:11:02 +01006857 if (s || G_interrupt) {
6858 bc_program_reset();
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006859 return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01006860 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006861
6862 // If the stack has changed, pointers may be invalid.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006863 ip = bc_vec_top(&G.prog.stack);
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006864 func = bc_program_func(ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006865 code = func->code.v;
6866 }
6867
Denys Vlasenko927a7d62018-12-09 02:24:14 +01006868 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06006869}
6870
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006871#if ENABLE_BC
Denys Vlasenko54214c32018-12-06 09:07:06 +01006872static void bc_vm_info(void)
6873{
6874 printf("%s "BB_VER"\n"
6875 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
Denys Vlasenko54214c32018-12-06 09:07:06 +01006876 , applet_name);
6877}
6878
6879static void bc_args(char **argv)
6880{
6881 unsigned opts;
6882 int i;
6883
6884 GETOPT_RESET();
6885#if ENABLE_FEATURE_BC_LONG_OPTIONS
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006886 opts = option_mask32 |= getopt32long(argv, "wvsqli",
Denys Vlasenko54214c32018-12-06 09:07:06 +01006887 "warn\0" No_argument "w"
6888 "version\0" No_argument "v"
6889 "standard\0" No_argument "s"
6890 "quiet\0" No_argument "q"
6891 "mathlib\0" No_argument "l"
6892 "interactive\0" No_argument "i"
6893 );
6894#else
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006895 opts = option_mask32 |= getopt32(argv, "wvsqli");
Denys Vlasenko54214c32018-12-06 09:07:06 +01006896#endif
6897 if (getenv("POSIXLY_CORRECT"))
6898 option_mask32 |= BC_FLAG_S;
6899
Denys Vlasenko54214c32018-12-06 09:07:06 +01006900 if (opts & BC_FLAG_V) {
6901 bc_vm_info();
6902 exit(0);
6903 }
6904
6905 for (i = optind; argv[i]; ++i)
6906 bc_vec_push(&G.files, argv + i);
6907}
6908
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006909static void bc_vm_envArgs(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006910{
Gavin Howard01055ba2018-11-03 11:00:21 -06006911 BcVec v;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006912 char *buf;
Denys Vlasenko54214c32018-12-06 09:07:06 +01006913 char *env_args = getenv("BC_ENV_ARGS");
Gavin Howard01055ba2018-11-03 11:00:21 -06006914
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01006915 if (!env_args) return;
Gavin Howard01055ba2018-11-03 11:00:21 -06006916
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006917 G.env_args = xstrdup(env_args);
6918 buf = G.env_args;
Gavin Howard01055ba2018-11-03 11:00:21 -06006919
6920 bc_vec_init(&v, sizeof(char *), NULL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006921
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006922 while (*(buf = skip_whitespace(buf)) != '\0') {
6923 bc_vec_push(&v, &buf);
6924 buf = skip_non_whitespace(buf);
6925 if (!*buf)
6926 break;
6927 *buf++ = '\0';
Gavin Howard01055ba2018-11-03 11:00:21 -06006928 }
6929
Denys Vlasenko54214c32018-12-06 09:07:06 +01006930 // NULL terminate, and pass argv[] so that first arg is argv[1]
6931 if (sizeof(int) == sizeof(char*)) {
6932 bc_vec_push(&v, &const_int_0);
6933 } else {
6934 static char *const nullptr = NULL;
6935 bc_vec_push(&v, &nullptr);
6936 }
6937 bc_args(((char **)v.v) - 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006938
6939 bc_vec_free(&v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006940}
6941#endif // ENABLE_BC
6942
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006943static unsigned bc_vm_envLen(const char *var)
Gavin Howard01055ba2018-11-03 11:00:21 -06006944{
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006945 char *lenv;
6946 unsigned len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006947
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006948 lenv = getenv(var);
6949 len = BC_NUM_PRINT_WIDTH;
Gavin Howard01055ba2018-11-03 11:00:21 -06006950 if (!lenv) return len;
6951
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006952 len = bb_strtou(lenv, NULL, 10) - 1;
6953 if (errno || len < 2 || len >= INT_MAX)
Gavin Howard01055ba2018-11-03 11:00:21 -06006954 len = BC_NUM_PRINT_WIDTH;
6955
6956 return len;
6957}
6958
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006959static BcStatus bc_vm_process(const char *text)
Gavin Howard01055ba2018-11-03 11:00:21 -06006960{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006961 BcStatus s = bc_parse_text(&G.prs, text);
Gavin Howard01055ba2018-11-03 11:00:21 -06006962
Gavin Howard01055ba2018-11-03 11:00:21 -06006963 if (s) return s;
6964
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006965 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006966 s = G.prs.parse(&G.prs);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006967 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006968 }
6969
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006970 if (BC_PARSE_CAN_EXEC(&G.prs)) {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006971 s = bc_program_exec();
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01006972 fflush_and_check();
Denys Vlasenko9b70f192018-12-04 20:51:40 +01006973 if (s)
Denys Vlasenkod38af482018-12-04 19:11:02 +01006974 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06006975 }
6976
6977 return s;
6978}
6979
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006980static BcStatus bc_vm_file(const char *file)
Gavin Howard01055ba2018-11-03 11:00:21 -06006981{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01006982 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06006983 char *data;
Denys Vlasenko0409ad32018-12-05 16:39:22 +01006984 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006985 BcFunc *main_func;
6986 BcInstPtr *ip;
6987
Denys Vlasenkodf515392018-12-02 19:27:48 +01006988 data = bc_read_file(file);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006989 if (!data) return bc_error_fmt("file '%s' is not text", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06006990
Denys Vlasenko0409ad32018-12-05 16:39:22 +01006991 sv_file = G.prog.file;
6992 G.prog.file = file;
6993 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006994 s = bc_vm_process(data);
Gavin Howard01055ba2018-11-03 11:00:21 -06006995 if (s) goto err;
6996
Denys Vlasenko8fa1e8e2018-12-09 00:03:57 +01006997 main_func = bc_program_func(BC_PROG_MAIN);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006998 ip = bc_vec_item(&G.prog.stack, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006999
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007000 if (main_func->code.len < ip->idx)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007001 s = bc_error_fmt("file '%s' is not executable", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007002
7003err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007004 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007005 free(data);
7006 return s;
7007}
7008
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007009static BcStatus bc_vm_stdin(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007010{
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007011 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007012 BcVec buf, buffer;
Gavin Howard01055ba2018-11-03 11:00:21 -06007013 size_t len, i, str = 0;
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007014 bool comment = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06007015
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007016 G.prog.file = NULL;
7017 bc_lex_file(&G.prs.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06007018
Denys Vlasenko7d628012018-12-04 21:46:47 +01007019 bc_char_vec_init(&buffer);
7020 bc_char_vec_init(&buf);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01007021 bc_vec_pushZeroByte(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007022
7023 // This loop is complex because the vm tries not to send any lines that end
7024 // with a backslash to the parser. The reason for that is because the parser
7025 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7026 // case, and for strings and comments, the parser will expect more stuff.
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007027 while ((s = bc_read_line(&buf)) == BC_STATUS_SUCCESS) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007028
7029 char *string = buf.v;
7030
7031 len = buf.len - 1;
7032
7033 if (len == 1) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007034 if (str && buf.v[0] == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007035 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007036 else if (buf.v[0] == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007037 str += 1;
7038 }
7039 else if (len > 1 || comment) {
7040
7041 for (i = 0; i < len; ++i) {
7042
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007043 bool notend = len > i + 1;
7044 char c = string[i];
Gavin Howard01055ba2018-11-03 11:00:21 -06007045
7046 if (i - 1 > len || string[i - 1] != '\\') {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007047 if (G.sbgn == G.send)
7048 str ^= c == G.sbgn;
7049 else if (c == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007050 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007051 else if (c == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007052 str += 1;
7053 }
7054
7055 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7056 comment = true;
7057 break;
7058 }
7059 else if (c == '*' && notend && comment && string[i + 1] == '/')
7060 comment = false;
7061 }
7062
7063 if (str || comment || string[len - 2] == '\\') {
7064 bc_vec_concat(&buffer, buf.v);
7065 continue;
7066 }
7067 }
7068
7069 bc_vec_concat(&buffer, buf.v);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007070 s = bc_vm_process(buffer.v);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007071 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007072 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007073 // Debug config, non-interactive mode:
7074 // return all the way back to main.
7075 // Non-debug builds do not come here, they exit.
7076 break;
7077 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007078 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007079
Denys Vlasenko7d628012018-12-04 21:46:47 +01007080 bc_vec_pop_all(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007081 }
Denys Vlasenkof522dd92018-12-07 16:35:43 +01007082 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7083 s = BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06007084
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007085 if (str) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007086 s = bc_error("string end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007087 }
7088 else if (comment) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007089 s = bc_error("comment end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007090 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007091
Gavin Howard01055ba2018-11-03 11:00:21 -06007092 bc_vec_free(&buf);
7093 bc_vec_free(&buffer);
7094 return s;
7095}
7096
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007097#if ENABLE_BC
7098static const char bc_lib[] = {
7099 "scale=20"
7100"\n" "define e(x){"
7101"\n" "auto b,s,n,r,d,i,p,f,v"
7102"\n" "b=ibase"
7103"\n" "ibase=A"
7104"\n" "if(x<0){"
7105"\n" "n=1"
7106"\n" "x=-x"
7107"\n" "}"
7108"\n" "s=scale"
7109"\n" "r=6+s+0.44*x"
7110"\n" "scale=scale(x)+1"
7111"\n" "while(x>1){"
7112"\n" "d+=1"
7113"\n" "x/=2"
7114"\n" "scale+=1"
7115"\n" "}"
7116"\n" "scale=r"
7117"\n" "r=x+1"
7118"\n" "p=x"
7119"\n" "f=v=1"
7120"\n" "for(i=2;v!=0;++i){"
7121"\n" "p*=x"
7122"\n" "f*=i"
7123"\n" "v=p/f"
7124"\n" "r+=v"
7125"\n" "}"
7126"\n" "while((d--)!=0)r*=r"
7127"\n" "scale=s"
7128"\n" "ibase=b"
7129"\n" "if(n!=0)return(1/r)"
7130"\n" "return(r/1)"
7131"\n" "}"
7132"\n" "define l(x){"
7133"\n" "auto b,s,r,p,a,q,i,v"
7134"\n" "b=ibase"
7135"\n" "ibase=A"
7136"\n" "if(x<=0){"
7137"\n" "r=(1-10^scale)/1"
7138"\n" "ibase=b"
7139"\n" "return(r)"
7140"\n" "}"
7141"\n" "s=scale"
7142"\n" "scale+=6"
7143"\n" "p=2"
7144"\n" "while(x>=2){"
7145"\n" "p*=2"
7146"\n" "x=sqrt(x)"
7147"\n" "}"
7148"\n" "while(x<=0.5){"
7149"\n" "p*=2"
7150"\n" "x=sqrt(x)"
7151"\n" "}"
7152"\n" "r=a=(x-1)/(x+1)"
7153"\n" "q=a*a"
7154"\n" "v=1"
7155"\n" "for(i=3;v!=0;i+=2){"
7156"\n" "a*=q"
7157"\n" "v=a/i"
7158"\n" "r+=v"
7159"\n" "}"
7160"\n" "r*=p"
7161"\n" "scale=s"
7162"\n" "ibase=b"
7163"\n" "return(r/1)"
7164"\n" "}"
7165"\n" "define s(x){"
7166"\n" "auto b,s,r,n,a,q,i"
7167"\n" "b=ibase"
7168"\n" "ibase=A"
7169"\n" "s=scale"
7170"\n" "scale=1.1*s+2"
7171"\n" "a=a(1)"
7172"\n" "if(x<0){"
7173"\n" "n=1"
7174"\n" "x=-x"
7175"\n" "}"
7176"\n" "scale=0"
7177"\n" "q=(x/a+2)/4"
7178"\n" "x=x-4*q*a"
7179"\n" "if(q%2!=0)x=-x"
7180"\n" "scale=s+2"
7181"\n" "r=a=x"
7182"\n" "q=-x*x"
7183"\n" "for(i=3;a!=0;i+=2){"
7184"\n" "a*=q/(i*(i-1))"
7185"\n" "r+=a"
7186"\n" "}"
7187"\n" "scale=s"
7188"\n" "ibase=b"
7189"\n" "if(n!=0)return(-r/1)"
7190"\n" "return(r/1)"
7191"\n" "}"
7192"\n" "define c(x){"
7193"\n" "auto b,s"
7194"\n" "b=ibase"
7195"\n" "ibase=A"
7196"\n" "s=scale"
7197"\n" "scale*=1.2"
7198"\n" "x=s(2*a(1)+x)"
7199"\n" "scale=s"
7200"\n" "ibase=b"
7201"\n" "return(x/1)"
7202"\n" "}"
7203"\n" "define a(x){"
7204"\n" "auto b,s,r,n,a,m,t,f,i,u"
7205"\n" "b=ibase"
7206"\n" "ibase=A"
7207"\n" "n=1"
7208"\n" "if(x<0){"
7209"\n" "n=-1"
7210"\n" "x=-x"
7211"\n" "}"
7212"\n" "if(x==1){"
7213"\n" "if(scale<65){"
7214"\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7215"\n" "}"
7216"\n" "}"
7217"\n" "if(x==.2){"
7218"\n" "if(scale<65){"
7219"\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7220"\n" "}"
7221"\n" "}"
7222"\n" "s=scale"
7223"\n" "if(x>.2){"
7224"\n" "scale+=5"
7225"\n" "a=a(.2)"
7226"\n" "}"
7227"\n" "scale=s+3"
7228"\n" "while(x>.2){"
7229"\n" "m+=1"
7230"\n" "x=(x-.2)/(1+.2*x)"
7231"\n" "}"
7232"\n" "r=u=x"
7233"\n" "f=-x*x"
7234"\n" "t=1"
7235"\n" "for(i=3;t!=0;i+=2){"
7236"\n" "u*=f"
7237"\n" "t=u/i"
7238"\n" "r+=t"
7239"\n" "}"
7240"\n" "scale=s"
7241"\n" "ibase=b"
7242"\n" "return((m*a+r)/n)"
7243"\n" "}"
7244"\n" "define j(n,x){"
7245"\n" "auto b,s,o,a,i,v,f"
7246"\n" "b=ibase"
7247"\n" "ibase=A"
7248"\n" "s=scale"
7249"\n" "scale=0"
7250"\n" "n/=1"
7251"\n" "if(n<0){"
7252"\n" "n=-n"
7253"\n" "if(n%2==1)o=1"
7254"\n" "}"
7255"\n" "a=1"
7256"\n" "for(i=2;i<=n;++i)a*=i"
7257"\n" "scale=1.5*s"
7258"\n" "a=(x^n)/2^n/a"
7259"\n" "r=v=1"
7260"\n" "f=-x*x/4"
7261"\n" "scale=scale+length(a)-scale(a)"
7262"\n" "for(i=1;v!=0;++i){"
7263"\n" "v=v*f/i/(n+i)"
7264"\n" "r+=v"
7265"\n" "}"
7266"\n" "scale=s"
7267"\n" "ibase=b"
7268"\n" "if(o!=0)a=-a"
7269"\n" "return(a*r/1)"
7270"\n" "}"
7271};
7272#endif // ENABLE_BC
7273
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007274static BcStatus bc_vm_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007275{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007276 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007277 size_t i;
7278
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007279#if ENABLE_BC
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007280 if (option_mask32 & BC_FLAG_L) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007281
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007282 // We know that internal library is not buggy,
7283 // thus error checking is normally disabled.
7284# define DEBUG_LIB 0
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007285 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007286 s = bc_parse_text(&G.prs, bc_lib);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007287 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007288
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007289 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007290 s = G.prs.parse(&G.prs);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007291 if (DEBUG_LIB && s) return s;
7292 }
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007293 s = bc_program_exec();
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007294 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007295 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007296#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007297
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007298 s = BC_STATUS_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007299 for (i = 0; !s && i < G.files.len; ++i)
7300 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007301 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7302 // Debug config, non-interactive mode:
7303 // return all the way back to main.
7304 // Non-debug builds do not come here, they exit.
7305 return s;
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007306 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007307
Denys Vlasenkoac6ed112018-12-08 21:39:10 +01007308 if (IS_BC || (option_mask32 & BC_FLAG_I))
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007309 s = bc_vm_stdin();
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007310
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007311 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7312 s = bc_vm_process("");
Gavin Howard01055ba2018-11-03 11:00:21 -06007313
Denys Vlasenko00d77792018-11-30 23:13:42 +01007314 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007315}
7316
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007317#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007318static void bc_program_free(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007319{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007320 bc_num_free(&G.prog.ib);
7321 bc_num_free(&G.prog.ob);
7322 bc_num_free(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007323# if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007324 bc_num_free(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007325# endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007326 bc_vec_free(&G.prog.fns);
7327 bc_vec_free(&G.prog.fn_map);
7328 bc_vec_free(&G.prog.vars);
7329 bc_vec_free(&G.prog.var_map);
7330 bc_vec_free(&G.prog.arrs);
7331 bc_vec_free(&G.prog.arr_map);
7332 bc_vec_free(&G.prog.strs);
7333 bc_vec_free(&G.prog.consts);
7334 bc_vec_free(&G.prog.results);
7335 bc_vec_free(&G.prog.stack);
7336 bc_num_free(&G.prog.last);
7337 bc_num_free(&G.prog.zero);
7338 bc_num_free(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007339}
7340
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007341static void bc_vm_free(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007342{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007343 bc_vec_free(&G.files);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007344 bc_program_free();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007345 bc_parse_free(&G.prs);
7346 free(G.env_args);
Gavin Howard01055ba2018-11-03 11:00:21 -06007347}
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007348#endif
7349
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007350static void bc_program_init(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007351{
7352 size_t idx;
7353 BcInstPtr ip;
7354
7355 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7356 memset(&ip, 0, sizeof(BcInstPtr));
7357
7358 /* G.prog.nchars = G.prog.scale = 0; - already is */
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007359
7360 bc_num_init(&G.prog.ib, BC_NUM_DEF_SIZE);
7361 bc_num_ten(&G.prog.ib);
7362 G.prog.ib_t = 10;
7363
7364 bc_num_init(&G.prog.ob, BC_NUM_DEF_SIZE);
7365 bc_num_ten(&G.prog.ob);
7366 G.prog.ob_t = 10;
7367
7368 bc_num_init(&G.prog.hexb, BC_NUM_DEF_SIZE);
7369 bc_num_ten(&G.prog.hexb);
7370 G.prog.hexb.num[0] = 6;
7371
7372#if ENABLE_DC
7373 bc_num_init(&G.prog.strmb, BC_NUM_DEF_SIZE);
7374 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7375#endif
7376
7377 bc_num_init(&G.prog.last, BC_NUM_DEF_SIZE);
7378 bc_num_zero(&G.prog.last);
7379
7380 bc_num_init(&G.prog.zero, BC_NUM_DEF_SIZE);
7381 bc_num_zero(&G.prog.zero);
7382
7383 bc_num_init(&G.prog.one, BC_NUM_DEF_SIZE);
7384 bc_num_one(&G.prog.one);
7385
7386 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007387 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007388
Denys Vlasenko1f67e932018-12-03 00:08:59 +01007389 bc_program_addFunc(xstrdup("(main)"), &idx);
7390 bc_program_addFunc(xstrdup("(read)"), &idx);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007391
7392 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007393 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007394
7395 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007396 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007397
7398 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7399 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7400 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7401 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7402 bc_vec_push(&G.prog.stack, &ip);
7403}
Gavin Howard01055ba2018-11-03 11:00:21 -06007404
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007405static int bc_vm_init(const char *env_len)
Gavin Howard01055ba2018-11-03 11:00:21 -06007406{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007407#if ENABLE_FEATURE_EDITING
7408 G.line_input_state = new_line_input_t(DO_HISTORY);
7409#endif
7410 G.prog.len = bc_vm_envLen(env_len);
7411
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007412 bc_vec_init(&G.files, sizeof(char *), NULL);
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007413 if (IS_BC)
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007414 IF_BC(bc_vm_envArgs();)
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007415 bc_program_init();
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007416 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007417 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007418 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007419 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007420 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007421
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007422 if (isatty(0)) {
Denys Vlasenkod38af482018-12-04 19:11:02 +01007423#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007424 G_ttyin = 1;
Denys Vlasenko17c54722018-12-04 21:21:32 +01007425 // With SA_RESTART, most system calls will restart
7426 // (IOW: they won't fail with EINTR).
7427 // In particular, this means ^C won't cause
7428 // stdout to get into "error state" if SIGINT hits
7429 // within write() syscall.
7430 // The downside is that ^C while line input is taken
7431 // will only be handled after [Enter] since read()
7432 // from stdin is not interrupted by ^C either,
7433 // it restarts, thus fgetc() does not return on ^C.
7434 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7435
7436 // Without SA_RESTART, this exhibits a bug:
7437 // "while (1) print 1" and try ^C-ing it.
7438 // Intermittently, instead of returning to input line,
7439 // you'll get "output error: Interrupted system call"
7440 // and exit.
7441 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
Denys Vlasenkod38af482018-12-04 19:11:02 +01007442#endif
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007443 return 1; // "tty"
Denys Vlasenkod38af482018-12-04 19:11:02 +01007444 }
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007445 return 0; // "not a tty"
7446}
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007447
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007448static BcStatus bc_vm_run(void)
7449{
7450 BcStatus st = bc_vm_exec();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007451#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01007452 if (G_exiting) // it was actually "halt" or "quit"
7453 st = EXIT_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007454 bc_vm_free();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007455# if ENABLE_FEATURE_EDITING
7456 free_line_input_t(G.line_input_state);
7457# endif
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007458 FREE_G();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007459#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007460 return st;
7461}
7462
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007463#if ENABLE_BC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007464int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007465int bc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007466{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007467 int is_tty;
7468
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007469 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007470 G.sbgn = G.send = '"';
Gavin Howard01055ba2018-11-03 11:00:21 -06007471
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007472 is_tty = bc_vm_init("BC_LINE_LENGTH");
7473
7474 bc_args(argv);
7475
7476 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7477 bc_vm_info();
7478
7479 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007480}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007481#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007482
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007483#if ENABLE_DC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007484int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007485int dc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007486{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007487 int noscript;
7488
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007489 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007490 G.sbgn = '[';
7491 G.send = ']';
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007492 /*
7493 * TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7494 * 1 char wider than bc from the same package.
7495 * Both default width, and xC_LINE_LENGTH=N are wider:
7496 * "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7497 * 1234\
7498 * 56
7499 * "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7500 * 123\
7501 * 456
7502 * Do the same, or it's a bug?
7503 */
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007504 bc_vm_init("DC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007505
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007506 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7507 noscript = BC_FLAG_I;
7508 for (;;) {
7509 int n = getopt(argc, argv, "e:f:x");
7510 if (n <= 0)
7511 break;
7512 switch (n) {
7513 case 'e':
7514 noscript = 0;
7515 n = bc_vm_process(optarg);
7516 if (n) return n;
7517 break;
7518 case 'f':
7519 noscript = 0;
7520 bc_vm_file(optarg);
7521 break;
7522 case 'x':
7523 option_mask32 |= DC_FLAG_X;
7524 break;
7525 default:
7526 bb_show_usage();
7527 }
7528 }
7529 argv += optind;
7530
7531 while (*argv) {
7532 noscript = 0;
7533 bc_vec_push(&G.files, argv++);
7534 }
7535
7536 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7537
7538 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007539}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007540#endif
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +01007541
7542#endif // not DC_SMALL