blob: cd38bfa42be91b9527de9cb3b279d5cbfa9e98c4 [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
Gavin Howard01055ba2018-11-03 11:00:21 -0600224typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
225typedef void (*BcNumDigitOp)(size_t, size_t, bool, size_t *, size_t);
226
Gavin Howard01055ba2018-11-03 11:00:21 -0600227static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
228static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
229static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
230static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
231static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
232static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
233static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
234static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
235 size_t scale);
236
237typedef enum BcInst {
238
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100239#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600240 BC_INST_INC_PRE,
241 BC_INST_DEC_PRE,
242 BC_INST_INC_POST,
243 BC_INST_DEC_POST,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100244#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600245
246 BC_INST_NEG,
247
248 BC_INST_POWER,
249 BC_INST_MULTIPLY,
250 BC_INST_DIVIDE,
251 BC_INST_MODULUS,
252 BC_INST_PLUS,
253 BC_INST_MINUS,
254
255 BC_INST_REL_EQ,
256 BC_INST_REL_LE,
257 BC_INST_REL_GE,
258 BC_INST_REL_NE,
259 BC_INST_REL_LT,
260 BC_INST_REL_GT,
261
262 BC_INST_BOOL_NOT,
263 BC_INST_BOOL_OR,
264 BC_INST_BOOL_AND,
265
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100266#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600267 BC_INST_ASSIGN_POWER,
268 BC_INST_ASSIGN_MULTIPLY,
269 BC_INST_ASSIGN_DIVIDE,
270 BC_INST_ASSIGN_MODULUS,
271 BC_INST_ASSIGN_PLUS,
272 BC_INST_ASSIGN_MINUS,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100273#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600274 BC_INST_ASSIGN,
275
276 BC_INST_NUM,
277 BC_INST_VAR,
278 BC_INST_ARRAY_ELEM,
279 BC_INST_ARRAY,
280
281 BC_INST_SCALE_FUNC,
282 BC_INST_IBASE,
283 BC_INST_SCALE,
284 BC_INST_LAST,
285 BC_INST_LENGTH,
286 BC_INST_READ,
287 BC_INST_OBASE,
288 BC_INST_SQRT,
289
290 BC_INST_PRINT,
291 BC_INST_PRINT_POP,
292 BC_INST_STR,
293 BC_INST_PRINT_STR,
294
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100295#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600296 BC_INST_JUMP,
297 BC_INST_JUMP_ZERO,
298
299 BC_INST_CALL,
300
301 BC_INST_RET,
302 BC_INST_RET0,
303
304 BC_INST_HALT,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100305#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600306
307 BC_INST_POP,
308 BC_INST_POP_EXEC,
309
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100310#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600311 BC_INST_MODEXP,
312 BC_INST_DIVMOD,
313
314 BC_INST_EXECUTE,
315 BC_INST_EXEC_COND,
316
317 BC_INST_ASCIIFY,
318 BC_INST_PRINT_STREAM,
319
320 BC_INST_PRINT_STACK,
321 BC_INST_CLEAR_STACK,
322 BC_INST_STACK_LEN,
323 BC_INST_DUPLICATE,
324 BC_INST_SWAP,
325
326 BC_INST_LOAD,
327 BC_INST_PUSH_VAR,
328 BC_INST_PUSH_TO_VAR,
329
330 BC_INST_QUIT,
331 BC_INST_NQUIT,
332
333 BC_INST_INVALID = -1,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100334#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600335
336} BcInst;
337
338typedef struct BcId {
339 char *name;
340 size_t idx;
341} BcId;
342
343typedef struct BcFunc {
344 BcVec code;
345 BcVec labels;
346 size_t nparams;
347 BcVec autos;
348} BcFunc;
349
350typedef enum BcResultType {
351
352 BC_RESULT_TEMP,
353
354 BC_RESULT_VAR,
355 BC_RESULT_ARRAY_ELEM,
356 BC_RESULT_ARRAY,
357
358 BC_RESULT_STR,
359
360 BC_RESULT_IBASE,
361 BC_RESULT_SCALE,
362 BC_RESULT_LAST,
363
364 // These are between to calculate ibase, obase, and last from instructions.
365 BC_RESULT_CONSTANT,
366 BC_RESULT_ONE,
367
368 BC_RESULT_OBASE,
369
370} BcResultType;
371
372typedef union BcResultData {
373 BcNum n;
374 BcVec v;
375 BcId id;
376} BcResultData;
377
378typedef struct BcResult {
379 BcResultType t;
380 BcResultData d;
381} BcResult;
382
383typedef struct BcInstPtr {
384 size_t func;
385 size_t idx;
386 size_t len;
387} BcInstPtr;
388
Gavin Howard01055ba2018-11-03 11:00:21 -0600389// BC_LEX_NEG is not used in lexing; it is only for parsing.
390typedef enum BcLexType {
391
392 BC_LEX_EOF,
393 BC_LEX_INVALID,
394
395 BC_LEX_OP_INC,
396 BC_LEX_OP_DEC,
397
398 BC_LEX_NEG,
399
400 BC_LEX_OP_POWER,
401 BC_LEX_OP_MULTIPLY,
402 BC_LEX_OP_DIVIDE,
403 BC_LEX_OP_MODULUS,
404 BC_LEX_OP_PLUS,
405 BC_LEX_OP_MINUS,
406
407 BC_LEX_OP_REL_EQ,
408 BC_LEX_OP_REL_LE,
409 BC_LEX_OP_REL_GE,
410 BC_LEX_OP_REL_NE,
411 BC_LEX_OP_REL_LT,
412 BC_LEX_OP_REL_GT,
413
414 BC_LEX_OP_BOOL_NOT,
415 BC_LEX_OP_BOOL_OR,
416 BC_LEX_OP_BOOL_AND,
417
418 BC_LEX_OP_ASSIGN_POWER,
419 BC_LEX_OP_ASSIGN_MULTIPLY,
420 BC_LEX_OP_ASSIGN_DIVIDE,
421 BC_LEX_OP_ASSIGN_MODULUS,
422 BC_LEX_OP_ASSIGN_PLUS,
423 BC_LEX_OP_ASSIGN_MINUS,
424 BC_LEX_OP_ASSIGN,
425
426 BC_LEX_NLINE,
427 BC_LEX_WHITESPACE,
428
429 BC_LEX_LPAREN,
430 BC_LEX_RPAREN,
431
432 BC_LEX_LBRACKET,
433 BC_LEX_COMMA,
434 BC_LEX_RBRACKET,
435
436 BC_LEX_LBRACE,
437 BC_LEX_SCOLON,
438 BC_LEX_RBRACE,
439
440 BC_LEX_STR,
441 BC_LEX_NAME,
442 BC_LEX_NUMBER,
443
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100444 BC_LEX_KEY_1st_keyword,
445 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
Gavin Howard01055ba2018-11-03 11:00:21 -0600446 BC_LEX_KEY_BREAK,
447 BC_LEX_KEY_CONTINUE,
448 BC_LEX_KEY_DEFINE,
449 BC_LEX_KEY_ELSE,
450 BC_LEX_KEY_FOR,
451 BC_LEX_KEY_HALT,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100452 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
453 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600454 BC_LEX_KEY_IF,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100455 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
Gavin Howard01055ba2018-11-03 11:00:21 -0600456 BC_LEX_KEY_LENGTH,
457 BC_LEX_KEY_LIMITS,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100458 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600459 BC_LEX_KEY_PRINT,
460 BC_LEX_KEY_QUIT,
461 BC_LEX_KEY_READ,
462 BC_LEX_KEY_RETURN,
463 BC_LEX_KEY_SCALE,
464 BC_LEX_KEY_SQRT,
465 BC_LEX_KEY_WHILE,
466
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100467#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600468 BC_LEX_EQ_NO_REG,
469 BC_LEX_OP_MODEXP,
470 BC_LEX_OP_DIVMOD,
471
472 BC_LEX_COLON,
473 BC_LEX_ELSE,
474 BC_LEX_EXECUTE,
475 BC_LEX_PRINT_STACK,
476 BC_LEX_CLEAR_STACK,
477 BC_LEX_STACK_LEVEL,
478 BC_LEX_DUPLICATE,
479 BC_LEX_SWAP,
480 BC_LEX_POP,
481
482 BC_LEX_ASCIIFY,
483 BC_LEX_PRINT_STREAM,
484
485 BC_LEX_STORE_IBASE,
486 BC_LEX_STORE_SCALE,
487 BC_LEX_LOAD,
488 BC_LEX_LOAD_POP,
489 BC_LEX_STORE_PUSH,
490 BC_LEX_STORE_OBASE,
491 BC_LEX_PRINT_POP,
492 BC_LEX_NQUIT,
493 BC_LEX_SCALE_FACTOR,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100494#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600495} BcLexType;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100496// must match order of BC_LEX_KEY_foo etc above
497#if ENABLE_BC
498struct BcLexKeyword {
499 char name8[8];
500};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100501#define BC_LEX_KW_ENTRY(a, b) \
502 { .name8 = a /*, .posix = b */ }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100503static const struct BcLexKeyword bc_lex_kws[20] = {
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100504 BC_LEX_KW_ENTRY("auto" , 1), // 0
505 BC_LEX_KW_ENTRY("break" , 1), // 1
506 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
507 BC_LEX_KW_ENTRY("define" , 1), // 3
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100508
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100509 BC_LEX_KW_ENTRY("else" , 0), // 4
510 BC_LEX_KW_ENTRY("for" , 1), // 5
511 BC_LEX_KW_ENTRY("halt" , 0), // 6
512 BC_LEX_KW_ENTRY("ibase" , 1), // 7
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100513
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100514 BC_LEX_KW_ENTRY("if" , 1), // 8
515 BC_LEX_KW_ENTRY("last" , 0), // 9
516 BC_LEX_KW_ENTRY("length" , 1), // 10
517 BC_LEX_KW_ENTRY("limits" , 0), // 11
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100518
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100519 BC_LEX_KW_ENTRY("obase" , 1), // 12
520 BC_LEX_KW_ENTRY("print" , 0), // 13
521 BC_LEX_KW_ENTRY("quit" , 1), // 14
522 BC_LEX_KW_ENTRY("read" , 0), // 15
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100523
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100524 BC_LEX_KW_ENTRY("return" , 1), // 16
525 BC_LEX_KW_ENTRY("scale" , 1), // 17
526 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
527 BC_LEX_KW_ENTRY("while" , 1), // 19
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100528};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100529#undef BC_LEX_KW_ENTRY
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100530enum {
531 POSIX_KWORD_MASK = 0
532 | (1 << 0)
533 | (1 << 1)
534 | (0 << 2)
535 | (1 << 3)
536 \
537 | (0 << 4)
538 | (1 << 5)
539 | (0 << 6)
540 | (1 << 7)
541 \
542 | (1 << 8)
543 | (0 << 9)
544 | (1 << 10)
545 | (0 << 11)
546 \
547 | (1 << 12)
548 | (0 << 13)
549 | (1 << 14)
550 | (0 << 15)
551 \
552 | (1 << 16)
553 | (1 << 17)
554 | (1 << 18)
555 | (1 << 19)
556};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100557#define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100558#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600559
560struct BcLex;
561typedef BcStatus (*BcLexNext)(struct BcLex *);
562
563typedef struct BcLex {
564
565 const char *buf;
566 size_t i;
567 size_t line;
Gavin Howard01055ba2018-11-03 11:00:21 -0600568 size_t len;
569 bool newline;
570
571 struct {
572 BcLexType t;
573 BcLexType last;
574 BcVec v;
575 } t;
576
577 BcLexNext next;
578
579} BcLex;
580
581#define BC_PARSE_STREND ((char) UCHAR_MAX)
582
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100583#define BC_PARSE_REL (1 << 0)
584#define BC_PARSE_PRINT (1 << 1)
Gavin Howard01055ba2018-11-03 11:00:21 -0600585#define BC_PARSE_NOCALL (1 << 2)
586#define BC_PARSE_NOREAD (1 << 3)
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100587#define BC_PARSE_ARRAY (1 << 4)
Gavin Howard01055ba2018-11-03 11:00:21 -0600588
589#define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
590#define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
591
592#define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
593#define BC_PARSE_FUNC_INNER(parse) \
594 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
595
596#define BC_PARSE_FLAG_FUNC (1 << 1)
597#define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
598
599#define BC_PARSE_FLAG_BODY (1 << 2)
600#define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
601
602#define BC_PARSE_FLAG_LOOP (1 << 3)
603#define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
604
605#define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
606#define BC_PARSE_LOOP_INNER(parse) \
607 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
608
609#define BC_PARSE_FLAG_IF (1 << 5)
610#define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
611
612#define BC_PARSE_FLAG_ELSE (1 << 6)
613#define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
614
615#define BC_PARSE_FLAG_IF_END (1 << 7)
616#define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
617
618#define BC_PARSE_CAN_EXEC(parse) \
619 (!(BC_PARSE_TOP_FLAG(parse) & \
620 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
621 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
622 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
623
Gavin Howard01055ba2018-11-03 11:00:21 -0600624struct BcParse;
625
626struct BcProgram;
627
Gavin Howard01055ba2018-11-03 11:00:21 -0600628typedef BcStatus (*BcParseParse)(struct BcParse *);
Gavin Howard01055ba2018-11-03 11:00:21 -0600629
630typedef struct BcParse {
631
632 BcParseParse parse;
633
634 BcLex l;
635
636 BcVec flags;
637
638 BcVec exits;
639 BcVec conds;
640
641 BcVec ops;
642
Gavin Howard01055ba2018-11-03 11:00:21 -0600643 BcFunc *func;
644 size_t fidx;
645
646 size_t nbraces;
647 bool auto_part;
648
649} BcParse;
650
Gavin Howard01055ba2018-11-03 11:00:21 -0600651typedef struct BcProgram {
652
653 size_t len;
654 size_t scale;
655
656 BcNum ib;
657 size_t ib_t;
658 BcNum ob;
659 size_t ob_t;
660
661 BcNum hexb;
662
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100663#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600664 BcNum strmb;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100665#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600666
667 BcVec results;
668 BcVec stack;
669
670 BcVec fns;
671 BcVec fn_map;
672
673 BcVec vars;
674 BcVec var_map;
675
676 BcVec arrs;
677 BcVec arr_map;
678
679 BcVec strs;
680 BcVec consts;
681
682 const char *file;
683
684 BcNum last;
685 BcNum zero;
686 BcNum one;
687
688 size_t nchars;
689
Gavin Howard01055ba2018-11-03 11:00:21 -0600690} BcProgram;
691
692#define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
693
694#define BC_PROG_MAIN (0)
695#define BC_PROG_READ (1)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100696#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600697#define BC_PROG_REQ_FUNCS (2)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100698#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600699
700#define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
701#define BC_PROG_NUM(r, n) \
702 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
703
704typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
705
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100706#define BC_FLAG_W (1 << 0)
707#define BC_FLAG_V (1 << 1)
708#define BC_FLAG_S (1 << 2)
709#define BC_FLAG_Q (1 << 3)
710#define BC_FLAG_L (1 << 4)
711#define BC_FLAG_I (1 << 5)
712#define DC_FLAG_X (1 << 6)
Gavin Howard01055ba2018-11-03 11:00:21 -0600713
714#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
715#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
716
Denys Vlasenko64074a12018-12-07 15:50:14 +0100717#define BC_MAX_OBASE ((unsigned) 999)
718#define BC_MAX_DIM ((unsigned) INT_MAX)
719#define BC_MAX_SCALE ((unsigned) UINT_MAX)
720#define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
721#define BC_MAX_NUM BC_MAX_STRING
722// Unused apart from "limits" message. Just show a "biggish number" there.
723//#define BC_MAX_NAME BC_MAX_STRING
724//#define BC_MAX_EXP ((unsigned long) LONG_MAX)
725//#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
726#define BC_MAX_NAME_STR "999999999"
727#define BC_MAX_EXP_STR "999999999"
728#define BC_MAX_VARS_STR "999999999"
729
730#define BC_MAX_OBASE_STR "999"
731
732#if INT_MAX == 2147483647
733# define BC_MAX_DIM_STR "2147483647"
734#elif INT_MAX == 9223372036854775807
735# define BC_MAX_DIM_STR "9223372036854775807"
736#else
737# error Strange INT_MAX
738#endif
739
740#if UINT_MAX == 4294967295
741# define BC_MAX_SCALE_STR "4294967295"
742# define BC_MAX_STRING_STR "4294967294"
743#elif UINT_MAX == 18446744073709551615
744# define BC_MAX_SCALE_STR "18446744073709551615"
745# define BC_MAX_STRING_STR "18446744073709551614"
746#else
747# error Strange UINT_MAX
748#endif
749#define BC_MAX_NUM_STR BC_MAX_STRING_STR
Gavin Howard01055ba2018-11-03 11:00:21 -0600750
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100751struct globals {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100752 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100753 IF_FEATURE_CLEAN_UP(smallint exiting;)
Gavin Howard01055ba2018-11-03 11:00:21 -0600754 char sbgn;
755 char send;
Gavin Howard01055ba2018-11-03 11:00:21 -0600756
757 BcParse prs;
758 BcProgram prog;
759
Denys Vlasenko5318f812018-12-05 17:48:01 +0100760 // For error messages. Can be set to current parsed line,
761 // or [TODO] to current executing line (can be before last parsed one)
762 unsigned err_line;
763
Gavin Howard01055ba2018-11-03 11:00:21 -0600764 BcVec files;
765
766 char *env_args;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100767
768#if ENABLE_FEATURE_EDITING
769 line_input_t *line_input_state;
770#endif
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100771} FIX_ALIASING;
772#define G (*ptr_to_globals)
773#define INIT_G() do { \
774 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
775} while (0)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100776#define FREE_G() do { \
777 FREE_PTR_TO_GLOBALS(); \
778} while (0)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100779#define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
780#define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
Denys Vlasenko6d0be102018-12-06 18:41:59 +0100781#define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100782#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkob9c321d2018-12-07 12:41:42 +0100783# define G_interrupt bb_got_signal
784# define G_ttyin G.ttyin
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100785#else
Denys Vlasenkob9c321d2018-12-07 12:41:42 +0100786# define G_interrupt 0
787# define G_ttyin 0
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100788#endif
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100789#if ENABLE_FEATURE_CLEAN_UP
790# define G_exiting G.exiting
791#else
792# define G_exiting 0
793#endif
Denys Vlasenko00d77792018-11-30 23:13:42 +0100794#define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
795
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100796#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600797
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100798// This is a bit array that corresponds to token types. An entry is
Gavin Howard01055ba2018-11-03 11:00:21 -0600799// true if the token is valid in an expression, false otherwise.
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100800enum {
801 BC_PARSE_EXPRS_BITS = 0
802 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
803 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
804 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
805 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
806 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
807 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
808 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
809 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
Gavin Howard01055ba2018-11-03 11:00:21 -0600810};
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100811static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
812{
813#if ULONG_MAX > 0xffffffff
814 // 64-bit version (will not work correctly for 32-bit longs!)
815 return BC_PARSE_EXPRS_BITS & (1UL << i);
816#else
817 // 32-bit version
818 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
819 if (i >= 32) {
820 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
821 i &= 31;
822 }
823 return m & (1UL << i);
824#endif
825}
Gavin Howard01055ba2018-11-03 11:00:21 -0600826
827// This is an array of data for operators that correspond to token types.
Denys Vlasenko65437582018-12-05 19:37:19 +0100828static const uint8_t bc_parse_ops[] = {
829#define OP(p,l) ((int)(l) * 0x10 + (p))
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100830 OP(0, false), OP( 0, false ), // inc dec
831 OP(1, false), // neg
Denys Vlasenko65437582018-12-05 19:37:19 +0100832 OP(2, false),
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100833 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
834 OP(4, true ), OP( 4, true ), // mod + -
835 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
836 OP(1, false), // not
837 OP(7, true ), OP( 7, true ), // or and
838 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
839 OP(5, false), OP( 5, false ), // -= =
Denys Vlasenko65437582018-12-05 19:37:19 +0100840#undef OP
Gavin Howard01055ba2018-11-03 11:00:21 -0600841};
Denys Vlasenko65437582018-12-05 19:37:19 +0100842#define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
843#define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
Gavin Howard01055ba2018-11-03 11:00:21 -0600844
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100845// Byte array of up to 4 BC_LEX's, packed into 32-bit word
846typedef uint32_t BcParseNext;
847
Gavin Howard01055ba2018-11-03 11:00:21 -0600848// These identify what tokens can come after expressions in certain cases.
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100849enum {
850#define BC_PARSE_NEXT4(a,b,c,d) ( (a) | ((b)<<8) | ((c)<<16) | ((((d)|0x80)<<24)) )
851#define BC_PARSE_NEXT2(a,b) BC_PARSE_NEXT4(a,b,0xff,0xff)
852#define BC_PARSE_NEXT1(a) BC_PARSE_NEXT4(a,0xff,0xff,0xff)
853 bc_parse_next_expr = BC_PARSE_NEXT4(BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF),
854 bc_parse_next_param = BC_PARSE_NEXT2(BC_LEX_RPAREN, BC_LEX_COMMA),
855 bc_parse_next_print = BC_PARSE_NEXT4(BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF),
856 bc_parse_next_rel = BC_PARSE_NEXT1(BC_LEX_RPAREN),
857 bc_parse_next_elem = BC_PARSE_NEXT1(BC_LEX_RBRACKET),
858 bc_parse_next_for = BC_PARSE_NEXT1(BC_LEX_SCOLON),
859 bc_parse_next_read = BC_PARSE_NEXT2(BC_LEX_NLINE, BC_LEX_EOF),
860#undef BC_PARSE_NEXT4
861#undef BC_PARSE_NEXT2
862#undef BC_PARSE_NEXT1
863};
Gavin Howard01055ba2018-11-03 11:00:21 -0600864#endif // ENABLE_BC
865
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100866#if ENABLE_DC
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100867static const //BcLexType - should be this type, but narrower type saves size:
868uint8_t
869dc_lex_regs[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600870 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
871 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
872 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
873 BC_LEX_STORE_PUSH,
874};
875
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100876static const //BcLexType - should be this type
877uint8_t
878dc_lex_tokens[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600879 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
880 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
881 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
882 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
883 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
884 BC_LEX_INVALID, BC_LEX_INVALID,
885 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
886 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
887 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
888 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
889 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
890 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
891 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
892 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
893 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
894 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
895 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
896 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
897 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
898 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
899 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
900 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
901 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
902 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
903 BC_LEX_INVALID
904};
905
Denys Vlasenko18c6b542018-12-07 12:57:32 +0100906static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
907int8_t
908dc_parse_insts[] = {
Gavin Howard01055ba2018-11-03 11:00:21 -0600909 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
910 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
911 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
912 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
913 BC_INST_INVALID, BC_INST_INVALID,
914 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
915 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
916 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
917 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
918 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
919 BC_INST_INVALID, BC_INST_INVALID,
920 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
921 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
922 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
923 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
924 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
925 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
926 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
927 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
928 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
929 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
930 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
931 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
932};
933#endif // ENABLE_DC
934
Gavin Howard01055ba2018-11-03 11:00:21 -0600935static const BcNumBinaryOp bc_program_ops[] = {
936 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
937};
938
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100939static void fflush_and_check(void)
940{
941 fflush_all();
942 if (ferror(stdout) || ferror(stderr))
943 bb_perror_msg_and_die("output error");
944}
945
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100946#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100947#define QUIT_OR_RETURN_TO_MAIN \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100948do { \
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100949 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100950 G_exiting = 1; \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100951 return BC_STATUS_FAILURE; \
952} while (0)
953#else
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +0100954#define QUIT_OR_RETURN_TO_MAIN quit()
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100955#endif
956
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100957static void quit(void) NORETURN;
958static void quit(void)
959{
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100960 if (ferror(stdin))
961 bb_perror_msg_and_die("input error");
962 fflush_and_check();
963 exit(0);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100964}
965
Denys Vlasenko5318f812018-12-05 17:48:01 +0100966static void bc_verror_msg(const char *fmt, va_list p)
967{
968 const char *sv = sv; /* for compiler */
969 if (G.prog.file) {
970 sv = applet_name;
971 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
972 }
973 bb_verror_msg(fmt, p, NULL);
974 if (G.prog.file) {
975 free((char*)applet_name);
976 applet_name = sv;
977 }
978}
979
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100980static NOINLINE int bc_error_fmt(const char *fmt, ...)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100981{
982 va_list p;
983
984 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +0100985 bc_verror_msg(fmt, p);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100986 va_end(p);
Denys Vlasenko0409ad32018-12-05 16:39:22 +0100987
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100988 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100989 exit(1);
990 return BC_STATUS_FAILURE;
991}
992
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +0100993#if ENABLE_BC
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100994static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100995{
996 va_list p;
997
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100998 // Are non-POSIX constructs totally ok?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100999 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001000 return BC_STATUS_SUCCESS; // yes
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001001
1002 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +01001003 bc_verror_msg(fmt, p);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001004 va_end(p);
1005
1006 // Do we treat non-POSIX constructs as errors?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01001007 if (!(option_mask32 & BC_FLAG_S))
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001008 return BC_STATUS_SUCCESS; // no, it's a warning
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01001009 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001010 exit(1);
1011 return BC_STATUS_FAILURE;
1012}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001013#endif
Denys Vlasenko9b70f192018-12-04 20:51:40 +01001014
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001015// We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
1016// This idiom begs for tail-call optimization, but for it to work,
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001017// function must not have caller-cleaned parameters on stack.
1018// Unfortunately, vararg function API does exactly that on most arches.
1019// Thus, use these shims for the cases when we have no vararg PARAMS:
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001020static int bc_error(const char *msg)
1021{
1022 return bc_error_fmt("%s", msg);
1023}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001024#if ENABLE_BC
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001025static int bc_POSIX_requires(const char *msg)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001026{
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001027 return bc_posix_error_fmt("POSIX requires %s", msg);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001028}
Denys Vlasenko00646792018-12-05 18:12:27 +01001029static int bc_POSIX_does_not_allow(const char *msg)
1030{
1031 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1032}
1033static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1034{
1035 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1036}
1037static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1038{
1039 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1040}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001041#endif
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001042static int bc_error_bad_character(char c)
1043{
1044 return bc_error_fmt("bad character '%c'", c);
1045}
1046static int bc_error_bad_expression(void)
1047{
1048 return bc_error("bad expression");
1049}
1050static int bc_error_bad_token(void)
1051{
1052 return bc_error("bad token");
1053}
1054static int bc_error_stack_has_too_few_elements(void)
1055{
1056 return bc_error("stack has too few elements");
1057}
1058static int bc_error_variable_is_wrong_type(void)
1059{
1060 return bc_error("variable is wrong type");
1061}
1062static int bc_error_nested_read_call(void)
1063{
1064 return bc_error("read() call inside of a read() call");
1065}
1066
Gavin Howard01055ba2018-11-03 11:00:21 -06001067static void bc_vec_grow(BcVec *v, size_t n)
1068{
1069 size_t cap = v->cap * 2;
1070 while (cap < v->len + n) cap *= 2;
1071 v->v = xrealloc(v->v, v->size * cap);
1072 v->cap = cap;
1073}
1074
1075static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1076{
1077 v->size = esize;
1078 v->cap = BC_VEC_START_CAP;
1079 v->len = 0;
1080 v->dtor = dtor;
1081 v->v = xmalloc(esize * BC_VEC_START_CAP);
1082}
1083
Denys Vlasenko7d628012018-12-04 21:46:47 +01001084static void bc_char_vec_init(BcVec *v)
1085{
1086 bc_vec_init(v, sizeof(char), NULL);
1087}
1088
Gavin Howard01055ba2018-11-03 11:00:21 -06001089static void bc_vec_expand(BcVec *v, size_t req)
1090{
1091 if (v->cap < req) {
1092 v->v = xrealloc(v->v, v->size * req);
1093 v->cap = req;
1094 }
1095}
1096
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001097static void bc_vec_pop(BcVec *v)
1098{
1099 v->len--;
1100 if (v->dtor)
1101 v->dtor(v->v + (v->size * v->len));
1102}
Denys Vlasenko2fa11b62018-12-06 12:34:39 +01001103
Gavin Howard01055ba2018-11-03 11:00:21 -06001104static void bc_vec_npop(BcVec *v, size_t n)
1105{
1106 if (!v->dtor)
1107 v->len -= n;
1108 else {
1109 size_t len = v->len - n;
1110 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1111 }
1112}
1113
Denys Vlasenko7d628012018-12-04 21:46:47 +01001114static void bc_vec_pop_all(BcVec *v)
1115{
1116 bc_vec_npop(v, v->len);
1117}
1118
Gavin Howard01055ba2018-11-03 11:00:21 -06001119static void bc_vec_push(BcVec *v, const void *data)
1120{
1121 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1122 memmove(v->v + (v->size * v->len), data, v->size);
1123 v->len += 1;
1124}
1125
1126static void bc_vec_pushByte(BcVec *v, char data)
1127{
1128 bc_vec_push(v, &data);
1129}
1130
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001131static void bc_vec_pushZeroByte(BcVec *v)
1132{
1133 //bc_vec_pushByte(v, '\0');
1134 // better:
1135 bc_vec_push(v, &const_int_0);
1136}
1137
Gavin Howard01055ba2018-11-03 11:00:21 -06001138static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1139{
1140 if (idx == v->len)
1141 bc_vec_push(v, data);
1142 else {
1143
1144 char *ptr;
1145
1146 if (v->len == v->cap) bc_vec_grow(v, 1);
1147
1148 ptr = v->v + v->size * idx;
1149
1150 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1151 memmove(ptr, data, v->size);
1152 }
1153}
1154
1155static void bc_vec_string(BcVec *v, size_t len, const char *str)
1156{
Denys Vlasenko7d628012018-12-04 21:46:47 +01001157 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001158 bc_vec_expand(v, len + 1);
1159 memcpy(v->v, str, len);
1160 v->len = len;
1161
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001162 bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001163}
1164
1165static void bc_vec_concat(BcVec *v, const char *str)
1166{
1167 size_t len;
1168
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001169 if (v->len == 0) bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001170
1171 len = v->len + strlen(str);
1172
1173 if (v->cap < len) bc_vec_grow(v, len - v->len);
Denys Vlasenko1ff88622018-12-06 12:06:16 +01001174 strcpy(v->v + v->len - 1, str);
Gavin Howard01055ba2018-11-03 11:00:21 -06001175
1176 v->len = len;
1177}
1178
1179static void *bc_vec_item(const BcVec *v, size_t idx)
1180{
1181 return v->v + v->size * idx;
1182}
1183
1184static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1185{
1186 return v->v + v->size * (v->len - idx - 1);
1187}
1188
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001189static void *bc_vec_top(const BcVec *v)
1190{
1191 return v->v + v->size * (v->len - 1);
1192}
1193
Gavin Howard01055ba2018-11-03 11:00:21 -06001194static void bc_vec_free(void *vec)
1195{
1196 BcVec *v = (BcVec *) vec;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001197 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001198 free(v->v);
1199}
1200
Denys Vlasenkocca79a02018-12-05 21:15:46 +01001201static int bc_id_cmp(const void *e1, const void *e2)
1202{
1203 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1204}
1205
1206static void bc_id_free(void *id)
1207{
1208 free(((BcId *) id)->name);
1209}
1210
Gavin Howard01055ba2018-11-03 11:00:21 -06001211static size_t bc_map_find(const BcVec *v, const void *ptr)
1212{
1213 size_t low = 0, high = v->len;
1214
1215 while (low < high) {
1216
1217 size_t mid = (low + high) / 2;
1218 BcId *id = bc_vec_item(v, mid);
1219 int result = bc_id_cmp(ptr, id);
1220
1221 if (result == 0)
1222 return mid;
1223 else if (result < 0)
1224 high = mid;
1225 else
1226 low = mid + 1;
1227 }
1228
1229 return low;
1230}
1231
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001232static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
Gavin Howard01055ba2018-11-03 11:00:21 -06001233{
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001234 size_t n = *i = bc_map_find(v, ptr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001235
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001236 if (n == v->len)
Gavin Howard01055ba2018-11-03 11:00:21 -06001237 bc_vec_push(v, ptr);
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001238 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1239 return 0; // "was not inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001240 else
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001241 bc_vec_pushAt(v, ptr, n);
1242 return 1; // "was inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001243}
1244
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001245#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06001246static size_t bc_map_index(const BcVec *v, const void *ptr)
1247{
1248 size_t i = bc_map_find(v, ptr);
1249 if (i >= v->len) return BC_VEC_INVALID_IDX;
1250 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1251}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001252#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06001253
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001254static int push_input_byte(BcVec *vec, char c)
1255{
1256 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1257 || c > 0x7e
1258 ) {
1259 // Bad chars on this line, ignore entire line
1260 bc_error_fmt("illegal character 0x%02x", c);
1261 return 1;
1262 }
1263 bc_vec_pushByte(vec, (char)c);
1264 return 0;
1265}
1266
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01001267static BcStatus bc_read_line(BcVec *vec)
Gavin Howard01055ba2018-11-03 11:00:21 -06001268{
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001269 BcStatus s;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001270 bool bad_chars;
Gavin Howard01055ba2018-11-03 11:00:21 -06001271
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001272 s = BC_STATUS_SUCCESS;
Denys Vlasenko00d77792018-11-30 23:13:42 +01001273 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001274 int c;
Gavin Howard01055ba2018-11-03 11:00:21 -06001275
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001276 bad_chars = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001277 bc_vec_pop_all(vec);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001278
1279 fflush_and_check();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001280
Gavin Howard01055ba2018-11-03 11:00:21 -06001281#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001282 if (G_interrupt) { // ^C was pressed
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001283 intr:
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001284 G_interrupt = 0;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001285 fputs(IS_BC
1286 ? "\ninterrupt (type \"quit\" to exit)\n"
1287 : "\ninterrupt (type \"q\" to exit)\n"
1288 , stderr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001289 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001290# if ENABLE_FEATURE_EDITING
1291 if (G_ttyin) {
1292 int n, i;
1293# define line_buf bb_common_bufsiz1
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01001294 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001295 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1296 if (n == 0) // ^C
1297 goto intr;
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001298 s = BC_STATUS_EOF;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001299 break;
1300 }
1301 i = 0;
1302 for (;;) {
1303 c = line_buf[i++];
1304 if (!c) break;
1305 bad_chars |= push_input_byte(vec, c);
1306 }
1307# undef line_buf
1308 } else
1309# endif
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001310#endif
Denys Vlasenkoed849352018-12-06 10:26:13 +01001311 {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001312 IF_FEATURE_BC_SIGNALS(errno = 0;)
1313 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001314 c = fgetc(stdin);
1315#if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1316 // Both conditions appear simultaneously, check both just in case
Denys Vlasenkob9c321d2018-12-07 12:41:42 +01001317 if (errno == EINTR || G_interrupt) {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001318 // ^C was pressed
1319 clearerr(stdin);
1320 goto intr;
1321 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001322#endif
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001323 if (c == EOF) {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001324 if (ferror(stdin))
1325 quit(); // this emits error message
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001326 s = BC_STATUS_EOF;
Denys Vlasenkoed849352018-12-06 10:26:13 +01001327 // Note: EOF does not append '\n', therefore:
1328 // printf 'print 123\n' | bc - works
1329 // printf 'print 123' | bc - fails (syntax error)
1330 break;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001331 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001332 bad_chars |= push_input_byte(vec, c);
1333 } while (c != '\n');
Denys Vlasenkoed849352018-12-06 10:26:13 +01001334 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001335 } while (bad_chars);
Gavin Howard01055ba2018-11-03 11:00:21 -06001336
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001337 bc_vec_pushZeroByte(vec);
Gavin Howard01055ba2018-11-03 11:00:21 -06001338
Denys Vlasenkof522dd92018-12-07 16:35:43 +01001339 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06001340}
1341
Denys Vlasenkodf515392018-12-02 19:27:48 +01001342static char* bc_read_file(const char *path)
Gavin Howard01055ba2018-11-03 11:00:21 -06001343{
Denys Vlasenkodf515392018-12-02 19:27:48 +01001344 char *buf;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001345 size_t size = ((size_t) -1);
1346 size_t i;
Gavin Howard01055ba2018-11-03 11:00:21 -06001347
Denys Vlasenko4c9455f2018-12-06 15:21:39 +01001348 // Never returns NULL (dies on errors)
1349 buf = xmalloc_xopen_read_close(path, &size);
Gavin Howard01055ba2018-11-03 11:00:21 -06001350
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001351 for (i = 0; i < size; ++i) {
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001352 char c = buf[i];
1353 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1354 || c > 0x7e
1355 ) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01001356 free(buf);
1357 buf = NULL;
1358 break;
1359 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001360 }
1361
Denys Vlasenkodf515392018-12-02 19:27:48 +01001362 return buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06001363}
1364
Gavin Howard01055ba2018-11-03 11:00:21 -06001365static void bc_num_setToZero(BcNum *n, size_t scale)
1366{
1367 n->len = 0;
1368 n->neg = false;
1369 n->rdx = scale;
1370}
1371
1372static void bc_num_zero(BcNum *n)
1373{
1374 bc_num_setToZero(n, 0);
1375}
1376
1377static void bc_num_one(BcNum *n)
1378{
1379 bc_num_setToZero(n, 0);
1380 n->len = 1;
1381 n->num[0] = 1;
1382}
1383
1384static void bc_num_ten(BcNum *n)
1385{
1386 bc_num_setToZero(n, 0);
1387 n->len = 2;
1388 n->num[0] = 0;
1389 n->num[1] = 1;
1390}
1391
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001392static void bc_num_init(BcNum *n, size_t req)
1393{
1394 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1395 memset(n, 0, sizeof(BcNum));
1396 n->num = xmalloc(req);
1397 n->cap = req;
1398}
1399
1400static void bc_num_expand(BcNum *n, size_t req)
1401{
1402 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1403 if (req > n->cap) {
1404 n->num = xrealloc(n->num, req);
1405 n->cap = req;
1406 }
1407}
1408
1409static void bc_num_free(void *num)
1410{
1411 free(((BcNum *) num)->num);
1412}
1413
1414static void bc_num_copy(BcNum *d, BcNum *s)
1415{
1416 if (d != s) {
1417 bc_num_expand(d, s->cap);
1418 d->len = s->len;
1419 d->neg = s->neg;
1420 d->rdx = s->rdx;
1421 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1422 }
1423}
1424
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001425static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001426{
1427 size_t i;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001428 unsigned long pow, result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001429
1430 if (n->neg) return bc_error("negative number");
1431
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001432 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001433
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001434 unsigned long prev = result, powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001435
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001436 result += ((unsigned long) n->num[i]) * pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001437 pow *= 10;
1438
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001439 if (result < prev || pow < powprev)
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001440 return bc_error("overflow");
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001441 prev = result;
1442 powprev = pow;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001443 }
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01001444 *result_p = result;
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001445
1446 return BC_STATUS_SUCCESS;
1447}
1448
1449static void bc_num_ulong2num(BcNum *n, unsigned long val)
1450{
1451 size_t len;
1452 BcDig *ptr;
1453 unsigned long i;
1454
1455 bc_num_zero(n);
1456
1457 if (val == 0) return;
1458
1459 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1460 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1461}
1462
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001463static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001464 size_t len)
1465{
1466 size_t i, j;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001467 for (i = 0; i < len; ++i) {
1468 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001469 a[i + j++] += 10;
1470 a[i + j] -= 1;
1471 }
1472 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001473}
1474
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01001475#define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1476#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1477#define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1478//#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1479static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1480{
1481 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1482}
1483//#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1484static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1485{
1486 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1487}
1488
Gavin Howard01055ba2018-11-03 11:00:21 -06001489static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1490{
1491 size_t i;
1492 int c = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001493 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
Gavin Howard01055ba2018-11-03 11:00:21 -06001494 return BC_NUM_NEG(i + 1, c < 0);
1495}
1496
1497static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1498{
1499 size_t i, min, a_int, b_int, diff;
1500 BcDig *max_num, *min_num;
1501 bool a_max, neg = false;
1502 ssize_t cmp;
1503
1504 if (a == b) return 0;
1505 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1506 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1507 if (a->neg) {
1508 if (b->neg)
1509 neg = true;
1510 else
1511 return -1;
1512 }
1513 else if (b->neg)
1514 return 1;
1515
1516 a_int = BC_NUM_INT(a);
1517 b_int = BC_NUM_INT(b);
1518 a_int -= b_int;
1519 a_max = (a->rdx > b->rdx);
1520
1521 if (a_int != 0) return (ssize_t) a_int;
1522
1523 if (a_max) {
1524 min = b->rdx;
1525 diff = a->rdx - b->rdx;
1526 max_num = a->num + diff;
1527 min_num = b->num;
1528 }
1529 else {
1530 min = a->rdx;
1531 diff = b->rdx - a->rdx;
1532 max_num = b->num + diff;
1533 min_num = a->num;
1534 }
1535
1536 cmp = bc_num_compare(max_num, min_num, b_int + min);
1537 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1538
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001539 for (max_num -= diff, i = diff - 1; i < diff; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001540 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1541 }
1542
1543 return 0;
1544}
1545
1546static void bc_num_truncate(BcNum *n, size_t places)
1547{
1548 if (places == 0) return;
1549
1550 n->rdx -= places;
1551
1552 if (n->len != 0) {
1553 n->len -= places;
1554 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1555 }
1556}
1557
1558static void bc_num_extend(BcNum *n, size_t places)
1559{
1560 size_t len = n->len + places;
1561
1562 if (places != 0) {
1563
1564 if (n->cap < len) bc_num_expand(n, len);
1565
1566 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1567 memset(n->num, 0, sizeof(BcDig) * places);
1568
1569 n->len += places;
1570 n->rdx += places;
1571 }
1572}
1573
1574static void bc_num_clean(BcNum *n)
1575{
1576 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1577 if (n->len == 0)
1578 n->neg = false;
1579 else if (n->len < n->rdx)
1580 n->len = n->rdx;
1581}
1582
1583static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1584{
1585 if (n->rdx < scale)
1586 bc_num_extend(n, scale - n->rdx);
1587 else
1588 bc_num_truncate(n, n->rdx - scale);
1589
1590 bc_num_clean(n);
1591 if (n->len != 0) n->neg = !neg1 != !neg2;
1592}
1593
1594static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1595 BcNum *restrict b)
1596{
1597 if (idx < n->len) {
1598
1599 b->len = n->len - idx;
1600 a->len = idx;
1601 a->rdx = b->rdx = 0;
1602
1603 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1604 memcpy(a->num, n->num, idx * sizeof(BcDig));
1605 }
1606 else {
1607 bc_num_zero(b);
1608 bc_num_copy(a, n);
1609 }
1610
1611 bc_num_clean(a);
1612 bc_num_clean(b);
1613}
1614
1615static BcStatus bc_num_shift(BcNum *n, size_t places)
1616{
1617 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
Denys Vlasenko64074a12018-12-07 15:50:14 +01001618
1619 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1620 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1621 if (places + n->len > BC_MAX_NUM)
1622 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1623 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001624
1625 if (n->rdx >= places)
1626 n->rdx -= places;
1627 else {
1628 bc_num_extend(n, places - n->rdx);
1629 n->rdx = 0;
1630 }
1631
1632 bc_num_clean(n);
1633
1634 return BC_STATUS_SUCCESS;
1635}
1636
1637static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1638{
1639 BcNum one;
1640 BcDig num[2];
1641
1642 one.cap = 2;
1643 one.num = num;
1644 bc_num_one(&one);
1645
1646 return bc_num_div(&one, a, b, scale);
1647}
1648
1649static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1650{
1651 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1652 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1653 int carry, in;
1654
1655 // Because this function doesn't need to use scale (per the bc spec),
1656 // I am hijacking it to say whether it's doing an add or a subtract.
1657
1658 if (a->len == 0) {
1659 bc_num_copy(c, b);
1660 if (sub && c->len) c->neg = !c->neg;
1661 return BC_STATUS_SUCCESS;
1662 }
1663 else if (b->len == 0) {
1664 bc_num_copy(c, a);
1665 return BC_STATUS_SUCCESS;
1666 }
1667
1668 c->neg = a->neg;
1669 c->rdx = BC_MAX(a->rdx, b->rdx);
1670 min_rdx = BC_MIN(a->rdx, b->rdx);
1671 c->len = 0;
1672
1673 if (a->rdx > b->rdx) {
1674 diff = a->rdx - b->rdx;
1675 ptr = a->num;
1676 ptr_a = a->num + diff;
1677 ptr_b = b->num;
1678 }
1679 else {
1680 diff = b->rdx - a->rdx;
1681 ptr = b->num;
1682 ptr_a = a->num;
1683 ptr_b = b->num + diff;
1684 }
1685
1686 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1687
1688 ptr_c += diff;
1689 a_int = BC_NUM_INT(a);
1690 b_int = BC_NUM_INT(b);
1691
1692 if (a_int > b_int) {
1693 min_int = b_int;
1694 max = a_int;
1695 ptr = ptr_a;
1696 }
1697 else {
1698 min_int = a_int;
1699 max = b_int;
1700 ptr = ptr_b;
1701 }
1702
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001703 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001704 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1705 carry = in / 10;
1706 ptr_c[i] = (BcDig)(in % 10);
1707 }
1708
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001709 for (; i < max + min_rdx; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001710 in = ((int) ptr[i]) + carry;
1711 carry = in / 10;
1712 ptr_c[i] = (BcDig)(in % 10);
1713 }
1714
1715 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1716
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001717 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001718}
1719
1720static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1721{
Gavin Howard01055ba2018-11-03 11:00:21 -06001722 ssize_t cmp;
1723 BcNum *minuend, *subtrahend;
1724 size_t start;
1725 bool aneg, bneg, neg;
1726
1727 // Because this function doesn't need to use scale (per the bc spec),
1728 // I am hijacking it to say whether it's doing an add or a subtract.
1729
1730 if (a->len == 0) {
1731 bc_num_copy(c, b);
1732 if (sub && c->len) c->neg = !c->neg;
1733 return BC_STATUS_SUCCESS;
1734 }
1735 else if (b->len == 0) {
1736 bc_num_copy(c, a);
1737 return BC_STATUS_SUCCESS;
1738 }
1739
1740 aneg = a->neg;
1741 bneg = b->neg;
1742 a->neg = b->neg = false;
1743
1744 cmp = bc_num_cmp(a, b);
1745
1746 a->neg = aneg;
1747 b->neg = bneg;
1748
1749 if (cmp == 0) {
1750 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1751 return BC_STATUS_SUCCESS;
1752 }
1753 else if (cmp > 0) {
1754 neg = a->neg;
1755 minuend = a;
1756 subtrahend = b;
1757 }
1758 else {
1759 neg = b->neg;
1760 if (sub) neg = !neg;
1761 minuend = b;
1762 subtrahend = a;
1763 }
1764
1765 bc_num_copy(c, minuend);
1766 c->neg = neg;
1767
1768 if (c->rdx < subtrahend->rdx) {
1769 bc_num_extend(c, subtrahend->rdx - c->rdx);
1770 start = 0;
1771 }
1772 else
1773 start = c->rdx - subtrahend->rdx;
1774
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001775 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001776
1777 bc_num_clean(c);
1778
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001779 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001780}
1781
1782static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1783 BcNum *restrict c)
1784{
1785 BcStatus s;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001786 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
Gavin Howard01055ba2018-11-03 11:00:21 -06001787 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001788 bool aone;
Gavin Howard01055ba2018-11-03 11:00:21 -06001789
Gavin Howard01055ba2018-11-03 11:00:21 -06001790 if (a->len == 0 || b->len == 0) {
1791 bc_num_zero(c);
1792 return BC_STATUS_SUCCESS;
1793 }
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001794 aone = BC_NUM_ONE(a);
1795 if (aone || BC_NUM_ONE(b)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001796 bc_num_copy(c, aone ? b : a);
1797 return BC_STATUS_SUCCESS;
1798 }
1799
1800 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1801 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1802 {
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001803 size_t i, j, len;
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001804 unsigned carry;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001805
Gavin Howard01055ba2018-11-03 11:00:21 -06001806 bc_num_expand(c, a->len + b->len + 1);
1807
1808 memset(c->num, 0, sizeof(BcDig) * c->cap);
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001809 c->len = len = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06001810
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001811 for (i = 0; i < b->len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001812
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001813 carry = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001814 for (j = 0; j < a->len; ++j) {
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001815 unsigned in = c->num[i + j];
1816 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1817 // note: compilers prefer _unsigned_ div/const
Gavin Howard01055ba2018-11-03 11:00:21 -06001818 carry = in / 10;
1819 c->num[i + j] = (BcDig)(in % 10);
1820 }
1821
1822 c->num[i + j] += (BcDig) carry;
1823 len = BC_MAX(len, i + j + !!carry);
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01001824
1825 // a=2^1000000
1826 // a*a <- without check below, this will not be interruptible
1827 if (G_interrupt) return BC_STATUS_FAILURE;
Gavin Howard01055ba2018-11-03 11:00:21 -06001828 }
1829
1830 c->len = len;
1831
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001832 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06001833 }
1834
1835 bc_num_init(&l1, max);
1836 bc_num_init(&h1, max);
1837 bc_num_init(&l2, max);
1838 bc_num_init(&h2, max);
1839 bc_num_init(&m1, max);
1840 bc_num_init(&m2, max);
1841 bc_num_init(&z0, max);
1842 bc_num_init(&z1, max);
1843 bc_num_init(&z2, max);
1844 bc_num_init(&temp, max + max);
1845
1846 bc_num_split(a, max2, &l1, &h1);
1847 bc_num_split(b, max2, &l2, &h2);
1848
1849 s = bc_num_add(&h1, &l1, &m1, 0);
1850 if (s) goto err;
1851 s = bc_num_add(&h2, &l2, &m2, 0);
1852 if (s) goto err;
1853
1854 s = bc_num_k(&h1, &h2, &z0);
1855 if (s) goto err;
1856 s = bc_num_k(&m1, &m2, &z1);
1857 if (s) goto err;
1858 s = bc_num_k(&l1, &l2, &z2);
1859 if (s) goto err;
1860
1861 s = bc_num_sub(&z1, &z0, &temp, 0);
1862 if (s) goto err;
1863 s = bc_num_sub(&temp, &z2, &z1, 0);
1864 if (s) goto err;
1865
1866 s = bc_num_shift(&z0, max2 * 2);
1867 if (s) goto err;
1868 s = bc_num_shift(&z1, max2);
1869 if (s) goto err;
1870 s = bc_num_add(&z0, &z1, &temp, 0);
1871 if (s) goto err;
1872 s = bc_num_add(&temp, &z2, c, 0);
1873
1874err:
1875 bc_num_free(&temp);
1876 bc_num_free(&z2);
1877 bc_num_free(&z1);
1878 bc_num_free(&z0);
1879 bc_num_free(&m2);
1880 bc_num_free(&m1);
1881 bc_num_free(&h2);
1882 bc_num_free(&l2);
1883 bc_num_free(&h1);
1884 bc_num_free(&l1);
1885 return s;
1886}
1887
1888static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1889{
1890 BcStatus s;
1891 BcNum cpa, cpb;
1892 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1893
1894 scale = BC_MAX(scale, a->rdx);
1895 scale = BC_MAX(scale, b->rdx);
1896 scale = BC_MIN(a->rdx + b->rdx, scale);
1897 maxrdx = BC_MAX(maxrdx, scale);
1898
1899 bc_num_init(&cpa, a->len);
1900 bc_num_init(&cpb, b->len);
1901
1902 bc_num_copy(&cpa, a);
1903 bc_num_copy(&cpb, b);
1904 cpa.neg = cpb.neg = false;
1905
1906 s = bc_num_shift(&cpa, maxrdx);
1907 if (s) goto err;
1908 s = bc_num_shift(&cpb, maxrdx);
1909 if (s) goto err;
1910 s = bc_num_k(&cpa, &cpb, c);
1911 if (s) goto err;
1912
1913 maxrdx += scale;
1914 bc_num_expand(c, c->len + maxrdx);
1915
1916 if (c->len < maxrdx) {
1917 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1918 c->len += maxrdx;
1919 }
1920
1921 c->rdx = maxrdx;
1922 bc_num_retireMul(c, scale, a->neg, b->neg);
1923
1924err:
1925 bc_num_free(&cpb);
1926 bc_num_free(&cpa);
1927 return s;
1928}
1929
1930static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1931{
1932 BcStatus s = BC_STATUS_SUCCESS;
1933 BcDig *n, *p, q;
1934 size_t len, end, i;
1935 BcNum cp;
1936 bool zero = true;
1937
1938 if (b->len == 0)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001939 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001940 else if (a->len == 0) {
1941 bc_num_setToZero(c, scale);
1942 return BC_STATUS_SUCCESS;
1943 }
1944 else if (BC_NUM_ONE(b)) {
1945 bc_num_copy(c, a);
1946 bc_num_retireMul(c, scale, a->neg, b->neg);
1947 return BC_STATUS_SUCCESS;
1948 }
1949
1950 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1951 bc_num_copy(&cp, a);
1952 len = b->len;
1953
1954 if (len > cp.len) {
1955 bc_num_expand(&cp, len + 2);
1956 bc_num_extend(&cp, len - cp.len);
1957 }
1958
1959 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1960 cp.rdx -= b->rdx;
1961 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1962
1963 if (b->rdx == b->len) {
1964 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1965 len -= i - 1;
1966 }
1967
1968 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1969
1970 // We want an extra zero in front to make things simpler.
1971 cp.num[cp.len++] = 0;
1972 end = cp.len - len;
1973
1974 bc_num_expand(c, cp.len);
1975
1976 bc_num_zero(c);
1977 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1978 c->rdx = cp.rdx;
1979 c->len = cp.len;
1980 p = b->num;
1981
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001982 for (i = end - 1; !s && i < end; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001983 n = cp.num + i;
1984 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001985 bc_num_subArrays(n, p, len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001986 c->num[i] = q;
Denys Vlasenkof381a882018-12-05 19:21:34 +01001987 // a=2^100000
1988 // scale=40000
1989 // 1/a <- without check below, this will not be interruptible
1990 if (G_interrupt) {
1991 s = BC_STATUS_FAILURE;
1992 break;
1993 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001994 }
1995
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001996 bc_num_retireMul(c, scale, a->neg, b->neg);
Gavin Howard01055ba2018-11-03 11:00:21 -06001997 bc_num_free(&cp);
1998
Denys Vlasenkof381a882018-12-05 19:21:34 +01001999 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06002000}
2001
2002static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2003 BcNum *restrict d, size_t scale, size_t ts)
2004{
2005 BcStatus s;
2006 BcNum temp;
2007 bool neg;
2008
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002009 if (b->len == 0)
2010 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06002011
2012 if (a->len == 0) {
2013 bc_num_setToZero(d, ts);
2014 return BC_STATUS_SUCCESS;
2015 }
2016
2017 bc_num_init(&temp, d->cap);
Denys Vlasenkof381a882018-12-05 19:21:34 +01002018 s = bc_num_d(a, b, c, scale);
2019 if (s) goto err;
Gavin Howard01055ba2018-11-03 11:00:21 -06002020
2021 if (scale != 0) scale = ts;
2022
2023 s = bc_num_m(c, b, &temp, scale);
2024 if (s) goto err;
2025 s = bc_num_sub(a, &temp, d, scale);
2026 if (s) goto err;
2027
2028 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2029
2030 neg = d->neg;
2031 bc_num_retireMul(d, ts, a->neg, b->neg);
2032 d->neg = neg;
2033
2034err:
2035 bc_num_free(&temp);
2036 return s;
2037}
2038
2039static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2040{
2041 BcStatus s;
2042 BcNum c1;
2043 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2044
2045 bc_num_init(&c1, len);
2046 s = bc_num_r(a, b, &c1, c, scale, ts);
2047 bc_num_free(&c1);
2048
2049 return s;
2050}
2051
2052static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2053{
2054 BcStatus s = BC_STATUS_SUCCESS;
2055 BcNum copy;
2056 unsigned long pow;
2057 size_t i, powrdx, resrdx;
2058 bool neg, zero;
2059
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002060 if (b->rdx) return bc_error("non integer number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002061
2062 if (b->len == 0) {
2063 bc_num_one(c);
2064 return BC_STATUS_SUCCESS;
2065 }
2066 else if (a->len == 0) {
2067 bc_num_setToZero(c, scale);
2068 return BC_STATUS_SUCCESS;
2069 }
2070 else if (BC_NUM_ONE(b)) {
2071 if (!b->neg)
2072 bc_num_copy(c, a);
2073 else
2074 s = bc_num_inv(a, c, scale);
2075 return s;
2076 }
2077
2078 neg = b->neg;
2079 b->neg = false;
2080
2081 s = bc_num_ulong(b, &pow);
2082 if (s) return s;
2083
2084 bc_num_init(&copy, a->len);
2085 bc_num_copy(&copy, a);
2086
Denys Vlasenko2d615fe2018-12-07 16:22:45 +01002087 if (!neg) {
2088 if (a->rdx > scale)
2089 scale = a->rdx;
2090 if (a->rdx * pow < scale)
2091 scale = a->rdx * pow;
2092 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002093
2094 b->neg = neg;
2095
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002096 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002097 powrdx <<= 1;
2098 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2099 if (s) goto err;
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002100 // Not needed: bc_num_mul() has a check for ^C:
2101 //if (G_interrupt) {
2102 // s = BC_STATUS_FAILURE;
2103 // goto err;
2104 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002105 }
2106
Gavin Howard01055ba2018-11-03 11:00:21 -06002107 bc_num_copy(c, &copy);
2108
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002109 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002110
2111 powrdx <<= 1;
2112 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2113 if (s) goto err;
2114
2115 if (pow & 1) {
2116 resrdx += powrdx;
2117 s = bc_num_mul(c, &copy, c, resrdx);
2118 if (s) goto err;
2119 }
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002120 // Not needed: bc_num_mul() has a check for ^C:
2121 //if (G_interrupt) {
2122 // s = BC_STATUS_FAILURE;
2123 // goto err;
2124 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002125 }
2126
2127 if (neg) {
2128 s = bc_num_inv(c, c, scale);
2129 if (s) goto err;
2130 }
2131
Gavin Howard01055ba2018-11-03 11:00:21 -06002132 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2133
2134 // We can't use bc_num_clean() here.
2135 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2136 if (zero) bc_num_setToZero(c, scale);
2137
2138err:
2139 bc_num_free(&copy);
2140 return s;
2141}
2142
2143static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2144 BcNumBinaryOp op, size_t req)
2145{
2146 BcStatus s;
2147 BcNum num2, *ptr_a, *ptr_b;
2148 bool init = false;
2149
2150 if (c == a) {
2151 ptr_a = &num2;
2152 memcpy(ptr_a, c, sizeof(BcNum));
2153 init = true;
2154 }
2155 else
2156 ptr_a = a;
2157
2158 if (c == b) {
2159 ptr_b = &num2;
2160 if (c != a) {
2161 memcpy(ptr_b, c, sizeof(BcNum));
2162 init = true;
2163 }
2164 }
2165 else
2166 ptr_b = b;
2167
2168 if (init)
2169 bc_num_init(c, req);
2170 else
2171 bc_num_expand(c, req);
2172
2173 s = op(ptr_a, ptr_b, c, scale);
2174
2175 if (init) bc_num_free(&num2);
2176
2177 return s;
2178}
2179
2180static bool bc_num_strValid(const char *val, size_t base)
2181{
2182 BcDig b;
2183 bool small, radix = false;
2184 size_t i, len = strlen(val);
2185
2186 if (!len) return true;
2187
2188 small = base <= 10;
2189 b = (BcDig)(small ? base + '0' : base - 10 + 'A');
2190
2191 for (i = 0; i < len; ++i) {
2192
2193 BcDig c = val[i];
2194
2195 if (c == '.') {
2196
2197 if (radix) return false;
2198
2199 radix = true;
2200 continue;
2201 }
2202
2203 if (c < '0' || (small && c >= b) || (c > '9' && (c < 'A' || c >= b)))
2204 return false;
2205 }
2206
2207 return true;
2208}
2209
2210static void bc_num_parseDecimal(BcNum *n, const char *val)
2211{
2212 size_t len, i;
2213 const char *ptr;
2214 bool zero = true;
2215
2216 for (i = 0; val[i] == '0'; ++i);
2217
2218 val += i;
2219 len = strlen(val);
2220 bc_num_zero(n);
2221
2222 if (len != 0) {
2223 for (i = 0; zero && i < len; ++i) zero = val[i] == '0' || val[i] == '.';
2224 bc_num_expand(n, len);
2225 }
2226
2227 ptr = strchr(val, '.');
2228
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002229 n->rdx = 0;
2230 if (ptr != NULL)
2231 n->rdx = (size_t)((val + len) - (ptr + 1));
Gavin Howard01055ba2018-11-03 11:00:21 -06002232
2233 if (!zero) {
2234 for (i = len - 1; i < len; ++n->len, i -= 1 + (i && val[i - 1] == '.'))
2235 n->num[n->len] = val[i] - '0';
2236 }
2237}
2238
2239static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2240{
2241 BcStatus s;
2242 BcNum temp, mult, result;
2243 BcDig c = '\0';
2244 bool zero = true;
2245 unsigned long v;
2246 size_t i, digits, len = strlen(val);
2247
2248 bc_num_zero(n);
2249
2250 for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
2251 if (zero) return;
2252
2253 bc_num_init(&temp, BC_NUM_DEF_SIZE);
2254 bc_num_init(&mult, BC_NUM_DEF_SIZE);
2255
2256 for (i = 0; i < len; ++i) {
2257
2258 c = val[i];
2259 if (c == '.') break;
2260
2261 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2262
2263 s = bc_num_mul(n, base, &mult, 0);
2264 if (s) goto int_err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002265 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002266 s = bc_num_add(&mult, &temp, n, 0);
2267 if (s) goto int_err;
2268 }
2269
2270 if (i == len) {
2271 c = val[i];
2272 if (c == 0) goto int_err;
2273 }
2274
2275 bc_num_init(&result, base->len);
2276 bc_num_zero(&result);
2277 bc_num_one(&mult);
2278
2279 for (i += 1, digits = 0; i < len; ++i, ++digits) {
2280
2281 c = val[i];
2282 if (c == 0) break;
2283
2284 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2285
2286 s = bc_num_mul(&result, base, &result, 0);
2287 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002288 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002289 s = bc_num_add(&result, &temp, &result, 0);
2290 if (s) goto err;
2291 s = bc_num_mul(&mult, base, &mult, 0);
2292 if (s) goto err;
2293 }
2294
2295 s = bc_num_div(&result, &mult, &result, digits);
2296 if (s) goto err;
2297 s = bc_num_add(n, &result, n, digits);
2298 if (s) goto err;
2299
2300 if (n->len != 0) {
2301 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2302 }
2303 else
2304 bc_num_zero(n);
2305
2306err:
2307 bc_num_free(&result);
2308int_err:
2309 bc_num_free(&mult);
2310 bc_num_free(&temp);
2311}
2312
2313static void bc_num_printNewline(size_t *nchars, size_t line_len)
2314{
2315 if (*nchars == line_len - 1) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002316 bb_putchar('\\');
2317 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06002318 *nchars = 0;
2319 }
2320}
2321
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002322#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002323static void bc_num_printChar(size_t num, size_t width, bool radix,
2324 size_t *nchars, size_t line_len)
2325{
2326 (void) radix, (void) line_len;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002327 bb_putchar((char) num);
Gavin Howard01055ba2018-11-03 11:00:21 -06002328 *nchars = *nchars + width;
2329}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002330#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002331
2332static void bc_num_printDigits(size_t num, size_t width, bool radix,
2333 size_t *nchars, size_t line_len)
2334{
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002335 size_t exp, pow;
Gavin Howard01055ba2018-11-03 11:00:21 -06002336
2337 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002338 bb_putchar(radix ? '.' : ' ');
Gavin Howard01055ba2018-11-03 11:00:21 -06002339 ++(*nchars);
2340
2341 bc_num_printNewline(nchars, line_len);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002342 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2343 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002344
2345 for (exp = 0; exp < width; pow /= 10, ++(*nchars), ++exp) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002346 size_t dig;
Gavin Howard01055ba2018-11-03 11:00:21 -06002347 bc_num_printNewline(nchars, line_len);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002348 dig = num / pow;
2349 num -= dig * pow;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002350 bb_putchar(((char) dig) + '0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002351 }
2352}
2353
2354static void bc_num_printHex(size_t num, size_t width, bool radix,
2355 size_t *nchars, size_t line_len)
2356{
2357 if (radix) {
2358 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002359 bb_putchar('.');
Gavin Howard01055ba2018-11-03 11:00:21 -06002360 *nchars += 1;
2361 }
2362
2363 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002364 bb_putchar(bb_hexdigits_upcase[num]);
Gavin Howard01055ba2018-11-03 11:00:21 -06002365 *nchars = *nchars + width;
2366}
2367
2368static void bc_num_printDecimal(BcNum *n, size_t *nchars, size_t len)
2369{
2370 size_t i, rdx = n->rdx - 1;
2371
Denys Vlasenko00d77792018-11-30 23:13:42 +01002372 if (n->neg) bb_putchar('-');
Gavin Howard01055ba2018-11-03 11:00:21 -06002373 (*nchars) += n->neg;
2374
2375 for (i = n->len - 1; i < n->len; --i)
2376 bc_num_printHex((size_t) n->num[i], 1, i == rdx, nchars, len);
2377}
2378
2379static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width,
2380 size_t *nchars, size_t len, BcNumDigitOp print)
2381{
2382 BcStatus s;
2383 BcVec stack;
2384 BcNum intp, fracp, digit, frac_len;
2385 unsigned long dig, *ptr;
2386 size_t i;
2387 bool radix;
2388
2389 if (n->len == 0) {
2390 print(0, width, false, nchars, len);
2391 return BC_STATUS_SUCCESS;
2392 }
2393
2394 bc_vec_init(&stack, sizeof(long), NULL);
2395 bc_num_init(&intp, n->len);
2396 bc_num_init(&fracp, n->rdx);
2397 bc_num_init(&digit, width);
2398 bc_num_init(&frac_len, BC_NUM_INT(n));
2399 bc_num_copy(&intp, n);
2400 bc_num_one(&frac_len);
2401
2402 bc_num_truncate(&intp, intp.rdx);
2403 s = bc_num_sub(n, &intp, &fracp, 0);
2404 if (s) goto err;
2405
2406 while (intp.len != 0) {
2407 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2408 if (s) goto err;
2409 s = bc_num_ulong(&digit, &dig);
2410 if (s) goto err;
2411 bc_vec_push(&stack, &dig);
2412 }
2413
2414 for (i = 0; i < stack.len; ++i) {
2415 ptr = bc_vec_item_rev(&stack, i);
2416 print(*ptr, width, false, nchars, len);
2417 }
2418
2419 if (!n->rdx) goto err;
2420
2421 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2422 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2423 if (s) goto err;
2424 s = bc_num_ulong(&fracp, &dig);
2425 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002426 bc_num_ulong2num(&intp, dig);
Gavin Howard01055ba2018-11-03 11:00:21 -06002427 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2428 if (s) goto err;
2429 print(dig, width, radix, nchars, len);
2430 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2431 if (s) goto err;
2432 }
2433
2434err:
2435 bc_num_free(&frac_len);
2436 bc_num_free(&digit);
2437 bc_num_free(&fracp);
2438 bc_num_free(&intp);
2439 bc_vec_free(&stack);
2440 return s;
2441}
2442
2443static BcStatus bc_num_printBase(BcNum *n, BcNum *base, size_t base_t,
2444 size_t *nchars, size_t line_len)
2445{
2446 BcStatus s;
2447 size_t width, i;
2448 BcNumDigitOp print;
2449 bool neg = n->neg;
2450
Denys Vlasenko00d77792018-11-30 23:13:42 +01002451 if (neg) bb_putchar('-');
Gavin Howard01055ba2018-11-03 11:00:21 -06002452 (*nchars) += neg;
2453
2454 n->neg = false;
2455
2456 if (base_t <= BC_NUM_MAX_IBASE) {
2457 width = 1;
2458 print = bc_num_printHex;
2459 }
2460 else {
2461 for (i = base_t - 1, width = 0; i != 0; i /= 10, ++width);
2462 print = bc_num_printDigits;
2463 }
2464
2465 s = bc_num_printNum(n, base, width, nchars, line_len, print);
2466 n->neg = neg;
2467
2468 return s;
2469}
2470
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002471#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002472static BcStatus bc_num_stream(BcNum *n, BcNum *base, size_t *nchars, size_t len)
2473{
2474 return bc_num_printNum(n, base, 1, nchars, len, bc_num_printChar);
2475}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002476#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002477
Gavin Howard01055ba2018-11-03 11:00:21 -06002478static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2479 size_t base_t)
2480{
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002481 if (!bc_num_strValid(val, base_t))
2482 return bc_error("bad number string");
Gavin Howard01055ba2018-11-03 11:00:21 -06002483
2484 if (base_t == 10)
2485 bc_num_parseDecimal(n, val);
2486 else
2487 bc_num_parseBase(n, val, base);
2488
2489 return BC_STATUS_SUCCESS;
2490}
2491
2492static BcStatus bc_num_print(BcNum *n, BcNum *base, size_t base_t, bool newline,
2493 size_t *nchars, size_t line_len)
2494{
2495 BcStatus s = BC_STATUS_SUCCESS;
2496
2497 bc_num_printNewline(nchars, line_len);
2498
2499 if (n->len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002500 bb_putchar('0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002501 ++(*nchars);
2502 }
2503 else if (base_t == 10)
2504 bc_num_printDecimal(n, nchars, line_len);
2505 else
2506 s = bc_num_printBase(n, base, base_t, nchars, line_len);
2507
2508 if (newline) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002509 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06002510 *nchars = 0;
2511 }
2512
2513 return s;
2514}
2515
Gavin Howard01055ba2018-11-03 11:00:21 -06002516static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2517{
2518 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2519 (void) scale;
2520 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2521}
2522
2523static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2524{
2525 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2526 (void) scale;
2527 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2528}
2529
2530static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2531{
2532 size_t req = BC_NUM_MREQ(a, b, scale);
2533 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2534}
2535
2536static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2537{
2538 size_t req = BC_NUM_MREQ(a, b, scale);
2539 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2540}
2541
2542static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2543{
2544 size_t req = BC_NUM_MREQ(a, b, scale);
2545 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2546}
2547
2548static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2549{
2550 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2551}
2552
2553static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2554{
2555 BcStatus s;
2556 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2557 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2558 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2559
2560 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2561 bc_num_expand(b, req);
2562
2563 if (a->len == 0) {
2564 bc_num_setToZero(b, scale);
2565 return BC_STATUS_SUCCESS;
2566 }
2567 else if (a->neg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002568 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002569 else if (BC_NUM_ONE(a)) {
2570 bc_num_one(b);
2571 bc_num_extend(b, scale);
2572 return BC_STATUS_SUCCESS;
2573 }
2574
2575 scale = BC_MAX(scale, a->rdx) + 1;
2576 len = a->len + scale;
2577
2578 bc_num_init(&num1, len);
2579 bc_num_init(&num2, len);
2580 bc_num_init(&half, BC_NUM_DEF_SIZE);
2581
2582 bc_num_one(&half);
2583 half.num[0] = 5;
2584 half.rdx = 1;
2585
2586 bc_num_init(&f, len);
2587 bc_num_init(&fprime, len);
2588
2589 x0 = &num1;
2590 x1 = &num2;
2591
2592 bc_num_one(x0);
2593 pow = BC_NUM_INT(a);
2594
2595 if (pow) {
2596
2597 if (pow & 1)
2598 x0->num[0] = 2;
2599 else
2600 x0->num[0] = 6;
2601
2602 pow -= 2 - (pow & 1);
2603
2604 bc_num_extend(x0, pow);
2605
2606 // Make sure to move the radix back.
2607 x0->rdx -= pow;
2608 }
2609
2610 x0->rdx = digs = digs1 = 0;
2611 resrdx = scale + 2;
2612 len = BC_NUM_INT(x0) + resrdx - 1;
2613
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002614 while (cmp != 0 || digs < len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002615
2616 s = bc_num_div(a, x0, &f, resrdx);
2617 if (s) goto err;
2618 s = bc_num_add(x0, &f, &fprime, resrdx);
2619 if (s) goto err;
2620 s = bc_num_mul(&fprime, &half, x1, resrdx);
2621 if (s) goto err;
2622
2623 cmp = bc_num_cmp(x1, x0);
2624 digs = x1->len - (unsigned long long) llabs(cmp);
2625
2626 if (cmp == cmp2 && digs == digs1)
2627 times += 1;
2628 else
2629 times = 0;
2630
2631 resrdx += times > 4;
2632
2633 cmp2 = cmp1;
2634 cmp1 = cmp;
2635 digs1 = digs;
2636
2637 temp = x0;
2638 x0 = x1;
2639 x1 = temp;
2640 }
2641
Gavin Howard01055ba2018-11-03 11:00:21 -06002642 bc_num_copy(b, x0);
2643 scale -= 1;
2644 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2645
2646err:
2647 bc_num_free(&fprime);
2648 bc_num_free(&f);
2649 bc_num_free(&half);
2650 bc_num_free(&num2);
2651 bc_num_free(&num1);
2652 return s;
2653}
2654
2655static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2656 size_t scale)
2657{
2658 BcStatus s;
2659 BcNum num2, *ptr_a;
2660 bool init = false;
2661 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2662
2663 if (c == a) {
2664 memcpy(&num2, c, sizeof(BcNum));
2665 ptr_a = &num2;
2666 bc_num_init(c, len);
2667 init = true;
2668 }
2669 else {
2670 ptr_a = a;
2671 bc_num_expand(c, len);
2672 }
2673
2674 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2675
2676 if (init) bc_num_free(&num2);
2677
2678 return s;
2679}
2680
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002681#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002682static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2683{
2684 BcStatus s;
2685 BcNum base, exp, two, temp;
2686
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002687 if (c->len == 0)
2688 return bc_error("divide by zero");
2689 if (a->rdx || b->rdx || c->rdx)
2690 return bc_error("non integer number");
2691 if (b->neg)
2692 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002693
2694 bc_num_expand(d, c->len);
2695 bc_num_init(&base, c->len);
2696 bc_num_init(&exp, b->len);
2697 bc_num_init(&two, BC_NUM_DEF_SIZE);
2698 bc_num_init(&temp, b->len);
2699
2700 bc_num_one(&two);
2701 two.num[0] = 2;
2702 bc_num_one(d);
2703
2704 s = bc_num_rem(a, c, &base, 0);
2705 if (s) goto err;
2706 bc_num_copy(&exp, b);
2707
2708 while (exp.len != 0) {
2709
2710 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2711 if (s) goto err;
2712
2713 if (BC_NUM_ONE(&temp)) {
2714 s = bc_num_mul(d, &base, &temp, 0);
2715 if (s) goto err;
2716 s = bc_num_rem(&temp, c, d, 0);
2717 if (s) goto err;
2718 }
2719
2720 s = bc_num_mul(&base, &base, &temp, 0);
2721 if (s) goto err;
2722 s = bc_num_rem(&temp, c, &base, 0);
2723 if (s) goto err;
2724 }
2725
2726err:
2727 bc_num_free(&temp);
2728 bc_num_free(&two);
2729 bc_num_free(&exp);
2730 bc_num_free(&base);
2731 return s;
2732}
2733#endif // ENABLE_DC
2734
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002735#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002736static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2737{
2738 BcId a;
2739 size_t i;
2740
2741 for (i = 0; i < f->autos.len; ++i) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002742 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2743 return bc_error("function parameter or auto var has the same name as another");
Gavin Howard01055ba2018-11-03 11:00:21 -06002744 }
2745
2746 a.idx = var;
2747 a.name = name;
2748
2749 bc_vec_push(&f->autos, &a);
2750
2751 return BC_STATUS_SUCCESS;
2752}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002753#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002754
2755static void bc_func_init(BcFunc *f)
2756{
Denys Vlasenko7d628012018-12-04 21:46:47 +01002757 bc_char_vec_init(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06002758 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2759 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2760 f->nparams = 0;
2761}
2762
2763static void bc_func_free(void *func)
2764{
2765 BcFunc *f = (BcFunc *) func;
2766 bc_vec_free(&f->code);
2767 bc_vec_free(&f->autos);
2768 bc_vec_free(&f->labels);
2769}
2770
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002771static void bc_array_expand(BcVec *a, size_t len);
2772
Gavin Howard01055ba2018-11-03 11:00:21 -06002773static void bc_array_init(BcVec *a, bool nums)
2774{
2775 if (nums)
2776 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2777 else
2778 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2779 bc_array_expand(a, 1);
2780}
2781
Gavin Howard01055ba2018-11-03 11:00:21 -06002782static void bc_array_expand(BcVec *a, size_t len)
2783{
2784 BcResultData data;
2785
2786 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2787 while (len > a->len) {
2788 bc_num_init(&data.n, BC_NUM_DEF_SIZE);
2789 bc_vec_push(a, &data.n);
2790 }
2791 }
2792 else {
2793 while (len > a->len) {
2794 bc_array_init(&data.v, true);
2795 bc_vec_push(a, &data.v);
2796 }
2797 }
2798}
2799
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002800static void bc_array_copy(BcVec *d, const BcVec *s)
2801{
2802 size_t i;
2803
2804 bc_vec_pop_all(d);
2805 bc_vec_expand(d, s->cap);
2806 d->len = s->len;
2807
2808 for (i = 0; i < s->len; ++i) {
2809 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2810 bc_num_init(dnum, snum->len);
2811 bc_num_copy(dnum, snum);
2812 }
2813}
2814
Gavin Howard01055ba2018-11-03 11:00:21 -06002815static void bc_string_free(void *string)
2816{
2817 free(*((char **) string));
2818}
2819
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002820#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002821static void bc_result_copy(BcResult *d, BcResult *src)
2822{
2823 d->t = src->t;
2824
2825 switch (d->t) {
2826
2827 case BC_RESULT_TEMP:
2828 case BC_RESULT_IBASE:
2829 case BC_RESULT_SCALE:
2830 case BC_RESULT_OBASE:
2831 {
2832 bc_num_init(&d->d.n, src->d.n.len);
2833 bc_num_copy(&d->d.n, &src->d.n);
2834 break;
2835 }
2836
2837 case BC_RESULT_VAR:
2838 case BC_RESULT_ARRAY:
2839 case BC_RESULT_ARRAY_ELEM:
2840 {
2841 d->d.id.name = xstrdup(src->d.id.name);
2842 break;
2843 }
2844
2845 case BC_RESULT_CONSTANT:
2846 case BC_RESULT_LAST:
2847 case BC_RESULT_ONE:
2848 case BC_RESULT_STR:
2849 {
2850 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2851 break;
2852 }
2853 }
2854}
2855#endif // ENABLE_DC
2856
2857static void bc_result_free(void *result)
2858{
2859 BcResult *r = (BcResult *) result;
2860
2861 switch (r->t) {
2862
2863 case BC_RESULT_TEMP:
2864 case BC_RESULT_IBASE:
2865 case BC_RESULT_SCALE:
2866 case BC_RESULT_OBASE:
2867 {
2868 bc_num_free(&r->d.n);
2869 break;
2870 }
2871
2872 case BC_RESULT_VAR:
2873 case BC_RESULT_ARRAY:
2874 case BC_RESULT_ARRAY_ELEM:
2875 {
2876 free(r->d.id.name);
2877 break;
2878 }
2879
2880 default:
2881 {
2882 // Do nothing.
2883 break;
2884 }
2885 }
2886}
2887
2888static void bc_lex_lineComment(BcLex *l)
2889{
2890 l->t.t = BC_LEX_WHITESPACE;
2891 while (l->i < l->len && l->buf[l->i++] != '\n');
2892 --l->i;
2893}
2894
2895static void bc_lex_whitespace(BcLex *l)
2896{
2897 char c;
2898 l->t.t = BC_LEX_WHITESPACE;
2899 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2900}
2901
2902static BcStatus bc_lex_number(BcLex *l, char start)
2903{
2904 const char *buf = l->buf + l->i;
2905 size_t len, hits = 0, bslashes = 0, i = 0, j;
2906 char c = buf[i];
2907 bool last_pt, pt = start == '.';
2908
2909 last_pt = pt;
2910 l->t.t = BC_LEX_NUMBER;
2911
2912 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2913 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2914 {
2915 if (c != '\\') {
2916 last_pt = c == '.';
2917 pt = pt || last_pt;
2918 }
2919 else {
2920 ++i;
2921 bslashes += 1;
2922 }
2923
2924 c = buf[++i];
2925 }
2926
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002927 len = i + !last_pt - bslashes * 2;
Denys Vlasenko64074a12018-12-07 15:50:14 +01002928 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2929 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2930 if (len > BC_MAX_NUM)
2931 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2932 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002933
Denys Vlasenko7d628012018-12-04 21:46:47 +01002934 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002935 bc_vec_expand(&l->t.v, len + 1);
2936 bc_vec_push(&l->t.v, &start);
2937
2938 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2939
2940 c = buf[j];
2941
2942 // If we have hit a backslash, skip it. We don't have
2943 // to check for a newline because it's guaranteed.
2944 if (hits < bslashes && c == '\\') {
2945 ++hits;
2946 ++j;
2947 continue;
2948 }
2949
2950 bc_vec_push(&l->t.v, &c);
2951 }
2952
Denys Vlasenko08c033c2018-12-05 16:55:08 +01002953 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002954 l->i += i;
2955
2956 return BC_STATUS_SUCCESS;
2957}
2958
2959static BcStatus bc_lex_name(BcLex *l)
2960{
2961 size_t i = 0;
2962 const char *buf = l->buf + l->i - 1;
2963 char c = buf[i];
2964
2965 l->t.t = BC_LEX_NAME;
2966
2967 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2968
Denys Vlasenko64074a12018-12-07 15:50:14 +01002969 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2970 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2971 if (i > BC_MAX_STRING)
2972 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2973 }
Gavin Howard01055ba2018-11-03 11:00:21 -06002974 bc_vec_string(&l->t.v, i, buf);
2975
2976 // Increment the index. We minus 1 because it has already been incremented.
2977 l->i += i - 1;
2978
2979 return BC_STATUS_SUCCESS;
2980}
2981
2982static void bc_lex_init(BcLex *l, BcLexNext next)
2983{
2984 l->next = next;
Denys Vlasenko7d628012018-12-04 21:46:47 +01002985 bc_char_vec_init(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002986}
2987
2988static void bc_lex_free(BcLex *l)
2989{
2990 bc_vec_free(&l->t.v);
2991}
2992
Denys Vlasenko0409ad32018-12-05 16:39:22 +01002993static void bc_lex_file(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06002994{
Denys Vlasenko5318f812018-12-05 17:48:01 +01002995 G.err_line = l->line = 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06002996 l->newline = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06002997}
2998
2999static BcStatus bc_lex_next(BcLex *l)
3000{
3001 BcStatus s;
3002
3003 l->t.last = l->t.t;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003004 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06003005
3006 l->line += l->newline;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003007 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003008 l->t.t = BC_LEX_EOF;
3009
3010 l->newline = (l->i == l->len);
3011 if (l->newline) return BC_STATUS_SUCCESS;
3012
3013 // Loop until failure or we don't have whitespace. This
3014 // is so the parser doesn't get inundated with whitespace.
3015 do {
3016 s = l->next(l);
3017 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3018
3019 return s;
3020}
3021
3022static BcStatus bc_lex_text(BcLex *l, const char *text)
3023{
3024 l->buf = text;
3025 l->i = 0;
3026 l->len = strlen(text);
3027 l->t.t = l->t.last = BC_LEX_INVALID;
3028 return bc_lex_next(l);
3029}
3030
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003031#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06003032static BcStatus bc_lex_identifier(BcLex *l)
3033{
3034 BcStatus s;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003035 unsigned i;
Gavin Howard01055ba2018-11-03 11:00:21 -06003036 const char *buf = l->buf + l->i - 1;
3037
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003038 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3039 const char *keyword8 = bc_lex_kws[i].name8;
3040 unsigned j = 0;
3041 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3042 j++;
3043 if (j == 8) goto match;
Gavin Howard01055ba2018-11-03 11:00:21 -06003044 }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003045 if (keyword8[j] != '\0')
3046 continue;
3047 match:
3048 // buf starts with keyword bc_lex_kws[i]
3049 l->t.t = BC_LEX_KEY_1st_keyword + i;
Denys Vlasenkod00d2f92018-12-06 12:59:40 +01003050 if (!bc_lex_kws_POSIX(i)) {
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003051 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003052 if (s) return s;
3053 }
3054
3055 // We minus 1 because the index has already been incremented.
3056 l->i += j - 1;
3057 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06003058 }
3059
3060 s = bc_lex_name(l);
3061 if (s) return s;
3062
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003063 if (l->t.v.len > 2) {
3064 // Prevent this:
3065 // >>> qwe=1
3066 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3067 // '
3068 unsigned len = strchrnul(buf, '\n') - buf;
3069 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3070 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003071
3072 return s;
3073}
3074
3075static BcStatus bc_lex_string(BcLex *l)
3076{
3077 size_t len, nls = 0, i = l->i;
3078 char c;
3079
3080 l->t.t = BC_LEX_STR;
3081
3082 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3083
3084 if (c == '\0') {
3085 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003086 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003087 }
3088
3089 len = i - l->i;
Denys Vlasenko64074a12018-12-07 15:50:14 +01003090 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3091 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3092 if (len > BC_MAX_STRING)
3093 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3094 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003095 bc_vec_string(&l->t.v, len, l->buf + l->i);
3096
3097 l->i = i + 1;
3098 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003099 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003100
3101 return BC_STATUS_SUCCESS;
3102}
3103
3104static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3105{
3106 if (l->buf[l->i] == '=') {
3107 ++l->i;
3108 l->t.t = with;
3109 }
3110 else
3111 l->t.t = without;
3112}
3113
3114static BcStatus bc_lex_comment(BcLex *l)
3115{
3116 size_t i, nls = 0;
3117 const char *buf = l->buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003118
3119 l->t.t = BC_LEX_WHITESPACE;
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003120 i = ++l->i;
3121 for (;;) {
3122 char c = buf[i];
3123 check_star:
3124 if (c == '*') {
3125 c = buf[++i];
3126 if (c == '/')
3127 break;
3128 goto check_star;
3129 }
3130 if (c == '\0') {
Gavin Howard01055ba2018-11-03 11:00:21 -06003131 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003132 return bc_error("comment end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003133 }
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003134 nls += (c == '\n');
3135 i++;
Gavin Howard01055ba2018-11-03 11:00:21 -06003136 }
3137
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003138 l->i = i + 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003139 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003140 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003141
3142 return BC_STATUS_SUCCESS;
3143}
3144
3145static BcStatus bc_lex_token(BcLex *l)
3146{
3147 BcStatus s = BC_STATUS_SUCCESS;
3148 char c = l->buf[l->i++], c2;
3149
3150 // This is the workhorse of the lexer.
3151 switch (c) {
3152
3153 case '\0':
3154 case '\n':
3155 {
3156 l->newline = true;
3157 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3158 break;
3159 }
3160
3161 case '\t':
3162 case '\v':
3163 case '\f':
3164 case '\r':
3165 case ' ':
3166 {
3167 bc_lex_whitespace(l);
3168 break;
3169 }
3170
3171 case '!':
3172 {
3173 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3174
3175 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
Denys Vlasenko00646792018-12-05 18:12:27 +01003176 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
Gavin Howard01055ba2018-11-03 11:00:21 -06003177 if (s) return s;
3178 }
3179
3180 break;
3181 }
3182
3183 case '"':
3184 {
3185 s = bc_lex_string(l);
3186 break;
3187 }
3188
3189 case '#':
3190 {
Denys Vlasenko00646792018-12-05 18:12:27 +01003191 s = bc_POSIX_does_not_allow("'#' script comments");
Gavin Howard01055ba2018-11-03 11:00:21 -06003192 if (s) return s;
3193
3194 bc_lex_lineComment(l);
3195
3196 break;
3197 }
3198
3199 case '%':
3200 {
3201 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3202 break;
3203 }
3204
3205 case '&':
3206 {
3207 c2 = l->buf[l->i];
3208 if (c2 == '&') {
3209
Denys Vlasenko00646792018-12-05 18:12:27 +01003210 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
Gavin Howard01055ba2018-11-03 11:00:21 -06003211 if (s) return s;
3212
3213 ++l->i;
3214 l->t.t = BC_LEX_OP_BOOL_AND;
3215 }
3216 else {
3217 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003218 s = bc_error_bad_character('&');
Gavin Howard01055ba2018-11-03 11:00:21 -06003219 }
3220
3221 break;
3222 }
3223
3224 case '(':
3225 case ')':
3226 {
3227 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3228 break;
3229 }
3230
3231 case '*':
3232 {
3233 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3234 break;
3235 }
3236
3237 case '+':
3238 {
3239 c2 = l->buf[l->i];
3240 if (c2 == '+') {
3241 ++l->i;
3242 l->t.t = BC_LEX_OP_INC;
3243 }
3244 else
3245 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3246 break;
3247 }
3248
3249 case ',':
3250 {
3251 l->t.t = BC_LEX_COMMA;
3252 break;
3253 }
3254
3255 case '-':
3256 {
3257 c2 = l->buf[l->i];
3258 if (c2 == '-') {
3259 ++l->i;
3260 l->t.t = BC_LEX_OP_DEC;
3261 }
3262 else
3263 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3264 break;
3265 }
3266
3267 case '.':
3268 {
3269 if (isdigit(l->buf[l->i]))
3270 s = bc_lex_number(l, c);
3271 else {
3272 l->t.t = BC_LEX_KEY_LAST;
Denys Vlasenko00646792018-12-05 18:12:27 +01003273 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
Gavin Howard01055ba2018-11-03 11:00:21 -06003274 }
3275 break;
3276 }
3277
3278 case '/':
3279 {
3280 c2 = l->buf[l->i];
3281 if (c2 == '*')
3282 s = bc_lex_comment(l);
3283 else
3284 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3285 break;
3286 }
3287
3288 case '0':
3289 case '1':
3290 case '2':
3291 case '3':
3292 case '4':
3293 case '5':
3294 case '6':
3295 case '7':
3296 case '8':
3297 case '9':
3298 case 'A':
3299 case 'B':
3300 case 'C':
3301 case 'D':
3302 case 'E':
3303 case 'F':
3304 {
3305 s = bc_lex_number(l, c);
3306 break;
3307 }
3308
3309 case ';':
3310 {
3311 l->t.t = BC_LEX_SCOLON;
3312 break;
3313 }
3314
3315 case '<':
3316 {
3317 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3318 break;
3319 }
3320
3321 case '=':
3322 {
3323 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3324 break;
3325 }
3326
3327 case '>':
3328 {
3329 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3330 break;
3331 }
3332
3333 case '[':
3334 case ']':
3335 {
3336 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3337 break;
3338 }
3339
3340 case '\\':
3341 {
3342 if (l->buf[l->i] == '\n') {
3343 l->t.t = BC_LEX_WHITESPACE;
3344 ++l->i;
3345 }
3346 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003347 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003348 break;
3349 }
3350
3351 case '^':
3352 {
3353 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3354 break;
3355 }
3356
3357 case 'a':
3358 case 'b':
3359 case 'c':
3360 case 'd':
3361 case 'e':
3362 case 'f':
3363 case 'g':
3364 case 'h':
3365 case 'i':
3366 case 'j':
3367 case 'k':
3368 case 'l':
3369 case 'm':
3370 case 'n':
3371 case 'o':
3372 case 'p':
3373 case 'q':
3374 case 'r':
3375 case 's':
3376 case 't':
3377 case 'u':
3378 case 'v':
3379 case 'w':
3380 case 'x':
3381 case 'y':
3382 case 'z':
3383 {
3384 s = bc_lex_identifier(l);
3385 break;
3386 }
3387
3388 case '{':
3389 case '}':
3390 {
3391 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3392 break;
3393 }
3394
3395 case '|':
3396 {
3397 c2 = l->buf[l->i];
3398
3399 if (c2 == '|') {
Denys Vlasenko00646792018-12-05 18:12:27 +01003400 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
Gavin Howard01055ba2018-11-03 11:00:21 -06003401 if (s) return s;
3402
3403 ++l->i;
3404 l->t.t = BC_LEX_OP_BOOL_OR;
3405 }
3406 else {
3407 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003408 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003409 }
3410
3411 break;
3412 }
3413
3414 default:
3415 {
3416 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003417 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003418 break;
3419 }
3420 }
3421
3422 return s;
3423}
3424#endif // ENABLE_BC
3425
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003426#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06003427static BcStatus dc_lex_register(BcLex *l)
3428{
3429 BcStatus s = BC_STATUS_SUCCESS;
3430
3431 if (isspace(l->buf[l->i - 1])) {
3432 bc_lex_whitespace(l);
3433 ++l->i;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01003434 if (!G_exreg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003435 s = bc_error("extended register");
Gavin Howard01055ba2018-11-03 11:00:21 -06003436 else
3437 s = bc_lex_name(l);
3438 }
3439 else {
Denys Vlasenko7d628012018-12-04 21:46:47 +01003440 bc_vec_pop_all(&l->t.v);
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003441 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003442 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003443 l->t.t = BC_LEX_NAME;
3444 }
3445
3446 return s;
3447}
3448
3449static BcStatus dc_lex_string(BcLex *l)
3450{
3451 size_t depth = 1, nls = 0, i = l->i;
3452 char c;
3453
3454 l->t.t = BC_LEX_STR;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003455 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003456
3457 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3458
3459 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3460 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3461 nls += (c == '\n');
3462
3463 if (depth) bc_vec_push(&l->t.v, &c);
3464 }
3465
3466 if (c == '\0') {
3467 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003468 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003469 }
3470
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003471 bc_vec_pushZeroByte(&l->t.v);
Denys Vlasenko64074a12018-12-07 15:50:14 +01003472 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3473 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3474 if (i - l->i > BC_MAX_STRING)
3475 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3476 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003477
3478 l->i = i;
3479 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003480 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003481
3482 return BC_STATUS_SUCCESS;
3483}
3484
3485static BcStatus dc_lex_token(BcLex *l)
3486{
3487 BcStatus s = BC_STATUS_SUCCESS;
3488 char c = l->buf[l->i++], c2;
3489 size_t i;
3490
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003491 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3492 if (l->t.last == dc_lex_regs[i])
3493 return dc_lex_register(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003494 }
3495
3496 if (c >= '%' && c <= '~' &&
3497 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3498 {
3499 return s;
3500 }
3501
3502 // This is the workhorse of the lexer.
3503 switch (c) {
3504
3505 case '\0':
3506 {
3507 l->t.t = BC_LEX_EOF;
3508 break;
3509 }
3510
3511 case '\n':
3512 case '\t':
3513 case '\v':
3514 case '\f':
3515 case '\r':
3516 case ' ':
3517 {
3518 l->newline = (c == '\n');
3519 bc_lex_whitespace(l);
3520 break;
3521 }
3522
3523 case '!':
3524 {
3525 c2 = l->buf[l->i];
3526
3527 if (c2 == '=')
3528 l->t.t = BC_LEX_OP_REL_NE;
3529 else if (c2 == '<')
3530 l->t.t = BC_LEX_OP_REL_LE;
3531 else if (c2 == '>')
3532 l->t.t = BC_LEX_OP_REL_GE;
3533 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003534 return bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003535
3536 ++l->i;
3537 break;
3538 }
3539
3540 case '#':
3541 {
3542 bc_lex_lineComment(l);
3543 break;
3544 }
3545
3546 case '.':
3547 {
3548 if (isdigit(l->buf[l->i]))
3549 s = bc_lex_number(l, c);
3550 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003551 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003552 break;
3553 }
3554
3555 case '0':
3556 case '1':
3557 case '2':
3558 case '3':
3559 case '4':
3560 case '5':
3561 case '6':
3562 case '7':
3563 case '8':
3564 case '9':
3565 case 'A':
3566 case 'B':
3567 case 'C':
3568 case 'D':
3569 case 'E':
3570 case 'F':
3571 {
3572 s = bc_lex_number(l, c);
3573 break;
3574 }
3575
3576 case '[':
3577 {
3578 s = dc_lex_string(l);
3579 break;
3580 }
3581
3582 default:
3583 {
3584 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003585 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003586 break;
3587 }
3588 }
3589
3590 return s;
3591}
3592#endif // ENABLE_DC
3593
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003594static void bc_program_addFunc(char *name, size_t *idx);
3595
Gavin Howard01055ba2018-11-03 11:00:21 -06003596static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3597{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003598 bc_program_addFunc(name, idx);
3599 p->func = bc_vec_item(&G.prog.fns, p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003600}
3601
Denys Vlasenkob23ac512018-12-06 13:10:56 +01003602#define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3603
Gavin Howard01055ba2018-11-03 11:00:21 -06003604static void bc_parse_pushName(BcParse *p, char *name)
3605{
3606 size_t i = 0, len = strlen(name);
3607
3608 for (; i < len; ++i) bc_parse_push(p, name[i]);
3609 bc_parse_push(p, BC_PARSE_STREND);
3610
3611 free(name);
3612}
3613
3614static void bc_parse_pushIndex(BcParse *p, size_t idx)
3615{
3616 unsigned char amt, i, nums[sizeof(size_t)];
3617
3618 for (amt = 0; idx; ++amt) {
3619 nums[amt] = (char) idx;
3620 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3621 }
3622
3623 bc_parse_push(p, amt);
3624 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3625}
3626
3627static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3628{
3629 char *num = xstrdup(p->l.t.v.v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003630 size_t idx = G.prog.consts.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06003631
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003632 bc_vec_push(&G.prog.consts, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06003633
3634 bc_parse_push(p, BC_INST_NUM);
3635 bc_parse_pushIndex(p, idx);
3636
3637 ++(*nexs);
3638 (*prev) = BC_INST_NUM;
3639}
3640
3641static BcStatus bc_parse_text(BcParse *p, const char *text)
3642{
3643 BcStatus s;
3644
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003645 p->func = bc_vec_item(&G.prog.fns, p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003646
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003647 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003648 p->l.t.t = BC_LEX_INVALID;
3649 s = p->parse(p);
3650 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003651 if (!BC_PARSE_CAN_EXEC(p))
3652 return bc_error("file is not executable");
Gavin Howard01055ba2018-11-03 11:00:21 -06003653 }
3654
3655 return bc_lex_text(&p->l, text);
3656}
3657
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003658// Called when parsing or execution detects a failure,
3659// resets execution structures.
3660static void bc_program_reset(void)
3661{
3662 BcFunc *f;
3663 BcInstPtr *ip;
3664
3665 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3666 bc_vec_pop_all(&G.prog.results);
3667
3668 f = bc_vec_item(&G.prog.fns, 0);
3669 ip = bc_vec_top(&G.prog.stack);
3670 ip->idx = f->code.len;
3671}
3672
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003673#define bc_parse_updateFunc(p, f) \
3674 ((p)->func = bc_vec_item(&G.prog.fns, ((p)->fidx = (f))))
3675
Denys Vlasenkod38af482018-12-04 19:11:02 +01003676// Called when bc/dc_parse_parse() detects a failure,
3677// resets parsing structures.
3678static void bc_parse_reset(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06003679{
3680 if (p->fidx != BC_PROG_MAIN) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003681 p->func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003682 bc_vec_pop_all(&p->func->code);
3683 bc_vec_pop_all(&p->func->autos);
3684 bc_vec_pop_all(&p->func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06003685
3686 bc_parse_updateFunc(p, BC_PROG_MAIN);
3687 }
3688
3689 p->l.i = p->l.len;
3690 p->l.t.t = BC_LEX_EOF;
3691 p->auto_part = (p->nbraces = 0);
3692
3693 bc_vec_npop(&p->flags, p->flags.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01003694 bc_vec_pop_all(&p->exits);
3695 bc_vec_pop_all(&p->conds);
3696 bc_vec_pop_all(&p->ops);
Gavin Howard01055ba2018-11-03 11:00:21 -06003697
Denys Vlasenkod38af482018-12-04 19:11:02 +01003698 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06003699}
3700
3701static void bc_parse_free(BcParse *p)
3702{
3703 bc_vec_free(&p->flags);
3704 bc_vec_free(&p->exits);
3705 bc_vec_free(&p->conds);
3706 bc_vec_free(&p->ops);
3707 bc_lex_free(&p->l);
3708}
3709
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003710static void bc_parse_create(BcParse *p, size_t func,
Gavin Howard01055ba2018-11-03 11:00:21 -06003711 BcParseParse parse, BcLexNext next)
3712{
3713 memset(p, 0, sizeof(BcParse));
3714
3715 bc_lex_init(&p->l, next);
3716 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3717 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3718 bc_vec_init(&p->conds, sizeof(size_t), NULL);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003719 bc_vec_pushZeroByte(&p->flags);
Gavin Howard01055ba2018-11-03 11:00:21 -06003720 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3721
3722 p->parse = parse;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01003723 // p->auto_part = p->nbraces = 0; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06003724 bc_parse_updateFunc(p, func);
3725}
3726
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003727#if ENABLE_BC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003728
3729#define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3730#define BC_PARSE_LEAF(p, rparen) \
3731 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3732 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3733
3734// We can calculate the conversion between tokens and exprs by subtracting the
3735// position of the first operator in the lex enum and adding the position of the
3736// first in the expr enum. Note: This only works for binary operators.
3737#define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3738
Gavin Howard01055ba2018-11-03 11:00:21 -06003739static BcStatus bc_parse_else(BcParse *p);
3740static BcStatus bc_parse_stmt(BcParse *p);
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003741static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01003742static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
Gavin Howard01055ba2018-11-03 11:00:21 -06003743
3744static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3745 size_t *nexprs, bool next)
3746{
3747 BcStatus s = BC_STATUS_SUCCESS;
3748 BcLexType t;
Denys Vlasenko65437582018-12-05 19:37:19 +01003749 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3750 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003751
3752 while (p->ops.len > start) {
3753
3754 t = BC_PARSE_TOP_OP(p);
3755 if (t == BC_LEX_LPAREN) break;
3756
Denys Vlasenko65437582018-12-05 19:37:19 +01003757 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003758 if (l >= r && (l != r || !left)) break;
3759
3760 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3761 bc_vec_pop(&p->ops);
3762 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3763 }
3764
3765 bc_vec_push(&p->ops, &type);
3766 if (next) s = bc_lex_next(&p->l);
3767
3768 return s;
3769}
3770
3771static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3772{
3773 BcLexType top;
3774
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003775 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003776 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003777 top = BC_PARSE_TOP_OP(p);
3778
3779 while (top != BC_LEX_LPAREN) {
3780
3781 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3782
3783 bc_vec_pop(&p->ops);
3784 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3785
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003786 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003787 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003788 top = BC_PARSE_TOP_OP(p);
3789 }
3790
3791 bc_vec_pop(&p->ops);
3792
3793 return bc_lex_next(&p->l);
3794}
3795
3796static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3797{
3798 BcStatus s;
3799 bool comma = false;
3800 size_t nparams;
3801
3802 s = bc_lex_next(&p->l);
3803 if (s) return s;
3804
3805 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3806
3807 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3808 s = bc_parse_expr(p, flags, bc_parse_next_param);
3809 if (s) return s;
3810
3811 comma = p->l.t.t == BC_LEX_COMMA;
3812 if (comma) {
3813 s = bc_lex_next(&p->l);
3814 if (s) return s;
3815 }
3816 }
3817
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003818 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003819 bc_parse_push(p, BC_INST_CALL);
3820 bc_parse_pushIndex(p, nparams);
3821
3822 return BC_STATUS_SUCCESS;
3823}
3824
3825static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3826{
3827 BcStatus s;
3828 BcId entry, *entry_ptr;
3829 size_t idx;
3830
3831 entry.name = name;
3832
3833 s = bc_parse_params(p, flags);
3834 if (s) goto err;
3835
3836 if (p->l.t.t != BC_LEX_RPAREN) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003837 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003838 goto err;
3839 }
3840
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003841 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003842
3843 if (idx == BC_VEC_INVALID_IDX) {
3844 name = xstrdup(entry.name);
3845 bc_parse_addFunc(p, name, &idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003846 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003847 free(entry.name);
3848 }
3849 else
3850 free(name);
3851
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003852 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003853 bc_parse_pushIndex(p, entry_ptr->idx);
3854
3855 return bc_lex_next(&p->l);
3856
3857err:
3858 free(name);
3859 return s;
3860}
3861
3862static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3863{
3864 BcStatus s;
3865 char *name;
3866
3867 name = xstrdup(p->l.t.v.v);
3868 s = bc_lex_next(&p->l);
3869 if (s) goto err;
3870
3871 if (p->l.t.t == BC_LEX_LBRACKET) {
3872
3873 s = bc_lex_next(&p->l);
3874 if (s) goto err;
3875
3876 if (p->l.t.t == BC_LEX_RBRACKET) {
3877
3878 if (!(flags & BC_PARSE_ARRAY)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003879 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003880 goto err;
3881 }
3882
3883 *type = BC_INST_ARRAY;
3884 }
3885 else {
3886
3887 *type = BC_INST_ARRAY_ELEM;
3888
3889 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3890 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3891 if (s) goto err;
3892 }
3893
3894 s = bc_lex_next(&p->l);
3895 if (s) goto err;
3896 bc_parse_push(p, *type);
3897 bc_parse_pushName(p, name);
3898 }
3899 else if (p->l.t.t == BC_LEX_LPAREN) {
3900
3901 if (flags & BC_PARSE_NOCALL) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003902 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003903 goto err;
3904 }
3905
3906 *type = BC_INST_CALL;
3907 s = bc_parse_call(p, name, flags);
3908 }
3909 else {
3910 *type = BC_INST_VAR;
3911 bc_parse_push(p, BC_INST_VAR);
3912 bc_parse_pushName(p, name);
3913 }
3914
3915 return s;
3916
3917err:
3918 free(name);
3919 return s;
3920}
3921
3922static BcStatus bc_parse_read(BcParse *p)
3923{
3924 BcStatus s;
3925
3926 s = bc_lex_next(&p->l);
3927 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003928 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003929
3930 s = bc_lex_next(&p->l);
3931 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003932 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003933
3934 bc_parse_push(p, BC_INST_READ);
3935
3936 return bc_lex_next(&p->l);
3937}
3938
3939static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3940 BcInst *prev)
3941{
3942 BcStatus s;
3943
3944 s = bc_lex_next(&p->l);
3945 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003946 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003947
3948 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3949
3950 s = bc_lex_next(&p->l);
3951 if (s) return s;
3952
3953 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3954 if (s) return s;
3955
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003956 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003957
3958 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3959 bc_parse_push(p, *prev);
3960
3961 return bc_lex_next(&p->l);
3962}
3963
3964static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3965{
3966 BcStatus s;
3967
3968 s = bc_lex_next(&p->l);
3969 if (s) return s;
3970
3971 if (p->l.t.t != BC_LEX_LPAREN) {
3972 *type = BC_INST_SCALE;
3973 bc_parse_push(p, BC_INST_SCALE);
3974 return BC_STATUS_SUCCESS;
3975 }
3976
3977 *type = BC_INST_SCALE_FUNC;
3978 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3979
3980 s = bc_lex_next(&p->l);
3981 if (s) return s;
3982
3983 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3984 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003985 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003986 bc_parse_push(p, BC_INST_SCALE_FUNC);
3987
3988 return bc_lex_next(&p->l);
3989}
3990
3991static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3992 size_t *nexprs, uint8_t flags)
3993{
3994 BcStatus s;
3995 BcLexType type;
3996 char inst;
3997 BcInst etype = *prev;
3998
3999 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4000 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4001 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4002 {
4003 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4004 bc_parse_push(p, inst);
4005 s = bc_lex_next(&p->l);
4006 }
4007 else {
4008
4009 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4010 *paren_expr = true;
4011
4012 s = bc_lex_next(&p->l);
4013 if (s) return s;
4014 type = p->l.t.t;
4015
4016 // Because we parse the next part of the expression
4017 // right here, we need to increment this.
4018 *nexprs = *nexprs + 1;
4019
4020 switch (type) {
4021
4022 case BC_LEX_NAME:
4023 {
4024 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4025 break;
4026 }
4027
4028 case BC_LEX_KEY_IBASE:
4029 case BC_LEX_KEY_LAST:
4030 case BC_LEX_KEY_OBASE:
4031 {
4032 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4033 s = bc_lex_next(&p->l);
4034 break;
4035 }
4036
4037 case BC_LEX_KEY_SCALE:
4038 {
4039 s = bc_lex_next(&p->l);
4040 if (s) return s;
4041 if (p->l.t.t == BC_LEX_LPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004042 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004043 else
4044 bc_parse_push(p, BC_INST_SCALE);
4045 break;
4046 }
4047
4048 default:
4049 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004050 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004051 break;
4052 }
4053 }
4054
4055 if (!s) bc_parse_push(p, inst);
4056 }
4057
4058 return s;
4059}
4060
4061static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4062 bool rparen, size_t *nexprs)
4063{
4064 BcStatus s;
4065 BcLexType type;
4066 BcInst etype = *prev;
4067
4068 s = bc_lex_next(&p->l);
4069 if (s) return s;
4070
4071 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4072 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4073 BC_LEX_OP_MINUS :
4074 BC_LEX_NEG;
4075 *prev = BC_PARSE_TOKEN_INST(type);
4076
4077 // We can just push onto the op stack because this is the largest
4078 // precedence operator that gets pushed. Inc/dec does not.
4079 if (type != BC_LEX_OP_MINUS)
4080 bc_vec_push(&p->ops, &type);
4081 else
4082 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4083
4084 return s;
4085}
4086
4087static BcStatus bc_parse_string(BcParse *p, char inst)
4088{
4089 char *str = xstrdup(p->l.t.v.v);
4090
4091 bc_parse_push(p, BC_INST_STR);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004092 bc_parse_pushIndex(p, G.prog.strs.len);
4093 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06004094 bc_parse_push(p, inst);
4095
4096 return bc_lex_next(&p->l);
4097}
4098
4099static BcStatus bc_parse_print(BcParse *p)
4100{
4101 BcStatus s;
4102 BcLexType type;
4103 bool comma = false;
4104
4105 s = bc_lex_next(&p->l);
4106 if (s) return s;
4107
4108 type = p->l.t.t;
4109
4110 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004111 return bc_error("bad print statement");
Gavin Howard01055ba2018-11-03 11:00:21 -06004112
4113 while (!s && type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4114
4115 if (type == BC_LEX_STR)
4116 s = bc_parse_string(p, BC_INST_PRINT_POP);
4117 else {
4118 s = bc_parse_expr(p, 0, bc_parse_next_print);
4119 if (s) return s;
4120 bc_parse_push(p, BC_INST_PRINT_POP);
4121 }
4122
4123 if (s) return s;
4124
4125 comma = p->l.t.t == BC_LEX_COMMA;
4126 if (comma) s = bc_lex_next(&p->l);
4127 type = p->l.t.t;
4128 }
4129
4130 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004131 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004132
4133 return bc_lex_next(&p->l);
4134}
4135
4136static BcStatus bc_parse_return(BcParse *p)
4137{
4138 BcStatus s;
4139 BcLexType t;
4140 bool paren;
4141
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004142 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004143
4144 s = bc_lex_next(&p->l);
4145 if (s) return s;
4146
4147 t = p->l.t.t;
4148 paren = t == BC_LEX_LPAREN;
4149
4150 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4151 bc_parse_push(p, BC_INST_RET0);
4152 else {
4153
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004154 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004155 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004156 bc_parse_push(p, BC_INST_RET0);
4157 s = bc_lex_next(&p->l);
Gavin Howard01055ba2018-11-03 11:00:21 -06004158 }
Denys Vlasenko452df922018-12-05 20:28:26 +01004159 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06004160
4161 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004162 s = bc_POSIX_requires("parentheses around return expressions");
Gavin Howard01055ba2018-11-03 11:00:21 -06004163 if (s) return s;
4164 }
4165
4166 bc_parse_push(p, BC_INST_RET);
4167 }
4168
4169 return s;
4170}
4171
4172static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4173{
4174 BcStatus s = BC_STATUS_SUCCESS;
4175
4176 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004177 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004178
4179 if (brace) {
4180
4181 if (p->l.t.t == BC_LEX_RBRACE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004182 if (!p->nbraces) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004183 --p->nbraces;
4184 s = bc_lex_next(&p->l);
4185 if (s) return s;
4186 }
4187 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004188 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004189 }
4190
4191 if (BC_PARSE_IF(p)) {
4192
4193 uint8_t *flag_ptr;
4194
4195 while (p->l.t.t == BC_LEX_NLINE) {
4196 s = bc_lex_next(&p->l);
4197 if (s) return s;
4198 }
4199
4200 bc_vec_pop(&p->flags);
4201
4202 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4203 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4204
4205 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4206 }
4207 else if (BC_PARSE_ELSE(p)) {
4208
4209 BcInstPtr *ip;
4210 size_t *label;
4211
4212 bc_vec_pop(&p->flags);
4213
4214 ip = bc_vec_top(&p->exits);
4215 label = bc_vec_item(&p->func->labels, ip->idx);
4216 *label = p->func->code.len;
4217
4218 bc_vec_pop(&p->exits);
4219 }
4220 else if (BC_PARSE_FUNC_INNER(p)) {
4221 bc_parse_push(p, BC_INST_RET0);
4222 bc_parse_updateFunc(p, BC_PROG_MAIN);
4223 bc_vec_pop(&p->flags);
4224 }
4225 else {
4226
4227 BcInstPtr *ip = bc_vec_top(&p->exits);
4228 size_t *label = bc_vec_top(&p->conds);
4229
4230 bc_parse_push(p, BC_INST_JUMP);
4231 bc_parse_pushIndex(p, *label);
4232
4233 label = bc_vec_item(&p->func->labels, ip->idx);
4234 *label = p->func->code.len;
4235
4236 bc_vec_pop(&p->flags);
4237 bc_vec_pop(&p->exits);
4238 bc_vec_pop(&p->conds);
4239 }
4240
4241 return s;
4242}
4243
4244static void bc_parse_startBody(BcParse *p, uint8_t flags)
4245{
4246 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4247 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4248 flags |= BC_PARSE_FLAG_BODY;
4249 bc_vec_push(&p->flags, &flags);
4250}
4251
4252static void bc_parse_noElse(BcParse *p)
4253{
4254 BcInstPtr *ip;
4255 size_t *label;
4256 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4257
4258 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4259
4260 ip = bc_vec_top(&p->exits);
4261 label = bc_vec_item(&p->func->labels, ip->idx);
4262 *label = p->func->code.len;
4263
4264 bc_vec_pop(&p->exits);
4265}
4266
4267static BcStatus bc_parse_if(BcParse *p)
4268{
4269 BcStatus s;
4270 BcInstPtr ip;
4271
4272 s = bc_lex_next(&p->l);
4273 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004274 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004275
4276 s = bc_lex_next(&p->l);
4277 if (s) return s;
4278 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4279 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004280 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004281
4282 s = bc_lex_next(&p->l);
4283 if (s) return s;
4284 bc_parse_push(p, BC_INST_JUMP_ZERO);
4285
4286 ip.idx = p->func->labels.len;
4287 ip.func = ip.len = 0;
4288
4289 bc_parse_pushIndex(p, ip.idx);
4290 bc_vec_push(&p->exits, &ip);
4291 bc_vec_push(&p->func->labels, &ip.idx);
4292 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4293
4294 return BC_STATUS_SUCCESS;
4295}
4296
4297static BcStatus bc_parse_else(BcParse *p)
4298{
4299 BcInstPtr ip;
4300
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004301 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004302
4303 ip.idx = p->func->labels.len;
4304 ip.func = ip.len = 0;
4305
4306 bc_parse_push(p, BC_INST_JUMP);
4307 bc_parse_pushIndex(p, ip.idx);
4308
4309 bc_parse_noElse(p);
4310
4311 bc_vec_push(&p->exits, &ip);
4312 bc_vec_push(&p->func->labels, &ip.idx);
4313 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4314
4315 return bc_lex_next(&p->l);
4316}
4317
4318static BcStatus bc_parse_while(BcParse *p)
4319{
4320 BcStatus s;
4321 BcInstPtr ip;
4322
4323 s = bc_lex_next(&p->l);
4324 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004325 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004326 s = bc_lex_next(&p->l);
4327 if (s) return s;
4328
4329 ip.idx = p->func->labels.len;
4330
4331 bc_vec_push(&p->func->labels, &p->func->code.len);
4332 bc_vec_push(&p->conds, &ip.idx);
4333
4334 ip.idx = p->func->labels.len;
4335 ip.func = 1;
4336 ip.len = 0;
4337
4338 bc_vec_push(&p->exits, &ip);
4339 bc_vec_push(&p->func->labels, &ip.idx);
4340
4341 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4342 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004343 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004344 s = bc_lex_next(&p->l);
4345 if (s) return s;
4346
4347 bc_parse_push(p, BC_INST_JUMP_ZERO);
4348 bc_parse_pushIndex(p, ip.idx);
4349 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4350
4351 return BC_STATUS_SUCCESS;
4352}
4353
4354static BcStatus bc_parse_for(BcParse *p)
4355{
4356 BcStatus s;
4357 BcInstPtr ip;
4358 size_t cond_idx, exit_idx, body_idx, update_idx;
4359
4360 s = bc_lex_next(&p->l);
4361 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004362 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004363 s = bc_lex_next(&p->l);
4364 if (s) return s;
4365
4366 if (p->l.t.t != BC_LEX_SCOLON)
4367 s = bc_parse_expr(p, 0, bc_parse_next_for);
4368 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004369 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
Gavin Howard01055ba2018-11-03 11:00:21 -06004370
4371 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004372 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004373 s = bc_lex_next(&p->l);
4374 if (s) return s;
4375
4376 cond_idx = p->func->labels.len;
4377 update_idx = cond_idx + 1;
4378 body_idx = update_idx + 1;
4379 exit_idx = body_idx + 1;
4380
4381 bc_vec_push(&p->func->labels, &p->func->code.len);
4382
4383 if (p->l.t.t != BC_LEX_SCOLON)
4384 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4385 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004386 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004387
4388 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004389 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004390
4391 s = bc_lex_next(&p->l);
4392 if (s) return s;
4393
4394 bc_parse_push(p, BC_INST_JUMP_ZERO);
4395 bc_parse_pushIndex(p, exit_idx);
4396 bc_parse_push(p, BC_INST_JUMP);
4397 bc_parse_pushIndex(p, body_idx);
4398
4399 ip.idx = p->func->labels.len;
4400
4401 bc_vec_push(&p->conds, &update_idx);
4402 bc_vec_push(&p->func->labels, &p->func->code.len);
4403
4404 if (p->l.t.t != BC_LEX_RPAREN)
4405 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4406 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004407 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
Gavin Howard01055ba2018-11-03 11:00:21 -06004408
4409 if (s) return s;
4410
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004411 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004412 bc_parse_push(p, BC_INST_JUMP);
4413 bc_parse_pushIndex(p, cond_idx);
4414 bc_vec_push(&p->func->labels, &p->func->code.len);
4415
4416 ip.idx = exit_idx;
4417 ip.func = 1;
4418 ip.len = 0;
4419
4420 bc_vec_push(&p->exits, &ip);
4421 bc_vec_push(&p->func->labels, &ip.idx);
4422 bc_lex_next(&p->l);
4423 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4424
4425 return BC_STATUS_SUCCESS;
4426}
4427
4428static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4429{
4430 BcStatus s;
4431 size_t i;
4432 BcInstPtr *ip;
4433
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004434 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004435
4436 if (type == BC_LEX_KEY_BREAK) {
4437
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004438 if (p->exits.len == 0) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004439
4440 i = p->exits.len - 1;
4441 ip = bc_vec_item(&p->exits, i);
4442
4443 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004444 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004445
4446 i = ip->idx;
4447 }
4448 else
4449 i = *((size_t *) bc_vec_top(&p->conds));
4450
4451 bc_parse_push(p, BC_INST_JUMP);
4452 bc_parse_pushIndex(p, i);
4453
4454 s = bc_lex_next(&p->l);
4455 if (s) return s;
4456
4457 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004458 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004459
4460 return bc_lex_next(&p->l);
4461}
4462
4463static BcStatus bc_parse_func(BcParse *p)
4464{
4465 BcStatus s;
4466 bool var, comma = false;
4467 uint8_t flags;
4468 char *name;
4469
4470 s = bc_lex_next(&p->l);
4471 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004472 if (p->l.t.t != BC_LEX_NAME)
4473 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004474
4475 name = xstrdup(p->l.t.v.v);
4476 bc_parse_addFunc(p, name, &p->fidx);
4477
4478 s = bc_lex_next(&p->l);
4479 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004480 if (p->l.t.t != BC_LEX_LPAREN)
4481 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004482 s = bc_lex_next(&p->l);
4483 if (s) return s;
4484
4485 while (p->l.t.t != BC_LEX_RPAREN) {
4486
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004487 if (p->l.t.t != BC_LEX_NAME)
4488 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004489
4490 ++p->func->nparams;
4491
4492 name = xstrdup(p->l.t.v.v);
4493 s = bc_lex_next(&p->l);
4494 if (s) goto err;
4495
4496 var = p->l.t.t != BC_LEX_LBRACKET;
4497
4498 if (!var) {
4499
4500 s = bc_lex_next(&p->l);
4501 if (s) goto err;
4502
4503 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004504 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004505 goto err;
4506 }
4507
4508 s = bc_lex_next(&p->l);
4509 if (s) goto err;
4510 }
4511
4512 comma = p->l.t.t == BC_LEX_COMMA;
4513 if (comma) {
4514 s = bc_lex_next(&p->l);
4515 if (s) goto err;
4516 }
4517
4518 s = bc_func_insert(p->func, name, var);
4519 if (s) goto err;
4520 }
4521
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004522 if (comma) return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004523
4524 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4525 bc_parse_startBody(p, flags);
4526
4527 s = bc_lex_next(&p->l);
4528 if (s) return s;
4529
4530 if (p->l.t.t != BC_LEX_LBRACE)
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004531 s = bc_POSIX_requires("the left brace be on the same line as the function header");
Gavin Howard01055ba2018-11-03 11:00:21 -06004532
4533 return s;
4534
4535err:
4536 free(name);
4537 return s;
4538}
4539
4540static BcStatus bc_parse_auto(BcParse *p)
4541{
4542 BcStatus s;
4543 bool comma, var, one;
4544 char *name;
4545
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004546 if (!p->auto_part) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004547 s = bc_lex_next(&p->l);
4548 if (s) return s;
4549
4550 p->auto_part = comma = false;
4551 one = p->l.t.t == BC_LEX_NAME;
4552
4553 while (p->l.t.t == BC_LEX_NAME) {
4554
4555 name = xstrdup(p->l.t.v.v);
4556 s = bc_lex_next(&p->l);
4557 if (s) goto err;
4558
4559 var = p->l.t.t != BC_LEX_LBRACKET;
4560 if (!var) {
4561
4562 s = bc_lex_next(&p->l);
4563 if (s) goto err;
4564
4565 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004566 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004567 goto err;
4568 }
4569
4570 s = bc_lex_next(&p->l);
4571 if (s) goto err;
4572 }
4573
4574 comma = p->l.t.t == BC_LEX_COMMA;
4575 if (comma) {
4576 s = bc_lex_next(&p->l);
4577 if (s) goto err;
4578 }
4579
4580 s = bc_func_insert(p->func, name, var);
4581 if (s) goto err;
4582 }
4583
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004584 if (comma) return bc_error("bad function definition");
Denys Vlasenkoabbc4332018-12-03 21:46:41 +01004585 if (!one) return bc_error("no auto variable found");
Gavin Howard01055ba2018-11-03 11:00:21 -06004586
4587 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004588 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004589
4590 return bc_lex_next(&p->l);
4591
4592err:
4593 free(name);
4594 return s;
4595}
4596
4597static BcStatus bc_parse_body(BcParse *p, bool brace)
4598{
4599 BcStatus s = BC_STATUS_SUCCESS;
4600 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4601
4602 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4603
4604 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4605
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004606 if (!brace) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004607 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4608
4609 if (!p->auto_part) {
4610 s = bc_parse_auto(p);
4611 if (s) return s;
4612 }
4613
4614 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4615 }
4616 else {
4617 s = bc_parse_stmt(p);
4618 if (!s && !brace) s = bc_parse_endBody(p, false);
4619 }
4620
4621 return s;
4622}
4623
4624static BcStatus bc_parse_stmt(BcParse *p)
4625{
4626 BcStatus s = BC_STATUS_SUCCESS;
4627
4628 switch (p->l.t.t) {
4629
4630 case BC_LEX_NLINE:
4631 {
4632 return bc_lex_next(&p->l);
4633 }
4634
4635 case BC_LEX_KEY_ELSE:
4636 {
4637 p->auto_part = false;
4638 break;
4639 }
4640
4641 case BC_LEX_LBRACE:
4642 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004643 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004644
4645 ++p->nbraces;
4646 s = bc_lex_next(&p->l);
4647 if (s) return s;
4648
4649 return bc_parse_body(p, true);
4650 }
4651
4652 case BC_LEX_KEY_AUTO:
4653 {
4654 return bc_parse_auto(p);
4655 }
4656
4657 default:
4658 {
4659 p->auto_part = false;
4660
4661 if (BC_PARSE_IF_END(p)) {
4662 bc_parse_noElse(p);
4663 return BC_STATUS_SUCCESS;
4664 }
4665 else if (BC_PARSE_BODY(p))
4666 return bc_parse_body(p, false);
4667
4668 break;
4669 }
4670 }
4671
4672 switch (p->l.t.t) {
4673
4674 case BC_LEX_OP_INC:
4675 case BC_LEX_OP_DEC:
4676 case BC_LEX_OP_MINUS:
4677 case BC_LEX_OP_BOOL_NOT:
4678 case BC_LEX_LPAREN:
4679 case BC_LEX_NAME:
4680 case BC_LEX_NUMBER:
4681 case BC_LEX_KEY_IBASE:
4682 case BC_LEX_KEY_LAST:
4683 case BC_LEX_KEY_LENGTH:
4684 case BC_LEX_KEY_OBASE:
4685 case BC_LEX_KEY_READ:
4686 case BC_LEX_KEY_SCALE:
4687 case BC_LEX_KEY_SQRT:
4688 {
4689 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4690 break;
4691 }
4692
4693 case BC_LEX_KEY_ELSE:
4694 {
4695 s = bc_parse_else(p);
4696 break;
4697 }
4698
4699 case BC_LEX_SCOLON:
4700 {
4701 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4702 break;
4703 }
4704
4705 case BC_LEX_RBRACE:
4706 {
4707 s = bc_parse_endBody(p, true);
4708 break;
4709 }
4710
4711 case BC_LEX_STR:
4712 {
4713 s = bc_parse_string(p, BC_INST_PRINT_STR);
4714 break;
4715 }
4716
4717 case BC_LEX_KEY_BREAK:
4718 case BC_LEX_KEY_CONTINUE:
4719 {
4720 s = bc_parse_loopExit(p, p->l.t.t);
4721 break;
4722 }
4723
4724 case BC_LEX_KEY_FOR:
4725 {
4726 s = bc_parse_for(p);
4727 break;
4728 }
4729
4730 case BC_LEX_KEY_HALT:
4731 {
4732 bc_parse_push(p, BC_INST_HALT);
4733 s = bc_lex_next(&p->l);
4734 break;
4735 }
4736
4737 case BC_LEX_KEY_IF:
4738 {
4739 s = bc_parse_if(p);
4740 break;
4741 }
4742
4743 case BC_LEX_KEY_LIMITS:
4744 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004745 // "limits" is a compile-time command,
4746 // the output is produced at _parse time_.
Gavin Howard01055ba2018-11-03 11:00:21 -06004747 s = bc_lex_next(&p->l);
4748 if (s) return s;
Denys Vlasenko64074a12018-12-07 15:50:14 +01004749 printf(
4750 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4751 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4752 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4753 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4754 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4755 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4756 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4757 "Number of vars = "BC_MAX_VARS_STR "\n"
4758 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004759 break;
4760 }
4761
4762 case BC_LEX_KEY_PRINT:
4763 {
4764 s = bc_parse_print(p);
4765 break;
4766 }
4767
4768 case BC_LEX_KEY_QUIT:
4769 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004770 // "quit" is a compile-time command. For example,
4771 // "if (0 == 1) quit" terminates when parsing the statement,
4772 // not when it is executed
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01004773 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06004774 }
4775
4776 case BC_LEX_KEY_RETURN:
4777 {
4778 s = bc_parse_return(p);
4779 break;
4780 }
4781
4782 case BC_LEX_KEY_WHILE:
4783 {
4784 s = bc_parse_while(p);
4785 break;
4786 }
4787
4788 default:
4789 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004790 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004791 break;
4792 }
4793 }
4794
4795 return s;
4796}
4797
4798static BcStatus bc_parse_parse(BcParse *p)
4799{
4800 BcStatus s;
4801
4802 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004803 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 -06004804 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004805 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004806 s = bc_parse_func(p);
4807 }
4808 else
4809 s = bc_parse_stmt(p);
4810
Denys Vlasenkod38af482018-12-04 19:11:02 +01004811 if (s || G_interrupt) {
4812 bc_parse_reset(p);
4813 s = BC_STATUS_FAILURE;
4814 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004815
4816 return s;
4817}
4818
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004819static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
Gavin Howard01055ba2018-11-03 11:00:21 -06004820{
4821 BcStatus s = BC_STATUS_SUCCESS;
4822 BcInst prev = BC_INST_PRINT;
4823 BcLexType top, t = p->l.t.t;
4824 size_t nexprs = 0, ops_bgn = p->ops.len;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01004825 unsigned nparens, nrelops;
Gavin Howard01055ba2018-11-03 11:00:21 -06004826 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4827
4828 paren_first = p->l.t.t == BC_LEX_LPAREN;
4829 nparens = nrelops = 0;
4830 paren_expr = rprn = done = get_token = assign = false;
4831 bin_last = true;
4832
Denys Vlasenkobcb62a72018-12-05 20:17:48 +01004833 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004834 switch (t) {
4835
4836 case BC_LEX_OP_INC:
4837 case BC_LEX_OP_DEC:
4838 {
4839 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4840 rprn = get_token = bin_last = false;
4841 break;
4842 }
4843
4844 case BC_LEX_OP_MINUS:
4845 {
4846 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4847 rprn = get_token = false;
4848 bin_last = prev == BC_INST_MINUS;
4849 break;
4850 }
4851
4852 case BC_LEX_OP_ASSIGN_POWER:
4853 case BC_LEX_OP_ASSIGN_MULTIPLY:
4854 case BC_LEX_OP_ASSIGN_DIVIDE:
4855 case BC_LEX_OP_ASSIGN_MODULUS:
4856 case BC_LEX_OP_ASSIGN_PLUS:
4857 case BC_LEX_OP_ASSIGN_MINUS:
4858 case BC_LEX_OP_ASSIGN:
4859 {
4860 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4861 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4862 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4863 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004864 s = bc_error("bad assignment:"
4865 " left side must be scale,"
4866 " ibase, obase, last, var,"
4867 " or array element"
4868 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004869 break;
4870 }
4871 }
4872 // Fallthrough.
4873 case BC_LEX_OP_POWER:
4874 case BC_LEX_OP_MULTIPLY:
4875 case BC_LEX_OP_DIVIDE:
4876 case BC_LEX_OP_MODULUS:
4877 case BC_LEX_OP_PLUS:
4878 case BC_LEX_OP_REL_EQ:
4879 case BC_LEX_OP_REL_LE:
4880 case BC_LEX_OP_REL_GE:
4881 case BC_LEX_OP_REL_NE:
4882 case BC_LEX_OP_REL_LT:
4883 case BC_LEX_OP_REL_GT:
4884 case BC_LEX_OP_BOOL_NOT:
4885 case BC_LEX_OP_BOOL_OR:
4886 case BC_LEX_OP_BOOL_AND:
4887 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004888 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4889 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4890 ) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004891 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004892 }
4893
4894 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4895 prev = BC_PARSE_TOKEN_INST(t);
4896 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4897 rprn = get_token = false;
4898 bin_last = t != BC_LEX_OP_BOOL_NOT;
4899
4900 break;
4901 }
4902
4903 case BC_LEX_LPAREN:
4904 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004905 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004906 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004907 ++nparens;
4908 paren_expr = rprn = bin_last = false;
4909 get_token = true;
4910 bc_vec_push(&p->ops, &t);
4911
4912 break;
4913 }
4914
4915 case BC_LEX_RPAREN:
4916 {
4917 if (bin_last || prev == BC_INST_BOOL_NOT)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004918 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004919
4920 if (nparens == 0) {
4921 s = BC_STATUS_SUCCESS;
4922 done = true;
4923 get_token = false;
4924 break;
4925 }
4926 else if (!paren_expr)
4927 return BC_STATUS_PARSE_EMPTY_EXP;
4928
4929 --nparens;
4930 paren_expr = rprn = true;
4931 get_token = bin_last = false;
4932
4933 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4934
4935 break;
4936 }
4937
4938 case BC_LEX_NAME:
4939 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004940 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004941 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004942 paren_expr = true;
4943 rprn = get_token = bin_last = false;
4944 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4945 ++nexprs;
4946
4947 break;
4948 }
4949
4950 case BC_LEX_NUMBER:
4951 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004952 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004953 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004954 bc_parse_number(p, &prev, &nexprs);
4955 paren_expr = get_token = true;
4956 rprn = bin_last = false;
4957
4958 break;
4959 }
4960
4961 case BC_LEX_KEY_IBASE:
4962 case BC_LEX_KEY_LAST:
4963 case BC_LEX_KEY_OBASE:
4964 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004965 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004966 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004967 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4968 bc_parse_push(p, (char) prev);
4969
4970 paren_expr = get_token = true;
4971 rprn = bin_last = false;
4972 ++nexprs;
4973
4974 break;
4975 }
4976
4977 case BC_LEX_KEY_LENGTH:
4978 case BC_LEX_KEY_SQRT:
4979 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004980 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004981 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004982 s = bc_parse_builtin(p, t, flags, &prev);
4983 paren_expr = true;
4984 rprn = get_token = bin_last = false;
4985 ++nexprs;
4986
4987 break;
4988 }
4989
4990 case BC_LEX_KEY_READ:
4991 {
4992 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004993 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004994 else if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004995 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06004996 else
4997 s = bc_parse_read(p);
4998
4999 paren_expr = true;
5000 rprn = get_token = bin_last = false;
5001 ++nexprs;
5002 prev = BC_INST_READ;
5003
5004 break;
5005 }
5006
5007 case BC_LEX_KEY_SCALE:
5008 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005009 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005010 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005011 s = bc_parse_scale(p, &prev, flags);
5012 paren_expr = true;
5013 rprn = get_token = bin_last = false;
5014 ++nexprs;
5015 prev = BC_INST_SCALE;
5016
5017 break;
5018 }
5019
5020 default:
5021 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005022 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005023 break;
5024 }
5025 }
5026
5027 if (!s && get_token) s = bc_lex_next(&p->l);
5028 }
5029
5030 if (s) return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01005031 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
Gavin Howard01055ba2018-11-03 11:00:21 -06005032
5033 while (p->ops.len > ops_bgn) {
5034
5035 top = BC_PARSE_TOP_OP(p);
5036 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5037
5038 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005039 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005040
5041 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5042
5043 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5044 bc_vec_pop(&p->ops);
5045 }
5046
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005047 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005048 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06005049
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005050 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5051 for (;;) {
5052 if (t == (next & 0x7f))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005053 goto ok;
Denys Vlasenko18c6b542018-12-07 12:57:32 +01005054 if (next & 0x80) // last element?
5055 break;
5056 next >>= 8;
5057 }
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005058 return bc_error_bad_expression();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005059 ok:
Gavin Howard01055ba2018-11-03 11:00:21 -06005060
5061 if (!(flags & BC_PARSE_REL) && nrelops) {
Denys Vlasenko00646792018-12-05 18:12:27 +01005062 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
Gavin Howard01055ba2018-11-03 11:00:21 -06005063 if (s) return s;
5064 }
5065 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01005066 s = bc_POSIX_requires("exactly one comparison operator per condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06005067 if (s) return s;
5068 }
5069
5070 if (flags & BC_PARSE_PRINT) {
5071 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5072 bc_parse_push(p, BC_INST_POP);
5073 }
5074
5075 return s;
5076}
5077
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01005078static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5079{
5080 BcStatus s;
5081
5082 s = bc_parse_expr_empty_ok(p, flags, next);
5083 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5084 return bc_error("empty expression");
5085 return s;
5086}
5087
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005088static void bc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005089{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005090 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005091}
5092
5093static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5094{
5095 return bc_parse_expr(p, flags, bc_parse_next_read);
5096}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005097
Gavin Howard01055ba2018-11-03 11:00:21 -06005098#endif // ENABLE_BC
5099
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005100#if ENABLE_DC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005101
5102#define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5103
Gavin Howard01055ba2018-11-03 11:00:21 -06005104static BcStatus dc_parse_register(BcParse *p)
5105{
5106 BcStatus s;
5107 char *name;
5108
5109 s = bc_lex_next(&p->l);
5110 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005111 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005112
5113 name = xstrdup(p->l.t.v.v);
5114 bc_parse_pushName(p, name);
5115
5116 return s;
5117}
5118
5119static BcStatus dc_parse_string(BcParse *p)
5120{
5121 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005122 size_t idx, len = G.prog.strs.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005123
5124 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5125 name = xstrdup(b);
5126
5127 str = xstrdup(p->l.t.v.v);
5128 bc_parse_push(p, BC_INST_STR);
5129 bc_parse_pushIndex(p, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005130 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06005131 bc_parse_addFunc(p, name, &idx);
5132
5133 return bc_lex_next(&p->l);
5134}
5135
5136static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5137{
5138 BcStatus s;
5139
5140 bc_parse_push(p, inst);
5141 if (name) {
5142 s = dc_parse_register(p);
5143 if (s) return s;
5144 }
5145
5146 if (store) {
5147 bc_parse_push(p, BC_INST_SWAP);
5148 bc_parse_push(p, BC_INST_ASSIGN);
5149 bc_parse_push(p, BC_INST_POP);
5150 }
5151
5152 return bc_lex_next(&p->l);
5153}
5154
5155static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5156{
5157 BcStatus s;
5158
5159 bc_parse_push(p, inst);
5160 bc_parse_push(p, BC_INST_EXEC_COND);
5161
5162 s = dc_parse_register(p);
5163 if (s) return s;
5164
5165 s = bc_lex_next(&p->l);
5166 if (s) return s;
5167
5168 if (p->l.t.t == BC_LEX_ELSE) {
5169 s = dc_parse_register(p);
5170 if (s) return s;
5171 s = bc_lex_next(&p->l);
5172 }
5173 else
5174 bc_parse_push(p, BC_PARSE_STREND);
5175
5176 return s;
5177}
5178
5179static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5180{
5181 BcStatus s = BC_STATUS_SUCCESS;
5182 BcInst prev;
5183 uint8_t inst;
5184 bool assign, get_token = false;
5185
5186 switch (t) {
5187
5188 case BC_LEX_OP_REL_EQ:
5189 case BC_LEX_OP_REL_LE:
5190 case BC_LEX_OP_REL_GE:
5191 case BC_LEX_OP_REL_NE:
5192 case BC_LEX_OP_REL_LT:
5193 case BC_LEX_OP_REL_GT:
5194 {
5195 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5196 break;
5197 }
5198
5199 case BC_LEX_SCOLON:
5200 case BC_LEX_COLON:
5201 {
5202 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5203 break;
5204 }
5205
5206 case BC_LEX_STR:
5207 {
5208 s = dc_parse_string(p);
5209 break;
5210 }
5211
5212 case BC_LEX_NEG:
5213 case BC_LEX_NUMBER:
5214 {
5215 if (t == BC_LEX_NEG) {
5216 s = bc_lex_next(&p->l);
5217 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005218 if (p->l.t.t != BC_LEX_NUMBER)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005219 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005220 }
5221
5222 bc_parse_number(p, &prev, &p->nbraces);
5223
5224 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5225 get_token = true;
5226
5227 break;
5228 }
5229
5230 case BC_LEX_KEY_READ:
5231 {
5232 if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005233 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005234 else
5235 bc_parse_push(p, BC_INST_READ);
5236 get_token = true;
5237 break;
5238 }
5239
5240 case BC_LEX_OP_ASSIGN:
5241 case BC_LEX_STORE_PUSH:
5242 {
5243 assign = t == BC_LEX_OP_ASSIGN;
5244 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5245 s = dc_parse_mem(p, inst, true, assign);
5246 break;
5247 }
5248
5249 case BC_LEX_LOAD:
5250 case BC_LEX_LOAD_POP:
5251 {
5252 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5253 s = dc_parse_mem(p, inst, true, false);
5254 break;
5255 }
5256
5257 case BC_LEX_STORE_IBASE:
5258 case BC_LEX_STORE_SCALE:
5259 case BC_LEX_STORE_OBASE:
5260 {
5261 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5262 s = dc_parse_mem(p, inst, false, true);
5263 break;
5264 }
5265
5266 default:
5267 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005268 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005269 get_token = true;
5270 break;
5271 }
5272 }
5273
5274 if (!s && get_token) s = bc_lex_next(&p->l);
5275
5276 return s;
5277}
5278
5279static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5280{
5281 BcStatus s = BC_STATUS_SUCCESS;
5282 BcInst inst;
5283 BcLexType t;
5284
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005285 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005286
5287 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5288
5289 inst = dc_parse_insts[t];
5290
5291 if (inst != BC_INST_INVALID) {
5292 bc_parse_push(p, inst);
5293 s = bc_lex_next(&p->l);
5294 }
5295 else
5296 s = dc_parse_token(p, t, flags);
5297 }
5298
5299 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5300 bc_parse_push(p, BC_INST_POP_EXEC);
5301
5302 return s;
5303}
5304
5305static BcStatus dc_parse_parse(BcParse *p)
5306{
5307 BcStatus s;
5308
5309 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005310 s = bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06005311 else
5312 s = dc_parse_expr(p, 0);
5313
Denys Vlasenkod38af482018-12-04 19:11:02 +01005314 if (s || G_interrupt) {
5315 bc_parse_reset(p);
5316 s = BC_STATUS_FAILURE;
5317 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005318
5319 return s;
5320}
5321
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005322static void dc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005323{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005324 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005325}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005326
Gavin Howard01055ba2018-11-03 11:00:21 -06005327#endif // ENABLE_DC
5328
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005329static void common_parse_init(BcParse *p, size_t func)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005330{
5331 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005332 IF_BC(bc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005333 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005334 IF_DC(dc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005335 }
5336}
5337
5338static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5339{
5340 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005341 IF_BC(return bc_parse_expression(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005342 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005343 IF_DC(return dc_parse_expr(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005344 }
5345}
5346
Denys Vlasenkodf515392018-12-02 19:27:48 +01005347static BcVec* bc_program_search(char *id, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005348{
Gavin Howard01055ba2018-11-03 11:00:21 -06005349 BcId e, *ptr;
5350 BcVec *v, *map;
5351 size_t i;
5352 BcResultData data;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005353 int new;
Gavin Howard01055ba2018-11-03 11:00:21 -06005354
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005355 v = var ? &G.prog.vars : &G.prog.arrs;
5356 map = var ? &G.prog.var_map : &G.prog.arr_map;
Gavin Howard01055ba2018-11-03 11:00:21 -06005357
5358 e.name = id;
5359 e.idx = v->len;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005360 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
Gavin Howard01055ba2018-11-03 11:00:21 -06005361
5362 if (new) {
5363 bc_array_init(&data.v, var);
5364 bc_vec_push(v, &data.v);
5365 }
5366
5367 ptr = bc_vec_item(map, i);
5368 if (new) ptr->name = xstrdup(e.name);
Denys Vlasenkodf515392018-12-02 19:27:48 +01005369 return bc_vec_item(v, ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005370}
5371
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005372static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
Gavin Howard01055ba2018-11-03 11:00:21 -06005373{
5374 BcStatus s = BC_STATUS_SUCCESS;
5375
5376 switch (r->t) {
5377
5378 case BC_RESULT_STR:
5379 case BC_RESULT_TEMP:
5380 case BC_RESULT_IBASE:
5381 case BC_RESULT_SCALE:
5382 case BC_RESULT_OBASE:
5383 {
5384 *num = &r->d.n;
5385 break;
5386 }
5387
5388 case BC_RESULT_CONSTANT:
5389 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005390 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005391 size_t base_t, len = strlen(*str);
5392 BcNum *base;
5393
5394 bc_num_init(&r->d.n, len);
5395
5396 hex = hex && len == 1;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005397 base = hex ? &G.prog.hexb : &G.prog.ib;
5398 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005399 s = bc_num_parse(&r->d.n, *str, base, base_t);
5400
5401 if (s) {
5402 bc_num_free(&r->d.n);
5403 return s;
5404 }
5405
5406 *num = &r->d.n;
5407 r->t = BC_RESULT_TEMP;
5408
5409 break;
5410 }
5411
5412 case BC_RESULT_VAR:
5413 case BC_RESULT_ARRAY:
5414 case BC_RESULT_ARRAY_ELEM:
5415 {
5416 BcVec *v;
5417
Denys Vlasenkodf515392018-12-02 19:27:48 +01005418 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
Gavin Howard01055ba2018-11-03 11:00:21 -06005419
5420 if (r->t == BC_RESULT_ARRAY_ELEM) {
5421 v = bc_vec_top(v);
5422 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5423 *num = bc_vec_item(v, r->d.id.idx);
5424 }
5425 else
5426 *num = bc_vec_top(v);
5427
5428 break;
5429 }
5430
5431 case BC_RESULT_LAST:
5432 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005433 *num = &G.prog.last;
Gavin Howard01055ba2018-11-03 11:00:21 -06005434 break;
5435 }
5436
5437 case BC_RESULT_ONE:
5438 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005439 *num = &G.prog.one;
Gavin Howard01055ba2018-11-03 11:00:21 -06005440 break;
5441 }
5442 }
5443
5444 return s;
5445}
5446
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005447static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
Gavin Howard01055ba2018-11-03 11:00:21 -06005448 BcResult **r, BcNum **rn, bool assign)
5449{
5450 BcStatus s;
5451 bool hex;
5452 BcResultType lt, rt;
5453
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005454 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005455 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005456
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005457 *r = bc_vec_item_rev(&G.prog.results, 0);
5458 *l = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06005459
5460 lt = (*l)->t;
5461 rt = (*r)->t;
5462 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5463
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005464 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005465 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005466 s = bc_program_num(*r, rn, hex);
Gavin Howard01055ba2018-11-03 11:00:21 -06005467 if (s) return s;
5468
5469 // We run this again under these conditions in case any vector has been
5470 // reallocated out from under the BcNums or arrays we had.
5471 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005472 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005473 if (s) return s;
5474 }
5475
5476 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005477 return bc_error_variable_is_wrong_type();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005478 if (!assign && !BC_PROG_NUM((*r), (*ln)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005479 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005480
Gavin Howard01055ba2018-11-03 11:00:21 -06005481 return s;
5482}
5483
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005484static void bc_program_binOpRetire(BcResult *r)
Gavin Howard01055ba2018-11-03 11:00:21 -06005485{
5486 r->t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005487 bc_vec_pop(&G.prog.results);
5488 bc_vec_pop(&G.prog.results);
5489 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005490}
5491
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005492static BcStatus bc_program_prep(BcResult **r, BcNum **n)
Gavin Howard01055ba2018-11-03 11:00:21 -06005493{
5494 BcStatus s;
5495
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005496 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005497 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005498 *r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005499
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005500 s = bc_program_num(*r, n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005501 if (s) return s;
5502
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005503 if (!BC_PROG_NUM((*r), (*n)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005504 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005505
5506 return s;
5507}
5508
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005509static void bc_program_retire(BcResult *r, BcResultType t)
Gavin Howard01055ba2018-11-03 11:00:21 -06005510{
5511 r->t = t;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005512 bc_vec_pop(&G.prog.results);
5513 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005514}
5515
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005516static BcStatus bc_program_op(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005517{
5518 BcStatus s;
5519 BcResult *opd1, *opd2, res;
5520 BcNum *n1, *n2 = NULL;
5521
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005522 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005523 if (s) return s;
5524 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5525
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005526 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005527 if (s) goto err;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005528 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005529
5530 return s;
5531
5532err:
5533 bc_num_free(&res.d.n);
5534 return s;
5535}
5536
Denys Vlasenko785e4b32018-12-02 17:18:52 +01005537static BcStatus bc_program_read(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005538{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005539 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005540 BcStatus s;
5541 BcParse parse;
5542 BcVec buf;
5543 BcInstPtr ip;
5544 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005545 BcFunc *f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005546
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005547 for (i = 0; i < G.prog.stack.len; ++i) {
5548 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005549 if (ip_ptr->func == BC_PROG_READ)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005550 return bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005551 }
5552
Denys Vlasenko7d628012018-12-04 21:46:47 +01005553 bc_vec_pop_all(&f->code);
5554 bc_char_vec_init(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005555
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005556 sv_file = G.prog.file;
5557 G.prog.file = NULL;
5558
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01005559 s = bc_read_line(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005560 if (s) goto io_err;
5561
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005562 common_parse_init(&parse, BC_PROG_READ);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005563 bc_lex_file(&parse.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005564
5565 s = bc_parse_text(&parse, buf.v);
5566 if (s) goto exec_err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005567 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
Gavin Howard01055ba2018-11-03 11:00:21 -06005568 if (s) goto exec_err;
5569
5570 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005571 s = bc_error("bad read() expression");
Gavin Howard01055ba2018-11-03 11:00:21 -06005572 goto exec_err;
5573 }
5574
5575 ip.func = BC_PROG_READ;
5576 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005577 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005578
5579 // Update this pointer, just in case.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005580 f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005581
5582 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005583 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06005584
5585exec_err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005586 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005587 bc_parse_free(&parse);
5588io_err:
5589 bc_vec_free(&buf);
5590 return s;
5591}
5592
5593static size_t bc_program_index(char *code, size_t *bgn)
5594{
5595 char amt = code[(*bgn)++], i = 0;
5596 size_t res = 0;
5597
5598 for (; i < amt; ++i, ++(*bgn))
5599 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5600
5601 return res;
5602}
5603
5604static char *bc_program_name(char *code, size_t *bgn)
5605{
5606 size_t i;
5607 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5608
5609 s = xmalloc(ptr - str + 1);
5610 c = code[(*bgn)++];
5611
5612 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5613 s[i] = c;
5614
5615 s[i] = '\0';
5616
5617 return s;
5618}
5619
5620static void bc_program_printString(const char *str, size_t *nchars)
5621{
5622 size_t i, len = strlen(str);
5623
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005624#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005625 if (len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005626 bb_putchar('\0');
Gavin Howard01055ba2018-11-03 11:00:21 -06005627 return;
5628 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005629#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005630
5631 for (i = 0; i < len; ++i, ++(*nchars)) {
5632
5633 int c = str[i];
5634
5635 if (c != '\\' || i == len - 1)
Denys Vlasenko00d77792018-11-30 23:13:42 +01005636 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005637 else {
5638
5639 c = str[++i];
5640
5641 switch (c) {
5642
5643 case 'a':
5644 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005645 bb_putchar('\a');
Gavin Howard01055ba2018-11-03 11:00:21 -06005646 break;
5647 }
5648
5649 case 'b':
5650 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005651 bb_putchar('\b');
Gavin Howard01055ba2018-11-03 11:00:21 -06005652 break;
5653 }
5654
5655 case '\\':
5656 case 'e':
5657 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005658 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005659 break;
5660 }
5661
5662 case 'f':
5663 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005664 bb_putchar('\f');
Gavin Howard01055ba2018-11-03 11:00:21 -06005665 break;
5666 }
5667
5668 case 'n':
5669 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005670 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005671 *nchars = SIZE_MAX;
5672 break;
5673 }
5674
5675 case 'r':
5676 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005677 bb_putchar('\r');
Gavin Howard01055ba2018-11-03 11:00:21 -06005678 break;
5679 }
5680
5681 case 'q':
5682 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005683 bb_putchar('"');
Gavin Howard01055ba2018-11-03 11:00:21 -06005684 break;
5685 }
5686
5687 case 't':
5688 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005689 bb_putchar('\t');
Gavin Howard01055ba2018-11-03 11:00:21 -06005690 break;
5691 }
5692
5693 default:
5694 {
5695 // Just print the backslash and following character.
Denys Vlasenko00d77792018-11-30 23:13:42 +01005696 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005697 ++(*nchars);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005698 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005699 break;
5700 }
5701 }
5702 }
5703 }
5704}
5705
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005706static BcStatus bc_program_print(char inst, size_t idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005707{
5708 BcStatus s = BC_STATUS_SUCCESS;
5709 BcResult *r;
5710 size_t len, i;
5711 char *str;
5712 BcNum *num = NULL;
5713 bool pop = inst != BC_INST_PRINT;
5714
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005715 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005716 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005717
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005718 r = bc_vec_item_rev(&G.prog.results, idx);
5719 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005720 if (s) return s;
5721
5722 if (BC_PROG_NUM(r, num)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005723 s = bc_num_print(num, &G.prog.ob, G.prog.ob_t, !pop, &G.prog.nchars, G.prog.len);
5724 if (!s) bc_num_copy(&G.prog.last, num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005725 }
5726 else {
5727
5728 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005729 str = *((char **) bc_vec_item(&G.prog.strs, idx));
Gavin Howard01055ba2018-11-03 11:00:21 -06005730
5731 if (inst == BC_INST_PRINT_STR) {
5732 for (i = 0, len = strlen(str); i < len; ++i) {
5733 char c = str[i];
Denys Vlasenko00d77792018-11-30 23:13:42 +01005734 bb_putchar(c);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005735 if (c == '\n') G.prog.nchars = SIZE_MAX;
5736 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06005737 }
5738 }
5739 else {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005740 bc_program_printString(str, &G.prog.nchars);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005741 if (inst == BC_INST_PRINT) bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005742 }
5743 }
5744
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005745 if (!s && pop) bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005746
5747 return s;
5748}
5749
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005750static BcStatus bc_program_negate(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005751{
5752 BcStatus s;
5753 BcResult res, *ptr;
5754 BcNum *num = NULL;
5755
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005756 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005757 if (s) return s;
5758
5759 bc_num_init(&res.d.n, num->len);
5760 bc_num_copy(&res.d.n, num);
5761 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5762
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005763 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06005764
5765 return s;
5766}
5767
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005768static BcStatus bc_program_logical(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005769{
5770 BcStatus s;
5771 BcResult *opd1, *opd2, res;
5772 BcNum *n1, *n2;
5773 bool cond = 0;
5774 ssize_t cmp;
5775
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005776 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005777 if (s) return s;
5778 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5779
5780 if (inst == BC_INST_BOOL_AND)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005781 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005782 else if (inst == BC_INST_BOOL_OR)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005783 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005784 else {
5785
5786 cmp = bc_num_cmp(n1, n2);
5787
5788 switch (inst) {
5789
5790 case BC_INST_REL_EQ:
5791 {
5792 cond = cmp == 0;
5793 break;
5794 }
5795
5796 case BC_INST_REL_LE:
5797 {
5798 cond = cmp <= 0;
5799 break;
5800 }
5801
5802 case BC_INST_REL_GE:
5803 {
5804 cond = cmp >= 0;
5805 break;
5806 }
5807
5808 case BC_INST_REL_NE:
5809 {
5810 cond = cmp != 0;
5811 break;
5812 }
5813
5814 case BC_INST_REL_LT:
5815 {
5816 cond = cmp < 0;
5817 break;
5818 }
5819
5820 case BC_INST_REL_GT:
5821 {
5822 cond = cmp > 0;
5823 break;
5824 }
5825 }
5826 }
5827
5828 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5829
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005830 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005831
5832 return s;
5833}
5834
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005835#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005836static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
Gavin Howard01055ba2018-11-03 11:00:21 -06005837 bool push)
5838{
5839 BcNum n2;
5840 BcResult res;
5841
5842 memset(&n2, 0, sizeof(BcNum));
5843 n2.rdx = res.d.id.idx = r->d.id.idx;
5844 res.t = BC_RESULT_STR;
5845
5846 if (!push) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005847 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005848 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005849 bc_vec_pop(v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005850 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005851 }
5852
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005853 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005854
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005855 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005856 bc_vec_push(v, &n2);
5857
5858 return BC_STATUS_SUCCESS;
5859}
5860#endif // ENABLE_DC
5861
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005862static BcStatus bc_program_copyToVar(char *name, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005863{
5864 BcStatus s;
5865 BcResult *ptr, r;
5866 BcVec *v;
5867 BcNum *n;
5868
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005869 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005870 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005871
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005872 ptr = bc_vec_top(&G.prog.results);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005873 if ((ptr->t == BC_RESULT_ARRAY) != !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005874 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005875 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005876
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005877#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005878 if (ptr->t == BC_RESULT_STR && !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005879 return bc_error_variable_is_wrong_type();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005880 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005881#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005882
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005883 s = bc_program_num(ptr, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005884 if (s) return s;
5885
5886 // Do this once more to make sure that pointers were not invalidated.
Denys Vlasenkodf515392018-12-02 19:27:48 +01005887 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005888
5889 if (var) {
5890 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5891 bc_num_copy(&r.d.n, n);
5892 }
5893 else {
5894 bc_array_init(&r.d.v, true);
5895 bc_array_copy(&r.d.v, (BcVec *) n);
5896 }
5897
5898 bc_vec_push(v, &r.d);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005899 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005900
5901 return s;
5902}
5903
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005904static BcStatus bc_program_assign(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005905{
5906 BcStatus s;
5907 BcResult *left, *right, res;
5908 BcNum *l = NULL, *r = NULL;
Gavin Howard01055ba2018-11-03 11:00:21 -06005909 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5910
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005911 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
Gavin Howard01055ba2018-11-03 11:00:21 -06005912 if (s) return s;
5913
5914 ib = left->t == BC_RESULT_IBASE;
5915 sc = left->t == BC_RESULT_SCALE;
5916
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005917#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005918
5919 if (right->t == BC_RESULT_STR) {
5920
5921 BcVec *v;
5922
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005923 if (left->t != BC_RESULT_VAR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005924 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005925 v = bc_program_search(left->d.id.name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06005926
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005927 return bc_program_assignStr(right, v, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005928 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005929#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005930
5931 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005932 return bc_error("bad assignment:"
5933 " left side must be scale,"
5934 " ibase, obase, last, var,"
5935 " or array element"
5936 );
Gavin Howard01055ba2018-11-03 11:00:21 -06005937
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005938#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005939 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005940 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06005941
5942 if (assign)
5943 bc_num_copy(l, r);
5944 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005945 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005946
5947 if (s) return s;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005948#else
Gavin Howard01055ba2018-11-03 11:00:21 -06005949 bc_num_copy(l, r);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005950#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005951
5952 if (ib || sc || left->t == BC_RESULT_OBASE) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005953 static const char *const msg[] = {
Denys Vlasenko64074a12018-12-07 15:50:14 +01005954 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5955 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5956 NULL, //can't happen //BC_RESULT_LAST
5957 NULL, //can't happen //BC_RESULT_CONSTANT
5958 NULL, //can't happen //BC_RESULT_ONE
5959 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005960 };
Gavin Howard01055ba2018-11-03 11:00:21 -06005961 size_t *ptr;
Denys Vlasenkoffdcebd2018-12-07 15:10:05 +01005962 unsigned long val, max;
Gavin Howard01055ba2018-11-03 11:00:21 -06005963
5964 s = bc_num_ulong(l, &val);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005965 if (s)
5966 return s;
5967 s = left->t - BC_RESULT_IBASE;
Gavin Howard01055ba2018-11-03 11:00:21 -06005968 if (sc) {
5969 max = BC_MAX_SCALE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005970 ptr = &G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06005971 }
5972 else {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005973 if (val < BC_NUM_MIN_BASE)
5974 return bc_error(msg[s]);
Gavin Howard01055ba2018-11-03 11:00:21 -06005975 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005976 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005977 }
5978
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005979 if (val > max)
5980 return bc_error(msg[s]);
5981 if (!sc)
5982 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005983
5984 *ptr = (size_t) val;
5985 s = BC_STATUS_SUCCESS;
5986 }
5987
5988 bc_num_init(&res.d.n, l->len);
5989 bc_num_copy(&res.d.n, l);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005990 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005991
5992 return s;
5993}
5994
Denys Vlasenko416ce762018-12-02 20:57:17 +01005995#if !ENABLE_DC
5996#define bc_program_pushVar(code, bgn, pop, copy) \
5997 bc_program_pushVar(code, bgn)
5998// for bc, 'pop' and 'copy' are always false
5999#endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006000static BcStatus bc_program_pushVar(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006001 bool pop, bool copy)
6002{
6003 BcStatus s = BC_STATUS_SUCCESS;
6004 BcResult r;
6005 char *name = bc_program_name(code, bgn);
Gavin Howard01055ba2018-11-03 11:00:21 -06006006
6007 r.t = BC_RESULT_VAR;
6008 r.d.id.name = name;
6009
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006010#if ENABLE_DC
Denys Vlasenko416ce762018-12-02 20:57:17 +01006011 {
6012 BcVec *v = bc_program_search(name, true);
6013 BcNum *num = bc_vec_top(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006014
Denys Vlasenko416ce762018-12-02 20:57:17 +01006015 if (pop || copy) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006016
Denys Vlasenko416ce762018-12-02 20:57:17 +01006017 if (!BC_PROG_STACK(v, 2 - copy)) {
6018 free(name);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006019 return bc_error_stack_has_too_few_elements();
Denys Vlasenko416ce762018-12-02 20:57:17 +01006020 }
6021
Gavin Howard01055ba2018-11-03 11:00:21 -06006022 free(name);
Denys Vlasenko416ce762018-12-02 20:57:17 +01006023 name = NULL;
6024
6025 if (!BC_PROG_STR(num)) {
6026
6027 r.t = BC_RESULT_TEMP;
6028
6029 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
6030 bc_num_copy(&r.d.n, num);
6031 }
6032 else {
6033 r.t = BC_RESULT_STR;
6034 r.d.id.idx = num->rdx;
6035 }
6036
6037 if (!copy) bc_vec_pop(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006038 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006039 }
6040#endif // ENABLE_DC
6041
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006042 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006043
6044 return s;
6045}
6046
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006047static BcStatus bc_program_pushArray(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006048 char inst)
6049{
6050 BcStatus s = BC_STATUS_SUCCESS;
6051 BcResult r;
6052 BcNum *num;
6053
6054 r.d.id.name = bc_program_name(code, bgn);
6055
6056 if (inst == BC_INST_ARRAY) {
6057 r.t = BC_RESULT_ARRAY;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006058 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006059 }
6060 else {
6061
6062 BcResult *operand;
6063 unsigned long temp;
6064
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006065 s = bc_program_prep(&operand, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006066 if (s) goto err;
6067 s = bc_num_ulong(num, &temp);
6068 if (s) goto err;
6069
6070 if (temp > BC_MAX_DIM) {
Denys Vlasenko64074a12018-12-07 15:50:14 +01006071 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
Gavin Howard01055ba2018-11-03 11:00:21 -06006072 goto err;
6073 }
6074
6075 r.d.id.idx = (size_t) temp;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006076 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
Gavin Howard01055ba2018-11-03 11:00:21 -06006077 }
6078
6079err:
6080 if (s) free(r.d.id.name);
6081 return s;
6082}
6083
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006084#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006085static BcStatus bc_program_incdec(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006086{
6087 BcStatus s;
6088 BcResult *ptr, res, copy;
6089 BcNum *num = NULL;
6090 char inst2 = inst;
6091
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006092 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006093 if (s) return s;
6094
6095 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6096 copy.t = BC_RESULT_TEMP;
6097 bc_num_init(&copy.d.n, num->len);
6098 bc_num_copy(&copy.d.n, num);
6099 }
6100
6101 res.t = BC_RESULT_ONE;
6102 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6103 BC_INST_ASSIGN_PLUS :
6104 BC_INST_ASSIGN_MINUS;
6105
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006106 bc_vec_push(&G.prog.results, &res);
6107 bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006108
6109 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006110 bc_vec_pop(&G.prog.results);
6111 bc_vec_push(&G.prog.results, &copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006112 }
6113
6114 return s;
6115}
6116
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006117static BcStatus bc_program_call(char *code, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006118{
6119 BcStatus s = BC_STATUS_SUCCESS;
6120 BcInstPtr ip;
6121 size_t i, nparams = bc_program_index(code, idx);
6122 BcFunc *func;
Gavin Howard01055ba2018-11-03 11:00:21 -06006123 BcId *a;
6124 BcResultData param;
6125 BcResult *arg;
6126
6127 ip.idx = 0;
6128 ip.func = bc_program_index(code, idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006129 func = bc_vec_item(&G.prog.fns, ip.func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006130
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006131 if (func->code.len == 0) {
6132 return bc_error("undefined function");
6133 }
6134 if (nparams != func->nparams) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006135 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006136 }
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006137 ip.len = G.prog.results.len - nparams;
Gavin Howard01055ba2018-11-03 11:00:21 -06006138
6139 for (i = 0; i < nparams; ++i) {
6140
6141 a = bc_vec_item(&func->autos, nparams - 1 - i);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006142 arg = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006143
6144 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006145 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006146
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006147 s = bc_program_copyToVar(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006148 if (s) return s;
6149 }
6150
6151 for (; i < func->autos.len; ++i) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006152 BcVec *v;
Gavin Howard01055ba2018-11-03 11:00:21 -06006153
6154 a = bc_vec_item(&func->autos, i);
Denys Vlasenkodf515392018-12-02 19:27:48 +01006155 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006156
6157 if (a->idx) {
6158 bc_num_init(&param.n, BC_NUM_DEF_SIZE);
6159 bc_vec_push(v, &param.n);
6160 }
6161 else {
6162 bc_array_init(&param.v, true);
6163 bc_vec_push(v, &param.v);
6164 }
6165 }
6166
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006167 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006168
6169 return BC_STATUS_SUCCESS;
6170}
6171
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006172static BcStatus bc_program_return(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006173{
6174 BcStatus s;
6175 BcResult res;
6176 BcFunc *f;
6177 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006178 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006179
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006180 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006181 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006182
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006183 f = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006184 res.t = BC_RESULT_TEMP;
6185
6186 if (inst == BC_INST_RET) {
6187
6188 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006189 BcResult *operand = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006190
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006191 s = bc_program_num(operand, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006192 if (s) return s;
6193 bc_num_init(&res.d.n, num->len);
6194 bc_num_copy(&res.d.n, num);
6195 }
6196 else {
6197 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6198 bc_num_zero(&res.d.n);
6199 }
6200
6201 // We need to pop arguments as well, so this takes that into account.
6202 for (i = 0; i < f->autos.len; ++i) {
6203
6204 BcVec *v;
6205 BcId *a = bc_vec_item(&f->autos, i);
6206
Denys Vlasenkodf515392018-12-02 19:27:48 +01006207 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006208 bc_vec_pop(v);
6209 }
6210
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006211 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6212 bc_vec_push(&G.prog.results, &res);
6213 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006214
6215 return BC_STATUS_SUCCESS;
6216}
6217#endif // ENABLE_BC
6218
6219static unsigned long bc_program_scale(BcNum *n)
6220{
6221 return (unsigned long) n->rdx;
6222}
6223
6224static unsigned long bc_program_len(BcNum *n)
6225{
6226 unsigned long len = n->len;
6227 size_t i;
6228
6229 if (n->rdx != n->len) return len;
6230 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6231
6232 return len;
6233}
6234
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006235static BcStatus bc_program_builtin(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006236{
6237 BcStatus s;
6238 BcResult *opnd;
6239 BcNum *num = NULL;
6240 BcResult res;
6241 bool len = inst == BC_INST_LENGTH;
6242
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006243 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006244 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006245 opnd = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006246
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006247 s = bc_program_num(opnd, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006248 if (s) return s;
6249
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006250#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006251 if (!BC_PROG_NUM(opnd, num) && !len)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006252 return bc_error_variable_is_wrong_type();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006253#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006254
6255 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6256
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006257 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006258#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006259 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006260 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006261 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006262#endif
6263#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006264 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6265
6266 char **str;
6267 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6268
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006269 str = bc_vec_item(&G.prog.strs, idx);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006270 bc_num_ulong2num(&res.d.n, strlen(*str));
Gavin Howard01055ba2018-11-03 11:00:21 -06006271 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006272#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006273 else {
6274 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006275 bc_num_ulong2num(&res.d.n, f(num));
Gavin Howard01055ba2018-11-03 11:00:21 -06006276 }
6277
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006278 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006279
6280 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006281}
6282
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006283#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006284static BcStatus bc_program_divmod(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006285{
6286 BcStatus s;
6287 BcResult *opd1, *opd2, res, res2;
6288 BcNum *n1, *n2 = NULL;
6289
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006290 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006291 if (s) return s;
6292
6293 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6294 bc_num_init(&res2.d.n, n2->len);
6295
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006296 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006297 if (s) goto err;
6298
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006299 bc_program_binOpRetire(&res2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006300 res.t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006301 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006302
6303 return s;
6304
6305err:
6306 bc_num_free(&res2.d.n);
6307 bc_num_free(&res.d.n);
6308 return s;
6309}
6310
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006311static BcStatus bc_program_modexp(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006312{
6313 BcStatus s;
6314 BcResult *r1, *r2, *r3, res;
6315 BcNum *n1, *n2, *n3;
6316
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006317 if (!BC_PROG_STACK(&G.prog.results, 3))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006318 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006319 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006320 if (s) return s;
6321
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006322 r1 = bc_vec_item_rev(&G.prog.results, 2);
6323 s = bc_program_num(r1, &n1, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006324 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006325 if (!BC_PROG_NUM(r1, n1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006326 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006327
6328 // Make sure that the values have their pointers updated, if necessary.
6329 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6330
6331 if (r1->t == r2->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006332 s = bc_program_num(r2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006333 if (s) return s;
6334 }
6335
6336 if (r1->t == r3->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006337 s = bc_program_num(r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006338 if (s) return s;
6339 }
6340 }
6341
6342 bc_num_init(&res.d.n, n3->len);
6343 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6344 if (s) goto err;
6345
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006346 bc_vec_pop(&G.prog.results);
6347 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006348
6349 return s;
6350
6351err:
6352 bc_num_free(&res.d.n);
6353 return s;
6354}
6355
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006356static void bc_program_stackLen(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006357{
Gavin Howard01055ba2018-11-03 11:00:21 -06006358 BcResult res;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006359 size_t len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006360
6361 res.t = BC_RESULT_TEMP;
6362
6363 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006364 bc_num_ulong2num(&res.d.n, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006365 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006366}
6367
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006368static BcStatus bc_program_asciify(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006369{
6370 BcStatus s;
6371 BcResult *r, res;
6372 BcNum *num = NULL, n;
6373 char *str, *str2, c;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006374 size_t len = G.prog.strs.len, idx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006375 unsigned long val;
6376
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006377 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006378 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006379 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006380
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006381 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006382 if (s) return s;
6383
6384 if (BC_PROG_NUM(r, num)) {
6385
6386 bc_num_init(&n, BC_NUM_DEF_SIZE);
6387 bc_num_copy(&n, num);
6388 bc_num_truncate(&n, n.rdx);
6389
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006390 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006391 if (s) goto num_err;
6392 s = bc_num_ulong(&n, &val);
6393 if (s) goto num_err;
6394
6395 c = (char) val;
6396
6397 bc_num_free(&n);
6398 }
6399 else {
6400 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006401 str2 = *((char **) bc_vec_item(&G.prog.strs, idx));
Gavin Howard01055ba2018-11-03 11:00:21 -06006402 c = str2[0];
6403 }
6404
6405 str = xmalloc(2);
6406 str[0] = c;
6407 str[1] = '\0';
6408
6409 str2 = xstrdup(str);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006410 bc_program_addFunc(str2, &idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006411
6412 if (idx != len + BC_PROG_REQ_FUNCS) {
6413
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006414 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6415 if (!strcmp(*((char **) bc_vec_item(&G.prog.strs, idx)), str)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006416 len = idx;
6417 break;
6418 }
6419 }
6420
6421 free(str);
6422 }
6423 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006424 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006425
6426 res.t = BC_RESULT_STR;
6427 res.d.id.idx = len;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006428 bc_vec_pop(&G.prog.results);
6429 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006430
6431 return BC_STATUS_SUCCESS;
6432
6433num_err:
6434 bc_num_free(&n);
6435 return s;
6436}
6437
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006438static BcStatus bc_program_printStream(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006439{
6440 BcStatus s;
6441 BcResult *r;
6442 BcNum *n = NULL;
6443 size_t idx;
6444 char *str;
6445
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006446 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006447 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006448 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006449
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006450 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006451 if (s) return s;
6452
6453 if (BC_PROG_NUM(r, n))
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006454 s = bc_num_stream(n, &G.prog.strmb, &G.prog.nchars, G.prog.len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006455 else {
6456 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006457 str = *((char **) bc_vec_item(&G.prog.strs, idx));
Denys Vlasenko00d77792018-11-30 23:13:42 +01006458 printf("%s", str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006459 }
6460
6461 return s;
6462}
6463
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006464static BcStatus bc_program_nquit(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006465{
6466 BcStatus s;
6467 BcResult *opnd;
6468 BcNum *num = NULL;
6469 unsigned long val;
6470
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006471 s = bc_program_prep(&opnd, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006472 if (s) return s;
6473 s = bc_num_ulong(num, &val);
6474 if (s) return s;
6475
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006476 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006477
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006478 if (G.prog.stack.len < val)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006479 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006480 if (G.prog.stack.len == val) {
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006481 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006482 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006483
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006484 bc_vec_npop(&G.prog.stack, val);
Gavin Howard01055ba2018-11-03 11:00:21 -06006485
6486 return s;
6487}
6488
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006489static BcStatus bc_program_execStr(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006490 bool cond)
6491{
6492 BcStatus s = BC_STATUS_SUCCESS;
6493 BcResult *r;
6494 char **str;
6495 BcFunc *f;
6496 BcParse prs;
6497 BcInstPtr ip;
6498 size_t fidx, sidx;
6499 BcNum *n;
6500 bool exec;
6501
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006502 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006503 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006504
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006505 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006506
6507 if (cond) {
6508
Gavin Howard01055ba2018-11-03 11:00:21 -06006509 char *name, *then_name = bc_program_name(code, bgn), *else_name = NULL;
6510
6511 if (code[*bgn] == BC_PARSE_STREND)
6512 (*bgn) += 1;
6513 else
6514 else_name = bc_program_name(code, bgn);
6515
6516 exec = r->d.n.len != 0;
6517
6518 if (exec)
6519 name = then_name;
6520 else if (else_name != NULL) {
6521 exec = true;
6522 name = else_name;
6523 }
6524
6525 if (exec) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006526 BcVec *v;
6527 v = bc_program_search(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006528 n = bc_vec_top(v);
6529 }
6530
6531 free(then_name);
6532 free(else_name);
6533
6534 if (!exec) goto exit;
6535 if (!BC_PROG_STR(n)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006536 s = bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006537 goto exit;
6538 }
6539
6540 sidx = n->rdx;
6541 }
6542 else {
6543
6544 if (r->t == BC_RESULT_STR)
6545 sidx = r->d.id.idx;
6546 else if (r->t == BC_RESULT_VAR) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006547 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006548 if (s || !BC_PROG_STR(n)) goto exit;
6549 sidx = n->rdx;
6550 }
6551 else
6552 goto exit;
6553 }
6554
6555 fidx = sidx + BC_PROG_REQ_FUNCS;
6556
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006557 str = bc_vec_item(&G.prog.strs, sidx);
6558 f = bc_vec_item(&G.prog.fns, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006559
6560 if (f->code.len == 0) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006561 common_parse_init(&prs, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006562 s = bc_parse_text(&prs, *str);
6563 if (s) goto err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01006564 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006565 if (s) goto err;
6566
6567 if (prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006568 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06006569 goto err;
6570 }
6571
6572 bc_parse_free(&prs);
6573 }
6574
6575 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006576 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006577 ip.func = fidx;
6578
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006579 bc_vec_pop(&G.prog.results);
6580 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006581
6582 return BC_STATUS_SUCCESS;
6583
6584err:
6585 bc_parse_free(&prs);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006586 f = bc_vec_item(&G.prog.fns, fidx);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006587 bc_vec_pop_all(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06006588exit:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006589 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006590 return s;
6591}
6592#endif // ENABLE_DC
6593
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006594static void bc_program_pushGlobal(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006595{
Gavin Howard01055ba2018-11-03 11:00:21 -06006596 BcResult res;
6597 unsigned long val;
6598
6599 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6600 if (inst == BC_INST_IBASE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006601 val = (unsigned long) G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006602 else if (inst == BC_INST_SCALE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006603 val = (unsigned long) G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006604 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006605 val = (unsigned long) G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006606
6607 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006608 bc_num_ulong2num(&res.d.n, val);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006609 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006610}
6611
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006612static void bc_program_addFunc(char *name, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006613{
Gavin Howard01055ba2018-11-03 11:00:21 -06006614 BcId entry, *entry_ptr;
6615 BcFunc f;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006616 int inserted;
Gavin Howard01055ba2018-11-03 11:00:21 -06006617
6618 entry.name = name;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006619 entry.idx = G.prog.fns.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006620
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006621 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6622 if (!inserted) free(name);
Gavin Howard01055ba2018-11-03 11:00:21 -06006623
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006624 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006625 *idx = entry_ptr->idx;
6626
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006627 if (!inserted) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006628
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006629 BcFunc *func = bc_vec_item(&G.prog.fns, entry_ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006630
6631 // We need to reset these, so the function can be repopulated.
6632 func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01006633 bc_vec_pop_all(&func->autos);
6634 bc_vec_pop_all(&func->code);
6635 bc_vec_pop_all(&func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06006636 }
6637 else {
6638 bc_func_init(&f);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006639 bc_vec_push(&G.prog.fns, &f);
Gavin Howard01055ba2018-11-03 11:00:21 -06006640 }
6641}
6642
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006643static BcStatus bc_program_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006644{
6645 BcStatus s = BC_STATUS_SUCCESS;
6646 size_t idx;
6647 BcResult r, *ptr;
6648 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006649 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6650 BcFunc *func = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006651 char *code = func->code.v;
6652 bool cond = false;
6653
6654 while (!s && ip->idx < func->code.len) {
6655
6656 char inst = code[(ip->idx)++];
6657
6658 switch (inst) {
6659
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006660#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006661 case BC_INST_JUMP_ZERO:
6662 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006663 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006664 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006665 cond = !bc_num_cmp(num, &G.prog.zero);
6666 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006667 }
6668 // Fallthrough.
6669 case BC_INST_JUMP:
6670 {
6671 size_t *addr;
6672 idx = bc_program_index(code, &ip->idx);
6673 addr = bc_vec_item(&func->labels, idx);
6674 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6675 break;
6676 }
6677
6678 case BC_INST_CALL:
6679 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006680 s = bc_program_call(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006681 break;
6682 }
6683
6684 case BC_INST_INC_PRE:
6685 case BC_INST_DEC_PRE:
6686 case BC_INST_INC_POST:
6687 case BC_INST_DEC_POST:
6688 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006689 s = bc_program_incdec(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006690 break;
6691 }
6692
6693 case BC_INST_HALT:
6694 {
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006695 QUIT_OR_RETURN_TO_MAIN;
Gavin Howard01055ba2018-11-03 11:00:21 -06006696 break;
6697 }
6698
6699 case BC_INST_RET:
6700 case BC_INST_RET0:
6701 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006702 s = bc_program_return(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006703 break;
6704 }
6705
6706 case BC_INST_BOOL_OR:
6707 case BC_INST_BOOL_AND:
6708#endif // ENABLE_BC
6709 case BC_INST_REL_EQ:
6710 case BC_INST_REL_LE:
6711 case BC_INST_REL_GE:
6712 case BC_INST_REL_NE:
6713 case BC_INST_REL_LT:
6714 case BC_INST_REL_GT:
6715 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006716 s = bc_program_logical(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006717 break;
6718 }
6719
6720 case BC_INST_READ:
6721 {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006722 s = bc_program_read();
Gavin Howard01055ba2018-11-03 11:00:21 -06006723 break;
6724 }
6725
6726 case BC_INST_VAR:
6727 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006728 s = bc_program_pushVar(code, &ip->idx, false, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006729 break;
6730 }
6731
6732 case BC_INST_ARRAY_ELEM:
6733 case BC_INST_ARRAY:
6734 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006735 s = bc_program_pushArray(code, &ip->idx, inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006736 break;
6737 }
6738
6739 case BC_INST_LAST:
6740 {
6741 r.t = BC_RESULT_LAST;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006742 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006743 break;
6744 }
6745
6746 case BC_INST_IBASE:
6747 case BC_INST_SCALE:
6748 case BC_INST_OBASE:
6749 {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006750 bc_program_pushGlobal(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006751 break;
6752 }
6753
6754 case BC_INST_SCALE_FUNC:
6755 case BC_INST_LENGTH:
6756 case BC_INST_SQRT:
6757 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006758 s = bc_program_builtin(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006759 break;
6760 }
6761
6762 case BC_INST_NUM:
6763 {
6764 r.t = BC_RESULT_CONSTANT;
6765 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006766 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006767 break;
6768 }
6769
6770 case BC_INST_POP:
6771 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006772 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006773 s = bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006774 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006775 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006776 break;
6777 }
6778
6779 case BC_INST_POP_EXEC:
6780 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006781 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006782 break;
6783 }
6784
6785 case BC_INST_PRINT:
6786 case BC_INST_PRINT_POP:
6787 case BC_INST_PRINT_STR:
6788 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006789 s = bc_program_print(inst, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006790 break;
6791 }
6792
6793 case BC_INST_STR:
6794 {
6795 r.t = BC_RESULT_STR;
6796 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006797 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006798 break;
6799 }
6800
6801 case BC_INST_POWER:
6802 case BC_INST_MULTIPLY:
6803 case BC_INST_DIVIDE:
6804 case BC_INST_MODULUS:
6805 case BC_INST_PLUS:
6806 case BC_INST_MINUS:
6807 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006808 s = bc_program_op(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006809 break;
6810 }
6811
6812 case BC_INST_BOOL_NOT:
6813 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006814 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006815 if (s) return s;
6816
6817 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006818 (!bc_num_cmp(num, &G.prog.zero) ? bc_num_one : bc_num_zero)(&r.d.n);
6819 bc_program_retire(&r, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006820
6821 break;
6822 }
6823
6824 case BC_INST_NEG:
6825 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006826 s = bc_program_negate();
Gavin Howard01055ba2018-11-03 11:00:21 -06006827 break;
6828 }
6829
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006830#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006831 case BC_INST_ASSIGN_POWER:
6832 case BC_INST_ASSIGN_MULTIPLY:
6833 case BC_INST_ASSIGN_DIVIDE:
6834 case BC_INST_ASSIGN_MODULUS:
6835 case BC_INST_ASSIGN_PLUS:
6836 case BC_INST_ASSIGN_MINUS:
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006837#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006838 case BC_INST_ASSIGN:
6839 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006840 s = bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006841 break;
6842 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006843#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006844 case BC_INST_MODEXP:
6845 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006846 s = bc_program_modexp();
Gavin Howard01055ba2018-11-03 11:00:21 -06006847 break;
6848 }
6849
6850 case BC_INST_DIVMOD:
6851 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006852 s = bc_program_divmod();
Gavin Howard01055ba2018-11-03 11:00:21 -06006853 break;
6854 }
6855
6856 case BC_INST_EXECUTE:
6857 case BC_INST_EXEC_COND:
6858 {
6859 cond = inst == BC_INST_EXEC_COND;
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006860 s = bc_program_execStr(code, &ip->idx, cond);
Gavin Howard01055ba2018-11-03 11:00:21 -06006861 break;
6862 }
6863
6864 case BC_INST_PRINT_STACK:
6865 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006866 for (idx = 0; !s && idx < G.prog.results.len; ++idx)
6867 s = bc_program_print(BC_INST_PRINT, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006868 break;
6869 }
6870
6871 case BC_INST_CLEAR_STACK:
6872 {
Denys Vlasenko7d628012018-12-04 21:46:47 +01006873 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006874 break;
6875 }
6876
6877 case BC_INST_STACK_LEN:
6878 {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006879 bc_program_stackLen();
Gavin Howard01055ba2018-11-03 11:00:21 -06006880 break;
6881 }
6882
6883 case BC_INST_DUPLICATE:
6884 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006885 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006886 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006887 ptr = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006888 bc_result_copy(&r, ptr);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006889 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006890 break;
6891 }
6892
6893 case BC_INST_SWAP:
6894 {
6895 BcResult *ptr2;
6896
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006897 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006898 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006899
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006900 ptr = bc_vec_item_rev(&G.prog.results, 0);
6901 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006902 memcpy(&r, ptr, sizeof(BcResult));
6903 memcpy(ptr, ptr2, sizeof(BcResult));
6904 memcpy(ptr2, &r, sizeof(BcResult));
6905
6906 break;
6907 }
6908
6909 case BC_INST_ASCIIFY:
6910 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006911 s = bc_program_asciify();
Gavin Howard01055ba2018-11-03 11:00:21 -06006912 break;
6913 }
6914
6915 case BC_INST_PRINT_STREAM:
6916 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006917 s = bc_program_printStream();
Gavin Howard01055ba2018-11-03 11:00:21 -06006918 break;
6919 }
6920
6921 case BC_INST_LOAD:
6922 case BC_INST_PUSH_VAR:
6923 {
6924 bool copy = inst == BC_INST_LOAD;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006925 s = bc_program_pushVar(code, &ip->idx, true, copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006926 break;
6927 }
6928
6929 case BC_INST_PUSH_TO_VAR:
6930 {
6931 char *name = bc_program_name(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006932 s = bc_program_copyToVar(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006933 free(name);
6934 break;
6935 }
6936
6937 case BC_INST_QUIT:
6938 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006939 if (G.prog.stack.len <= 2)
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01006940 QUIT_OR_RETURN_TO_MAIN;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006941 bc_vec_npop(&G.prog.stack, 2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006942 break;
6943 }
6944
6945 case BC_INST_NQUIT:
6946 {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006947 s = bc_program_nquit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006948 break;
6949 }
6950#endif // ENABLE_DC
6951 }
6952
Denys Vlasenkod38af482018-12-04 19:11:02 +01006953 if (s || G_interrupt) {
6954 bc_program_reset();
6955 break;
6956 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006957
6958 // If the stack has changed, pointers may be invalid.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006959 ip = bc_vec_top(&G.prog.stack);
6960 func = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006961 code = func->code.v;
6962 }
6963
6964 return s;
6965}
6966
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006967#if ENABLE_BC
Denys Vlasenko54214c32018-12-06 09:07:06 +01006968static void bc_vm_info(void)
6969{
6970 printf("%s "BB_VER"\n"
6971 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
Denys Vlasenko54214c32018-12-06 09:07:06 +01006972 , applet_name);
6973}
6974
6975static void bc_args(char **argv)
6976{
6977 unsigned opts;
6978 int i;
6979
6980 GETOPT_RESET();
6981#if ENABLE_FEATURE_BC_LONG_OPTIONS
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006982 opts = option_mask32 |= getopt32long(argv, "wvsqli",
Denys Vlasenko54214c32018-12-06 09:07:06 +01006983 "warn\0" No_argument "w"
6984 "version\0" No_argument "v"
6985 "standard\0" No_argument "s"
6986 "quiet\0" No_argument "q"
6987 "mathlib\0" No_argument "l"
6988 "interactive\0" No_argument "i"
6989 );
6990#else
Denys Vlasenko6d0be102018-12-06 18:41:59 +01006991 opts = option_mask32 |= getopt32(argv, "wvsqli");
Denys Vlasenko54214c32018-12-06 09:07:06 +01006992#endif
6993 if (getenv("POSIXLY_CORRECT"))
6994 option_mask32 |= BC_FLAG_S;
6995
Denys Vlasenko54214c32018-12-06 09:07:06 +01006996 if (opts & BC_FLAG_V) {
6997 bc_vm_info();
6998 exit(0);
6999 }
7000
7001 for (i = optind; argv[i]; ++i)
7002 bc_vec_push(&G.files, argv + i);
7003}
7004
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007005static void bc_vm_envArgs(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007006{
Gavin Howard01055ba2018-11-03 11:00:21 -06007007 BcVec v;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007008 char *buf;
Denys Vlasenko54214c32018-12-06 09:07:06 +01007009 char *env_args = getenv("BC_ENV_ARGS");
Gavin Howard01055ba2018-11-03 11:00:21 -06007010
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007011 if (!env_args) return;
Gavin Howard01055ba2018-11-03 11:00:21 -06007012
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007013 G.env_args = xstrdup(env_args);
7014 buf = G.env_args;
Gavin Howard01055ba2018-11-03 11:00:21 -06007015
7016 bc_vec_init(&v, sizeof(char *), NULL);
Gavin Howard01055ba2018-11-03 11:00:21 -06007017
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007018 while (*(buf = skip_whitespace(buf)) != '\0') {
7019 bc_vec_push(&v, &buf);
7020 buf = skip_non_whitespace(buf);
7021 if (!*buf)
7022 break;
7023 *buf++ = '\0';
Gavin Howard01055ba2018-11-03 11:00:21 -06007024 }
7025
Denys Vlasenko54214c32018-12-06 09:07:06 +01007026 // NULL terminate, and pass argv[] so that first arg is argv[1]
7027 if (sizeof(int) == sizeof(char*)) {
7028 bc_vec_push(&v, &const_int_0);
7029 } else {
7030 static char *const nullptr = NULL;
7031 bc_vec_push(&v, &nullptr);
7032 }
7033 bc_args(((char **)v.v) - 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06007034
7035 bc_vec_free(&v);
Gavin Howard01055ba2018-11-03 11:00:21 -06007036}
7037#endif // ENABLE_BC
7038
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007039static unsigned bc_vm_envLen(const char *var)
Gavin Howard01055ba2018-11-03 11:00:21 -06007040{
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007041 char *lenv;
7042 unsigned len;
Gavin Howard01055ba2018-11-03 11:00:21 -06007043
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007044 lenv = getenv(var);
7045 len = BC_NUM_PRINT_WIDTH;
Gavin Howard01055ba2018-11-03 11:00:21 -06007046 if (!lenv) return len;
7047
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007048 len = bb_strtou(lenv, NULL, 10) - 1;
7049 if (errno || len < 2 || len >= INT_MAX)
Gavin Howard01055ba2018-11-03 11:00:21 -06007050 len = BC_NUM_PRINT_WIDTH;
7051
7052 return len;
7053}
7054
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007055static BcStatus bc_vm_process(const char *text)
Gavin Howard01055ba2018-11-03 11:00:21 -06007056{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007057 BcStatus s = bc_parse_text(&G.prs, text);
Gavin Howard01055ba2018-11-03 11:00:21 -06007058
Gavin Howard01055ba2018-11-03 11:00:21 -06007059 if (s) return s;
7060
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007061 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007062 s = G.prs.parse(&G.prs);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01007063 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007064 }
7065
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007066 if (BC_PARSE_CAN_EXEC(&G.prs)) {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007067 s = bc_program_exec();
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01007068 fflush_and_check();
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007069 if (s)
Denys Vlasenkod38af482018-12-04 19:11:02 +01007070 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06007071 }
7072
7073 return s;
7074}
7075
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007076static BcStatus bc_vm_file(const char *file)
Gavin Howard01055ba2018-11-03 11:00:21 -06007077{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007078 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007079 char *data;
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007080 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007081 BcFunc *main_func;
7082 BcInstPtr *ip;
7083
Denys Vlasenkodf515392018-12-02 19:27:48 +01007084 data = bc_read_file(file);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007085 if (!data) return bc_error_fmt("file '%s' is not text", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007086
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007087 sv_file = G.prog.file;
7088 G.prog.file = file;
7089 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007090 s = bc_vm_process(data);
Gavin Howard01055ba2018-11-03 11:00:21 -06007091 if (s) goto err;
7092
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007093 main_func = bc_vec_item(&G.prog.fns, BC_PROG_MAIN);
7094 ip = bc_vec_item(&G.prog.stack, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06007095
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007096 if (main_func->code.len < ip->idx)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007097 s = bc_error_fmt("file '%s' is not executable", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007098
7099err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007100 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007101 free(data);
7102 return s;
7103}
7104
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007105static BcStatus bc_vm_stdin(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007106{
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007107 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007108 BcVec buf, buffer;
Gavin Howard01055ba2018-11-03 11:00:21 -06007109 size_t len, i, str = 0;
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007110 bool comment = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06007111
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007112 G.prog.file = NULL;
7113 bc_lex_file(&G.prs.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06007114
Denys Vlasenko7d628012018-12-04 21:46:47 +01007115 bc_char_vec_init(&buffer);
7116 bc_char_vec_init(&buf);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01007117 bc_vec_pushZeroByte(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007118
7119 // This loop is complex because the vm tries not to send any lines that end
7120 // with a backslash to the parser. The reason for that is because the parser
7121 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7122 // case, and for strings and comments, the parser will expect more stuff.
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007123 while ((s = bc_read_line(&buf)) == BC_STATUS_SUCCESS) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007124
7125 char *string = buf.v;
7126
7127 len = buf.len - 1;
7128
7129 if (len == 1) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007130 if (str && buf.v[0] == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007131 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007132 else if (buf.v[0] == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007133 str += 1;
7134 }
7135 else if (len > 1 || comment) {
7136
7137 for (i = 0; i < len; ++i) {
7138
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007139 bool notend = len > i + 1;
7140 char c = string[i];
Gavin Howard01055ba2018-11-03 11:00:21 -06007141
7142 if (i - 1 > len || string[i - 1] != '\\') {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007143 if (G.sbgn == G.send)
7144 str ^= c == G.sbgn;
7145 else if (c == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007146 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007147 else if (c == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007148 str += 1;
7149 }
7150
7151 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7152 comment = true;
7153 break;
7154 }
7155 else if (c == '*' && notend && comment && string[i + 1] == '/')
7156 comment = false;
7157 }
7158
7159 if (str || comment || string[len - 2] == '\\') {
7160 bc_vec_concat(&buffer, buf.v);
7161 continue;
7162 }
7163 }
7164
7165 bc_vec_concat(&buffer, buf.v);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007166 s = bc_vm_process(buffer.v);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007167 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007168 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007169 // Debug config, non-interactive mode:
7170 // return all the way back to main.
7171 // Non-debug builds do not come here, they exit.
7172 break;
7173 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007174 fflush_and_check();
7175 fputs("ready for more input\n", stderr);
7176 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007177
Denys Vlasenko7d628012018-12-04 21:46:47 +01007178 bc_vec_pop_all(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007179 }
Denys Vlasenkof522dd92018-12-07 16:35:43 +01007180 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7181 s = BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06007182
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007183 if (str) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007184 s = bc_error("string end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007185 }
7186 else if (comment) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007187 s = bc_error("comment end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007188 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007189
Gavin Howard01055ba2018-11-03 11:00:21 -06007190 bc_vec_free(&buf);
7191 bc_vec_free(&buffer);
7192 return s;
7193}
7194
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007195#if ENABLE_BC
7196static const char bc_lib[] = {
7197 "scale=20"
7198"\n" "define e(x){"
7199"\n" "auto b,s,n,r,d,i,p,f,v"
7200"\n" "b=ibase"
7201"\n" "ibase=A"
7202"\n" "if(x<0){"
7203"\n" "n=1"
7204"\n" "x=-x"
7205"\n" "}"
7206"\n" "s=scale"
7207"\n" "r=6+s+0.44*x"
7208"\n" "scale=scale(x)+1"
7209"\n" "while(x>1){"
7210"\n" "d+=1"
7211"\n" "x/=2"
7212"\n" "scale+=1"
7213"\n" "}"
7214"\n" "scale=r"
7215"\n" "r=x+1"
7216"\n" "p=x"
7217"\n" "f=v=1"
7218"\n" "for(i=2;v!=0;++i){"
7219"\n" "p*=x"
7220"\n" "f*=i"
7221"\n" "v=p/f"
7222"\n" "r+=v"
7223"\n" "}"
7224"\n" "while((d--)!=0)r*=r"
7225"\n" "scale=s"
7226"\n" "ibase=b"
7227"\n" "if(n!=0)return(1/r)"
7228"\n" "return(r/1)"
7229"\n" "}"
7230"\n" "define l(x){"
7231"\n" "auto b,s,r,p,a,q,i,v"
7232"\n" "b=ibase"
7233"\n" "ibase=A"
7234"\n" "if(x<=0){"
7235"\n" "r=(1-10^scale)/1"
7236"\n" "ibase=b"
7237"\n" "return(r)"
7238"\n" "}"
7239"\n" "s=scale"
7240"\n" "scale+=6"
7241"\n" "p=2"
7242"\n" "while(x>=2){"
7243"\n" "p*=2"
7244"\n" "x=sqrt(x)"
7245"\n" "}"
7246"\n" "while(x<=0.5){"
7247"\n" "p*=2"
7248"\n" "x=sqrt(x)"
7249"\n" "}"
7250"\n" "r=a=(x-1)/(x+1)"
7251"\n" "q=a*a"
7252"\n" "v=1"
7253"\n" "for(i=3;v!=0;i+=2){"
7254"\n" "a*=q"
7255"\n" "v=a/i"
7256"\n" "r+=v"
7257"\n" "}"
7258"\n" "r*=p"
7259"\n" "scale=s"
7260"\n" "ibase=b"
7261"\n" "return(r/1)"
7262"\n" "}"
7263"\n" "define s(x){"
7264"\n" "auto b,s,r,n,a,q,i"
7265"\n" "b=ibase"
7266"\n" "ibase=A"
7267"\n" "s=scale"
7268"\n" "scale=1.1*s+2"
7269"\n" "a=a(1)"
7270"\n" "if(x<0){"
7271"\n" "n=1"
7272"\n" "x=-x"
7273"\n" "}"
7274"\n" "scale=0"
7275"\n" "q=(x/a+2)/4"
7276"\n" "x=x-4*q*a"
7277"\n" "if(q%2!=0)x=-x"
7278"\n" "scale=s+2"
7279"\n" "r=a=x"
7280"\n" "q=-x*x"
7281"\n" "for(i=3;a!=0;i+=2){"
7282"\n" "a*=q/(i*(i-1))"
7283"\n" "r+=a"
7284"\n" "}"
7285"\n" "scale=s"
7286"\n" "ibase=b"
7287"\n" "if(n!=0)return(-r/1)"
7288"\n" "return(r/1)"
7289"\n" "}"
7290"\n" "define c(x){"
7291"\n" "auto b,s"
7292"\n" "b=ibase"
7293"\n" "ibase=A"
7294"\n" "s=scale"
7295"\n" "scale*=1.2"
7296"\n" "x=s(2*a(1)+x)"
7297"\n" "scale=s"
7298"\n" "ibase=b"
7299"\n" "return(x/1)"
7300"\n" "}"
7301"\n" "define a(x){"
7302"\n" "auto b,s,r,n,a,m,t,f,i,u"
7303"\n" "b=ibase"
7304"\n" "ibase=A"
7305"\n" "n=1"
7306"\n" "if(x<0){"
7307"\n" "n=-1"
7308"\n" "x=-x"
7309"\n" "}"
7310"\n" "if(x==1){"
7311"\n" "if(scale<65){"
7312"\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7313"\n" "}"
7314"\n" "}"
7315"\n" "if(x==.2){"
7316"\n" "if(scale<65){"
7317"\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7318"\n" "}"
7319"\n" "}"
7320"\n" "s=scale"
7321"\n" "if(x>.2){"
7322"\n" "scale+=5"
7323"\n" "a=a(.2)"
7324"\n" "}"
7325"\n" "scale=s+3"
7326"\n" "while(x>.2){"
7327"\n" "m+=1"
7328"\n" "x=(x-.2)/(1+.2*x)"
7329"\n" "}"
7330"\n" "r=u=x"
7331"\n" "f=-x*x"
7332"\n" "t=1"
7333"\n" "for(i=3;t!=0;i+=2){"
7334"\n" "u*=f"
7335"\n" "t=u/i"
7336"\n" "r+=t"
7337"\n" "}"
7338"\n" "scale=s"
7339"\n" "ibase=b"
7340"\n" "return((m*a+r)/n)"
7341"\n" "}"
7342"\n" "define j(n,x){"
7343"\n" "auto b,s,o,a,i,v,f"
7344"\n" "b=ibase"
7345"\n" "ibase=A"
7346"\n" "s=scale"
7347"\n" "scale=0"
7348"\n" "n/=1"
7349"\n" "if(n<0){"
7350"\n" "n=-n"
7351"\n" "if(n%2==1)o=1"
7352"\n" "}"
7353"\n" "a=1"
7354"\n" "for(i=2;i<=n;++i)a*=i"
7355"\n" "scale=1.5*s"
7356"\n" "a=(x^n)/2^n/a"
7357"\n" "r=v=1"
7358"\n" "f=-x*x/4"
7359"\n" "scale=scale+length(a)-scale(a)"
7360"\n" "for(i=1;v!=0;++i){"
7361"\n" "v=v*f/i/(n+i)"
7362"\n" "r+=v"
7363"\n" "}"
7364"\n" "scale=s"
7365"\n" "ibase=b"
7366"\n" "if(o!=0)a=-a"
7367"\n" "return(a*r/1)"
7368"\n" "}"
7369};
7370#endif // ENABLE_BC
7371
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007372static BcStatus bc_vm_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007373{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007374 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007375 size_t i;
7376
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007377#if ENABLE_BC
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007378 if (option_mask32 & BC_FLAG_L) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007379
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007380 // We know that internal library is not buggy,
7381 // thus error checking is normally disabled.
7382# define DEBUG_LIB 0
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007383 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007384 s = bc_parse_text(&G.prs, bc_lib);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007385 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007386
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007387 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007388 s = G.prs.parse(&G.prs);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007389 if (DEBUG_LIB && s) return s;
7390 }
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007391 s = bc_program_exec();
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007392 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007393 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007394#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007395
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007396 s = BC_STATUS_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007397 for (i = 0; !s && i < G.files.len; ++i)
7398 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007399 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7400 // Debug config, non-interactive mode:
7401 // return all the way back to main.
7402 // Non-debug builds do not come here, they exit.
7403 return s;
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007404 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007405
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007406 if (IS_BC || (option_mask32 & BC_FLAG_I)) {
7407 if (s) {
7408 fflush_and_check();
7409 fputs("ready for more input\n", stderr);
7410 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007411 s = bc_vm_stdin();
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007412 }
7413
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007414 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7415 s = bc_vm_process("");
Gavin Howard01055ba2018-11-03 11:00:21 -06007416
Denys Vlasenko00d77792018-11-30 23:13:42 +01007417 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007418}
7419
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007420#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007421static void bc_program_free(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007422{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007423 bc_num_free(&G.prog.ib);
7424 bc_num_free(&G.prog.ob);
7425 bc_num_free(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007426# if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007427 bc_num_free(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007428# endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007429 bc_vec_free(&G.prog.fns);
7430 bc_vec_free(&G.prog.fn_map);
7431 bc_vec_free(&G.prog.vars);
7432 bc_vec_free(&G.prog.var_map);
7433 bc_vec_free(&G.prog.arrs);
7434 bc_vec_free(&G.prog.arr_map);
7435 bc_vec_free(&G.prog.strs);
7436 bc_vec_free(&G.prog.consts);
7437 bc_vec_free(&G.prog.results);
7438 bc_vec_free(&G.prog.stack);
7439 bc_num_free(&G.prog.last);
7440 bc_num_free(&G.prog.zero);
7441 bc_num_free(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007442}
7443
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007444static void bc_vm_free(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007445{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007446 bc_vec_free(&G.files);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007447 bc_program_free();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007448 bc_parse_free(&G.prs);
7449 free(G.env_args);
Gavin Howard01055ba2018-11-03 11:00:21 -06007450}
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007451#endif
7452
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007453static void bc_program_init(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007454{
7455 size_t idx;
7456 BcInstPtr ip;
7457
7458 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7459 memset(&ip, 0, sizeof(BcInstPtr));
7460
7461 /* G.prog.nchars = G.prog.scale = 0; - already is */
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007462
7463 bc_num_init(&G.prog.ib, BC_NUM_DEF_SIZE);
7464 bc_num_ten(&G.prog.ib);
7465 G.prog.ib_t = 10;
7466
7467 bc_num_init(&G.prog.ob, BC_NUM_DEF_SIZE);
7468 bc_num_ten(&G.prog.ob);
7469 G.prog.ob_t = 10;
7470
7471 bc_num_init(&G.prog.hexb, BC_NUM_DEF_SIZE);
7472 bc_num_ten(&G.prog.hexb);
7473 G.prog.hexb.num[0] = 6;
7474
7475#if ENABLE_DC
7476 bc_num_init(&G.prog.strmb, BC_NUM_DEF_SIZE);
7477 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7478#endif
7479
7480 bc_num_init(&G.prog.last, BC_NUM_DEF_SIZE);
7481 bc_num_zero(&G.prog.last);
7482
7483 bc_num_init(&G.prog.zero, BC_NUM_DEF_SIZE);
7484 bc_num_zero(&G.prog.zero);
7485
7486 bc_num_init(&G.prog.one, BC_NUM_DEF_SIZE);
7487 bc_num_one(&G.prog.one);
7488
7489 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007490 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007491
Denys Vlasenko1f67e932018-12-03 00:08:59 +01007492 bc_program_addFunc(xstrdup("(main)"), &idx);
7493 bc_program_addFunc(xstrdup("(read)"), &idx);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007494
7495 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007496 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007497
7498 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007499 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007500
7501 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7502 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7503 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7504 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7505 bc_vec_push(&G.prog.stack, &ip);
7506}
Gavin Howard01055ba2018-11-03 11:00:21 -06007507
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007508static int bc_vm_init(const char *env_len)
Gavin Howard01055ba2018-11-03 11:00:21 -06007509{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007510#if ENABLE_FEATURE_EDITING
7511 G.line_input_state = new_line_input_t(DO_HISTORY);
7512#endif
7513 G.prog.len = bc_vm_envLen(env_len);
7514
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007515 bc_vec_init(&G.files, sizeof(char *), NULL);
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007516 if (IS_BC)
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007517 IF_BC(bc_vm_envArgs();)
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007518 bc_program_init();
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007519 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007520 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007521 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007522 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007523 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007524
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007525 if (isatty(0)) {
Denys Vlasenkod38af482018-12-04 19:11:02 +01007526#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007527 G_ttyin = 1;
Denys Vlasenko17c54722018-12-04 21:21:32 +01007528 // With SA_RESTART, most system calls will restart
7529 // (IOW: they won't fail with EINTR).
7530 // In particular, this means ^C won't cause
7531 // stdout to get into "error state" if SIGINT hits
7532 // within write() syscall.
7533 // The downside is that ^C while line input is taken
7534 // will only be handled after [Enter] since read()
7535 // from stdin is not interrupted by ^C either,
7536 // it restarts, thus fgetc() does not return on ^C.
7537 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7538
7539 // Without SA_RESTART, this exhibits a bug:
7540 // "while (1) print 1" and try ^C-ing it.
7541 // Intermittently, instead of returning to input line,
7542 // you'll get "output error: Interrupted system call"
7543 // and exit.
7544 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
Denys Vlasenkod38af482018-12-04 19:11:02 +01007545#endif
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007546 return 1; // "tty"
Denys Vlasenkod38af482018-12-04 19:11:02 +01007547 }
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007548 return 0; // "not a tty"
7549}
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007550
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007551static BcStatus bc_vm_run(void)
7552{
7553 BcStatus st = bc_vm_exec();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007554#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoc7a7ce02018-12-06 23:06:57 +01007555 if (G_exiting) // it was actually "halt" or "quit"
7556 st = EXIT_SUCCESS;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007557 bc_vm_free();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007558# if ENABLE_FEATURE_EDITING
7559 free_line_input_t(G.line_input_state);
7560# endif
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007561 FREE_G();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007562#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007563 return st;
7564}
7565
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007566#if ENABLE_BC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007567int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007568int bc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007569{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007570 int is_tty;
7571
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007572 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007573 G.sbgn = G.send = '"';
Gavin Howard01055ba2018-11-03 11:00:21 -06007574
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007575 is_tty = bc_vm_init("BC_LINE_LENGTH");
7576
7577 bc_args(argv);
7578
7579 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7580 bc_vm_info();
7581
7582 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007583}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007584#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007585
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007586#if ENABLE_DC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007587int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007588int dc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007589{
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007590 int noscript;
7591
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007592 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007593 G.sbgn = '[';
7594 G.send = ']';
Denys Vlasenko6e7c65f2018-12-08 19:34:35 +01007595 /*
7596 * TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7597 * 1 char wider than bc from the same package.
7598 * Both default width, and xC_LINE_LENGTH=N are wider:
7599 * "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7600 * 1234\
7601 * 56
7602 * "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7603 * 123\
7604 * 456
7605 * Do the same, or it's a bug?
7606 */
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007607 bc_vm_init("DC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007608
Denys Vlasenko6d0be102018-12-06 18:41:59 +01007609 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7610 noscript = BC_FLAG_I;
7611 for (;;) {
7612 int n = getopt(argc, argv, "e:f:x");
7613 if (n <= 0)
7614 break;
7615 switch (n) {
7616 case 'e':
7617 noscript = 0;
7618 n = bc_vm_process(optarg);
7619 if (n) return n;
7620 break;
7621 case 'f':
7622 noscript = 0;
7623 bc_vm_file(optarg);
7624 break;
7625 case 'x':
7626 option_mask32 |= DC_FLAG_X;
7627 break;
7628 default:
7629 bb_show_usage();
7630 }
7631 }
7632 argv += optind;
7633
7634 while (*argv) {
7635 noscript = 0;
7636 bc_vec_push(&G.files, argv++);
7637 }
7638
7639 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7640
7641 return bc_vm_run();
Gavin Howard01055ba2018-11-03 11:00:21 -06007642}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007643#endif
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +01007644
7645#endif // not DC_SMALL