blob: 3d53db77815666f8b5431ec2bfad01a5cc2b2605 [file] [log] [blame]
Gavin Howard01055ba2018-11-03 11:00:21 -06001/* vi: set sw=4 ts=4: */
2/*
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Copyright (c) 2018 Gavin D. Howard and contributors.
5 *
6 * ** Automatically generated from https://github.com/gavinhoward/bc **
7 * ** Do not edit unless you know what you are doing. **
8 */
9//config:config BC
10//config: bool "bc (45 kb; 49 kb when combined with dc)"
11//config: default y
12//config: help
13//config: bc is a command-line, arbitrary-precision calculator with a
14//config: Turing-complete language. See the GNU bc manual
15//config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
16//config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
17//config: for details.
18//config:
19//config: This bc has four differences to the GNU bc:
20//config:
21//config: 1) The period (.) can also be used as a shortcut for "last", as in
22//config: the BSD bc.
23//config: 2) Arrays are copied before being passed as arguments to
24//config: functions. This behavior is required by the bc spec.
25//config: 3) Arrays can be passed to the builtin "length" function to get
26//config: the number of elements currently in the array. The following
27//config: example prints "1":
28//config:
29//config: a[0] = 0
30//config: length(a[])
31//config:
32//config: 4) The precedence of the boolean "not" operator (!) is equal to
33//config: that of the unary minus (-), or negation, operator. This still
34//config: allows POSIX-compliant scripts to work while somewhat
35//config: preserving expected behavior (versus C) and making parsing
36//config: easier.
37//config:
38//config: Options:
39//config:
40//config: -i --interactive force interactive mode
41//config: -l --mathlib use predefined math routines:
42//config:
43//config: s(expr) = sine of expr in radians
44//config: c(expr) = cosine of expr in radians
45//config: a(expr) = arctangent of expr, returning
46//config: radians
47//config: l(expr) = natural log of expr
48//config: e(expr) = raises e to the power of expr
49//config: j(n, x) = Bessel function of integer order
50//config: n of x
51//config:
52//config: -q --quiet don't print version and copyright.
53//config: -s --standard error if any non-POSIX extensions are used.
54//config: -w --warn warn if any non-POSIX extensions are used.
55//config: -v --version print version and copyright and exit.
56//config:
57//config: Long options are only available if FEATURE_BC_LONG_OPTIONS is
58//config: enabled.
59//config:
60//config:config DC
61//config: bool "dc (38 kb; 49 kb when combined with bc)"
62//config: default y
63//config: help
64//config: dc is a reverse-polish notation command-line calculator which
65//config: supports unlimited precision arithmetic. See the FreeBSD man page
66//config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
67//config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
68//config: for details.
69//config:
70//config: This dc has a few differences from the two above:
71//config:
72//config: 1) When printing a byte stream (command "P"), this bc follows what
73//config: the FreeBSD dc does.
74//config: 2) This dc implements the GNU extensions for divmod ("~") and
75//config: modular exponentiation ("|").
76//config: 3) This dc implements all FreeBSD extensions, except for "J" and
77//config: "M".
78//config: 4) Like the FreeBSD dc, this dc supports extended registers.
79//config: However, they are implemented differently. When it encounters
80//config: whitespace where a register should be, it skips the whitespace.
81//config: If the character following is not a lowercase letter, an error
82//config: is issued. Otherwise, the register name is parsed by the
83//config: following regex:
84//config:
85//config: [a-z][a-z0-9_]*
86//config:
87//config: This generally means that register names will be surrounded by
88//config: whitespace.
89//config:
90//config: Examples:
91//config:
92//config: l idx s temp L index S temp2 < do_thing
93//config:
94//config: Also note that, like the FreeBSD dc, extended registers are not
95//config: allowed unless the "-x" option is given.
96//config:
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +010097//config:config FEATURE_DC_SMALL
98//config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
99//config: depends on DC && !BC
100//config: default y
101//config:
102//config:config FEATURE_DC_LIBM
103//config: bool "Enable power and exp functions (requires libm)"
104//config: default y
105//config: depends on FEATURE_DC_SMALL
106//config: help
107//config: Enable power and exp functions.
108//config: NOTE: This will require libm to be present for linking.
109//config:
Gavin Howard01055ba2018-11-03 11:00:21 -0600110//config:config FEATURE_BC_SIGNALS
111//config: bool "Enable bc/dc signal handling"
112//config: default y
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100113//config: depends on (BC || DC) && !FEATURE_DC_SMALL
Gavin Howard01055ba2018-11-03 11:00:21 -0600114//config: help
115//config: Enable signal handling for bc and dc.
116//config:
117//config:config FEATURE_BC_LONG_OPTIONS
118//config: bool "Enable bc/dc long options"
119//config: default y
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100120//config: depends on (BC || DC) && !FEATURE_DC_SMALL
Gavin Howard01055ba2018-11-03 11:00:21 -0600121//config: help
122//config: Enable long options for bc and dc.
123
124//applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
125//applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
126
127//kbuild:lib-$(CONFIG_BC) += bc.o
128//kbuild:lib-$(CONFIG_DC) += bc.o
129
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100130//See www.gnu.org/software/bc/manual/bc.html
Gavin Howard01055ba2018-11-03 11:00:21 -0600131//usage:#define bc_trivial_usage
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100132//usage: "[-sqliw] FILE..."
Gavin Howard01055ba2018-11-03 11:00:21 -0600133//usage:
Denys Vlasenko9721f6c2018-12-02 20:34:03 +0100134//usage:#define bc_full_usage "\n"
135//usage: "\nArbitrary precision calculator"
136//usage: "\n"
137//usage: "\n -i Interactive"
138//usage: "\n -l Load standard math library"
139//usage: "\n -s Be POSIX compatible"
140//usage: "\n -q Quiet"
141//usage: "\n -w Warn if extensions are used"
142///////: "\n -v Version"
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100143//usage: "\n$BC_LINE_LENGTH changes output width"
Gavin Howard01055ba2018-11-03 11:00:21 -0600144//usage:
145//usage:#define bc_example_usage
146//usage: "3 + 4.129\n"
147//usage: "1903 - 2893\n"
148//usage: "-129 * 213.28935\n"
149//usage: "12 / -1932\n"
150//usage: "12 % 12\n"
151//usage: "34 ^ 189\n"
152//usage: "scale = 13\n"
153//usage: "ibase = 2\n"
154//usage: "obase = A\n"
155//usage:
156//usage:#define dc_trivial_usage
157//usage: "EXPRESSION..."
158//usage:
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100159//usage:#define dc_full_usage "\n"
160//usage: "\nTiny RPN calculator. Operations:"
161//usage: "\n+, add, -, sub, *, mul, /, div, %, mod, ^, exp, ~, divmod, |, "
162//usage: "modular exponentiation,"
163//usage: "\np - print top of the stack (without popping),"
164//usage: "\nf - print entire stack,"
165//usage: "\nk - pop the value and set the precision."
166//usage: "\ni - pop the value and set input radix."
167//usage: "\no - pop the value and set output radix."
168//usage: "\nExamples: 'dc 2 2 add p' -> 4, 'dc 8 8 mul 2 2 + / p' -> 16"
Gavin Howard01055ba2018-11-03 11:00:21 -0600169//usage:
170//usage:#define dc_example_usage
171//usage: "$ dc 2 2 + p\n"
172//usage: "4\n"
173//usage: "$ dc 8 8 \\* 2 2 + / p\n"
174//usage: "16\n"
175//usage: "$ dc 0 1 and p\n"
176//usage: "0\n"
177//usage: "$ dc 0 1 or p\n"
178//usage: "1\n"
179//usage: "$ echo 72 9 div 8 mul p | dc\n"
180//usage: "64\n"
181
182#include "libbb.h"
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100183#include "common_bufsiz.h"
Gavin Howard01055ba2018-11-03 11:00:21 -0600184
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +0100185#if ENABLE_FEATURE_DC_SMALL
186# include "dc.c"
187#else
188
Gavin Howard01055ba2018-11-03 11:00:21 -0600189typedef enum BcStatus {
Denys Vlasenko60cf7472018-12-04 20:05:28 +0100190 BC_STATUS_SUCCESS = 0,
191 BC_STATUS_FAILURE = 1,
192 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
Gavin Howard01055ba2018-11-03 11:00:21 -0600193} BcStatus;
194
Gavin Howard01055ba2018-11-03 11:00:21 -0600195#define BC_VEC_INVALID_IDX ((size_t) -1)
196#define BC_VEC_START_CAP (1 << 5)
197
198typedef void (*BcVecFree)(void *);
Gavin Howard01055ba2018-11-03 11:00:21 -0600199
200typedef struct BcVec {
201 char *v;
202 size_t len;
203 size_t cap;
204 size_t size;
205 BcVecFree dtor;
206} BcVec;
207
Gavin Howard01055ba2018-11-03 11:00:21 -0600208typedef signed char BcDig;
209
210typedef struct BcNum {
211 BcDig *restrict num;
212 size_t rdx;
213 size_t len;
214 size_t cap;
215 bool neg;
216} BcNum;
217
Denys Vlasenko2fa11b62018-12-06 12:34:39 +0100218#define BC_NUM_MIN_BASE ((unsigned long) 2)
219#define BC_NUM_MAX_IBASE ((unsigned long) 16)
220// larger value might speed up BIGNUM calculations a bit:
221#define BC_NUM_DEF_SIZE (16)
222#define BC_NUM_PRINT_WIDTH (69)
Gavin Howard01055ba2018-11-03 11:00:21 -0600223
Denys Vlasenko2fa11b62018-12-06 12:34:39 +0100224#define BC_NUM_KARATSUBA_LEN (32)
Gavin Howard01055ba2018-11-03 11:00:21 -0600225
Denys Vlasenko2fa11b62018-12-06 12:34:39 +0100226#define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
227#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
228#define BC_NUM_INT(n) ((n)->len - (n)->rdx)
Gavin Howard01055ba2018-11-03 11:00:21 -0600229#define BC_NUM_AREQ(a, b) \
230 (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
231#define BC_NUM_MREQ(a, b, scale) \
232 (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
233
234typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
235typedef void (*BcNumDigitOp)(size_t, size_t, bool, size_t *, size_t);
236
Gavin Howard01055ba2018-11-03 11:00:21 -0600237static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
238static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
239static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
240static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
241static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
242static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
243static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
244static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
245 size_t scale);
246
247typedef enum BcInst {
248
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100249#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600250 BC_INST_INC_PRE,
251 BC_INST_DEC_PRE,
252 BC_INST_INC_POST,
253 BC_INST_DEC_POST,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100254#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600255
256 BC_INST_NEG,
257
258 BC_INST_POWER,
259 BC_INST_MULTIPLY,
260 BC_INST_DIVIDE,
261 BC_INST_MODULUS,
262 BC_INST_PLUS,
263 BC_INST_MINUS,
264
265 BC_INST_REL_EQ,
266 BC_INST_REL_LE,
267 BC_INST_REL_GE,
268 BC_INST_REL_NE,
269 BC_INST_REL_LT,
270 BC_INST_REL_GT,
271
272 BC_INST_BOOL_NOT,
273 BC_INST_BOOL_OR,
274 BC_INST_BOOL_AND,
275
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100276#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600277 BC_INST_ASSIGN_POWER,
278 BC_INST_ASSIGN_MULTIPLY,
279 BC_INST_ASSIGN_DIVIDE,
280 BC_INST_ASSIGN_MODULUS,
281 BC_INST_ASSIGN_PLUS,
282 BC_INST_ASSIGN_MINUS,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100283#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600284 BC_INST_ASSIGN,
285
286 BC_INST_NUM,
287 BC_INST_VAR,
288 BC_INST_ARRAY_ELEM,
289 BC_INST_ARRAY,
290
291 BC_INST_SCALE_FUNC,
292 BC_INST_IBASE,
293 BC_INST_SCALE,
294 BC_INST_LAST,
295 BC_INST_LENGTH,
296 BC_INST_READ,
297 BC_INST_OBASE,
298 BC_INST_SQRT,
299
300 BC_INST_PRINT,
301 BC_INST_PRINT_POP,
302 BC_INST_STR,
303 BC_INST_PRINT_STR,
304
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100305#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600306 BC_INST_JUMP,
307 BC_INST_JUMP_ZERO,
308
309 BC_INST_CALL,
310
311 BC_INST_RET,
312 BC_INST_RET0,
313
314 BC_INST_HALT,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100315#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600316
317 BC_INST_POP,
318 BC_INST_POP_EXEC,
319
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100320#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600321 BC_INST_MODEXP,
322 BC_INST_DIVMOD,
323
324 BC_INST_EXECUTE,
325 BC_INST_EXEC_COND,
326
327 BC_INST_ASCIIFY,
328 BC_INST_PRINT_STREAM,
329
330 BC_INST_PRINT_STACK,
331 BC_INST_CLEAR_STACK,
332 BC_INST_STACK_LEN,
333 BC_INST_DUPLICATE,
334 BC_INST_SWAP,
335
336 BC_INST_LOAD,
337 BC_INST_PUSH_VAR,
338 BC_INST_PUSH_TO_VAR,
339
340 BC_INST_QUIT,
341 BC_INST_NQUIT,
342
343 BC_INST_INVALID = -1,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100344#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600345
346} BcInst;
347
348typedef struct BcId {
349 char *name;
350 size_t idx;
351} BcId;
352
353typedef struct BcFunc {
354 BcVec code;
355 BcVec labels;
356 size_t nparams;
357 BcVec autos;
358} BcFunc;
359
360typedef enum BcResultType {
361
362 BC_RESULT_TEMP,
363
364 BC_RESULT_VAR,
365 BC_RESULT_ARRAY_ELEM,
366 BC_RESULT_ARRAY,
367
368 BC_RESULT_STR,
369
370 BC_RESULT_IBASE,
371 BC_RESULT_SCALE,
372 BC_RESULT_LAST,
373
374 // These are between to calculate ibase, obase, and last from instructions.
375 BC_RESULT_CONSTANT,
376 BC_RESULT_ONE,
377
378 BC_RESULT_OBASE,
379
380} BcResultType;
381
382typedef union BcResultData {
383 BcNum n;
384 BcVec v;
385 BcId id;
386} BcResultData;
387
388typedef struct BcResult {
389 BcResultType t;
390 BcResultData d;
391} BcResult;
392
393typedef struct BcInstPtr {
394 size_t func;
395 size_t idx;
396 size_t len;
397} BcInstPtr;
398
Gavin Howard01055ba2018-11-03 11:00:21 -0600399// BC_LEX_NEG is not used in lexing; it is only for parsing.
400typedef enum BcLexType {
401
402 BC_LEX_EOF,
403 BC_LEX_INVALID,
404
405 BC_LEX_OP_INC,
406 BC_LEX_OP_DEC,
407
408 BC_LEX_NEG,
409
410 BC_LEX_OP_POWER,
411 BC_LEX_OP_MULTIPLY,
412 BC_LEX_OP_DIVIDE,
413 BC_LEX_OP_MODULUS,
414 BC_LEX_OP_PLUS,
415 BC_LEX_OP_MINUS,
416
417 BC_LEX_OP_REL_EQ,
418 BC_LEX_OP_REL_LE,
419 BC_LEX_OP_REL_GE,
420 BC_LEX_OP_REL_NE,
421 BC_LEX_OP_REL_LT,
422 BC_LEX_OP_REL_GT,
423
424 BC_LEX_OP_BOOL_NOT,
425 BC_LEX_OP_BOOL_OR,
426 BC_LEX_OP_BOOL_AND,
427
428 BC_LEX_OP_ASSIGN_POWER,
429 BC_LEX_OP_ASSIGN_MULTIPLY,
430 BC_LEX_OP_ASSIGN_DIVIDE,
431 BC_LEX_OP_ASSIGN_MODULUS,
432 BC_LEX_OP_ASSIGN_PLUS,
433 BC_LEX_OP_ASSIGN_MINUS,
434 BC_LEX_OP_ASSIGN,
435
436 BC_LEX_NLINE,
437 BC_LEX_WHITESPACE,
438
439 BC_LEX_LPAREN,
440 BC_LEX_RPAREN,
441
442 BC_LEX_LBRACKET,
443 BC_LEX_COMMA,
444 BC_LEX_RBRACKET,
445
446 BC_LEX_LBRACE,
447 BC_LEX_SCOLON,
448 BC_LEX_RBRACE,
449
450 BC_LEX_STR,
451 BC_LEX_NAME,
452 BC_LEX_NUMBER,
453
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100454 BC_LEX_KEY_1st_keyword,
455 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
Gavin Howard01055ba2018-11-03 11:00:21 -0600456 BC_LEX_KEY_BREAK,
457 BC_LEX_KEY_CONTINUE,
458 BC_LEX_KEY_DEFINE,
459 BC_LEX_KEY_ELSE,
460 BC_LEX_KEY_FOR,
461 BC_LEX_KEY_HALT,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100462 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
463 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600464 BC_LEX_KEY_IF,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100465 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
Gavin Howard01055ba2018-11-03 11:00:21 -0600466 BC_LEX_KEY_LENGTH,
467 BC_LEX_KEY_LIMITS,
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100468 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
Gavin Howard01055ba2018-11-03 11:00:21 -0600469 BC_LEX_KEY_PRINT,
470 BC_LEX_KEY_QUIT,
471 BC_LEX_KEY_READ,
472 BC_LEX_KEY_RETURN,
473 BC_LEX_KEY_SCALE,
474 BC_LEX_KEY_SQRT,
475 BC_LEX_KEY_WHILE,
476
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100477#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600478 BC_LEX_EQ_NO_REG,
479 BC_LEX_OP_MODEXP,
480 BC_LEX_OP_DIVMOD,
481
482 BC_LEX_COLON,
483 BC_LEX_ELSE,
484 BC_LEX_EXECUTE,
485 BC_LEX_PRINT_STACK,
486 BC_LEX_CLEAR_STACK,
487 BC_LEX_STACK_LEVEL,
488 BC_LEX_DUPLICATE,
489 BC_LEX_SWAP,
490 BC_LEX_POP,
491
492 BC_LEX_ASCIIFY,
493 BC_LEX_PRINT_STREAM,
494
495 BC_LEX_STORE_IBASE,
496 BC_LEX_STORE_SCALE,
497 BC_LEX_LOAD,
498 BC_LEX_LOAD_POP,
499 BC_LEX_STORE_PUSH,
500 BC_LEX_STORE_OBASE,
501 BC_LEX_PRINT_POP,
502 BC_LEX_NQUIT,
503 BC_LEX_SCALE_FACTOR,
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100504#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600505} BcLexType;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100506// must match order of BC_LEX_KEY_foo etc above
507#if ENABLE_BC
508struct BcLexKeyword {
509 char name8[8];
510};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100511#define BC_LEX_KW_ENTRY(a, b) \
512 { .name8 = a /*, .posix = b */ }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100513static const struct BcLexKeyword bc_lex_kws[20] = {
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100514 BC_LEX_KW_ENTRY("auto" , 1), // 0
515 BC_LEX_KW_ENTRY("break" , 1), // 1
516 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
517 BC_LEX_KW_ENTRY("define" , 1), // 3
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100518
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100519 BC_LEX_KW_ENTRY("else" , 0), // 4
520 BC_LEX_KW_ENTRY("for" , 1), // 5
521 BC_LEX_KW_ENTRY("halt" , 0), // 6
522 BC_LEX_KW_ENTRY("ibase" , 1), // 7
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100523
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100524 BC_LEX_KW_ENTRY("if" , 1), // 8
525 BC_LEX_KW_ENTRY("last" , 0), // 9
526 BC_LEX_KW_ENTRY("length" , 1), // 10
527 BC_LEX_KW_ENTRY("limits" , 0), // 11
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100528
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100529 BC_LEX_KW_ENTRY("obase" , 1), // 12
530 BC_LEX_KW_ENTRY("print" , 0), // 13
531 BC_LEX_KW_ENTRY("quit" , 1), // 14
532 BC_LEX_KW_ENTRY("read" , 0), // 15
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100533
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100534 BC_LEX_KW_ENTRY("return" , 1), // 16
535 BC_LEX_KW_ENTRY("scale" , 1), // 17
536 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
537 BC_LEX_KW_ENTRY("while" , 1), // 19
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100538};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100539#undef BC_LEX_KW_ENTRY
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100540enum {
541 POSIX_KWORD_MASK = 0
542 | (1 << 0)
543 | (1 << 1)
544 | (0 << 2)
545 | (1 << 3)
546 \
547 | (0 << 4)
548 | (1 << 5)
549 | (0 << 6)
550 | (1 << 7)
551 \
552 | (1 << 8)
553 | (0 << 9)
554 | (1 << 10)
555 | (0 << 11)
556 \
557 | (1 << 12)
558 | (0 << 13)
559 | (1 << 14)
560 | (0 << 15)
561 \
562 | (1 << 16)
563 | (1 << 17)
564 | (1 << 18)
565 | (1 << 19)
566};
Denys Vlasenkod00d2f92018-12-06 12:59:40 +0100567#define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +0100568#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600569
570struct BcLex;
571typedef BcStatus (*BcLexNext)(struct BcLex *);
572
573typedef struct BcLex {
574
575 const char *buf;
576 size_t i;
577 size_t line;
Gavin Howard01055ba2018-11-03 11:00:21 -0600578 size_t len;
579 bool newline;
580
581 struct {
582 BcLexType t;
583 BcLexType last;
584 BcVec v;
585 } t;
586
587 BcLexNext next;
588
589} BcLex;
590
591#define BC_PARSE_STREND ((char) UCHAR_MAX)
592
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100593#define BC_PARSE_REL (1 << 0)
594#define BC_PARSE_PRINT (1 << 1)
Gavin Howard01055ba2018-11-03 11:00:21 -0600595#define BC_PARSE_NOCALL (1 << 2)
596#define BC_PARSE_NOREAD (1 << 3)
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100597#define BC_PARSE_ARRAY (1 << 4)
Gavin Howard01055ba2018-11-03 11:00:21 -0600598
599#define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
600#define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
601
602#define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
603#define BC_PARSE_FUNC_INNER(parse) \
604 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
605
606#define BC_PARSE_FLAG_FUNC (1 << 1)
607#define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
608
609#define BC_PARSE_FLAG_BODY (1 << 2)
610#define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
611
612#define BC_PARSE_FLAG_LOOP (1 << 3)
613#define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
614
615#define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
616#define BC_PARSE_LOOP_INNER(parse) \
617 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
618
619#define BC_PARSE_FLAG_IF (1 << 5)
620#define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
621
622#define BC_PARSE_FLAG_ELSE (1 << 6)
623#define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
624
625#define BC_PARSE_FLAG_IF_END (1 << 7)
626#define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
627
628#define BC_PARSE_CAN_EXEC(parse) \
629 (!(BC_PARSE_TOP_FLAG(parse) & \
630 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
631 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
632 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
633
Gavin Howard01055ba2018-11-03 11:00:21 -0600634typedef struct BcParseNext {
635 uint32_t len;
636 BcLexType tokens[4];
637} BcParseNext;
638
Gavin Howard01055ba2018-11-03 11:00:21 -0600639struct BcParse;
640
641struct BcProgram;
642
Gavin Howard01055ba2018-11-03 11:00:21 -0600643typedef BcStatus (*BcParseParse)(struct BcParse *);
Gavin Howard01055ba2018-11-03 11:00:21 -0600644
645typedef struct BcParse {
646
647 BcParseParse parse;
648
649 BcLex l;
650
651 BcVec flags;
652
653 BcVec exits;
654 BcVec conds;
655
656 BcVec ops;
657
Gavin Howard01055ba2018-11-03 11:00:21 -0600658 BcFunc *func;
659 size_t fidx;
660
661 size_t nbraces;
662 bool auto_part;
663
664} BcParse;
665
Gavin Howard01055ba2018-11-03 11:00:21 -0600666typedef struct BcProgram {
667
668 size_t len;
669 size_t scale;
670
671 BcNum ib;
672 size_t ib_t;
673 BcNum ob;
674 size_t ob_t;
675
676 BcNum hexb;
677
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100678#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600679 BcNum strmb;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100680#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600681
682 BcVec results;
683 BcVec stack;
684
685 BcVec fns;
686 BcVec fn_map;
687
688 BcVec vars;
689 BcVec var_map;
690
691 BcVec arrs;
692 BcVec arr_map;
693
694 BcVec strs;
695 BcVec consts;
696
697 const char *file;
698
699 BcNum last;
700 BcNum zero;
701 BcNum one;
702
703 size_t nchars;
704
Gavin Howard01055ba2018-11-03 11:00:21 -0600705} BcProgram;
706
707#define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
708
709#define BC_PROG_MAIN (0)
710#define BC_PROG_READ (1)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100711#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600712#define BC_PROG_REQ_FUNCS (2)
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100713#endif
Gavin Howard01055ba2018-11-03 11:00:21 -0600714
715#define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
716#define BC_PROG_NUM(r, n) \
717 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
718
719typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
720
Gavin Howard01055ba2018-11-03 11:00:21 -0600721#define BC_FLAG_X (1 << 0)
722#define BC_FLAG_W (1 << 1)
723#define BC_FLAG_V (1 << 2)
724#define BC_FLAG_S (1 << 3)
725#define BC_FLAG_Q (1 << 4)
726#define BC_FLAG_L (1 << 5)
727#define BC_FLAG_I (1 << 6)
728
729#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
730#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
731
Denys Vlasenkod9d66552018-12-02 21:02:54 +0100732#define BC_MAX_OBASE ((unsigned) 999)
733#define BC_MAX_DIM ((unsigned) INT_MAX)
734#define BC_MAX_SCALE ((unsigned) UINT_MAX)
735#define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
736#define BC_MAX_NAME BC_MAX_STRING
737#define BC_MAX_NUM BC_MAX_STRING
738#define BC_MAX_EXP ((unsigned long) LONG_MAX)
739#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
Gavin Howard01055ba2018-11-03 11:00:21 -0600740
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100741struct globals {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100742 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100743 smallint eof;
Gavin Howard01055ba2018-11-03 11:00:21 -0600744 char sbgn;
745 char send;
Gavin Howard01055ba2018-11-03 11:00:21 -0600746
747 BcParse prs;
748 BcProgram prog;
749
Denys Vlasenko5318f812018-12-05 17:48:01 +0100750 // For error messages. Can be set to current parsed line,
751 // or [TODO] to current executing line (can be before last parsed one)
752 unsigned err_line;
753
Gavin Howard01055ba2018-11-03 11:00:21 -0600754 BcVec files;
755
756 char *env_args;
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100757
758#if ENABLE_FEATURE_EDITING
759 line_input_t *line_input_state;
760#endif
Denys Vlasenko6d9146a2018-12-02 15:48:37 +0100761} FIX_ALIASING;
762#define G (*ptr_to_globals)
763#define INIT_G() do { \
764 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
765} while (0)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100766#define FREE_G() do { \
767 FREE_PTR_TO_GLOBALS(); \
768} while (0)
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100769#define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
770#define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
771#define G_exreg (ENABLE_DC && (option_mask32 & BC_FLAG_X))
Denys Vlasenkoab3c5682018-12-02 16:32:36 +0100772#define G_interrupt (ENABLE_FEATURE_BC_SIGNALS ? bb_got_signal : 0)
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100773#if ENABLE_FEATURE_BC_SIGNALS
774# define G_ttyin G.ttyin
775#else
776# define G_ttyin 0
777#endif
Denys Vlasenko00d77792018-11-30 23:13:42 +0100778#define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
779
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100780#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -0600781
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100782// This is a bit array that corresponds to token types. An entry is
Gavin Howard01055ba2018-11-03 11:00:21 -0600783// true if the token is valid in an expression, false otherwise.
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100784enum {
785 BC_PARSE_EXPRS_BITS = 0
786 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
787 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
788 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
789 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
790 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
791 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
792 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
793 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
Gavin Howard01055ba2018-11-03 11:00:21 -0600794};
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100795static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
796{
797#if ULONG_MAX > 0xffffffff
798 // 64-bit version (will not work correctly for 32-bit longs!)
799 return BC_PARSE_EXPRS_BITS & (1UL << i);
800#else
801 // 32-bit version
802 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
803 if (i >= 32) {
804 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
805 i &= 31;
806 }
807 return m & (1UL << i);
808#endif
809}
Gavin Howard01055ba2018-11-03 11:00:21 -0600810
811// This is an array of data for operators that correspond to token types.
Denys Vlasenko65437582018-12-05 19:37:19 +0100812static const uint8_t bc_parse_ops[] = {
813#define OP(p,l) ((int)(l) * 0x10 + (p))
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100814 OP(0, false), OP( 0, false ), // inc dec
815 OP(1, false), // neg
Denys Vlasenko65437582018-12-05 19:37:19 +0100816 OP(2, false),
Denys Vlasenkobcb62a72018-12-05 20:17:48 +0100817 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
818 OP(4, true ), OP( 4, true ), // mod + -
819 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
820 OP(1, false), // not
821 OP(7, true ), OP( 7, true ), // or and
822 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
823 OP(5, false), OP( 5, false ), // -= =
Denys Vlasenko65437582018-12-05 19:37:19 +0100824#undef OP
Gavin Howard01055ba2018-11-03 11:00:21 -0600825};
Denys Vlasenko65437582018-12-05 19:37:19 +0100826#define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
827#define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
Gavin Howard01055ba2018-11-03 11:00:21 -0600828
829// These identify what tokens can come after expressions in certain cases.
Denys Vlasenkoe55a5722018-12-06 12:47:17 +0100830#define BC_PARSE_NEXT_TOKENS(...) .tokens = { __VA_ARGS__ }
831#define BC_PARSE_NEXT(a, ...) \
832 { \
833 .len = (a), BC_PARSE_NEXT_TOKENS(__VA_ARGS__) \
834 }
Gavin Howard01055ba2018-11-03 11:00:21 -0600835static const BcParseNext bc_parse_next_expr =
836 BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF);
837static const BcParseNext bc_parse_next_param =
838 BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA);
839static const BcParseNext bc_parse_next_print =
840 BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF);
841static const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN);
842static const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET);
843static const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON);
844static const BcParseNext bc_parse_next_read =
845 BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF);
846#endif // ENABLE_BC
847
Denys Vlasenkoef869ec2018-12-02 18:49:16 +0100848#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -0600849static const BcLexType dc_lex_regs[] = {
850 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
851 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
852 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
853 BC_LEX_STORE_PUSH,
854};
855
Gavin Howard01055ba2018-11-03 11:00:21 -0600856static const BcLexType dc_lex_tokens[] = {
857 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
858 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
859 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
860 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
861 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
862 BC_LEX_INVALID, BC_LEX_INVALID,
863 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
864 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
865 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
866 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
867 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
868 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
869 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
870 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
871 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
872 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
873 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
874 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
875 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
876 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
877 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
878 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
879 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
880 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
881 BC_LEX_INVALID
882};
883
884static const BcInst dc_parse_insts[] = {
885 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
886 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
887 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
888 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
889 BC_INST_INVALID, BC_INST_INVALID,
890 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
891 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
892 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
893 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
894 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
895 BC_INST_INVALID, BC_INST_INVALID,
896 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
897 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
898 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
899 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
900 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
901 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
902 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
903 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
904 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
905 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
906 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
907 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
908};
909#endif // ENABLE_DC
910
Gavin Howard01055ba2018-11-03 11:00:21 -0600911static const BcNumBinaryOp bc_program_ops[] = {
912 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
913};
914
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100915static void fflush_and_check(void)
916{
917 fflush_all();
918 if (ferror(stdout) || ferror(stderr))
919 bb_perror_msg_and_die("output error");
920}
921
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100922#if ENABLE_FEATURE_CLEAN_UP
923#define quit_or_return_for_exit() \
924do { \
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100925 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
Denys Vlasenkoe873ff92018-12-06 00:29:22 +0100926 return BC_STATUS_FAILURE; \
927} while (0)
928#else
929#define quit_or_return_for_exit() quit()
930#endif
931
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100932static void quit(void) NORETURN;
933static void quit(void)
934{
Denys Vlasenkod4744ad2018-12-03 14:28:51 +0100935 if (ferror(stdin))
936 bb_perror_msg_and_die("input error");
937 fflush_and_check();
938 exit(0);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +0100939}
940
Denys Vlasenko5318f812018-12-05 17:48:01 +0100941static void bc_verror_msg(const char *fmt, va_list p)
942{
943 const char *sv = sv; /* for compiler */
944 if (G.prog.file) {
945 sv = applet_name;
946 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
947 }
948 bb_verror_msg(fmt, p, NULL);
949 if (G.prog.file) {
950 free((char*)applet_name);
951 applet_name = sv;
952 }
953}
954
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100955static NOINLINE int bc_error_fmt(const char *fmt, ...)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100956{
957 va_list p;
958
959 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +0100960 bc_verror_msg(fmt, p);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100961 va_end(p);
Denys Vlasenko0409ad32018-12-05 16:39:22 +0100962
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100963 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenkoc1c24702018-12-03 16:06:02 +0100964 exit(1);
965 return BC_STATUS_FAILURE;
966}
967
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +0100968#if ENABLE_BC
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100969static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100970{
971 va_list p;
972
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100973 // Are non-POSIX constructs totally ok?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100974 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100975 return BC_STATUS_SUCCESS; // yes
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100976
977 va_start(p, fmt);
Denys Vlasenko5318f812018-12-05 17:48:01 +0100978 bc_verror_msg(fmt, p);
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100979 va_end(p);
980
981 // Do we treat non-POSIX constructs as errors?
Denys Vlasenkod70d4a02018-12-04 20:58:40 +0100982 if (!(option_mask32 & BC_FLAG_S))
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100983 return BC_STATUS_SUCCESS; // no, it's a warning
Denys Vlasenko1a6a4822018-12-06 09:20:32 +0100984 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100985 exit(1);
986 return BC_STATUS_FAILURE;
987}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +0100988#endif
Denys Vlasenko9b70f192018-12-04 20:51:40 +0100989
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100990// We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
991// This idiom begs for tail-call optimization, but for it to work,
Denys Vlasenko95f93bd2018-12-06 10:29:12 +0100992// function must not have caller-cleaned parameters on stack.
993// Unfortunately, vararg function API does exactly that on most arches.
994// Thus, use these shims for the cases when we have no vararg PARAMS:
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +0100995static int bc_error(const char *msg)
996{
997 return bc_error_fmt("%s", msg);
998}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +0100999#if ENABLE_BC
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001000static int bc_POSIX_requires(const char *msg)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001001{
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01001002 return bc_posix_error_fmt("POSIX requires %s", msg);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001003}
Denys Vlasenko00646792018-12-05 18:12:27 +01001004static int bc_POSIX_does_not_allow(const char *msg)
1005{
1006 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1007}
1008static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1009{
1010 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1011}
1012static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1013{
1014 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1015}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001016#endif
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01001017static int bc_error_bad_character(char c)
1018{
1019 return bc_error_fmt("bad character '%c'", c);
1020}
1021static int bc_error_bad_expression(void)
1022{
1023 return bc_error("bad expression");
1024}
1025static int bc_error_bad_token(void)
1026{
1027 return bc_error("bad token");
1028}
1029static int bc_error_stack_has_too_few_elements(void)
1030{
1031 return bc_error("stack has too few elements");
1032}
1033static int bc_error_variable_is_wrong_type(void)
1034{
1035 return bc_error("variable is wrong type");
1036}
1037static int bc_error_nested_read_call(void)
1038{
1039 return bc_error("read() call inside of a read() call");
1040}
1041
Gavin Howard01055ba2018-11-03 11:00:21 -06001042static void bc_vec_grow(BcVec *v, size_t n)
1043{
1044 size_t cap = v->cap * 2;
1045 while (cap < v->len + n) cap *= 2;
1046 v->v = xrealloc(v->v, v->size * cap);
1047 v->cap = cap;
1048}
1049
1050static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1051{
1052 v->size = esize;
1053 v->cap = BC_VEC_START_CAP;
1054 v->len = 0;
1055 v->dtor = dtor;
1056 v->v = xmalloc(esize * BC_VEC_START_CAP);
1057}
1058
Denys Vlasenko7d628012018-12-04 21:46:47 +01001059static void bc_char_vec_init(BcVec *v)
1060{
1061 bc_vec_init(v, sizeof(char), NULL);
1062}
1063
Gavin Howard01055ba2018-11-03 11:00:21 -06001064static void bc_vec_expand(BcVec *v, size_t req)
1065{
1066 if (v->cap < req) {
1067 v->v = xrealloc(v->v, v->size * req);
1068 v->cap = req;
1069 }
1070}
1071
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001072static void bc_vec_pop(BcVec *v)
1073{
1074 v->len--;
1075 if (v->dtor)
1076 v->dtor(v->v + (v->size * v->len));
1077}
Denys Vlasenko2fa11b62018-12-06 12:34:39 +01001078
Gavin Howard01055ba2018-11-03 11:00:21 -06001079static void bc_vec_npop(BcVec *v, size_t n)
1080{
1081 if (!v->dtor)
1082 v->len -= n;
1083 else {
1084 size_t len = v->len - n;
1085 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1086 }
1087}
1088
Denys Vlasenko7d628012018-12-04 21:46:47 +01001089static void bc_vec_pop_all(BcVec *v)
1090{
1091 bc_vec_npop(v, v->len);
1092}
1093
Gavin Howard01055ba2018-11-03 11:00:21 -06001094static void bc_vec_push(BcVec *v, const void *data)
1095{
1096 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1097 memmove(v->v + (v->size * v->len), data, v->size);
1098 v->len += 1;
1099}
1100
1101static void bc_vec_pushByte(BcVec *v, char data)
1102{
1103 bc_vec_push(v, &data);
1104}
1105
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001106static void bc_vec_pushZeroByte(BcVec *v)
1107{
1108 //bc_vec_pushByte(v, '\0');
1109 // better:
1110 bc_vec_push(v, &const_int_0);
1111}
1112
Gavin Howard01055ba2018-11-03 11:00:21 -06001113static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1114{
1115 if (idx == v->len)
1116 bc_vec_push(v, data);
1117 else {
1118
1119 char *ptr;
1120
1121 if (v->len == v->cap) bc_vec_grow(v, 1);
1122
1123 ptr = v->v + v->size * idx;
1124
1125 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1126 memmove(ptr, data, v->size);
1127 }
1128}
1129
1130static void bc_vec_string(BcVec *v, size_t len, const char *str)
1131{
Denys Vlasenko7d628012018-12-04 21:46:47 +01001132 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001133 bc_vec_expand(v, len + 1);
1134 memcpy(v->v, str, len);
1135 v->len = len;
1136
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001137 bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001138}
1139
1140static void bc_vec_concat(BcVec *v, const char *str)
1141{
1142 size_t len;
1143
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001144 if (v->len == 0) bc_vec_pushZeroByte(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001145
1146 len = v->len + strlen(str);
1147
1148 if (v->cap < len) bc_vec_grow(v, len - v->len);
Denys Vlasenko1ff88622018-12-06 12:06:16 +01001149 strcpy(v->v + v->len - 1, str);
Gavin Howard01055ba2018-11-03 11:00:21 -06001150
1151 v->len = len;
1152}
1153
1154static void *bc_vec_item(const BcVec *v, size_t idx)
1155{
1156 return v->v + v->size * idx;
1157}
1158
1159static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1160{
1161 return v->v + v->size * (v->len - idx - 1);
1162}
1163
Denys Vlasenkob23ac512018-12-06 13:10:56 +01001164static void *bc_vec_top(const BcVec *v)
1165{
1166 return v->v + v->size * (v->len - 1);
1167}
1168
Gavin Howard01055ba2018-11-03 11:00:21 -06001169static void bc_vec_free(void *vec)
1170{
1171 BcVec *v = (BcVec *) vec;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001172 bc_vec_pop_all(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06001173 free(v->v);
1174}
1175
Denys Vlasenkocca79a02018-12-05 21:15:46 +01001176static int bc_id_cmp(const void *e1, const void *e2)
1177{
1178 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1179}
1180
1181static void bc_id_free(void *id)
1182{
1183 free(((BcId *) id)->name);
1184}
1185
Gavin Howard01055ba2018-11-03 11:00:21 -06001186static size_t bc_map_find(const BcVec *v, const void *ptr)
1187{
1188 size_t low = 0, high = v->len;
1189
1190 while (low < high) {
1191
1192 size_t mid = (low + high) / 2;
1193 BcId *id = bc_vec_item(v, mid);
1194 int result = bc_id_cmp(ptr, id);
1195
1196 if (result == 0)
1197 return mid;
1198 else if (result < 0)
1199 high = mid;
1200 else
1201 low = mid + 1;
1202 }
1203
1204 return low;
1205}
1206
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001207static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
Gavin Howard01055ba2018-11-03 11:00:21 -06001208{
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001209 size_t n = *i = bc_map_find(v, ptr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001210
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001211 if (n == v->len)
Gavin Howard01055ba2018-11-03 11:00:21 -06001212 bc_vec_push(v, ptr);
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001213 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1214 return 0; // "was not inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001215 else
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01001216 bc_vec_pushAt(v, ptr, n);
1217 return 1; // "was inserted"
Gavin Howard01055ba2018-11-03 11:00:21 -06001218}
1219
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001220#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06001221static size_t bc_map_index(const BcVec *v, const void *ptr)
1222{
1223 size_t i = bc_map_find(v, ptr);
1224 if (i >= v->len) return BC_VEC_INVALID_IDX;
1225 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1226}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01001227#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06001228
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001229static int push_input_byte(BcVec *vec, char c)
1230{
1231 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1232 || c > 0x7e
1233 ) {
1234 // Bad chars on this line, ignore entire line
1235 bc_error_fmt("illegal character 0x%02x", c);
1236 return 1;
1237 }
1238 bc_vec_pushByte(vec, (char)c);
1239 return 0;
1240}
1241
Gavin Howard01055ba2018-11-03 11:00:21 -06001242static BcStatus bc_read_line(BcVec *vec, const char *prompt)
1243{
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001244 bool bad_chars;
Gavin Howard01055ba2018-11-03 11:00:21 -06001245
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001246 if (G_posix) prompt = "";
1247
Denys Vlasenko00d77792018-11-30 23:13:42 +01001248 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001249 int c;
Gavin Howard01055ba2018-11-03 11:00:21 -06001250
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001251 bad_chars = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01001252 bc_vec_pop_all(vec);
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001253
1254 fflush_and_check();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001255
Gavin Howard01055ba2018-11-03 11:00:21 -06001256#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001257 if (bb_got_signal) { // ^C was pressed
1258 intr:
1259 bb_got_signal = 0; // resets G_interrupt to zero
1260 fputs(IS_BC
1261 ? "\ninterrupt (type \"quit\" to exit)\n"
1262 : "\ninterrupt (type \"q\" to exit)\n"
1263 , stderr);
Gavin Howard01055ba2018-11-03 11:00:21 -06001264 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001265# if ENABLE_FEATURE_EDITING
1266 if (G_ttyin) {
1267 int n, i;
1268# define line_buf bb_common_bufsiz1
1269 n = read_line_input(G.line_input_state, prompt, line_buf, COMMON_BUFSIZE);
1270 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1271 if (n == 0) // ^C
1272 goto intr;
1273 G.eof = 1;
1274 break;
1275 }
1276 i = 0;
1277 for (;;) {
1278 c = line_buf[i++];
1279 if (!c) break;
1280 bad_chars |= push_input_byte(vec, c);
1281 }
1282# undef line_buf
1283 } else
1284# endif
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001285#endif
Denys Vlasenkoed849352018-12-06 10:26:13 +01001286 {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001287 if (G_ttyin)
Denys Vlasenkoed849352018-12-06 10:26:13 +01001288 fputs(prompt, stderr);
Denys Vlasenkoed849352018-12-06 10:26:13 +01001289 IF_FEATURE_BC_SIGNALS(errno = 0;)
1290 do {
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001291 c = fgetc(stdin);
1292#if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1293 // Both conditions appear simultaneously, check both just in case
1294 if (errno == EINTR || bb_got_signal) {
1295 // ^C was pressed
1296 clearerr(stdin);
1297 goto intr;
1298 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001299#endif
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001300 if (c == EOF) {
Denys Vlasenkoed849352018-12-06 10:26:13 +01001301 if (ferror(stdin))
1302 quit(); // this emits error message
1303 G.eof = 1;
1304 // Note: EOF does not append '\n', therefore:
1305 // printf 'print 123\n' | bc - works
1306 // printf 'print 123' | bc - fails (syntax error)
1307 break;
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001308 }
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01001309 bad_chars |= push_input_byte(vec, c);
1310 } while (c != '\n');
Denys Vlasenkoed849352018-12-06 10:26:13 +01001311 }
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001312 } while (bad_chars);
Gavin Howard01055ba2018-11-03 11:00:21 -06001313
Denys Vlasenko08c033c2018-12-05 16:55:08 +01001314 bc_vec_pushZeroByte(vec);
Gavin Howard01055ba2018-11-03 11:00:21 -06001315
1316 return BC_STATUS_SUCCESS;
1317}
1318
Denys Vlasenkodf515392018-12-02 19:27:48 +01001319static char* bc_read_file(const char *path)
Gavin Howard01055ba2018-11-03 11:00:21 -06001320{
Denys Vlasenkodf515392018-12-02 19:27:48 +01001321 char *buf;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001322 size_t size = ((size_t) -1);
1323 size_t i;
Gavin Howard01055ba2018-11-03 11:00:21 -06001324
Denys Vlasenkodf515392018-12-02 19:27:48 +01001325 buf = xmalloc_open_read_close(path, &size);
Gavin Howard01055ba2018-11-03 11:00:21 -06001326
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01001327 for (i = 0; i < size; ++i) {
Denys Vlasenkoc1c24702018-12-03 16:06:02 +01001328 char c = buf[i];
1329 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1330 || c > 0x7e
1331 ) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01001332 free(buf);
1333 buf = NULL;
1334 break;
1335 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001336 }
1337
Denys Vlasenkodf515392018-12-02 19:27:48 +01001338 return buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06001339}
1340
Gavin Howard01055ba2018-11-03 11:00:21 -06001341static void bc_num_setToZero(BcNum *n, size_t scale)
1342{
1343 n->len = 0;
1344 n->neg = false;
1345 n->rdx = scale;
1346}
1347
1348static void bc_num_zero(BcNum *n)
1349{
1350 bc_num_setToZero(n, 0);
1351}
1352
1353static void bc_num_one(BcNum *n)
1354{
1355 bc_num_setToZero(n, 0);
1356 n->len = 1;
1357 n->num[0] = 1;
1358}
1359
1360static void bc_num_ten(BcNum *n)
1361{
1362 bc_num_setToZero(n, 0);
1363 n->len = 2;
1364 n->num[0] = 0;
1365 n->num[1] = 1;
1366}
1367
Denys Vlasenkob0e37612018-12-05 21:03:16 +01001368static void bc_num_init(BcNum *n, size_t req)
1369{
1370 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1371 memset(n, 0, sizeof(BcNum));
1372 n->num = xmalloc(req);
1373 n->cap = req;
1374}
1375
1376static void bc_num_expand(BcNum *n, size_t req)
1377{
1378 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1379 if (req > n->cap) {
1380 n->num = xrealloc(n->num, req);
1381 n->cap = req;
1382 }
1383}
1384
1385static void bc_num_free(void *num)
1386{
1387 free(((BcNum *) num)->num);
1388}
1389
1390static void bc_num_copy(BcNum *d, BcNum *s)
1391{
1392 if (d != s) {
1393 bc_num_expand(d, s->cap);
1394 d->len = s->len;
1395 d->neg = s->neg;
1396 d->rdx = s->rdx;
1397 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1398 }
1399}
1400
1401static BcStatus bc_num_ulong(BcNum *n, unsigned long *result)
1402{
1403 size_t i;
1404 unsigned long pow;
1405
1406 if (n->neg) return bc_error("negative number");
1407
1408 for (*result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1409
1410 unsigned long prev = *result, powprev = pow;
1411
1412 *result += ((unsigned long) n->num[i]) * pow;
1413 pow *= 10;
1414
1415 if (*result < prev || pow < powprev)
1416 return bc_error("overflow");
1417 }
1418
1419 return BC_STATUS_SUCCESS;
1420}
1421
1422static void bc_num_ulong2num(BcNum *n, unsigned long val)
1423{
1424 size_t len;
1425 BcDig *ptr;
1426 unsigned long i;
1427
1428 bc_num_zero(n);
1429
1430 if (val == 0) return;
1431
1432 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1433 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1434}
1435
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001436static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
Gavin Howard01055ba2018-11-03 11:00:21 -06001437 size_t len)
1438{
1439 size_t i, j;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001440 for (i = 0; i < len; ++i) {
1441 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001442 a[i + j++] += 10;
1443 a[i + j] -= 1;
1444 }
1445 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001446}
1447
1448static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1449{
1450 size_t i;
1451 int c = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001452 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
Gavin Howard01055ba2018-11-03 11:00:21 -06001453 return BC_NUM_NEG(i + 1, c < 0);
1454}
1455
1456static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1457{
1458 size_t i, min, a_int, b_int, diff;
1459 BcDig *max_num, *min_num;
1460 bool a_max, neg = false;
1461 ssize_t cmp;
1462
1463 if (a == b) return 0;
1464 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1465 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1466 if (a->neg) {
1467 if (b->neg)
1468 neg = true;
1469 else
1470 return -1;
1471 }
1472 else if (b->neg)
1473 return 1;
1474
1475 a_int = BC_NUM_INT(a);
1476 b_int = BC_NUM_INT(b);
1477 a_int -= b_int;
1478 a_max = (a->rdx > b->rdx);
1479
1480 if (a_int != 0) return (ssize_t) a_int;
1481
1482 if (a_max) {
1483 min = b->rdx;
1484 diff = a->rdx - b->rdx;
1485 max_num = a->num + diff;
1486 min_num = b->num;
1487 }
1488 else {
1489 min = a->rdx;
1490 diff = b->rdx - a->rdx;
1491 max_num = b->num + diff;
1492 min_num = a->num;
1493 }
1494
1495 cmp = bc_num_compare(max_num, min_num, b_int + min);
1496 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1497
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001498 for (max_num -= diff, i = diff - 1; i < diff; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001499 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1500 }
1501
1502 return 0;
1503}
1504
1505static void bc_num_truncate(BcNum *n, size_t places)
1506{
1507 if (places == 0) return;
1508
1509 n->rdx -= places;
1510
1511 if (n->len != 0) {
1512 n->len -= places;
1513 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1514 }
1515}
1516
1517static void bc_num_extend(BcNum *n, size_t places)
1518{
1519 size_t len = n->len + places;
1520
1521 if (places != 0) {
1522
1523 if (n->cap < len) bc_num_expand(n, len);
1524
1525 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1526 memset(n->num, 0, sizeof(BcDig) * places);
1527
1528 n->len += places;
1529 n->rdx += places;
1530 }
1531}
1532
1533static void bc_num_clean(BcNum *n)
1534{
1535 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1536 if (n->len == 0)
1537 n->neg = false;
1538 else if (n->len < n->rdx)
1539 n->len = n->rdx;
1540}
1541
1542static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1543{
1544 if (n->rdx < scale)
1545 bc_num_extend(n, scale - n->rdx);
1546 else
1547 bc_num_truncate(n, n->rdx - scale);
1548
1549 bc_num_clean(n);
1550 if (n->len != 0) n->neg = !neg1 != !neg2;
1551}
1552
1553static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1554 BcNum *restrict b)
1555{
1556 if (idx < n->len) {
1557
1558 b->len = n->len - idx;
1559 a->len = idx;
1560 a->rdx = b->rdx = 0;
1561
1562 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1563 memcpy(a->num, n->num, idx * sizeof(BcDig));
1564 }
1565 else {
1566 bc_num_zero(b);
1567 bc_num_copy(a, n);
1568 }
1569
1570 bc_num_clean(a);
1571 bc_num_clean(b);
1572}
1573
1574static BcStatus bc_num_shift(BcNum *n, size_t places)
1575{
1576 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001577 if (places + n->len > BC_MAX_NUM)
1578 return bc_error("number too long: must be [1, BC_NUM_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06001579
1580 if (n->rdx >= places)
1581 n->rdx -= places;
1582 else {
1583 bc_num_extend(n, places - n->rdx);
1584 n->rdx = 0;
1585 }
1586
1587 bc_num_clean(n);
1588
1589 return BC_STATUS_SUCCESS;
1590}
1591
1592static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1593{
1594 BcNum one;
1595 BcDig num[2];
1596
1597 one.cap = 2;
1598 one.num = num;
1599 bc_num_one(&one);
1600
1601 return bc_num_div(&one, a, b, scale);
1602}
1603
1604static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1605{
1606 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1607 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1608 int carry, in;
1609
1610 // Because this function doesn't need to use scale (per the bc spec),
1611 // I am hijacking it to say whether it's doing an add or a subtract.
1612
1613 if (a->len == 0) {
1614 bc_num_copy(c, b);
1615 if (sub && c->len) c->neg = !c->neg;
1616 return BC_STATUS_SUCCESS;
1617 }
1618 else if (b->len == 0) {
1619 bc_num_copy(c, a);
1620 return BC_STATUS_SUCCESS;
1621 }
1622
1623 c->neg = a->neg;
1624 c->rdx = BC_MAX(a->rdx, b->rdx);
1625 min_rdx = BC_MIN(a->rdx, b->rdx);
1626 c->len = 0;
1627
1628 if (a->rdx > b->rdx) {
1629 diff = a->rdx - b->rdx;
1630 ptr = a->num;
1631 ptr_a = a->num + diff;
1632 ptr_b = b->num;
1633 }
1634 else {
1635 diff = b->rdx - a->rdx;
1636 ptr = b->num;
1637 ptr_a = a->num;
1638 ptr_b = b->num + diff;
1639 }
1640
1641 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1642
1643 ptr_c += diff;
1644 a_int = BC_NUM_INT(a);
1645 b_int = BC_NUM_INT(b);
1646
1647 if (a_int > b_int) {
1648 min_int = b_int;
1649 max = a_int;
1650 ptr = ptr_a;
1651 }
1652 else {
1653 min_int = a_int;
1654 max = b_int;
1655 ptr = ptr_b;
1656 }
1657
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001658 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001659 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1660 carry = in / 10;
1661 ptr_c[i] = (BcDig)(in % 10);
1662 }
1663
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001664 for (; i < max + min_rdx; ++i, ++c->len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001665 in = ((int) ptr[i]) + carry;
1666 carry = in / 10;
1667 ptr_c[i] = (BcDig)(in % 10);
1668 }
1669
1670 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1671
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001672 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001673}
1674
1675static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1676{
Gavin Howard01055ba2018-11-03 11:00:21 -06001677 ssize_t cmp;
1678 BcNum *minuend, *subtrahend;
1679 size_t start;
1680 bool aneg, bneg, neg;
1681
1682 // Because this function doesn't need to use scale (per the bc spec),
1683 // I am hijacking it to say whether it's doing an add or a subtract.
1684
1685 if (a->len == 0) {
1686 bc_num_copy(c, b);
1687 if (sub && c->len) c->neg = !c->neg;
1688 return BC_STATUS_SUCCESS;
1689 }
1690 else if (b->len == 0) {
1691 bc_num_copy(c, a);
1692 return BC_STATUS_SUCCESS;
1693 }
1694
1695 aneg = a->neg;
1696 bneg = b->neg;
1697 a->neg = b->neg = false;
1698
1699 cmp = bc_num_cmp(a, b);
1700
1701 a->neg = aneg;
1702 b->neg = bneg;
1703
1704 if (cmp == 0) {
1705 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1706 return BC_STATUS_SUCCESS;
1707 }
1708 else if (cmp > 0) {
1709 neg = a->neg;
1710 minuend = a;
1711 subtrahend = b;
1712 }
1713 else {
1714 neg = b->neg;
1715 if (sub) neg = !neg;
1716 minuend = b;
1717 subtrahend = a;
1718 }
1719
1720 bc_num_copy(c, minuend);
1721 c->neg = neg;
1722
1723 if (c->rdx < subtrahend->rdx) {
1724 bc_num_extend(c, subtrahend->rdx - c->rdx);
1725 start = 0;
1726 }
1727 else
1728 start = c->rdx - subtrahend->rdx;
1729
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001730 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001731
1732 bc_num_clean(c);
1733
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001734 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
Gavin Howard01055ba2018-11-03 11:00:21 -06001735}
1736
1737static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1738 BcNum *restrict c)
1739{
1740 BcStatus s;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001741 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
Gavin Howard01055ba2018-11-03 11:00:21 -06001742 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001743 bool aone;
Gavin Howard01055ba2018-11-03 11:00:21 -06001744
Gavin Howard01055ba2018-11-03 11:00:21 -06001745 if (a->len == 0 || b->len == 0) {
1746 bc_num_zero(c);
1747 return BC_STATUS_SUCCESS;
1748 }
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001749 aone = BC_NUM_ONE(a);
1750 if (aone || BC_NUM_ONE(b)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001751 bc_num_copy(c, aone ? b : a);
1752 return BC_STATUS_SUCCESS;
1753 }
1754
1755 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1756 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1757 {
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001758 size_t i, j, len;
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001759 unsigned carry;
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001760
Gavin Howard01055ba2018-11-03 11:00:21 -06001761 bc_num_expand(c, a->len + b->len + 1);
1762
1763 memset(c->num, 0, sizeof(BcDig) * c->cap);
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001764 c->len = len = 0;
Gavin Howard01055ba2018-11-03 11:00:21 -06001765
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001766 for (i = 0; i < b->len; ++i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001767
Denys Vlasenkob692c2f2018-12-05 18:56:14 +01001768 carry = 0;
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001769 for (j = 0; j < a->len; ++j) {
Denys Vlasenkob3cb9012018-12-05 19:05:32 +01001770 unsigned in = c->num[i + j];
1771 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1772 // note: compilers prefer _unsigned_ div/const
Gavin Howard01055ba2018-11-03 11:00:21 -06001773 carry = in / 10;
1774 c->num[i + j] = (BcDig)(in % 10);
1775 }
1776
1777 c->num[i + j] += (BcDig) carry;
1778 len = BC_MAX(len, i + j + !!carry);
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01001779
1780 // a=2^1000000
1781 // a*a <- without check below, this will not be interruptible
1782 if (G_interrupt) return BC_STATUS_FAILURE;
Gavin Howard01055ba2018-11-03 11:00:21 -06001783 }
1784
1785 c->len = len;
1786
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001787 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06001788 }
1789
1790 bc_num_init(&l1, max);
1791 bc_num_init(&h1, max);
1792 bc_num_init(&l2, max);
1793 bc_num_init(&h2, max);
1794 bc_num_init(&m1, max);
1795 bc_num_init(&m2, max);
1796 bc_num_init(&z0, max);
1797 bc_num_init(&z1, max);
1798 bc_num_init(&z2, max);
1799 bc_num_init(&temp, max + max);
1800
1801 bc_num_split(a, max2, &l1, &h1);
1802 bc_num_split(b, max2, &l2, &h2);
1803
1804 s = bc_num_add(&h1, &l1, &m1, 0);
1805 if (s) goto err;
1806 s = bc_num_add(&h2, &l2, &m2, 0);
1807 if (s) goto err;
1808
1809 s = bc_num_k(&h1, &h2, &z0);
1810 if (s) goto err;
1811 s = bc_num_k(&m1, &m2, &z1);
1812 if (s) goto err;
1813 s = bc_num_k(&l1, &l2, &z2);
1814 if (s) goto err;
1815
1816 s = bc_num_sub(&z1, &z0, &temp, 0);
1817 if (s) goto err;
1818 s = bc_num_sub(&temp, &z2, &z1, 0);
1819 if (s) goto err;
1820
1821 s = bc_num_shift(&z0, max2 * 2);
1822 if (s) goto err;
1823 s = bc_num_shift(&z1, max2);
1824 if (s) goto err;
1825 s = bc_num_add(&z0, &z1, &temp, 0);
1826 if (s) goto err;
1827 s = bc_num_add(&temp, &z2, c, 0);
1828
1829err:
1830 bc_num_free(&temp);
1831 bc_num_free(&z2);
1832 bc_num_free(&z1);
1833 bc_num_free(&z0);
1834 bc_num_free(&m2);
1835 bc_num_free(&m1);
1836 bc_num_free(&h2);
1837 bc_num_free(&l2);
1838 bc_num_free(&h1);
1839 bc_num_free(&l1);
1840 return s;
1841}
1842
1843static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1844{
1845 BcStatus s;
1846 BcNum cpa, cpb;
1847 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1848
1849 scale = BC_MAX(scale, a->rdx);
1850 scale = BC_MAX(scale, b->rdx);
1851 scale = BC_MIN(a->rdx + b->rdx, scale);
1852 maxrdx = BC_MAX(maxrdx, scale);
1853
1854 bc_num_init(&cpa, a->len);
1855 bc_num_init(&cpb, b->len);
1856
1857 bc_num_copy(&cpa, a);
1858 bc_num_copy(&cpb, b);
1859 cpa.neg = cpb.neg = false;
1860
1861 s = bc_num_shift(&cpa, maxrdx);
1862 if (s) goto err;
1863 s = bc_num_shift(&cpb, maxrdx);
1864 if (s) goto err;
1865 s = bc_num_k(&cpa, &cpb, c);
1866 if (s) goto err;
1867
1868 maxrdx += scale;
1869 bc_num_expand(c, c->len + maxrdx);
1870
1871 if (c->len < maxrdx) {
1872 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1873 c->len += maxrdx;
1874 }
1875
1876 c->rdx = maxrdx;
1877 bc_num_retireMul(c, scale, a->neg, b->neg);
1878
1879err:
1880 bc_num_free(&cpb);
1881 bc_num_free(&cpa);
1882 return s;
1883}
1884
1885static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1886{
1887 BcStatus s = BC_STATUS_SUCCESS;
1888 BcDig *n, *p, q;
1889 size_t len, end, i;
1890 BcNum cp;
1891 bool zero = true;
1892
1893 if (b->len == 0)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001894 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001895 else if (a->len == 0) {
1896 bc_num_setToZero(c, scale);
1897 return BC_STATUS_SUCCESS;
1898 }
1899 else if (BC_NUM_ONE(b)) {
1900 bc_num_copy(c, a);
1901 bc_num_retireMul(c, scale, a->neg, b->neg);
1902 return BC_STATUS_SUCCESS;
1903 }
1904
1905 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1906 bc_num_copy(&cp, a);
1907 len = b->len;
1908
1909 if (len > cp.len) {
1910 bc_num_expand(&cp, len + 2);
1911 bc_num_extend(&cp, len - cp.len);
1912 }
1913
1914 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1915 cp.rdx -= b->rdx;
1916 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1917
1918 if (b->rdx == b->len) {
1919 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1920 len -= i - 1;
1921 }
1922
1923 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1924
1925 // We want an extra zero in front to make things simpler.
1926 cp.num[cp.len++] = 0;
1927 end = cp.len - len;
1928
1929 bc_num_expand(c, cp.len);
1930
1931 bc_num_zero(c);
1932 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1933 c->rdx = cp.rdx;
1934 c->len = cp.len;
1935 p = b->num;
1936
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001937 for (i = end - 1; !s && i < end; --i) {
Gavin Howard01055ba2018-11-03 11:00:21 -06001938 n = cp.num + i;
1939 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001940 bc_num_subArrays(n, p, len);
Gavin Howard01055ba2018-11-03 11:00:21 -06001941 c->num[i] = q;
Denys Vlasenkof381a882018-12-05 19:21:34 +01001942 // a=2^100000
1943 // scale=40000
1944 // 1/a <- without check below, this will not be interruptible
1945 if (G_interrupt) {
1946 s = BC_STATUS_FAILURE;
1947 break;
1948 }
Gavin Howard01055ba2018-11-03 11:00:21 -06001949 }
1950
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01001951 bc_num_retireMul(c, scale, a->neg, b->neg);
Gavin Howard01055ba2018-11-03 11:00:21 -06001952 bc_num_free(&cp);
1953
Denys Vlasenkof381a882018-12-05 19:21:34 +01001954 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06001955}
1956
1957static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
1958 BcNum *restrict d, size_t scale, size_t ts)
1959{
1960 BcStatus s;
1961 BcNum temp;
1962 bool neg;
1963
Denys Vlasenko60cf7472018-12-04 20:05:28 +01001964 if (b->len == 0)
1965 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06001966
1967 if (a->len == 0) {
1968 bc_num_setToZero(d, ts);
1969 return BC_STATUS_SUCCESS;
1970 }
1971
1972 bc_num_init(&temp, d->cap);
Denys Vlasenkof381a882018-12-05 19:21:34 +01001973 s = bc_num_d(a, b, c, scale);
1974 if (s) goto err;
Gavin Howard01055ba2018-11-03 11:00:21 -06001975
1976 if (scale != 0) scale = ts;
1977
1978 s = bc_num_m(c, b, &temp, scale);
1979 if (s) goto err;
1980 s = bc_num_sub(a, &temp, d, scale);
1981 if (s) goto err;
1982
1983 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
1984
1985 neg = d->neg;
1986 bc_num_retireMul(d, ts, a->neg, b->neg);
1987 d->neg = neg;
1988
1989err:
1990 bc_num_free(&temp);
1991 return s;
1992}
1993
1994static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1995{
1996 BcStatus s;
1997 BcNum c1;
1998 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
1999
2000 bc_num_init(&c1, len);
2001 s = bc_num_r(a, b, &c1, c, scale, ts);
2002 bc_num_free(&c1);
2003
2004 return s;
2005}
2006
2007static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2008{
2009 BcStatus s = BC_STATUS_SUCCESS;
2010 BcNum copy;
2011 unsigned long pow;
2012 size_t i, powrdx, resrdx;
2013 bool neg, zero;
2014
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002015 if (b->rdx) return bc_error("non integer number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002016
2017 if (b->len == 0) {
2018 bc_num_one(c);
2019 return BC_STATUS_SUCCESS;
2020 }
2021 else if (a->len == 0) {
2022 bc_num_setToZero(c, scale);
2023 return BC_STATUS_SUCCESS;
2024 }
2025 else if (BC_NUM_ONE(b)) {
2026 if (!b->neg)
2027 bc_num_copy(c, a);
2028 else
2029 s = bc_num_inv(a, c, scale);
2030 return s;
2031 }
2032
2033 neg = b->neg;
2034 b->neg = false;
2035
2036 s = bc_num_ulong(b, &pow);
2037 if (s) return s;
2038
2039 bc_num_init(&copy, a->len);
2040 bc_num_copy(&copy, a);
2041
2042 if (!neg) scale = BC_MIN(a->rdx * pow, BC_MAX(scale, a->rdx));
2043
2044 b->neg = neg;
2045
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002046 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002047 powrdx <<= 1;
2048 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2049 if (s) goto err;
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002050 // Not needed: bc_num_mul() has a check for ^C:
2051 //if (G_interrupt) {
2052 // s = BC_STATUS_FAILURE;
2053 // goto err;
2054 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002055 }
2056
Gavin Howard01055ba2018-11-03 11:00:21 -06002057 bc_num_copy(c, &copy);
2058
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002059 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002060
2061 powrdx <<= 1;
2062 s = bc_num_mul(&copy, &copy, &copy, powrdx);
2063 if (s) goto err;
2064
2065 if (pow & 1) {
2066 resrdx += powrdx;
2067 s = bc_num_mul(c, &copy, c, resrdx);
2068 if (s) goto err;
2069 }
Denys Vlasenko06fa65b2018-12-05 19:00:58 +01002070 // Not needed: bc_num_mul() has a check for ^C:
2071 //if (G_interrupt) {
2072 // s = BC_STATUS_FAILURE;
2073 // goto err;
2074 //}
Gavin Howard01055ba2018-11-03 11:00:21 -06002075 }
2076
2077 if (neg) {
2078 s = bc_num_inv(c, c, scale);
2079 if (s) goto err;
2080 }
2081
Gavin Howard01055ba2018-11-03 11:00:21 -06002082 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2083
2084 // We can't use bc_num_clean() here.
2085 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2086 if (zero) bc_num_setToZero(c, scale);
2087
2088err:
2089 bc_num_free(&copy);
2090 return s;
2091}
2092
2093static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2094 BcNumBinaryOp op, size_t req)
2095{
2096 BcStatus s;
2097 BcNum num2, *ptr_a, *ptr_b;
2098 bool init = false;
2099
2100 if (c == a) {
2101 ptr_a = &num2;
2102 memcpy(ptr_a, c, sizeof(BcNum));
2103 init = true;
2104 }
2105 else
2106 ptr_a = a;
2107
2108 if (c == b) {
2109 ptr_b = &num2;
2110 if (c != a) {
2111 memcpy(ptr_b, c, sizeof(BcNum));
2112 init = true;
2113 }
2114 }
2115 else
2116 ptr_b = b;
2117
2118 if (init)
2119 bc_num_init(c, req);
2120 else
2121 bc_num_expand(c, req);
2122
2123 s = op(ptr_a, ptr_b, c, scale);
2124
2125 if (init) bc_num_free(&num2);
2126
2127 return s;
2128}
2129
2130static bool bc_num_strValid(const char *val, size_t base)
2131{
2132 BcDig b;
2133 bool small, radix = false;
2134 size_t i, len = strlen(val);
2135
2136 if (!len) return true;
2137
2138 small = base <= 10;
2139 b = (BcDig)(small ? base + '0' : base - 10 + 'A');
2140
2141 for (i = 0; i < len; ++i) {
2142
2143 BcDig c = val[i];
2144
2145 if (c == '.') {
2146
2147 if (radix) return false;
2148
2149 radix = true;
2150 continue;
2151 }
2152
2153 if (c < '0' || (small && c >= b) || (c > '9' && (c < 'A' || c >= b)))
2154 return false;
2155 }
2156
2157 return true;
2158}
2159
2160static void bc_num_parseDecimal(BcNum *n, const char *val)
2161{
2162 size_t len, i;
2163 const char *ptr;
2164 bool zero = true;
2165
2166 for (i = 0; val[i] == '0'; ++i);
2167
2168 val += i;
2169 len = strlen(val);
2170 bc_num_zero(n);
2171
2172 if (len != 0) {
2173 for (i = 0; zero && i < len; ++i) zero = val[i] == '0' || val[i] == '.';
2174 bc_num_expand(n, len);
2175 }
2176
2177 ptr = strchr(val, '.');
2178
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002179 n->rdx = 0;
2180 if (ptr != NULL)
2181 n->rdx = (size_t)((val + len) - (ptr + 1));
Gavin Howard01055ba2018-11-03 11:00:21 -06002182
2183 if (!zero) {
2184 for (i = len - 1; i < len; ++n->len, i -= 1 + (i && val[i - 1] == '.'))
2185 n->num[n->len] = val[i] - '0';
2186 }
2187}
2188
2189static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2190{
2191 BcStatus s;
2192 BcNum temp, mult, result;
2193 BcDig c = '\0';
2194 bool zero = true;
2195 unsigned long v;
2196 size_t i, digits, len = strlen(val);
2197
2198 bc_num_zero(n);
2199
2200 for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
2201 if (zero) return;
2202
2203 bc_num_init(&temp, BC_NUM_DEF_SIZE);
2204 bc_num_init(&mult, BC_NUM_DEF_SIZE);
2205
2206 for (i = 0; i < len; ++i) {
2207
2208 c = val[i];
2209 if (c == '.') break;
2210
2211 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2212
2213 s = bc_num_mul(n, base, &mult, 0);
2214 if (s) goto int_err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002215 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002216 s = bc_num_add(&mult, &temp, n, 0);
2217 if (s) goto int_err;
2218 }
2219
2220 if (i == len) {
2221 c = val[i];
2222 if (c == 0) goto int_err;
2223 }
2224
2225 bc_num_init(&result, base->len);
2226 bc_num_zero(&result);
2227 bc_num_one(&mult);
2228
2229 for (i += 1, digits = 0; i < len; ++i, ++digits) {
2230
2231 c = val[i];
2232 if (c == 0) break;
2233
2234 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2235
2236 s = bc_num_mul(&result, base, &result, 0);
2237 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002238 bc_num_ulong2num(&temp, v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002239 s = bc_num_add(&result, &temp, &result, 0);
2240 if (s) goto err;
2241 s = bc_num_mul(&mult, base, &mult, 0);
2242 if (s) goto err;
2243 }
2244
2245 s = bc_num_div(&result, &mult, &result, digits);
2246 if (s) goto err;
2247 s = bc_num_add(n, &result, n, digits);
2248 if (s) goto err;
2249
2250 if (n->len != 0) {
2251 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2252 }
2253 else
2254 bc_num_zero(n);
2255
2256err:
2257 bc_num_free(&result);
2258int_err:
2259 bc_num_free(&mult);
2260 bc_num_free(&temp);
2261}
2262
2263static void bc_num_printNewline(size_t *nchars, size_t line_len)
2264{
2265 if (*nchars == line_len - 1) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002266 bb_putchar('\\');
2267 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06002268 *nchars = 0;
2269 }
2270}
2271
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002272#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002273static void bc_num_printChar(size_t num, size_t width, bool radix,
2274 size_t *nchars, size_t line_len)
2275{
2276 (void) radix, (void) line_len;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002277 bb_putchar((char) num);
Gavin Howard01055ba2018-11-03 11:00:21 -06002278 *nchars = *nchars + width;
2279}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002280#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002281
2282static void bc_num_printDigits(size_t num, size_t width, bool radix,
2283 size_t *nchars, size_t line_len)
2284{
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002285 size_t exp, pow;
Gavin Howard01055ba2018-11-03 11:00:21 -06002286
2287 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002288 bb_putchar(radix ? '.' : ' ');
Gavin Howard01055ba2018-11-03 11:00:21 -06002289 ++(*nchars);
2290
2291 bc_num_printNewline(nchars, line_len);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002292 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2293 continue;
Gavin Howard01055ba2018-11-03 11:00:21 -06002294
2295 for (exp = 0; exp < width; pow /= 10, ++(*nchars), ++exp) {
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002296 size_t dig;
Gavin Howard01055ba2018-11-03 11:00:21 -06002297 bc_num_printNewline(nchars, line_len);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002298 dig = num / pow;
2299 num -= dig * pow;
Denys Vlasenko00d77792018-11-30 23:13:42 +01002300 bb_putchar(((char) dig) + '0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002301 }
2302}
2303
2304static void bc_num_printHex(size_t num, size_t width, bool radix,
2305 size_t *nchars, size_t line_len)
2306{
2307 if (radix) {
2308 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002309 bb_putchar('.');
Gavin Howard01055ba2018-11-03 11:00:21 -06002310 *nchars += 1;
2311 }
2312
2313 bc_num_printNewline(nchars, line_len);
Denys Vlasenko00d77792018-11-30 23:13:42 +01002314 bb_putchar(bb_hexdigits_upcase[num]);
Gavin Howard01055ba2018-11-03 11:00:21 -06002315 *nchars = *nchars + width;
2316}
2317
2318static void bc_num_printDecimal(BcNum *n, size_t *nchars, size_t len)
2319{
2320 size_t i, rdx = n->rdx - 1;
2321
Denys Vlasenko00d77792018-11-30 23:13:42 +01002322 if (n->neg) bb_putchar('-');
Gavin Howard01055ba2018-11-03 11:00:21 -06002323 (*nchars) += n->neg;
2324
2325 for (i = n->len - 1; i < n->len; --i)
2326 bc_num_printHex((size_t) n->num[i], 1, i == rdx, nchars, len);
2327}
2328
2329static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width,
2330 size_t *nchars, size_t len, BcNumDigitOp print)
2331{
2332 BcStatus s;
2333 BcVec stack;
2334 BcNum intp, fracp, digit, frac_len;
2335 unsigned long dig, *ptr;
2336 size_t i;
2337 bool radix;
2338
2339 if (n->len == 0) {
2340 print(0, width, false, nchars, len);
2341 return BC_STATUS_SUCCESS;
2342 }
2343
2344 bc_vec_init(&stack, sizeof(long), NULL);
2345 bc_num_init(&intp, n->len);
2346 bc_num_init(&fracp, n->rdx);
2347 bc_num_init(&digit, width);
2348 bc_num_init(&frac_len, BC_NUM_INT(n));
2349 bc_num_copy(&intp, n);
2350 bc_num_one(&frac_len);
2351
2352 bc_num_truncate(&intp, intp.rdx);
2353 s = bc_num_sub(n, &intp, &fracp, 0);
2354 if (s) goto err;
2355
2356 while (intp.len != 0) {
2357 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2358 if (s) goto err;
2359 s = bc_num_ulong(&digit, &dig);
2360 if (s) goto err;
2361 bc_vec_push(&stack, &dig);
2362 }
2363
2364 for (i = 0; i < stack.len; ++i) {
2365 ptr = bc_vec_item_rev(&stack, i);
2366 print(*ptr, width, false, nchars, len);
2367 }
2368
2369 if (!n->rdx) goto err;
2370
2371 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2372 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2373 if (s) goto err;
2374 s = bc_num_ulong(&fracp, &dig);
2375 if (s) goto err;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01002376 bc_num_ulong2num(&intp, dig);
Gavin Howard01055ba2018-11-03 11:00:21 -06002377 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2378 if (s) goto err;
2379 print(dig, width, radix, nchars, len);
2380 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2381 if (s) goto err;
2382 }
2383
2384err:
2385 bc_num_free(&frac_len);
2386 bc_num_free(&digit);
2387 bc_num_free(&fracp);
2388 bc_num_free(&intp);
2389 bc_vec_free(&stack);
2390 return s;
2391}
2392
2393static BcStatus bc_num_printBase(BcNum *n, BcNum *base, size_t base_t,
2394 size_t *nchars, size_t line_len)
2395{
2396 BcStatus s;
2397 size_t width, i;
2398 BcNumDigitOp print;
2399 bool neg = n->neg;
2400
Denys Vlasenko00d77792018-11-30 23:13:42 +01002401 if (neg) bb_putchar('-');
Gavin Howard01055ba2018-11-03 11:00:21 -06002402 (*nchars) += neg;
2403
2404 n->neg = false;
2405
2406 if (base_t <= BC_NUM_MAX_IBASE) {
2407 width = 1;
2408 print = bc_num_printHex;
2409 }
2410 else {
2411 for (i = base_t - 1, width = 0; i != 0; i /= 10, ++width);
2412 print = bc_num_printDigits;
2413 }
2414
2415 s = bc_num_printNum(n, base, width, nchars, line_len, print);
2416 n->neg = neg;
2417
2418 return s;
2419}
2420
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002421#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002422static BcStatus bc_num_stream(BcNum *n, BcNum *base, size_t *nchars, size_t len)
2423{
2424 return bc_num_printNum(n, base, 1, nchars, len, bc_num_printChar);
2425}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002426#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002427
Gavin Howard01055ba2018-11-03 11:00:21 -06002428static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2429 size_t base_t)
2430{
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002431 if (!bc_num_strValid(val, base_t))
2432 return bc_error("bad number string");
Gavin Howard01055ba2018-11-03 11:00:21 -06002433
2434 if (base_t == 10)
2435 bc_num_parseDecimal(n, val);
2436 else
2437 bc_num_parseBase(n, val, base);
2438
2439 return BC_STATUS_SUCCESS;
2440}
2441
2442static BcStatus bc_num_print(BcNum *n, BcNum *base, size_t base_t, bool newline,
2443 size_t *nchars, size_t line_len)
2444{
2445 BcStatus s = BC_STATUS_SUCCESS;
2446
2447 bc_num_printNewline(nchars, line_len);
2448
2449 if (n->len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002450 bb_putchar('0');
Gavin Howard01055ba2018-11-03 11:00:21 -06002451 ++(*nchars);
2452 }
2453 else if (base_t == 10)
2454 bc_num_printDecimal(n, nchars, line_len);
2455 else
2456 s = bc_num_printBase(n, base, base_t, nchars, line_len);
2457
2458 if (newline) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01002459 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06002460 *nchars = 0;
2461 }
2462
2463 return s;
2464}
2465
Gavin Howard01055ba2018-11-03 11:00:21 -06002466static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2467{
2468 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2469 (void) scale;
2470 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2471}
2472
2473static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2474{
2475 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2476 (void) scale;
2477 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2478}
2479
2480static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2481{
2482 size_t req = BC_NUM_MREQ(a, b, scale);
2483 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2484}
2485
2486static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2487{
2488 size_t req = BC_NUM_MREQ(a, b, scale);
2489 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2490}
2491
2492static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2493{
2494 size_t req = BC_NUM_MREQ(a, b, scale);
2495 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2496}
2497
2498static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2499{
2500 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2501}
2502
2503static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2504{
2505 BcStatus s;
2506 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2507 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2508 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2509
2510 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2511 bc_num_expand(b, req);
2512
2513 if (a->len == 0) {
2514 bc_num_setToZero(b, scale);
2515 return BC_STATUS_SUCCESS;
2516 }
2517 else if (a->neg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002518 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002519 else if (BC_NUM_ONE(a)) {
2520 bc_num_one(b);
2521 bc_num_extend(b, scale);
2522 return BC_STATUS_SUCCESS;
2523 }
2524
2525 scale = BC_MAX(scale, a->rdx) + 1;
2526 len = a->len + scale;
2527
2528 bc_num_init(&num1, len);
2529 bc_num_init(&num2, len);
2530 bc_num_init(&half, BC_NUM_DEF_SIZE);
2531
2532 bc_num_one(&half);
2533 half.num[0] = 5;
2534 half.rdx = 1;
2535
2536 bc_num_init(&f, len);
2537 bc_num_init(&fprime, len);
2538
2539 x0 = &num1;
2540 x1 = &num2;
2541
2542 bc_num_one(x0);
2543 pow = BC_NUM_INT(a);
2544
2545 if (pow) {
2546
2547 if (pow & 1)
2548 x0->num[0] = 2;
2549 else
2550 x0->num[0] = 6;
2551
2552 pow -= 2 - (pow & 1);
2553
2554 bc_num_extend(x0, pow);
2555
2556 // Make sure to move the radix back.
2557 x0->rdx -= pow;
2558 }
2559
2560 x0->rdx = digs = digs1 = 0;
2561 resrdx = scale + 2;
2562 len = BC_NUM_INT(x0) + resrdx - 1;
2563
Denys Vlasenko71e1fc62018-12-02 19:43:34 +01002564 while (cmp != 0 || digs < len) {
Gavin Howard01055ba2018-11-03 11:00:21 -06002565
2566 s = bc_num_div(a, x0, &f, resrdx);
2567 if (s) goto err;
2568 s = bc_num_add(x0, &f, &fprime, resrdx);
2569 if (s) goto err;
2570 s = bc_num_mul(&fprime, &half, x1, resrdx);
2571 if (s) goto err;
2572
2573 cmp = bc_num_cmp(x1, x0);
2574 digs = x1->len - (unsigned long long) llabs(cmp);
2575
2576 if (cmp == cmp2 && digs == digs1)
2577 times += 1;
2578 else
2579 times = 0;
2580
2581 resrdx += times > 4;
2582
2583 cmp2 = cmp1;
2584 cmp1 = cmp;
2585 digs1 = digs;
2586
2587 temp = x0;
2588 x0 = x1;
2589 x1 = temp;
2590 }
2591
Gavin Howard01055ba2018-11-03 11:00:21 -06002592 bc_num_copy(b, x0);
2593 scale -= 1;
2594 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2595
2596err:
2597 bc_num_free(&fprime);
2598 bc_num_free(&f);
2599 bc_num_free(&half);
2600 bc_num_free(&num2);
2601 bc_num_free(&num1);
2602 return s;
2603}
2604
2605static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2606 size_t scale)
2607{
2608 BcStatus s;
2609 BcNum num2, *ptr_a;
2610 bool init = false;
2611 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2612
2613 if (c == a) {
2614 memcpy(&num2, c, sizeof(BcNum));
2615 ptr_a = &num2;
2616 bc_num_init(c, len);
2617 init = true;
2618 }
2619 else {
2620 ptr_a = a;
2621 bc_num_expand(c, len);
2622 }
2623
2624 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2625
2626 if (init) bc_num_free(&num2);
2627
2628 return s;
2629}
2630
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002631#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002632static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2633{
2634 BcStatus s;
2635 BcNum base, exp, two, temp;
2636
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002637 if (c->len == 0)
2638 return bc_error("divide by zero");
2639 if (a->rdx || b->rdx || c->rdx)
2640 return bc_error("non integer number");
2641 if (b->neg)
2642 return bc_error("negative number");
Gavin Howard01055ba2018-11-03 11:00:21 -06002643
2644 bc_num_expand(d, c->len);
2645 bc_num_init(&base, c->len);
2646 bc_num_init(&exp, b->len);
2647 bc_num_init(&two, BC_NUM_DEF_SIZE);
2648 bc_num_init(&temp, b->len);
2649
2650 bc_num_one(&two);
2651 two.num[0] = 2;
2652 bc_num_one(d);
2653
2654 s = bc_num_rem(a, c, &base, 0);
2655 if (s) goto err;
2656 bc_num_copy(&exp, b);
2657
2658 while (exp.len != 0) {
2659
2660 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2661 if (s) goto err;
2662
2663 if (BC_NUM_ONE(&temp)) {
2664 s = bc_num_mul(d, &base, &temp, 0);
2665 if (s) goto err;
2666 s = bc_num_rem(&temp, c, d, 0);
2667 if (s) goto err;
2668 }
2669
2670 s = bc_num_mul(&base, &base, &temp, 0);
2671 if (s) goto err;
2672 s = bc_num_rem(&temp, c, &base, 0);
2673 if (s) goto err;
2674 }
2675
2676err:
2677 bc_num_free(&temp);
2678 bc_num_free(&two);
2679 bc_num_free(&exp);
2680 bc_num_free(&base);
2681 return s;
2682}
2683#endif // ENABLE_DC
2684
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002685#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002686static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2687{
2688 BcId a;
2689 size_t i;
2690
2691 for (i = 0; i < f->autos.len; ++i) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002692 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2693 return bc_error("function parameter or auto var has the same name as another");
Gavin Howard01055ba2018-11-03 11:00:21 -06002694 }
2695
2696 a.idx = var;
2697 a.name = name;
2698
2699 bc_vec_push(&f->autos, &a);
2700
2701 return BC_STATUS_SUCCESS;
2702}
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01002703#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06002704
2705static void bc_func_init(BcFunc *f)
2706{
Denys Vlasenko7d628012018-12-04 21:46:47 +01002707 bc_char_vec_init(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06002708 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2709 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2710 f->nparams = 0;
2711}
2712
2713static void bc_func_free(void *func)
2714{
2715 BcFunc *f = (BcFunc *) func;
2716 bc_vec_free(&f->code);
2717 bc_vec_free(&f->autos);
2718 bc_vec_free(&f->labels);
2719}
2720
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002721static void bc_array_expand(BcVec *a, size_t len);
2722
Gavin Howard01055ba2018-11-03 11:00:21 -06002723static void bc_array_init(BcVec *a, bool nums)
2724{
2725 if (nums)
2726 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2727 else
2728 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2729 bc_array_expand(a, 1);
2730}
2731
Gavin Howard01055ba2018-11-03 11:00:21 -06002732static void bc_array_expand(BcVec *a, size_t len)
2733{
2734 BcResultData data;
2735
2736 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2737 while (len > a->len) {
2738 bc_num_init(&data.n, BC_NUM_DEF_SIZE);
2739 bc_vec_push(a, &data.n);
2740 }
2741 }
2742 else {
2743 while (len > a->len) {
2744 bc_array_init(&data.v, true);
2745 bc_vec_push(a, &data.v);
2746 }
2747 }
2748}
2749
Denys Vlasenkob0e37612018-12-05 21:03:16 +01002750static void bc_array_copy(BcVec *d, const BcVec *s)
2751{
2752 size_t i;
2753
2754 bc_vec_pop_all(d);
2755 bc_vec_expand(d, s->cap);
2756 d->len = s->len;
2757
2758 for (i = 0; i < s->len; ++i) {
2759 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2760 bc_num_init(dnum, snum->len);
2761 bc_num_copy(dnum, snum);
2762 }
2763}
2764
Gavin Howard01055ba2018-11-03 11:00:21 -06002765static void bc_string_free(void *string)
2766{
2767 free(*((char **) string));
2768}
2769
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002770#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06002771static void bc_result_copy(BcResult *d, BcResult *src)
2772{
2773 d->t = src->t;
2774
2775 switch (d->t) {
2776
2777 case BC_RESULT_TEMP:
2778 case BC_RESULT_IBASE:
2779 case BC_RESULT_SCALE:
2780 case BC_RESULT_OBASE:
2781 {
2782 bc_num_init(&d->d.n, src->d.n.len);
2783 bc_num_copy(&d->d.n, &src->d.n);
2784 break;
2785 }
2786
2787 case BC_RESULT_VAR:
2788 case BC_RESULT_ARRAY:
2789 case BC_RESULT_ARRAY_ELEM:
2790 {
2791 d->d.id.name = xstrdup(src->d.id.name);
2792 break;
2793 }
2794
2795 case BC_RESULT_CONSTANT:
2796 case BC_RESULT_LAST:
2797 case BC_RESULT_ONE:
2798 case BC_RESULT_STR:
2799 {
2800 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2801 break;
2802 }
2803 }
2804}
2805#endif // ENABLE_DC
2806
2807static void bc_result_free(void *result)
2808{
2809 BcResult *r = (BcResult *) result;
2810
2811 switch (r->t) {
2812
2813 case BC_RESULT_TEMP:
2814 case BC_RESULT_IBASE:
2815 case BC_RESULT_SCALE:
2816 case BC_RESULT_OBASE:
2817 {
2818 bc_num_free(&r->d.n);
2819 break;
2820 }
2821
2822 case BC_RESULT_VAR:
2823 case BC_RESULT_ARRAY:
2824 case BC_RESULT_ARRAY_ELEM:
2825 {
2826 free(r->d.id.name);
2827 break;
2828 }
2829
2830 default:
2831 {
2832 // Do nothing.
2833 break;
2834 }
2835 }
2836}
2837
2838static void bc_lex_lineComment(BcLex *l)
2839{
2840 l->t.t = BC_LEX_WHITESPACE;
2841 while (l->i < l->len && l->buf[l->i++] != '\n');
2842 --l->i;
2843}
2844
2845static void bc_lex_whitespace(BcLex *l)
2846{
2847 char c;
2848 l->t.t = BC_LEX_WHITESPACE;
2849 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2850}
2851
2852static BcStatus bc_lex_number(BcLex *l, char start)
2853{
2854 const char *buf = l->buf + l->i;
2855 size_t len, hits = 0, bslashes = 0, i = 0, j;
2856 char c = buf[i];
2857 bool last_pt, pt = start == '.';
2858
2859 last_pt = pt;
2860 l->t.t = BC_LEX_NUMBER;
2861
2862 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2863 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2864 {
2865 if (c != '\\') {
2866 last_pt = c == '.';
2867 pt = pt || last_pt;
2868 }
2869 else {
2870 ++i;
2871 bslashes += 1;
2872 }
2873
2874 c = buf[++i];
2875 }
2876
Denys Vlasenkod5f77032018-12-04 21:37:56 +01002877 len = i + !last_pt - bslashes * 2;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002878 if (len > BC_MAX_NUM)
2879 return bc_error("number too long: must be [1, BC_NUM_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06002880
Denys Vlasenko7d628012018-12-04 21:46:47 +01002881 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002882 bc_vec_expand(&l->t.v, len + 1);
2883 bc_vec_push(&l->t.v, &start);
2884
2885 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2886
2887 c = buf[j];
2888
2889 // If we have hit a backslash, skip it. We don't have
2890 // to check for a newline because it's guaranteed.
2891 if (hits < bslashes && c == '\\') {
2892 ++hits;
2893 ++j;
2894 continue;
2895 }
2896
2897 bc_vec_push(&l->t.v, &c);
2898 }
2899
Denys Vlasenko08c033c2018-12-05 16:55:08 +01002900 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002901 l->i += i;
2902
2903 return BC_STATUS_SUCCESS;
2904}
2905
2906static BcStatus bc_lex_name(BcLex *l)
2907{
2908 size_t i = 0;
2909 const char *buf = l->buf + l->i - 1;
2910 char c = buf[i];
2911
2912 l->t.t = BC_LEX_NAME;
2913
2914 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2915
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002916 if (i > BC_MAX_STRING)
2917 return bc_error("name too long: must be [1, BC_NAME_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06002918 bc_vec_string(&l->t.v, i, buf);
2919
2920 // Increment the index. We minus 1 because it has already been incremented.
2921 l->i += i - 1;
2922
2923 return BC_STATUS_SUCCESS;
2924}
2925
2926static void bc_lex_init(BcLex *l, BcLexNext next)
2927{
2928 l->next = next;
Denys Vlasenko7d628012018-12-04 21:46:47 +01002929 bc_char_vec_init(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06002930}
2931
2932static void bc_lex_free(BcLex *l)
2933{
2934 bc_vec_free(&l->t.v);
2935}
2936
Denys Vlasenko0409ad32018-12-05 16:39:22 +01002937static void bc_lex_file(BcLex *l)
Gavin Howard01055ba2018-11-03 11:00:21 -06002938{
Denys Vlasenko5318f812018-12-05 17:48:01 +01002939 G.err_line = l->line = 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06002940 l->newline = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06002941}
2942
2943static BcStatus bc_lex_next(BcLex *l)
2944{
2945 BcStatus s;
2946
2947 l->t.last = l->t.t;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01002948 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06002949
2950 l->line += l->newline;
Denys Vlasenko5318f812018-12-05 17:48:01 +01002951 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06002952 l->t.t = BC_LEX_EOF;
2953
2954 l->newline = (l->i == l->len);
2955 if (l->newline) return BC_STATUS_SUCCESS;
2956
2957 // Loop until failure or we don't have whitespace. This
2958 // is so the parser doesn't get inundated with whitespace.
2959 do {
2960 s = l->next(l);
2961 } while (!s && l->t.t == BC_LEX_WHITESPACE);
2962
2963 return s;
2964}
2965
2966static BcStatus bc_lex_text(BcLex *l, const char *text)
2967{
2968 l->buf = text;
2969 l->i = 0;
2970 l->len = strlen(text);
2971 l->t.t = l->t.last = BC_LEX_INVALID;
2972 return bc_lex_next(l);
2973}
2974
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01002975#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06002976static BcStatus bc_lex_identifier(BcLex *l)
2977{
2978 BcStatus s;
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002979 unsigned i;
Gavin Howard01055ba2018-11-03 11:00:21 -06002980 const char *buf = l->buf + l->i - 1;
2981
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002982 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2983 const char *keyword8 = bc_lex_kws[i].name8;
2984 unsigned j = 0;
2985 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2986 j++;
2987 if (j == 8) goto match;
Gavin Howard01055ba2018-11-03 11:00:21 -06002988 }
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002989 if (keyword8[j] != '\0')
2990 continue;
2991 match:
2992 // buf starts with keyword bc_lex_kws[i]
2993 l->t.t = BC_LEX_KEY_1st_keyword + i;
Denys Vlasenkod00d2f92018-12-06 12:59:40 +01002994 if (!bc_lex_kws_POSIX(i)) {
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01002995 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01002996 if (s) return s;
2997 }
2998
2999 // We minus 1 because the index has already been incremented.
3000 l->i += j - 1;
3001 return BC_STATUS_SUCCESS;
Gavin Howard01055ba2018-11-03 11:00:21 -06003002 }
3003
3004 s = bc_lex_name(l);
3005 if (s) return s;
3006
Denys Vlasenko0d7e46b2018-12-05 18:31:19 +01003007 if (l->t.v.len > 2) {
3008 // Prevent this:
3009 // >>> qwe=1
3010 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3011 // '
3012 unsigned len = strchrnul(buf, '\n') - buf;
3013 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3014 }
Gavin Howard01055ba2018-11-03 11:00:21 -06003015
3016 return s;
3017}
3018
3019static BcStatus bc_lex_string(BcLex *l)
3020{
3021 size_t len, nls = 0, i = l->i;
3022 char c;
3023
3024 l->t.t = BC_LEX_STR;
3025
3026 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3027
3028 if (c == '\0') {
3029 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003030 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003031 }
3032
3033 len = i - l->i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003034 if (len > BC_MAX_STRING)
3035 return bc_error("string too long: must be [1, BC_STRING_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06003036 bc_vec_string(&l->t.v, len, l->buf + l->i);
3037
3038 l->i = i + 1;
3039 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003040 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003041
3042 return BC_STATUS_SUCCESS;
3043}
3044
3045static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3046{
3047 if (l->buf[l->i] == '=') {
3048 ++l->i;
3049 l->t.t = with;
3050 }
3051 else
3052 l->t.t = without;
3053}
3054
3055static BcStatus bc_lex_comment(BcLex *l)
3056{
3057 size_t i, nls = 0;
3058 const char *buf = l->buf;
Gavin Howard01055ba2018-11-03 11:00:21 -06003059
3060 l->t.t = BC_LEX_WHITESPACE;
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003061 i = ++l->i;
3062 for (;;) {
3063 char c = buf[i];
3064 check_star:
3065 if (c == '*') {
3066 c = buf[++i];
3067 if (c == '/')
3068 break;
3069 goto check_star;
3070 }
3071 if (c == '\0') {
Gavin Howard01055ba2018-11-03 11:00:21 -06003072 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003073 return bc_error("comment end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003074 }
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003075 nls += (c == '\n');
3076 i++;
Gavin Howard01055ba2018-11-03 11:00:21 -06003077 }
3078
Denys Vlasenkobc5ce662018-12-03 19:12:29 +01003079 l->i = i + 1;
Gavin Howard01055ba2018-11-03 11:00:21 -06003080 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003081 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003082
3083 return BC_STATUS_SUCCESS;
3084}
3085
3086static BcStatus bc_lex_token(BcLex *l)
3087{
3088 BcStatus s = BC_STATUS_SUCCESS;
3089 char c = l->buf[l->i++], c2;
3090
3091 // This is the workhorse of the lexer.
3092 switch (c) {
3093
3094 case '\0':
3095 case '\n':
3096 {
3097 l->newline = true;
3098 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3099 break;
3100 }
3101
3102 case '\t':
3103 case '\v':
3104 case '\f':
3105 case '\r':
3106 case ' ':
3107 {
3108 bc_lex_whitespace(l);
3109 break;
3110 }
3111
3112 case '!':
3113 {
3114 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3115
3116 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
Denys Vlasenko00646792018-12-05 18:12:27 +01003117 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
Gavin Howard01055ba2018-11-03 11:00:21 -06003118 if (s) return s;
3119 }
3120
3121 break;
3122 }
3123
3124 case '"':
3125 {
3126 s = bc_lex_string(l);
3127 break;
3128 }
3129
3130 case '#':
3131 {
Denys Vlasenko00646792018-12-05 18:12:27 +01003132 s = bc_POSIX_does_not_allow("'#' script comments");
Gavin Howard01055ba2018-11-03 11:00:21 -06003133 if (s) return s;
3134
3135 bc_lex_lineComment(l);
3136
3137 break;
3138 }
3139
3140 case '%':
3141 {
3142 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3143 break;
3144 }
3145
3146 case '&':
3147 {
3148 c2 = l->buf[l->i];
3149 if (c2 == '&') {
3150
Denys Vlasenko00646792018-12-05 18:12:27 +01003151 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
Gavin Howard01055ba2018-11-03 11:00:21 -06003152 if (s) return s;
3153
3154 ++l->i;
3155 l->t.t = BC_LEX_OP_BOOL_AND;
3156 }
3157 else {
3158 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003159 s = bc_error_bad_character('&');
Gavin Howard01055ba2018-11-03 11:00:21 -06003160 }
3161
3162 break;
3163 }
3164
3165 case '(':
3166 case ')':
3167 {
3168 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3169 break;
3170 }
3171
3172 case '*':
3173 {
3174 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3175 break;
3176 }
3177
3178 case '+':
3179 {
3180 c2 = l->buf[l->i];
3181 if (c2 == '+') {
3182 ++l->i;
3183 l->t.t = BC_LEX_OP_INC;
3184 }
3185 else
3186 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3187 break;
3188 }
3189
3190 case ',':
3191 {
3192 l->t.t = BC_LEX_COMMA;
3193 break;
3194 }
3195
3196 case '-':
3197 {
3198 c2 = l->buf[l->i];
3199 if (c2 == '-') {
3200 ++l->i;
3201 l->t.t = BC_LEX_OP_DEC;
3202 }
3203 else
3204 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3205 break;
3206 }
3207
3208 case '.':
3209 {
3210 if (isdigit(l->buf[l->i]))
3211 s = bc_lex_number(l, c);
3212 else {
3213 l->t.t = BC_LEX_KEY_LAST;
Denys Vlasenko00646792018-12-05 18:12:27 +01003214 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
Gavin Howard01055ba2018-11-03 11:00:21 -06003215 }
3216 break;
3217 }
3218
3219 case '/':
3220 {
3221 c2 = l->buf[l->i];
3222 if (c2 == '*')
3223 s = bc_lex_comment(l);
3224 else
3225 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3226 break;
3227 }
3228
3229 case '0':
3230 case '1':
3231 case '2':
3232 case '3':
3233 case '4':
3234 case '5':
3235 case '6':
3236 case '7':
3237 case '8':
3238 case '9':
3239 case 'A':
3240 case 'B':
3241 case 'C':
3242 case 'D':
3243 case 'E':
3244 case 'F':
3245 {
3246 s = bc_lex_number(l, c);
3247 break;
3248 }
3249
3250 case ';':
3251 {
3252 l->t.t = BC_LEX_SCOLON;
3253 break;
3254 }
3255
3256 case '<':
3257 {
3258 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3259 break;
3260 }
3261
3262 case '=':
3263 {
3264 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3265 break;
3266 }
3267
3268 case '>':
3269 {
3270 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3271 break;
3272 }
3273
3274 case '[':
3275 case ']':
3276 {
3277 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3278 break;
3279 }
3280
3281 case '\\':
3282 {
3283 if (l->buf[l->i] == '\n') {
3284 l->t.t = BC_LEX_WHITESPACE;
3285 ++l->i;
3286 }
3287 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003288 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003289 break;
3290 }
3291
3292 case '^':
3293 {
3294 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3295 break;
3296 }
3297
3298 case 'a':
3299 case 'b':
3300 case 'c':
3301 case 'd':
3302 case 'e':
3303 case 'f':
3304 case 'g':
3305 case 'h':
3306 case 'i':
3307 case 'j':
3308 case 'k':
3309 case 'l':
3310 case 'm':
3311 case 'n':
3312 case 'o':
3313 case 'p':
3314 case 'q':
3315 case 'r':
3316 case 's':
3317 case 't':
3318 case 'u':
3319 case 'v':
3320 case 'w':
3321 case 'x':
3322 case 'y':
3323 case 'z':
3324 {
3325 s = bc_lex_identifier(l);
3326 break;
3327 }
3328
3329 case '{':
3330 case '}':
3331 {
3332 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3333 break;
3334 }
3335
3336 case '|':
3337 {
3338 c2 = l->buf[l->i];
3339
3340 if (c2 == '|') {
Denys Vlasenko00646792018-12-05 18:12:27 +01003341 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
Gavin Howard01055ba2018-11-03 11:00:21 -06003342 if (s) return s;
3343
3344 ++l->i;
3345 l->t.t = BC_LEX_OP_BOOL_OR;
3346 }
3347 else {
3348 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003349 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003350 }
3351
3352 break;
3353 }
3354
3355 default:
3356 {
3357 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003358 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003359 break;
3360 }
3361 }
3362
3363 return s;
3364}
3365#endif // ENABLE_BC
3366
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003367#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06003368static BcStatus dc_lex_register(BcLex *l)
3369{
3370 BcStatus s = BC_STATUS_SUCCESS;
3371
3372 if (isspace(l->buf[l->i - 1])) {
3373 bc_lex_whitespace(l);
3374 ++l->i;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01003375 if (!G_exreg)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003376 s = bc_error("extended register");
Gavin Howard01055ba2018-11-03 11:00:21 -06003377 else
3378 s = bc_lex_name(l);
3379 }
3380 else {
Denys Vlasenko7d628012018-12-04 21:46:47 +01003381 bc_vec_pop_all(&l->t.v);
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003382 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003383 bc_vec_pushZeroByte(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003384 l->t.t = BC_LEX_NAME;
3385 }
3386
3387 return s;
3388}
3389
3390static BcStatus dc_lex_string(BcLex *l)
3391{
3392 size_t depth = 1, nls = 0, i = l->i;
3393 char c;
3394
3395 l->t.t = BC_LEX_STR;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003396 bc_vec_pop_all(&l->t.v);
Gavin Howard01055ba2018-11-03 11:00:21 -06003397
3398 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3399
3400 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3401 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3402 nls += (c == '\n');
3403
3404 if (depth) bc_vec_push(&l->t.v, &c);
3405 }
3406
3407 if (c == '\0') {
3408 l->i = i;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003409 return bc_error("string end could not be found");
Gavin Howard01055ba2018-11-03 11:00:21 -06003410 }
3411
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003412 bc_vec_pushZeroByte(&l->t.v);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003413 if (i - l->i > BC_MAX_STRING)
3414 return bc_error("string too long: must be [1, BC_STRING_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06003415
3416 l->i = i;
3417 l->line += nls;
Denys Vlasenko5318f812018-12-05 17:48:01 +01003418 G.err_line = l->line;
Gavin Howard01055ba2018-11-03 11:00:21 -06003419
3420 return BC_STATUS_SUCCESS;
3421}
3422
3423static BcStatus dc_lex_token(BcLex *l)
3424{
3425 BcStatus s = BC_STATUS_SUCCESS;
3426 char c = l->buf[l->i++], c2;
3427 size_t i;
3428
Denys Vlasenko51fb8aa2018-12-05 00:22:34 +01003429 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3430 if (l->t.last == dc_lex_regs[i])
3431 return dc_lex_register(l);
Gavin Howard01055ba2018-11-03 11:00:21 -06003432 }
3433
3434 if (c >= '%' && c <= '~' &&
3435 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3436 {
3437 return s;
3438 }
3439
3440 // This is the workhorse of the lexer.
3441 switch (c) {
3442
3443 case '\0':
3444 {
3445 l->t.t = BC_LEX_EOF;
3446 break;
3447 }
3448
3449 case '\n':
3450 case '\t':
3451 case '\v':
3452 case '\f':
3453 case '\r':
3454 case ' ':
3455 {
3456 l->newline = (c == '\n');
3457 bc_lex_whitespace(l);
3458 break;
3459 }
3460
3461 case '!':
3462 {
3463 c2 = l->buf[l->i];
3464
3465 if (c2 == '=')
3466 l->t.t = BC_LEX_OP_REL_NE;
3467 else if (c2 == '<')
3468 l->t.t = BC_LEX_OP_REL_LE;
3469 else if (c2 == '>')
3470 l->t.t = BC_LEX_OP_REL_GE;
3471 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003472 return bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003473
3474 ++l->i;
3475 break;
3476 }
3477
3478 case '#':
3479 {
3480 bc_lex_lineComment(l);
3481 break;
3482 }
3483
3484 case '.':
3485 {
3486 if (isdigit(l->buf[l->i]))
3487 s = bc_lex_number(l, c);
3488 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003489 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003490 break;
3491 }
3492
3493 case '0':
3494 case '1':
3495 case '2':
3496 case '3':
3497 case '4':
3498 case '5':
3499 case '6':
3500 case '7':
3501 case '8':
3502 case '9':
3503 case 'A':
3504 case 'B':
3505 case 'C':
3506 case 'D':
3507 case 'E':
3508 case 'F':
3509 {
3510 s = bc_lex_number(l, c);
3511 break;
3512 }
3513
3514 case '[':
3515 {
3516 s = dc_lex_string(l);
3517 break;
3518 }
3519
3520 default:
3521 {
3522 l->t.t = BC_LEX_INVALID;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003523 s = bc_error_bad_character(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06003524 break;
3525 }
3526 }
3527
3528 return s;
3529}
3530#endif // ENABLE_DC
3531
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003532static void bc_program_addFunc(char *name, size_t *idx);
3533
Gavin Howard01055ba2018-11-03 11:00:21 -06003534static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3535{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003536 bc_program_addFunc(name, idx);
3537 p->func = bc_vec_item(&G.prog.fns, p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003538}
3539
Denys Vlasenkob23ac512018-12-06 13:10:56 +01003540#define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3541
Gavin Howard01055ba2018-11-03 11:00:21 -06003542static void bc_parse_pushName(BcParse *p, char *name)
3543{
3544 size_t i = 0, len = strlen(name);
3545
3546 for (; i < len; ++i) bc_parse_push(p, name[i]);
3547 bc_parse_push(p, BC_PARSE_STREND);
3548
3549 free(name);
3550}
3551
3552static void bc_parse_pushIndex(BcParse *p, size_t idx)
3553{
3554 unsigned char amt, i, nums[sizeof(size_t)];
3555
3556 for (amt = 0; idx; ++amt) {
3557 nums[amt] = (char) idx;
3558 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3559 }
3560
3561 bc_parse_push(p, amt);
3562 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3563}
3564
3565static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3566{
3567 char *num = xstrdup(p->l.t.v.v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003568 size_t idx = G.prog.consts.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06003569
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003570 bc_vec_push(&G.prog.consts, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06003571
3572 bc_parse_push(p, BC_INST_NUM);
3573 bc_parse_pushIndex(p, idx);
3574
3575 ++(*nexs);
3576 (*prev) = BC_INST_NUM;
3577}
3578
3579static BcStatus bc_parse_text(BcParse *p, const char *text)
3580{
3581 BcStatus s;
3582
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003583 p->func = bc_vec_item(&G.prog.fns, p->fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003584
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003585 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003586 p->l.t.t = BC_LEX_INVALID;
3587 s = p->parse(p);
3588 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003589 if (!BC_PARSE_CAN_EXEC(p))
3590 return bc_error("file is not executable");
Gavin Howard01055ba2018-11-03 11:00:21 -06003591 }
3592
3593 return bc_lex_text(&p->l, text);
3594}
3595
Denys Vlasenkob6f60862018-12-06 12:54:26 +01003596// Called when parsing or execution detects a failure,
3597// resets execution structures.
3598static void bc_program_reset(void)
3599{
3600 BcFunc *f;
3601 BcInstPtr *ip;
3602
3603 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3604 bc_vec_pop_all(&G.prog.results);
3605
3606 f = bc_vec_item(&G.prog.fns, 0);
3607 ip = bc_vec_top(&G.prog.stack);
3608 ip->idx = f->code.len;
3609}
3610
Denys Vlasenkoe55a5722018-12-06 12:47:17 +01003611#define bc_parse_updateFunc(p, f) \
3612 ((p)->func = bc_vec_item(&G.prog.fns, ((p)->fidx = (f))))
3613
Denys Vlasenkod38af482018-12-04 19:11:02 +01003614// Called when bc/dc_parse_parse() detects a failure,
3615// resets parsing structures.
3616static void bc_parse_reset(BcParse *p)
Gavin Howard01055ba2018-11-03 11:00:21 -06003617{
3618 if (p->fidx != BC_PROG_MAIN) {
Gavin Howard01055ba2018-11-03 11:00:21 -06003619 p->func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01003620 bc_vec_pop_all(&p->func->code);
3621 bc_vec_pop_all(&p->func->autos);
3622 bc_vec_pop_all(&p->func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06003623
3624 bc_parse_updateFunc(p, BC_PROG_MAIN);
3625 }
3626
3627 p->l.i = p->l.len;
3628 p->l.t.t = BC_LEX_EOF;
3629 p->auto_part = (p->nbraces = 0);
3630
3631 bc_vec_npop(&p->flags, p->flags.len - 1);
Denys Vlasenko7d628012018-12-04 21:46:47 +01003632 bc_vec_pop_all(&p->exits);
3633 bc_vec_pop_all(&p->conds);
3634 bc_vec_pop_all(&p->ops);
Gavin Howard01055ba2018-11-03 11:00:21 -06003635
Denys Vlasenkod38af482018-12-04 19:11:02 +01003636 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06003637}
3638
3639static void bc_parse_free(BcParse *p)
3640{
3641 bc_vec_free(&p->flags);
3642 bc_vec_free(&p->exits);
3643 bc_vec_free(&p->conds);
3644 bc_vec_free(&p->ops);
3645 bc_lex_free(&p->l);
3646}
3647
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003648static void bc_parse_create(BcParse *p, size_t func,
Gavin Howard01055ba2018-11-03 11:00:21 -06003649 BcParseParse parse, BcLexNext next)
3650{
3651 memset(p, 0, sizeof(BcParse));
3652
3653 bc_lex_init(&p->l, next);
3654 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3655 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3656 bc_vec_init(&p->conds, sizeof(size_t), NULL);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01003657 bc_vec_pushZeroByte(&p->flags);
Gavin Howard01055ba2018-11-03 11:00:21 -06003658 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3659
3660 p->parse = parse;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01003661 // p->auto_part = p->nbraces = 0; - already is
Gavin Howard01055ba2018-11-03 11:00:21 -06003662 bc_parse_updateFunc(p, func);
3663}
3664
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01003665#if ENABLE_BC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003666
3667#define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3668#define BC_PARSE_LEAF(p, rparen) \
3669 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3670 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3671
3672// We can calculate the conversion between tokens and exprs by subtracting the
3673// position of the first operator in the lex enum and adding the position of the
3674// first in the expr enum. Note: This only works for binary operators.
3675#define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3676
Gavin Howard01055ba2018-11-03 11:00:21 -06003677static BcStatus bc_parse_else(BcParse *p);
3678static BcStatus bc_parse_stmt(BcParse *p);
Denys Vlasenkocca79a02018-12-05 21:15:46 +01003679static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01003680static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
Gavin Howard01055ba2018-11-03 11:00:21 -06003681
3682static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3683 size_t *nexprs, bool next)
3684{
3685 BcStatus s = BC_STATUS_SUCCESS;
3686 BcLexType t;
Denys Vlasenko65437582018-12-05 19:37:19 +01003687 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3688 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003689
3690 while (p->ops.len > start) {
3691
3692 t = BC_PARSE_TOP_OP(p);
3693 if (t == BC_LEX_LPAREN) break;
3694
Denys Vlasenko65437582018-12-05 19:37:19 +01003695 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
Gavin Howard01055ba2018-11-03 11:00:21 -06003696 if (l >= r && (l != r || !left)) break;
3697
3698 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3699 bc_vec_pop(&p->ops);
3700 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3701 }
3702
3703 bc_vec_push(&p->ops, &type);
3704 if (next) s = bc_lex_next(&p->l);
3705
3706 return s;
3707}
3708
3709static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3710{
3711 BcLexType top;
3712
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003713 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003714 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003715 top = BC_PARSE_TOP_OP(p);
3716
3717 while (top != BC_LEX_LPAREN) {
3718
3719 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3720
3721 bc_vec_pop(&p->ops);
3722 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3723
Denys Vlasenko60cf7472018-12-04 20:05:28 +01003724 if (p->ops.len <= ops_bgn)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003725 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003726 top = BC_PARSE_TOP_OP(p);
3727 }
3728
3729 bc_vec_pop(&p->ops);
3730
3731 return bc_lex_next(&p->l);
3732}
3733
3734static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3735{
3736 BcStatus s;
3737 bool comma = false;
3738 size_t nparams;
3739
3740 s = bc_lex_next(&p->l);
3741 if (s) return s;
3742
3743 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3744
3745 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3746 s = bc_parse_expr(p, flags, bc_parse_next_param);
3747 if (s) return s;
3748
3749 comma = p->l.t.t == BC_LEX_COMMA;
3750 if (comma) {
3751 s = bc_lex_next(&p->l);
3752 if (s) return s;
3753 }
3754 }
3755
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003756 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003757 bc_parse_push(p, BC_INST_CALL);
3758 bc_parse_pushIndex(p, nparams);
3759
3760 return BC_STATUS_SUCCESS;
3761}
3762
3763static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3764{
3765 BcStatus s;
3766 BcId entry, *entry_ptr;
3767 size_t idx;
3768
3769 entry.name = name;
3770
3771 s = bc_parse_params(p, flags);
3772 if (s) goto err;
3773
3774 if (p->l.t.t != BC_LEX_RPAREN) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003775 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003776 goto err;
3777 }
3778
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003779 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003780
3781 if (idx == BC_VEC_INVALID_IDX) {
3782 name = xstrdup(entry.name);
3783 bc_parse_addFunc(p, name, &idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003784 idx = bc_map_index(&G.prog.fn_map, &entry);
Gavin Howard01055ba2018-11-03 11:00:21 -06003785 free(entry.name);
3786 }
3787 else
3788 free(name);
3789
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01003790 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06003791 bc_parse_pushIndex(p, entry_ptr->idx);
3792
3793 return bc_lex_next(&p->l);
3794
3795err:
3796 free(name);
3797 return s;
3798}
3799
3800static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3801{
3802 BcStatus s;
3803 char *name;
3804
3805 name = xstrdup(p->l.t.v.v);
3806 s = bc_lex_next(&p->l);
3807 if (s) goto err;
3808
3809 if (p->l.t.t == BC_LEX_LBRACKET) {
3810
3811 s = bc_lex_next(&p->l);
3812 if (s) goto err;
3813
3814 if (p->l.t.t == BC_LEX_RBRACKET) {
3815
3816 if (!(flags & BC_PARSE_ARRAY)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003817 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06003818 goto err;
3819 }
3820
3821 *type = BC_INST_ARRAY;
3822 }
3823 else {
3824
3825 *type = BC_INST_ARRAY_ELEM;
3826
3827 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3828 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3829 if (s) goto err;
3830 }
3831
3832 s = bc_lex_next(&p->l);
3833 if (s) goto err;
3834 bc_parse_push(p, *type);
3835 bc_parse_pushName(p, name);
3836 }
3837 else if (p->l.t.t == BC_LEX_LPAREN) {
3838
3839 if (flags & BC_PARSE_NOCALL) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003840 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003841 goto err;
3842 }
3843
3844 *type = BC_INST_CALL;
3845 s = bc_parse_call(p, name, flags);
3846 }
3847 else {
3848 *type = BC_INST_VAR;
3849 bc_parse_push(p, BC_INST_VAR);
3850 bc_parse_pushName(p, name);
3851 }
3852
3853 return s;
3854
3855err:
3856 free(name);
3857 return s;
3858}
3859
3860static BcStatus bc_parse_read(BcParse *p)
3861{
3862 BcStatus s;
3863
3864 s = bc_lex_next(&p->l);
3865 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003866 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003867
3868 s = bc_lex_next(&p->l);
3869 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003870 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003871
3872 bc_parse_push(p, BC_INST_READ);
3873
3874 return bc_lex_next(&p->l);
3875}
3876
3877static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3878 BcInst *prev)
3879{
3880 BcStatus s;
3881
3882 s = bc_lex_next(&p->l);
3883 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003884 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003885
3886 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3887
3888 s = bc_lex_next(&p->l);
3889 if (s) return s;
3890
3891 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3892 if (s) return s;
3893
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003894 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003895
3896 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3897 bc_parse_push(p, *prev);
3898
3899 return bc_lex_next(&p->l);
3900}
3901
3902static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3903{
3904 BcStatus s;
3905
3906 s = bc_lex_next(&p->l);
3907 if (s) return s;
3908
3909 if (p->l.t.t != BC_LEX_LPAREN) {
3910 *type = BC_INST_SCALE;
3911 bc_parse_push(p, BC_INST_SCALE);
3912 return BC_STATUS_SUCCESS;
3913 }
3914
3915 *type = BC_INST_SCALE_FUNC;
3916 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3917
3918 s = bc_lex_next(&p->l);
3919 if (s) return s;
3920
3921 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3922 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003923 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003924 bc_parse_push(p, BC_INST_SCALE_FUNC);
3925
3926 return bc_lex_next(&p->l);
3927}
3928
3929static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3930 size_t *nexprs, uint8_t flags)
3931{
3932 BcStatus s;
3933 BcLexType type;
3934 char inst;
3935 BcInst etype = *prev;
3936
3937 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
3938 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
3939 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
3940 {
3941 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
3942 bc_parse_push(p, inst);
3943 s = bc_lex_next(&p->l);
3944 }
3945 else {
3946
3947 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
3948 *paren_expr = true;
3949
3950 s = bc_lex_next(&p->l);
3951 if (s) return s;
3952 type = p->l.t.t;
3953
3954 // Because we parse the next part of the expression
3955 // right here, we need to increment this.
3956 *nexprs = *nexprs + 1;
3957
3958 switch (type) {
3959
3960 case BC_LEX_NAME:
3961 {
3962 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
3963 break;
3964 }
3965
3966 case BC_LEX_KEY_IBASE:
3967 case BC_LEX_KEY_LAST:
3968 case BC_LEX_KEY_OBASE:
3969 {
3970 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
3971 s = bc_lex_next(&p->l);
3972 break;
3973 }
3974
3975 case BC_LEX_KEY_SCALE:
3976 {
3977 s = bc_lex_next(&p->l);
3978 if (s) return s;
3979 if (p->l.t.t == BC_LEX_LPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003980 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003981 else
3982 bc_parse_push(p, BC_INST_SCALE);
3983 break;
3984 }
3985
3986 default:
3987 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01003988 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06003989 break;
3990 }
3991 }
3992
3993 if (!s) bc_parse_push(p, inst);
3994 }
3995
3996 return s;
3997}
3998
3999static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4000 bool rparen, size_t *nexprs)
4001{
4002 BcStatus s;
4003 BcLexType type;
4004 BcInst etype = *prev;
4005
4006 s = bc_lex_next(&p->l);
4007 if (s) return s;
4008
4009 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4010 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4011 BC_LEX_OP_MINUS :
4012 BC_LEX_NEG;
4013 *prev = BC_PARSE_TOKEN_INST(type);
4014
4015 // We can just push onto the op stack because this is the largest
4016 // precedence operator that gets pushed. Inc/dec does not.
4017 if (type != BC_LEX_OP_MINUS)
4018 bc_vec_push(&p->ops, &type);
4019 else
4020 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4021
4022 return s;
4023}
4024
4025static BcStatus bc_parse_string(BcParse *p, char inst)
4026{
4027 char *str = xstrdup(p->l.t.v.v);
4028
4029 bc_parse_push(p, BC_INST_STR);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01004030 bc_parse_pushIndex(p, G.prog.strs.len);
4031 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06004032 bc_parse_push(p, inst);
4033
4034 return bc_lex_next(&p->l);
4035}
4036
4037static BcStatus bc_parse_print(BcParse *p)
4038{
4039 BcStatus s;
4040 BcLexType type;
4041 bool comma = false;
4042
4043 s = bc_lex_next(&p->l);
4044 if (s) return s;
4045
4046 type = p->l.t.t;
4047
4048 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004049 return bc_error("bad print statement");
Gavin Howard01055ba2018-11-03 11:00:21 -06004050
4051 while (!s && type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4052
4053 if (type == BC_LEX_STR)
4054 s = bc_parse_string(p, BC_INST_PRINT_POP);
4055 else {
4056 s = bc_parse_expr(p, 0, bc_parse_next_print);
4057 if (s) return s;
4058 bc_parse_push(p, BC_INST_PRINT_POP);
4059 }
4060
4061 if (s) return s;
4062
4063 comma = p->l.t.t == BC_LEX_COMMA;
4064 if (comma) s = bc_lex_next(&p->l);
4065 type = p->l.t.t;
4066 }
4067
4068 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004069 if (comma) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004070
4071 return bc_lex_next(&p->l);
4072}
4073
4074static BcStatus bc_parse_return(BcParse *p)
4075{
4076 BcStatus s;
4077 BcLexType t;
4078 bool paren;
4079
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004080 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004081
4082 s = bc_lex_next(&p->l);
4083 if (s) return s;
4084
4085 t = p->l.t.t;
4086 paren = t == BC_LEX_LPAREN;
4087
4088 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4089 bc_parse_push(p, BC_INST_RET0);
4090 else {
4091
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004092 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004093 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004094 bc_parse_push(p, BC_INST_RET0);
4095 s = bc_lex_next(&p->l);
Gavin Howard01055ba2018-11-03 11:00:21 -06004096 }
Denys Vlasenko452df922018-12-05 20:28:26 +01004097 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06004098
4099 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004100 s = bc_POSIX_requires("parentheses around return expressions");
Gavin Howard01055ba2018-11-03 11:00:21 -06004101 if (s) return s;
4102 }
4103
4104 bc_parse_push(p, BC_INST_RET);
4105 }
4106
4107 return s;
4108}
4109
4110static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4111{
4112 BcStatus s = BC_STATUS_SUCCESS;
4113
4114 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004115 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004116
4117 if (brace) {
4118
4119 if (p->l.t.t == BC_LEX_RBRACE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004120 if (!p->nbraces) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004121 --p->nbraces;
4122 s = bc_lex_next(&p->l);
4123 if (s) return s;
4124 }
4125 else
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004126 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004127 }
4128
4129 if (BC_PARSE_IF(p)) {
4130
4131 uint8_t *flag_ptr;
4132
4133 while (p->l.t.t == BC_LEX_NLINE) {
4134 s = bc_lex_next(&p->l);
4135 if (s) return s;
4136 }
4137
4138 bc_vec_pop(&p->flags);
4139
4140 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4141 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4142
4143 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4144 }
4145 else if (BC_PARSE_ELSE(p)) {
4146
4147 BcInstPtr *ip;
4148 size_t *label;
4149
4150 bc_vec_pop(&p->flags);
4151
4152 ip = bc_vec_top(&p->exits);
4153 label = bc_vec_item(&p->func->labels, ip->idx);
4154 *label = p->func->code.len;
4155
4156 bc_vec_pop(&p->exits);
4157 }
4158 else if (BC_PARSE_FUNC_INNER(p)) {
4159 bc_parse_push(p, BC_INST_RET0);
4160 bc_parse_updateFunc(p, BC_PROG_MAIN);
4161 bc_vec_pop(&p->flags);
4162 }
4163 else {
4164
4165 BcInstPtr *ip = bc_vec_top(&p->exits);
4166 size_t *label = bc_vec_top(&p->conds);
4167
4168 bc_parse_push(p, BC_INST_JUMP);
4169 bc_parse_pushIndex(p, *label);
4170
4171 label = bc_vec_item(&p->func->labels, ip->idx);
4172 *label = p->func->code.len;
4173
4174 bc_vec_pop(&p->flags);
4175 bc_vec_pop(&p->exits);
4176 bc_vec_pop(&p->conds);
4177 }
4178
4179 return s;
4180}
4181
4182static void bc_parse_startBody(BcParse *p, uint8_t flags)
4183{
4184 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4185 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4186 flags |= BC_PARSE_FLAG_BODY;
4187 bc_vec_push(&p->flags, &flags);
4188}
4189
4190static void bc_parse_noElse(BcParse *p)
4191{
4192 BcInstPtr *ip;
4193 size_t *label;
4194 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4195
4196 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4197
4198 ip = bc_vec_top(&p->exits);
4199 label = bc_vec_item(&p->func->labels, ip->idx);
4200 *label = p->func->code.len;
4201
4202 bc_vec_pop(&p->exits);
4203}
4204
4205static BcStatus bc_parse_if(BcParse *p)
4206{
4207 BcStatus s;
4208 BcInstPtr ip;
4209
4210 s = bc_lex_next(&p->l);
4211 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004212 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004213
4214 s = bc_lex_next(&p->l);
4215 if (s) return s;
4216 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4217 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004218 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004219
4220 s = bc_lex_next(&p->l);
4221 if (s) return s;
4222 bc_parse_push(p, BC_INST_JUMP_ZERO);
4223
4224 ip.idx = p->func->labels.len;
4225 ip.func = ip.len = 0;
4226
4227 bc_parse_pushIndex(p, ip.idx);
4228 bc_vec_push(&p->exits, &ip);
4229 bc_vec_push(&p->func->labels, &ip.idx);
4230 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4231
4232 return BC_STATUS_SUCCESS;
4233}
4234
4235static BcStatus bc_parse_else(BcParse *p)
4236{
4237 BcInstPtr ip;
4238
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004239 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004240
4241 ip.idx = p->func->labels.len;
4242 ip.func = ip.len = 0;
4243
4244 bc_parse_push(p, BC_INST_JUMP);
4245 bc_parse_pushIndex(p, ip.idx);
4246
4247 bc_parse_noElse(p);
4248
4249 bc_vec_push(&p->exits, &ip);
4250 bc_vec_push(&p->func->labels, &ip.idx);
4251 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4252
4253 return bc_lex_next(&p->l);
4254}
4255
4256static BcStatus bc_parse_while(BcParse *p)
4257{
4258 BcStatus s;
4259 BcInstPtr ip;
4260
4261 s = bc_lex_next(&p->l);
4262 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004263 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004264 s = bc_lex_next(&p->l);
4265 if (s) return s;
4266
4267 ip.idx = p->func->labels.len;
4268
4269 bc_vec_push(&p->func->labels, &p->func->code.len);
4270 bc_vec_push(&p->conds, &ip.idx);
4271
4272 ip.idx = p->func->labels.len;
4273 ip.func = 1;
4274 ip.len = 0;
4275
4276 bc_vec_push(&p->exits, &ip);
4277 bc_vec_push(&p->func->labels, &ip.idx);
4278
4279 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4280 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004281 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004282 s = bc_lex_next(&p->l);
4283 if (s) return s;
4284
4285 bc_parse_push(p, BC_INST_JUMP_ZERO);
4286 bc_parse_pushIndex(p, ip.idx);
4287 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4288
4289 return BC_STATUS_SUCCESS;
4290}
4291
4292static BcStatus bc_parse_for(BcParse *p)
4293{
4294 BcStatus s;
4295 BcInstPtr ip;
4296 size_t cond_idx, exit_idx, body_idx, update_idx;
4297
4298 s = bc_lex_next(&p->l);
4299 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004300 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004301 s = bc_lex_next(&p->l);
4302 if (s) return s;
4303
4304 if (p->l.t.t != BC_LEX_SCOLON)
4305 s = bc_parse_expr(p, 0, bc_parse_next_for);
4306 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004307 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
Gavin Howard01055ba2018-11-03 11:00:21 -06004308
4309 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004310 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004311 s = bc_lex_next(&p->l);
4312 if (s) return s;
4313
4314 cond_idx = p->func->labels.len;
4315 update_idx = cond_idx + 1;
4316 body_idx = update_idx + 1;
4317 exit_idx = body_idx + 1;
4318
4319 bc_vec_push(&p->func->labels, &p->func->code.len);
4320
4321 if (p->l.t.t != BC_LEX_SCOLON)
4322 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4323 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004324 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004325
4326 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004327 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004328
4329 s = bc_lex_next(&p->l);
4330 if (s) return s;
4331
4332 bc_parse_push(p, BC_INST_JUMP_ZERO);
4333 bc_parse_pushIndex(p, exit_idx);
4334 bc_parse_push(p, BC_INST_JUMP);
4335 bc_parse_pushIndex(p, body_idx);
4336
4337 ip.idx = p->func->labels.len;
4338
4339 bc_vec_push(&p->conds, &update_idx);
4340 bc_vec_push(&p->func->labels, &p->func->code.len);
4341
4342 if (p->l.t.t != BC_LEX_RPAREN)
4343 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4344 else
Denys Vlasenko00646792018-12-05 18:12:27 +01004345 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
Gavin Howard01055ba2018-11-03 11:00:21 -06004346
4347 if (s) return s;
4348
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004349 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004350 bc_parse_push(p, BC_INST_JUMP);
4351 bc_parse_pushIndex(p, cond_idx);
4352 bc_vec_push(&p->func->labels, &p->func->code.len);
4353
4354 ip.idx = exit_idx;
4355 ip.func = 1;
4356 ip.len = 0;
4357
4358 bc_vec_push(&p->exits, &ip);
4359 bc_vec_push(&p->func->labels, &ip.idx);
4360 bc_lex_next(&p->l);
4361 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4362
4363 return BC_STATUS_SUCCESS;
4364}
4365
4366static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4367{
4368 BcStatus s;
4369 size_t i;
4370 BcInstPtr *ip;
4371
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004372 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004373
4374 if (type == BC_LEX_KEY_BREAK) {
4375
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004376 if (p->exits.len == 0) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004377
4378 i = p->exits.len - 1;
4379 ip = bc_vec_item(&p->exits, i);
4380
4381 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004382 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004383
4384 i = ip->idx;
4385 }
4386 else
4387 i = *((size_t *) bc_vec_top(&p->conds));
4388
4389 bc_parse_push(p, BC_INST_JUMP);
4390 bc_parse_pushIndex(p, i);
4391
4392 s = bc_lex_next(&p->l);
4393 if (s) return s;
4394
4395 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004396 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004397
4398 return bc_lex_next(&p->l);
4399}
4400
4401static BcStatus bc_parse_func(BcParse *p)
4402{
4403 BcStatus s;
4404 bool var, comma = false;
4405 uint8_t flags;
4406 char *name;
4407
4408 s = bc_lex_next(&p->l);
4409 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004410 if (p->l.t.t != BC_LEX_NAME)
4411 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004412
4413 name = xstrdup(p->l.t.v.v);
4414 bc_parse_addFunc(p, name, &p->fidx);
4415
4416 s = bc_lex_next(&p->l);
4417 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004418 if (p->l.t.t != BC_LEX_LPAREN)
4419 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004420 s = bc_lex_next(&p->l);
4421 if (s) return s;
4422
4423 while (p->l.t.t != BC_LEX_RPAREN) {
4424
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004425 if (p->l.t.t != BC_LEX_NAME)
4426 return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004427
4428 ++p->func->nparams;
4429
4430 name = xstrdup(p->l.t.v.v);
4431 s = bc_lex_next(&p->l);
4432 if (s) goto err;
4433
4434 var = p->l.t.t != BC_LEX_LBRACKET;
4435
4436 if (!var) {
4437
4438 s = bc_lex_next(&p->l);
4439 if (s) goto err;
4440
4441 if (p->l.t.t != BC_LEX_RBRACKET) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004442 s = bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004443 goto err;
4444 }
4445
4446 s = bc_lex_next(&p->l);
4447 if (s) goto err;
4448 }
4449
4450 comma = p->l.t.t == BC_LEX_COMMA;
4451 if (comma) {
4452 s = bc_lex_next(&p->l);
4453 if (s) goto err;
4454 }
4455
4456 s = bc_func_insert(p->func, name, var);
4457 if (s) goto err;
4458 }
4459
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004460 if (comma) return bc_error("bad function definition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004461
4462 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4463 bc_parse_startBody(p, flags);
4464
4465 s = bc_lex_next(&p->l);
4466 if (s) return s;
4467
4468 if (p->l.t.t != BC_LEX_LBRACE)
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004469 s = bc_POSIX_requires("the left brace be on the same line as the function header");
Gavin Howard01055ba2018-11-03 11:00:21 -06004470
4471 return s;
4472
4473err:
4474 free(name);
4475 return s;
4476}
4477
4478static BcStatus bc_parse_auto(BcParse *p)
4479{
4480 BcStatus s;
4481 bool comma, var, one;
4482 char *name;
4483
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004484 if (!p->auto_part) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004485 s = bc_lex_next(&p->l);
4486 if (s) return s;
4487
4488 p->auto_part = comma = false;
4489 one = p->l.t.t == BC_LEX_NAME;
4490
4491 while (p->l.t.t == BC_LEX_NAME) {
4492
4493 name = xstrdup(p->l.t.v.v);
4494 s = bc_lex_next(&p->l);
4495 if (s) goto err;
4496
4497 var = p->l.t.t != BC_LEX_LBRACKET;
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");
Denys Vlasenkoabbc4332018-12-03 21:46:41 +01004523 if (!one) return bc_error("no auto variable found");
Gavin Howard01055ba2018-11-03 11:00:21 -06004524
4525 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004526 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004527
4528 return bc_lex_next(&p->l);
4529
4530err:
4531 free(name);
4532 return s;
4533}
4534
4535static BcStatus bc_parse_body(BcParse *p, bool brace)
4536{
4537 BcStatus s = BC_STATUS_SUCCESS;
4538 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4539
4540 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4541
4542 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4543
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004544 if (!brace) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004545 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4546
4547 if (!p->auto_part) {
4548 s = bc_parse_auto(p);
4549 if (s) return s;
4550 }
4551
4552 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4553 }
4554 else {
4555 s = bc_parse_stmt(p);
4556 if (!s && !brace) s = bc_parse_endBody(p, false);
4557 }
4558
4559 return s;
4560}
4561
4562static BcStatus bc_parse_stmt(BcParse *p)
4563{
4564 BcStatus s = BC_STATUS_SUCCESS;
4565
4566 switch (p->l.t.t) {
4567
4568 case BC_LEX_NLINE:
4569 {
4570 return bc_lex_next(&p->l);
4571 }
4572
4573 case BC_LEX_KEY_ELSE:
4574 {
4575 p->auto_part = false;
4576 break;
4577 }
4578
4579 case BC_LEX_LBRACE:
4580 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004581 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004582
4583 ++p->nbraces;
4584 s = bc_lex_next(&p->l);
4585 if (s) return s;
4586
4587 return bc_parse_body(p, true);
4588 }
4589
4590 case BC_LEX_KEY_AUTO:
4591 {
4592 return bc_parse_auto(p);
4593 }
4594
4595 default:
4596 {
4597 p->auto_part = false;
4598
4599 if (BC_PARSE_IF_END(p)) {
4600 bc_parse_noElse(p);
4601 return BC_STATUS_SUCCESS;
4602 }
4603 else if (BC_PARSE_BODY(p))
4604 return bc_parse_body(p, false);
4605
4606 break;
4607 }
4608 }
4609
4610 switch (p->l.t.t) {
4611
4612 case BC_LEX_OP_INC:
4613 case BC_LEX_OP_DEC:
4614 case BC_LEX_OP_MINUS:
4615 case BC_LEX_OP_BOOL_NOT:
4616 case BC_LEX_LPAREN:
4617 case BC_LEX_NAME:
4618 case BC_LEX_NUMBER:
4619 case BC_LEX_KEY_IBASE:
4620 case BC_LEX_KEY_LAST:
4621 case BC_LEX_KEY_LENGTH:
4622 case BC_LEX_KEY_OBASE:
4623 case BC_LEX_KEY_READ:
4624 case BC_LEX_KEY_SCALE:
4625 case BC_LEX_KEY_SQRT:
4626 {
4627 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4628 break;
4629 }
4630
4631 case BC_LEX_KEY_ELSE:
4632 {
4633 s = bc_parse_else(p);
4634 break;
4635 }
4636
4637 case BC_LEX_SCOLON:
4638 {
4639 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4640 break;
4641 }
4642
4643 case BC_LEX_RBRACE:
4644 {
4645 s = bc_parse_endBody(p, true);
4646 break;
4647 }
4648
4649 case BC_LEX_STR:
4650 {
4651 s = bc_parse_string(p, BC_INST_PRINT_STR);
4652 break;
4653 }
4654
4655 case BC_LEX_KEY_BREAK:
4656 case BC_LEX_KEY_CONTINUE:
4657 {
4658 s = bc_parse_loopExit(p, p->l.t.t);
4659 break;
4660 }
4661
4662 case BC_LEX_KEY_FOR:
4663 {
4664 s = bc_parse_for(p);
4665 break;
4666 }
4667
4668 case BC_LEX_KEY_HALT:
4669 {
4670 bc_parse_push(p, BC_INST_HALT);
4671 s = bc_lex_next(&p->l);
4672 break;
4673 }
4674
4675 case BC_LEX_KEY_IF:
4676 {
4677 s = bc_parse_if(p);
4678 break;
4679 }
4680
4681 case BC_LEX_KEY_LIMITS:
4682 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004683 // "limits" is a compile-time command,
4684 // the output is produced at _parse time_.
Gavin Howard01055ba2018-11-03 11:00:21 -06004685 s = bc_lex_next(&p->l);
4686 if (s) return s;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004687 printf("BC_BASE_MAX = %u\n", BC_MAX_OBASE);
4688 printf("BC_DIM_MAX = %u\n", BC_MAX_DIM);
4689 printf("BC_SCALE_MAX = %u\n", BC_MAX_SCALE);
4690 printf("BC_STRING_MAX = %u\n", BC_MAX_STRING);
4691 printf("BC_NAME_MAX = %u\n", BC_MAX_NAME);
4692 printf("BC_NUM_MAX = %u\n", BC_MAX_NUM);
4693 printf("MAX Exponent = %lu\n", BC_MAX_EXP);
4694 printf("Number of vars = %lu\n", BC_MAX_VARS);
Gavin Howard01055ba2018-11-03 11:00:21 -06004695 break;
4696 }
4697
4698 case BC_LEX_KEY_PRINT:
4699 {
4700 s = bc_parse_print(p);
4701 break;
4702 }
4703
4704 case BC_LEX_KEY_QUIT:
4705 {
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01004706 // "quit" is a compile-time command. For example,
4707 // "if (0 == 1) quit" terminates when parsing the statement,
4708 // not when it is executed
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01004709 quit_or_return_for_exit();
Gavin Howard01055ba2018-11-03 11:00:21 -06004710 }
4711
4712 case BC_LEX_KEY_RETURN:
4713 {
4714 s = bc_parse_return(p);
4715 break;
4716 }
4717
4718 case BC_LEX_KEY_WHILE:
4719 {
4720 s = bc_parse_while(p);
4721 break;
4722 }
4723
4724 default:
4725 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004726 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004727 break;
4728 }
4729 }
4730
4731 return s;
4732}
4733
4734static BcStatus bc_parse_parse(BcParse *p)
4735{
4736 BcStatus s;
4737
4738 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004739 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 -06004740 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004741 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004742 s = bc_parse_func(p);
4743 }
4744 else
4745 s = bc_parse_stmt(p);
4746
Denys Vlasenkod38af482018-12-04 19:11:02 +01004747 if (s || G_interrupt) {
4748 bc_parse_reset(p);
4749 s = BC_STATUS_FAILURE;
4750 }
Gavin Howard01055ba2018-11-03 11:00:21 -06004751
4752 return s;
4753}
4754
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01004755static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
Gavin Howard01055ba2018-11-03 11:00:21 -06004756{
4757 BcStatus s = BC_STATUS_SUCCESS;
4758 BcInst prev = BC_INST_PRINT;
4759 BcLexType top, t = p->l.t.t;
4760 size_t nexprs = 0, ops_bgn = p->ops.len;
4761 uint32_t i, nparens, nrelops;
4762 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4763
4764 paren_first = p->l.t.t == BC_LEX_LPAREN;
4765 nparens = nrelops = 0;
4766 paren_expr = rprn = done = get_token = assign = false;
4767 bin_last = true;
4768
Denys Vlasenkobcb62a72018-12-05 20:17:48 +01004769 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
Gavin Howard01055ba2018-11-03 11:00:21 -06004770 switch (t) {
4771
4772 case BC_LEX_OP_INC:
4773 case BC_LEX_OP_DEC:
4774 {
4775 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4776 rprn = get_token = bin_last = false;
4777 break;
4778 }
4779
4780 case BC_LEX_OP_MINUS:
4781 {
4782 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4783 rprn = get_token = false;
4784 bin_last = prev == BC_INST_MINUS;
4785 break;
4786 }
4787
4788 case BC_LEX_OP_ASSIGN_POWER:
4789 case BC_LEX_OP_ASSIGN_MULTIPLY:
4790 case BC_LEX_OP_ASSIGN_DIVIDE:
4791 case BC_LEX_OP_ASSIGN_MODULUS:
4792 case BC_LEX_OP_ASSIGN_PLUS:
4793 case BC_LEX_OP_ASSIGN_MINUS:
4794 case BC_LEX_OP_ASSIGN:
4795 {
4796 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4797 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4798 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4799 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004800 s = bc_error("bad assignment:"
4801 " left side must be scale,"
4802 " ibase, obase, last, var,"
4803 " or array element"
4804 );
Gavin Howard01055ba2018-11-03 11:00:21 -06004805 break;
4806 }
4807 }
4808 // Fallthrough.
4809 case BC_LEX_OP_POWER:
4810 case BC_LEX_OP_MULTIPLY:
4811 case BC_LEX_OP_DIVIDE:
4812 case BC_LEX_OP_MODULUS:
4813 case BC_LEX_OP_PLUS:
4814 case BC_LEX_OP_REL_EQ:
4815 case BC_LEX_OP_REL_LE:
4816 case BC_LEX_OP_REL_GE:
4817 case BC_LEX_OP_REL_NE:
4818 case BC_LEX_OP_REL_LT:
4819 case BC_LEX_OP_REL_GT:
4820 case BC_LEX_OP_BOOL_NOT:
4821 case BC_LEX_OP_BOOL_OR:
4822 case BC_LEX_OP_BOOL_AND:
4823 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004824 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4825 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4826 ) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004827 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004828 }
4829
4830 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4831 prev = BC_PARSE_TOKEN_INST(t);
4832 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4833 rprn = get_token = false;
4834 bin_last = t != BC_LEX_OP_BOOL_NOT;
4835
4836 break;
4837 }
4838
4839 case BC_LEX_LPAREN:
4840 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004841 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004842 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004843 ++nparens;
4844 paren_expr = rprn = bin_last = false;
4845 get_token = true;
4846 bc_vec_push(&p->ops, &t);
4847
4848 break;
4849 }
4850
4851 case BC_LEX_RPAREN:
4852 {
4853 if (bin_last || prev == BC_INST_BOOL_NOT)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004854 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004855
4856 if (nparens == 0) {
4857 s = BC_STATUS_SUCCESS;
4858 done = true;
4859 get_token = false;
4860 break;
4861 }
4862 else if (!paren_expr)
4863 return BC_STATUS_PARSE_EMPTY_EXP;
4864
4865 --nparens;
4866 paren_expr = rprn = true;
4867 get_token = bin_last = false;
4868
4869 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4870
4871 break;
4872 }
4873
4874 case BC_LEX_NAME:
4875 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004876 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004877 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004878 paren_expr = true;
4879 rprn = get_token = bin_last = false;
4880 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4881 ++nexprs;
4882
4883 break;
4884 }
4885
4886 case BC_LEX_NUMBER:
4887 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004888 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004889 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004890 bc_parse_number(p, &prev, &nexprs);
4891 paren_expr = get_token = true;
4892 rprn = bin_last = false;
4893
4894 break;
4895 }
4896
4897 case BC_LEX_KEY_IBASE:
4898 case BC_LEX_KEY_LAST:
4899 case BC_LEX_KEY_OBASE:
4900 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004901 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004902 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004903 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4904 bc_parse_push(p, (char) prev);
4905
4906 paren_expr = get_token = true;
4907 rprn = bin_last = false;
4908 ++nexprs;
4909
4910 break;
4911 }
4912
4913 case BC_LEX_KEY_LENGTH:
4914 case BC_LEX_KEY_SQRT:
4915 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004916 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004917 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004918 s = bc_parse_builtin(p, t, flags, &prev);
4919 paren_expr = true;
4920 rprn = get_token = bin_last = false;
4921 ++nexprs;
4922
4923 break;
4924 }
4925
4926 case BC_LEX_KEY_READ:
4927 {
4928 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004929 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004930 else if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004931 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06004932 else
4933 s = bc_parse_read(p);
4934
4935 paren_expr = true;
4936 rprn = get_token = bin_last = false;
4937 ++nexprs;
4938 prev = BC_INST_READ;
4939
4940 break;
4941 }
4942
4943 case BC_LEX_KEY_SCALE:
4944 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004945 if (BC_PARSE_LEAF(prev, rprn))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004946 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004947 s = bc_parse_scale(p, &prev, flags);
4948 paren_expr = true;
4949 rprn = get_token = bin_last = false;
4950 ++nexprs;
4951 prev = BC_INST_SCALE;
4952
4953 break;
4954 }
4955
4956 default:
4957 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004958 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06004959 break;
4960 }
4961 }
4962
4963 if (!s && get_token) s = bc_lex_next(&p->l);
4964 }
4965
4966 if (s) return s;
Denys Vlasenkod38af482018-12-04 19:11:02 +01004967 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
Gavin Howard01055ba2018-11-03 11:00:21 -06004968
4969 while (p->ops.len > ops_bgn) {
4970
4971 top = BC_PARSE_TOP_OP(p);
4972 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
4973
4974 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004975 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004976
4977 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
4978
4979 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
4980 bc_vec_pop(&p->ops);
4981 }
4982
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004983 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004984 return bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06004985
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004986 for (i = 0; i < next.len; ++i)
4987 if (t == next.tokens[i])
4988 goto ok;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01004989 return bc_error_bad_expression();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01004990 ok:
Gavin Howard01055ba2018-11-03 11:00:21 -06004991
4992 if (!(flags & BC_PARSE_REL) && nrelops) {
Denys Vlasenko00646792018-12-05 18:12:27 +01004993 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
Gavin Howard01055ba2018-11-03 11:00:21 -06004994 if (s) return s;
4995 }
4996 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
Denys Vlasenkoa6f84e12018-12-06 11:10:11 +01004997 s = bc_POSIX_requires("exactly one comparison operator per condition");
Gavin Howard01055ba2018-11-03 11:00:21 -06004998 if (s) return s;
4999 }
5000
5001 if (flags & BC_PARSE_PRINT) {
5002 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5003 bc_parse_push(p, BC_INST_POP);
5004 }
5005
5006 return s;
5007}
5008
Denys Vlasenko050b0fe2018-12-05 22:40:44 +01005009static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5010{
5011 BcStatus s;
5012
5013 s = bc_parse_expr_empty_ok(p, flags, next);
5014 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5015 return bc_error("empty expression");
5016 return s;
5017}
5018
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005019static void bc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005020{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005021 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005022}
5023
5024static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5025{
5026 return bc_parse_expr(p, flags, bc_parse_next_read);
5027}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005028
Gavin Howard01055ba2018-11-03 11:00:21 -06005029#endif // ENABLE_BC
5030
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005031#if ENABLE_DC
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005032
5033#define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5034
Gavin Howard01055ba2018-11-03 11:00:21 -06005035static BcStatus dc_parse_register(BcParse *p)
5036{
5037 BcStatus s;
5038 char *name;
5039
5040 s = bc_lex_next(&p->l);
5041 if (s) return s;
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005042 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005043
5044 name = xstrdup(p->l.t.v.v);
5045 bc_parse_pushName(p, name);
5046
5047 return s;
5048}
5049
5050static BcStatus dc_parse_string(BcParse *p)
5051{
5052 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005053 size_t idx, len = G.prog.strs.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005054
5055 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5056 name = xstrdup(b);
5057
5058 str = xstrdup(p->l.t.v.v);
5059 bc_parse_push(p, BC_INST_STR);
5060 bc_parse_pushIndex(p, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005061 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06005062 bc_parse_addFunc(p, name, &idx);
5063
5064 return bc_lex_next(&p->l);
5065}
5066
5067static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5068{
5069 BcStatus s;
5070
5071 bc_parse_push(p, inst);
5072 if (name) {
5073 s = dc_parse_register(p);
5074 if (s) return s;
5075 }
5076
5077 if (store) {
5078 bc_parse_push(p, BC_INST_SWAP);
5079 bc_parse_push(p, BC_INST_ASSIGN);
5080 bc_parse_push(p, BC_INST_POP);
5081 }
5082
5083 return bc_lex_next(&p->l);
5084}
5085
5086static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5087{
5088 BcStatus s;
5089
5090 bc_parse_push(p, inst);
5091 bc_parse_push(p, BC_INST_EXEC_COND);
5092
5093 s = dc_parse_register(p);
5094 if (s) return s;
5095
5096 s = bc_lex_next(&p->l);
5097 if (s) return s;
5098
5099 if (p->l.t.t == BC_LEX_ELSE) {
5100 s = dc_parse_register(p);
5101 if (s) return s;
5102 s = bc_lex_next(&p->l);
5103 }
5104 else
5105 bc_parse_push(p, BC_PARSE_STREND);
5106
5107 return s;
5108}
5109
5110static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5111{
5112 BcStatus s = BC_STATUS_SUCCESS;
5113 BcInst prev;
5114 uint8_t inst;
5115 bool assign, get_token = false;
5116
5117 switch (t) {
5118
5119 case BC_LEX_OP_REL_EQ:
5120 case BC_LEX_OP_REL_LE:
5121 case BC_LEX_OP_REL_GE:
5122 case BC_LEX_OP_REL_NE:
5123 case BC_LEX_OP_REL_LT:
5124 case BC_LEX_OP_REL_GT:
5125 {
5126 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5127 break;
5128 }
5129
5130 case BC_LEX_SCOLON:
5131 case BC_LEX_COLON:
5132 {
5133 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5134 break;
5135 }
5136
5137 case BC_LEX_STR:
5138 {
5139 s = dc_parse_string(p);
5140 break;
5141 }
5142
5143 case BC_LEX_NEG:
5144 case BC_LEX_NUMBER:
5145 {
5146 if (t == BC_LEX_NEG) {
5147 s = bc_lex_next(&p->l);
5148 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005149 if (p->l.t.t != BC_LEX_NUMBER)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005150 return bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005151 }
5152
5153 bc_parse_number(p, &prev, &p->nbraces);
5154
5155 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5156 get_token = true;
5157
5158 break;
5159 }
5160
5161 case BC_LEX_KEY_READ:
5162 {
5163 if (flags & BC_PARSE_NOREAD)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005164 s = bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005165 else
5166 bc_parse_push(p, BC_INST_READ);
5167 get_token = true;
5168 break;
5169 }
5170
5171 case BC_LEX_OP_ASSIGN:
5172 case BC_LEX_STORE_PUSH:
5173 {
5174 assign = t == BC_LEX_OP_ASSIGN;
5175 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5176 s = dc_parse_mem(p, inst, true, assign);
5177 break;
5178 }
5179
5180 case BC_LEX_LOAD:
5181 case BC_LEX_LOAD_POP:
5182 {
5183 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5184 s = dc_parse_mem(p, inst, true, false);
5185 break;
5186 }
5187
5188 case BC_LEX_STORE_IBASE:
5189 case BC_LEX_STORE_SCALE:
5190 case BC_LEX_STORE_OBASE:
5191 {
5192 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5193 s = dc_parse_mem(p, inst, false, true);
5194 break;
5195 }
5196
5197 default:
5198 {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005199 s = bc_error_bad_token();
Gavin Howard01055ba2018-11-03 11:00:21 -06005200 get_token = true;
5201 break;
5202 }
5203 }
5204
5205 if (!s && get_token) s = bc_lex_next(&p->l);
5206
5207 return s;
5208}
5209
5210static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5211{
5212 BcStatus s = BC_STATUS_SUCCESS;
5213 BcInst inst;
5214 BcLexType t;
5215
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005216 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005217
5218 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5219
5220 inst = dc_parse_insts[t];
5221
5222 if (inst != BC_INST_INVALID) {
5223 bc_parse_push(p, inst);
5224 s = bc_lex_next(&p->l);
5225 }
5226 else
5227 s = dc_parse_token(p, t, flags);
5228 }
5229
5230 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5231 bc_parse_push(p, BC_INST_POP_EXEC);
5232
5233 return s;
5234}
5235
5236static BcStatus dc_parse_parse(BcParse *p)
5237{
5238 BcStatus s;
5239
5240 if (p->l.t.t == BC_LEX_EOF)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005241 s = bc_error("end of file");
Gavin Howard01055ba2018-11-03 11:00:21 -06005242 else
5243 s = dc_parse_expr(p, 0);
5244
Denys Vlasenkod38af482018-12-04 19:11:02 +01005245 if (s || G_interrupt) {
5246 bc_parse_reset(p);
5247 s = BC_STATUS_FAILURE;
5248 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005249
5250 return s;
5251}
5252
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005253static void dc_parse_init(BcParse *p, size_t func)
Gavin Howard01055ba2018-11-03 11:00:21 -06005254{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005255 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
Gavin Howard01055ba2018-11-03 11:00:21 -06005256}
Denys Vlasenkocca79a02018-12-05 21:15:46 +01005257
Gavin Howard01055ba2018-11-03 11:00:21 -06005258#endif // ENABLE_DC
5259
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005260static void common_parse_init(BcParse *p, size_t func)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005261{
5262 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005263 IF_BC(bc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005264 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005265 IF_DC(dc_parse_init(p, func);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005266 }
5267}
5268
5269static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5270{
5271 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005272 IF_BC(return bc_parse_expression(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005273 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01005274 IF_DC(return dc_parse_expr(p, flags);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005275 }
5276}
5277
Denys Vlasenkodf515392018-12-02 19:27:48 +01005278static BcVec* bc_program_search(char *id, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005279{
Gavin Howard01055ba2018-11-03 11:00:21 -06005280 BcId e, *ptr;
5281 BcVec *v, *map;
5282 size_t i;
5283 BcResultData data;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005284 int new;
Gavin Howard01055ba2018-11-03 11:00:21 -06005285
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005286 v = var ? &G.prog.vars : &G.prog.arrs;
5287 map = var ? &G.prog.var_map : &G.prog.arr_map;
Gavin Howard01055ba2018-11-03 11:00:21 -06005288
5289 e.name = id;
5290 e.idx = v->len;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01005291 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
Gavin Howard01055ba2018-11-03 11:00:21 -06005292
5293 if (new) {
5294 bc_array_init(&data.v, var);
5295 bc_vec_push(v, &data.v);
5296 }
5297
5298 ptr = bc_vec_item(map, i);
5299 if (new) ptr->name = xstrdup(e.name);
Denys Vlasenkodf515392018-12-02 19:27:48 +01005300 return bc_vec_item(v, ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005301}
5302
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005303static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
Gavin Howard01055ba2018-11-03 11:00:21 -06005304{
5305 BcStatus s = BC_STATUS_SUCCESS;
5306
5307 switch (r->t) {
5308
5309 case BC_RESULT_STR:
5310 case BC_RESULT_TEMP:
5311 case BC_RESULT_IBASE:
5312 case BC_RESULT_SCALE:
5313 case BC_RESULT_OBASE:
5314 {
5315 *num = &r->d.n;
5316 break;
5317 }
5318
5319 case BC_RESULT_CONSTANT:
5320 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005321 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06005322 size_t base_t, len = strlen(*str);
5323 BcNum *base;
5324
5325 bc_num_init(&r->d.n, len);
5326
5327 hex = hex && len == 1;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005328 base = hex ? &G.prog.hexb : &G.prog.ib;
5329 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005330 s = bc_num_parse(&r->d.n, *str, base, base_t);
5331
5332 if (s) {
5333 bc_num_free(&r->d.n);
5334 return s;
5335 }
5336
5337 *num = &r->d.n;
5338 r->t = BC_RESULT_TEMP;
5339
5340 break;
5341 }
5342
5343 case BC_RESULT_VAR:
5344 case BC_RESULT_ARRAY:
5345 case BC_RESULT_ARRAY_ELEM:
5346 {
5347 BcVec *v;
5348
Denys Vlasenkodf515392018-12-02 19:27:48 +01005349 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
Gavin Howard01055ba2018-11-03 11:00:21 -06005350
5351 if (r->t == BC_RESULT_ARRAY_ELEM) {
5352 v = bc_vec_top(v);
5353 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5354 *num = bc_vec_item(v, r->d.id.idx);
5355 }
5356 else
5357 *num = bc_vec_top(v);
5358
5359 break;
5360 }
5361
5362 case BC_RESULT_LAST:
5363 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005364 *num = &G.prog.last;
Gavin Howard01055ba2018-11-03 11:00:21 -06005365 break;
5366 }
5367
5368 case BC_RESULT_ONE:
5369 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005370 *num = &G.prog.one;
Gavin Howard01055ba2018-11-03 11:00:21 -06005371 break;
5372 }
5373 }
5374
5375 return s;
5376}
5377
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005378static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
Gavin Howard01055ba2018-11-03 11:00:21 -06005379 BcResult **r, BcNum **rn, bool assign)
5380{
5381 BcStatus s;
5382 bool hex;
5383 BcResultType lt, rt;
5384
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005385 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005386 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005387
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005388 *r = bc_vec_item_rev(&G.prog.results, 0);
5389 *l = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06005390
5391 lt = (*l)->t;
5392 rt = (*r)->t;
5393 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5394
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005395 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005396 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005397 s = bc_program_num(*r, rn, hex);
Gavin Howard01055ba2018-11-03 11:00:21 -06005398 if (s) return s;
5399
5400 // We run this again under these conditions in case any vector has been
5401 // reallocated out from under the BcNums or arrays we had.
5402 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005403 s = bc_program_num(*l, ln, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005404 if (s) return s;
5405 }
5406
5407 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005408 return bc_error_variable_is_wrong_type();
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005409 if (!assign && !BC_PROG_NUM((*r), (*ln)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005410 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005411
Gavin Howard01055ba2018-11-03 11:00:21 -06005412 return s;
5413}
5414
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005415static void bc_program_binOpRetire(BcResult *r)
Gavin Howard01055ba2018-11-03 11:00:21 -06005416{
5417 r->t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005418 bc_vec_pop(&G.prog.results);
5419 bc_vec_pop(&G.prog.results);
5420 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005421}
5422
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005423static BcStatus bc_program_prep(BcResult **r, BcNum **n)
Gavin Howard01055ba2018-11-03 11:00:21 -06005424{
5425 BcStatus s;
5426
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005427 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005428 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005429 *r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005430
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005431 s = bc_program_num(*r, n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005432 if (s) return s;
5433
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005434 if (!BC_PROG_NUM((*r), (*n)))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005435 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06005436
5437 return s;
5438}
5439
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005440static void bc_program_retire(BcResult *r, BcResultType t)
Gavin Howard01055ba2018-11-03 11:00:21 -06005441{
5442 r->t = t;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005443 bc_vec_pop(&G.prog.results);
5444 bc_vec_push(&G.prog.results, r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005445}
5446
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005447static BcStatus bc_program_op(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005448{
5449 BcStatus s;
5450 BcResult *opd1, *opd2, res;
5451 BcNum *n1, *n2 = NULL;
5452
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005453 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005454 if (s) return s;
5455 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5456
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005457 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005458 if (s) goto err;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005459 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005460
5461 return s;
5462
5463err:
5464 bc_num_free(&res.d.n);
5465 return s;
5466}
5467
Denys Vlasenko785e4b32018-12-02 17:18:52 +01005468static BcStatus bc_program_read(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005469{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005470 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005471 BcStatus s;
5472 BcParse parse;
5473 BcVec buf;
5474 BcInstPtr ip;
5475 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005476 BcFunc *f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005477
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005478 for (i = 0; i < G.prog.stack.len; ++i) {
5479 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005480 if (ip_ptr->func == BC_PROG_READ)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005481 return bc_error_nested_read_call();
Gavin Howard01055ba2018-11-03 11:00:21 -06005482 }
5483
Denys Vlasenko7d628012018-12-04 21:46:47 +01005484 bc_vec_pop_all(&f->code);
5485 bc_char_vec_init(&buf);
Gavin Howard01055ba2018-11-03 11:00:21 -06005486
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005487 sv_file = G.prog.file;
5488 G.prog.file = NULL;
5489
Gavin Howard01055ba2018-11-03 11:00:21 -06005490 s = bc_read_line(&buf, "read> ");
5491 if (s) goto io_err;
5492
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005493 common_parse_init(&parse, BC_PROG_READ);
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005494 bc_lex_file(&parse.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005495
5496 s = bc_parse_text(&parse, buf.v);
5497 if (s) goto exec_err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01005498 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
Gavin Howard01055ba2018-11-03 11:00:21 -06005499 if (s) goto exec_err;
5500
5501 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005502 s = bc_error("bad read() expression");
Gavin Howard01055ba2018-11-03 11:00:21 -06005503 goto exec_err;
5504 }
5505
5506 ip.func = BC_PROG_READ;
5507 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005508 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06005509
5510 // Update this pointer, just in case.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005511 f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
Gavin Howard01055ba2018-11-03 11:00:21 -06005512
5513 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005514 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06005515
5516exec_err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01005517 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06005518 bc_parse_free(&parse);
5519io_err:
5520 bc_vec_free(&buf);
5521 return s;
5522}
5523
5524static size_t bc_program_index(char *code, size_t *bgn)
5525{
5526 char amt = code[(*bgn)++], i = 0;
5527 size_t res = 0;
5528
5529 for (; i < amt; ++i, ++(*bgn))
5530 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5531
5532 return res;
5533}
5534
5535static char *bc_program_name(char *code, size_t *bgn)
5536{
5537 size_t i;
5538 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5539
5540 s = xmalloc(ptr - str + 1);
5541 c = code[(*bgn)++];
5542
5543 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5544 s[i] = c;
5545
5546 s[i] = '\0';
5547
5548 return s;
5549}
5550
5551static void bc_program_printString(const char *str, size_t *nchars)
5552{
5553 size_t i, len = strlen(str);
5554
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005555#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005556 if (len == 0) {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005557 bb_putchar('\0');
Gavin Howard01055ba2018-11-03 11:00:21 -06005558 return;
5559 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005560#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005561
5562 for (i = 0; i < len; ++i, ++(*nchars)) {
5563
5564 int c = str[i];
5565
5566 if (c != '\\' || i == len - 1)
Denys Vlasenko00d77792018-11-30 23:13:42 +01005567 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005568 else {
5569
5570 c = str[++i];
5571
5572 switch (c) {
5573
5574 case 'a':
5575 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005576 bb_putchar('\a');
Gavin Howard01055ba2018-11-03 11:00:21 -06005577 break;
5578 }
5579
5580 case 'b':
5581 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005582 bb_putchar('\b');
Gavin Howard01055ba2018-11-03 11:00:21 -06005583 break;
5584 }
5585
5586 case '\\':
5587 case 'e':
5588 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005589 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005590 break;
5591 }
5592
5593 case 'f':
5594 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005595 bb_putchar('\f');
Gavin Howard01055ba2018-11-03 11:00:21 -06005596 break;
5597 }
5598
5599 case 'n':
5600 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005601 bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005602 *nchars = SIZE_MAX;
5603 break;
5604 }
5605
5606 case 'r':
5607 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005608 bb_putchar('\r');
Gavin Howard01055ba2018-11-03 11:00:21 -06005609 break;
5610 }
5611
5612 case 'q':
5613 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005614 bb_putchar('"');
Gavin Howard01055ba2018-11-03 11:00:21 -06005615 break;
5616 }
5617
5618 case 't':
5619 {
Denys Vlasenko00d77792018-11-30 23:13:42 +01005620 bb_putchar('\t');
Gavin Howard01055ba2018-11-03 11:00:21 -06005621 break;
5622 }
5623
5624 default:
5625 {
5626 // Just print the backslash and following character.
Denys Vlasenko00d77792018-11-30 23:13:42 +01005627 bb_putchar('\\');
Gavin Howard01055ba2018-11-03 11:00:21 -06005628 ++(*nchars);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005629 bb_putchar(c);
Gavin Howard01055ba2018-11-03 11:00:21 -06005630 break;
5631 }
5632 }
5633 }
5634 }
5635}
5636
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005637static BcStatus bc_program_print(char inst, size_t idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06005638{
5639 BcStatus s = BC_STATUS_SUCCESS;
5640 BcResult *r;
5641 size_t len, i;
5642 char *str;
5643 BcNum *num = NULL;
5644 bool pop = inst != BC_INST_PRINT;
5645
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005646 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005647 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005648
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005649 r = bc_vec_item_rev(&G.prog.results, idx);
5650 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005651 if (s) return s;
5652
5653 if (BC_PROG_NUM(r, num)) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005654 s = bc_num_print(num, &G.prog.ob, G.prog.ob_t, !pop, &G.prog.nchars, G.prog.len);
5655 if (!s) bc_num_copy(&G.prog.last, num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005656 }
5657 else {
5658
5659 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005660 str = *((char **) bc_vec_item(&G.prog.strs, idx));
Gavin Howard01055ba2018-11-03 11:00:21 -06005661
5662 if (inst == BC_INST_PRINT_STR) {
5663 for (i = 0, len = strlen(str); i < len; ++i) {
5664 char c = str[i];
Denys Vlasenko00d77792018-11-30 23:13:42 +01005665 bb_putchar(c);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005666 if (c == '\n') G.prog.nchars = SIZE_MAX;
5667 ++G.prog.nchars;
Gavin Howard01055ba2018-11-03 11:00:21 -06005668 }
5669 }
5670 else {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005671 bc_program_printString(str, &G.prog.nchars);
Denys Vlasenko00d77792018-11-30 23:13:42 +01005672 if (inst == BC_INST_PRINT) bb_putchar('\n');
Gavin Howard01055ba2018-11-03 11:00:21 -06005673 }
5674 }
5675
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005676 if (!s && pop) bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005677
5678 return s;
5679}
5680
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005681static BcStatus bc_program_negate(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06005682{
5683 BcStatus s;
5684 BcResult res, *ptr;
5685 BcNum *num = NULL;
5686
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005687 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005688 if (s) return s;
5689
5690 bc_num_init(&res.d.n, num->len);
5691 bc_num_copy(&res.d.n, num);
5692 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5693
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005694 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06005695
5696 return s;
5697}
5698
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005699static BcStatus bc_program_logical(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005700{
5701 BcStatus s;
5702 BcResult *opd1, *opd2, res;
5703 BcNum *n1, *n2;
5704 bool cond = 0;
5705 ssize_t cmp;
5706
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005707 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005708 if (s) return s;
5709 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5710
5711 if (inst == BC_INST_BOOL_AND)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005712 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005713 else if (inst == BC_INST_BOOL_OR)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005714 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
Gavin Howard01055ba2018-11-03 11:00:21 -06005715 else {
5716
5717 cmp = bc_num_cmp(n1, n2);
5718
5719 switch (inst) {
5720
5721 case BC_INST_REL_EQ:
5722 {
5723 cond = cmp == 0;
5724 break;
5725 }
5726
5727 case BC_INST_REL_LE:
5728 {
5729 cond = cmp <= 0;
5730 break;
5731 }
5732
5733 case BC_INST_REL_GE:
5734 {
5735 cond = cmp >= 0;
5736 break;
5737 }
5738
5739 case BC_INST_REL_NE:
5740 {
5741 cond = cmp != 0;
5742 break;
5743 }
5744
5745 case BC_INST_REL_LT:
5746 {
5747 cond = cmp < 0;
5748 break;
5749 }
5750
5751 case BC_INST_REL_GT:
5752 {
5753 cond = cmp > 0;
5754 break;
5755 }
5756 }
5757 }
5758
5759 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5760
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005761 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005762
5763 return s;
5764}
5765
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005766#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005767static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
Gavin Howard01055ba2018-11-03 11:00:21 -06005768 bool push)
5769{
5770 BcNum n2;
5771 BcResult res;
5772
5773 memset(&n2, 0, sizeof(BcNum));
5774 n2.rdx = res.d.id.idx = r->d.id.idx;
5775 res.t = BC_RESULT_STR;
5776
5777 if (!push) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005778 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005779 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005780 bc_vec_pop(v);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005781 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005782 }
5783
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005784 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005785
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005786 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005787 bc_vec_push(v, &n2);
5788
5789 return BC_STATUS_SUCCESS;
5790}
5791#endif // ENABLE_DC
5792
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005793static BcStatus bc_program_copyToVar(char *name, bool var)
Gavin Howard01055ba2018-11-03 11:00:21 -06005794{
5795 BcStatus s;
5796 BcResult *ptr, r;
5797 BcVec *v;
5798 BcNum *n;
5799
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005800 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005801 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06005802
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005803 ptr = bc_vec_top(&G.prog.results);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005804 if ((ptr->t == BC_RESULT_ARRAY) != !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005805 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005806 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005807
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005808#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005809 if (ptr->t == BC_RESULT_STR && !var)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005810 return bc_error_variable_is_wrong_type();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005811 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005812#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005813
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005814 s = bc_program_num(ptr, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005815 if (s) return s;
5816
5817 // Do this once more to make sure that pointers were not invalidated.
Denys Vlasenkodf515392018-12-02 19:27:48 +01005818 v = bc_program_search(name, var);
Gavin Howard01055ba2018-11-03 11:00:21 -06005819
5820 if (var) {
5821 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5822 bc_num_copy(&r.d.n, n);
5823 }
5824 else {
5825 bc_array_init(&r.d.v, true);
5826 bc_array_copy(&r.d.v, (BcVec *) n);
5827 }
5828
5829 bc_vec_push(v, &r.d);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005830 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06005831
5832 return s;
5833}
5834
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005835static BcStatus bc_program_assign(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06005836{
5837 BcStatus s;
5838 BcResult *left, *right, res;
5839 BcNum *l = NULL, *r = NULL;
5840 unsigned long val, max;
5841 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5842
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005843 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
Gavin Howard01055ba2018-11-03 11:00:21 -06005844 if (s) return s;
5845
5846 ib = left->t == BC_RESULT_IBASE;
5847 sc = left->t == BC_RESULT_SCALE;
5848
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005849#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06005850
5851 if (right->t == BC_RESULT_STR) {
5852
5853 BcVec *v;
5854
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005855 if (left->t != BC_RESULT_VAR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005856 return bc_error_variable_is_wrong_type();
Denys Vlasenkodf515392018-12-02 19:27:48 +01005857 v = bc_program_search(left->d.id.name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06005858
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005859 return bc_program_assignStr(right, v, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06005860 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005861#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005862
5863 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005864 return bc_error("bad assignment:"
5865 " left side must be scale,"
5866 " ibase, obase, last, var,"
5867 " or array element"
5868 );
Gavin Howard01055ba2018-11-03 11:00:21 -06005869
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005870#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005871 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005872 return bc_error("divide by zero");
Gavin Howard01055ba2018-11-03 11:00:21 -06005873
5874 if (assign)
5875 bc_num_copy(l, r);
5876 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005877 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06005878
5879 if (s) return s;
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005880#else
Gavin Howard01055ba2018-11-03 11:00:21 -06005881 bc_num_copy(l, r);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005882#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06005883
5884 if (ib || sc || left->t == BC_RESULT_OBASE) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005885 static const char *const msg[] = {
5886 "bad ibase; must be [2, 16]", //BC_RESULT_IBASE
5887 "bad scale; must be [0, BC_SCALE_MAX]", //BC_RESULT_SCALE
Denys Vlasenkoaad652a2018-12-05 20:33:23 +01005888 NULL, //can't happen //BC_RESULT_LAST
5889 NULL, //can't happen //BC_RESULT_CONSTANT
5890 NULL, //can't happen //BC_RESULT_ONE
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005891 "bad obase; must be [2, BC_BASE_MAX]", //BC_RESULT_OBASE
5892 };
Gavin Howard01055ba2018-11-03 11:00:21 -06005893 size_t *ptr;
5894
5895 s = bc_num_ulong(l, &val);
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005896 if (s)
5897 return s;
5898 s = left->t - BC_RESULT_IBASE;
Gavin Howard01055ba2018-11-03 11:00:21 -06005899 if (sc) {
5900 max = BC_MAX_SCALE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005901 ptr = &G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06005902 }
5903 else {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005904 if (val < BC_NUM_MIN_BASE)
5905 return bc_error(msg[s]);
Gavin Howard01055ba2018-11-03 11:00:21 -06005906 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005907 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06005908 }
5909
Denys Vlasenko60cf7472018-12-04 20:05:28 +01005910 if (val > max)
5911 return bc_error(msg[s]);
5912 if (!sc)
5913 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
Gavin Howard01055ba2018-11-03 11:00:21 -06005914
5915 *ptr = (size_t) val;
5916 s = BC_STATUS_SUCCESS;
5917 }
5918
5919 bc_num_init(&res.d.n, l->len);
5920 bc_num_copy(&res.d.n, l);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005921 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06005922
5923 return s;
5924}
5925
Denys Vlasenko416ce762018-12-02 20:57:17 +01005926#if !ENABLE_DC
5927#define bc_program_pushVar(code, bgn, pop, copy) \
5928 bc_program_pushVar(code, bgn)
5929// for bc, 'pop' and 'copy' are always false
5930#endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005931static BcStatus bc_program_pushVar(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06005932 bool pop, bool copy)
5933{
5934 BcStatus s = BC_STATUS_SUCCESS;
5935 BcResult r;
5936 char *name = bc_program_name(code, bgn);
Gavin Howard01055ba2018-11-03 11:00:21 -06005937
5938 r.t = BC_RESULT_VAR;
5939 r.d.id.name = name;
5940
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01005941#if ENABLE_DC
Denys Vlasenko416ce762018-12-02 20:57:17 +01005942 {
5943 BcVec *v = bc_program_search(name, true);
5944 BcNum *num = bc_vec_top(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06005945
Denys Vlasenko416ce762018-12-02 20:57:17 +01005946 if (pop || copy) {
Gavin Howard01055ba2018-11-03 11:00:21 -06005947
Denys Vlasenko416ce762018-12-02 20:57:17 +01005948 if (!BC_PROG_STACK(v, 2 - copy)) {
5949 free(name);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01005950 return bc_error_stack_has_too_few_elements();
Denys Vlasenko416ce762018-12-02 20:57:17 +01005951 }
5952
Gavin Howard01055ba2018-11-03 11:00:21 -06005953 free(name);
Denys Vlasenko416ce762018-12-02 20:57:17 +01005954 name = NULL;
5955
5956 if (!BC_PROG_STR(num)) {
5957
5958 r.t = BC_RESULT_TEMP;
5959
5960 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5961 bc_num_copy(&r.d.n, num);
5962 }
5963 else {
5964 r.t = BC_RESULT_STR;
5965 r.d.id.idx = num->rdx;
5966 }
5967
5968 if (!copy) bc_vec_pop(v);
Gavin Howard01055ba2018-11-03 11:00:21 -06005969 }
Gavin Howard01055ba2018-11-03 11:00:21 -06005970 }
5971#endif // ENABLE_DC
5972
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005973 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005974
5975 return s;
5976}
5977
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005978static BcStatus bc_program_pushArray(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06005979 char inst)
5980{
5981 BcStatus s = BC_STATUS_SUCCESS;
5982 BcResult r;
5983 BcNum *num;
5984
5985 r.d.id.name = bc_program_name(code, bgn);
5986
5987 if (inst == BC_INST_ARRAY) {
5988 r.t = BC_RESULT_ARRAY;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005989 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06005990 }
5991 else {
5992
5993 BcResult *operand;
5994 unsigned long temp;
5995
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01005996 s = bc_program_prep(&operand, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06005997 if (s) goto err;
5998 s = bc_num_ulong(num, &temp);
5999 if (s) goto err;
6000
6001 if (temp > BC_MAX_DIM) {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006002 s = bc_error("array too long; must be [1, BC_DIM_MAX]");
Gavin Howard01055ba2018-11-03 11:00:21 -06006003 goto err;
6004 }
6005
6006 r.d.id.idx = (size_t) temp;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006007 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
Gavin Howard01055ba2018-11-03 11:00:21 -06006008 }
6009
6010err:
6011 if (s) free(r.d.id.name);
6012 return s;
6013}
6014
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006015#if ENABLE_BC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006016static BcStatus bc_program_incdec(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006017{
6018 BcStatus s;
6019 BcResult *ptr, res, copy;
6020 BcNum *num = NULL;
6021 char inst2 = inst;
6022
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006023 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006024 if (s) return s;
6025
6026 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6027 copy.t = BC_RESULT_TEMP;
6028 bc_num_init(&copy.d.n, num->len);
6029 bc_num_copy(&copy.d.n, num);
6030 }
6031
6032 res.t = BC_RESULT_ONE;
6033 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6034 BC_INST_ASSIGN_PLUS :
6035 BC_INST_ASSIGN_MINUS;
6036
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006037 bc_vec_push(&G.prog.results, &res);
6038 bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006039
6040 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006041 bc_vec_pop(&G.prog.results);
6042 bc_vec_push(&G.prog.results, &copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006043 }
6044
6045 return s;
6046}
6047
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006048static BcStatus bc_program_call(char *code, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006049{
6050 BcStatus s = BC_STATUS_SUCCESS;
6051 BcInstPtr ip;
6052 size_t i, nparams = bc_program_index(code, idx);
6053 BcFunc *func;
Gavin Howard01055ba2018-11-03 11:00:21 -06006054 BcId *a;
6055 BcResultData param;
6056 BcResult *arg;
6057
6058 ip.idx = 0;
6059 ip.func = bc_program_index(code, idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006060 func = bc_vec_item(&G.prog.fns, ip.func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006061
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006062 if (func->code.len == 0) {
6063 return bc_error("undefined function");
6064 }
6065 if (nparams != func->nparams) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006066 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
Denys Vlasenko04a1c762018-12-03 21:10:57 +01006067 }
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006068 ip.len = G.prog.results.len - nparams;
Gavin Howard01055ba2018-11-03 11:00:21 -06006069
6070 for (i = 0; i < nparams; ++i) {
6071
6072 a = bc_vec_item(&func->autos, nparams - 1 - i);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006073 arg = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006074
6075 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006076 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006077
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006078 s = bc_program_copyToVar(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006079 if (s) return s;
6080 }
6081
6082 for (; i < func->autos.len; ++i) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006083 BcVec *v;
Gavin Howard01055ba2018-11-03 11:00:21 -06006084
6085 a = bc_vec_item(&func->autos, i);
Denys Vlasenkodf515392018-12-02 19:27:48 +01006086 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006087
6088 if (a->idx) {
6089 bc_num_init(&param.n, BC_NUM_DEF_SIZE);
6090 bc_vec_push(v, &param.n);
6091 }
6092 else {
6093 bc_array_init(&param.v, true);
6094 bc_vec_push(v, &param.v);
6095 }
6096 }
6097
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006098 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006099
6100 return BC_STATUS_SUCCESS;
6101}
6102
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006103static BcStatus bc_program_return(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006104{
6105 BcStatus s;
6106 BcResult res;
6107 BcFunc *f;
6108 size_t i;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006109 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006110
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006111 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006112 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006113
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006114 f = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006115 res.t = BC_RESULT_TEMP;
6116
6117 if (inst == BC_INST_RET) {
6118
6119 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006120 BcResult *operand = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006121
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006122 s = bc_program_num(operand, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006123 if (s) return s;
6124 bc_num_init(&res.d.n, num->len);
6125 bc_num_copy(&res.d.n, num);
6126 }
6127 else {
6128 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6129 bc_num_zero(&res.d.n);
6130 }
6131
6132 // We need to pop arguments as well, so this takes that into account.
6133 for (i = 0; i < f->autos.len; ++i) {
6134
6135 BcVec *v;
6136 BcId *a = bc_vec_item(&f->autos, i);
6137
Denys Vlasenkodf515392018-12-02 19:27:48 +01006138 v = bc_program_search(a->name, a->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006139 bc_vec_pop(v);
6140 }
6141
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006142 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6143 bc_vec_push(&G.prog.results, &res);
6144 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006145
6146 return BC_STATUS_SUCCESS;
6147}
6148#endif // ENABLE_BC
6149
6150static unsigned long bc_program_scale(BcNum *n)
6151{
6152 return (unsigned long) n->rdx;
6153}
6154
6155static unsigned long bc_program_len(BcNum *n)
6156{
6157 unsigned long len = n->len;
6158 size_t i;
6159
6160 if (n->rdx != n->len) return len;
6161 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6162
6163 return len;
6164}
6165
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006166static BcStatus bc_program_builtin(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006167{
6168 BcStatus s;
6169 BcResult *opnd;
6170 BcNum *num = NULL;
6171 BcResult res;
6172 bool len = inst == BC_INST_LENGTH;
6173
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006174 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006175 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006176 opnd = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006177
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006178 s = bc_program_num(opnd, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006179 if (s) return s;
6180
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006181#if ENABLE_DC
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006182 if (!BC_PROG_NUM(opnd, num) && !len)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006183 return bc_error_variable_is_wrong_type();
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006184#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006185
6186 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6187
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006188 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006189#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006190 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006191 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006192 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006193#endif
6194#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006195 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6196
6197 char **str;
6198 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6199
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006200 str = bc_vec_item(&G.prog.strs, idx);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006201 bc_num_ulong2num(&res.d.n, strlen(*str));
Gavin Howard01055ba2018-11-03 11:00:21 -06006202 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006203#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006204 else {
6205 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006206 bc_num_ulong2num(&res.d.n, f(num));
Gavin Howard01055ba2018-11-03 11:00:21 -06006207 }
6208
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006209 bc_program_retire(&res, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006210
6211 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06006212}
6213
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006214#if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006215static BcStatus bc_program_divmod(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006216{
6217 BcStatus s;
6218 BcResult *opd1, *opd2, res, res2;
6219 BcNum *n1, *n2 = NULL;
6220
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006221 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006222 if (s) return s;
6223
6224 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6225 bc_num_init(&res2.d.n, n2->len);
6226
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006227 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
Gavin Howard01055ba2018-11-03 11:00:21 -06006228 if (s) goto err;
6229
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006230 bc_program_binOpRetire(&res2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006231 res.t = BC_RESULT_TEMP;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006232 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006233
6234 return s;
6235
6236err:
6237 bc_num_free(&res2.d.n);
6238 bc_num_free(&res.d.n);
6239 return s;
6240}
6241
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006242static BcStatus bc_program_modexp(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006243{
6244 BcStatus s;
6245 BcResult *r1, *r2, *r3, res;
6246 BcNum *n1, *n2, *n3;
6247
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006248 if (!BC_PROG_STACK(&G.prog.results, 3))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006249 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006250 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006251 if (s) return s;
6252
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006253 r1 = bc_vec_item_rev(&G.prog.results, 2);
6254 s = bc_program_num(r1, &n1, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006255 if (s) return s;
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006256 if (!BC_PROG_NUM(r1, n1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006257 return bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006258
6259 // Make sure that the values have their pointers updated, if necessary.
6260 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6261
6262 if (r1->t == r2->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006263 s = bc_program_num(r2, &n2, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006264 if (s) return s;
6265 }
6266
6267 if (r1->t == r3->t) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006268 s = bc_program_num(r3, &n3, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006269 if (s) return s;
6270 }
6271 }
6272
6273 bc_num_init(&res.d.n, n3->len);
6274 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6275 if (s) goto err;
6276
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006277 bc_vec_pop(&G.prog.results);
6278 bc_program_binOpRetire(&res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006279
6280 return s;
6281
6282err:
6283 bc_num_free(&res.d.n);
6284 return s;
6285}
6286
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006287static void bc_program_stackLen(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006288{
Gavin Howard01055ba2018-11-03 11:00:21 -06006289 BcResult res;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006290 size_t len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006291
6292 res.t = BC_RESULT_TEMP;
6293
6294 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006295 bc_num_ulong2num(&res.d.n, len);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006296 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006297}
6298
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006299static BcStatus bc_program_asciify(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006300{
6301 BcStatus s;
6302 BcResult *r, res;
6303 BcNum *num = NULL, n;
6304 char *str, *str2, c;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006305 size_t len = G.prog.strs.len, idx;
Gavin Howard01055ba2018-11-03 11:00:21 -06006306 unsigned long val;
6307
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006308 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006309 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006310 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006311
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006312 s = bc_program_num(r, &num, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006313 if (s) return s;
6314
6315 if (BC_PROG_NUM(r, num)) {
6316
6317 bc_num_init(&n, BC_NUM_DEF_SIZE);
6318 bc_num_copy(&n, num);
6319 bc_num_truncate(&n, n.rdx);
6320
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006321 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006322 if (s) goto num_err;
6323 s = bc_num_ulong(&n, &val);
6324 if (s) goto num_err;
6325
6326 c = (char) val;
6327
6328 bc_num_free(&n);
6329 }
6330 else {
6331 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006332 str2 = *((char **) bc_vec_item(&G.prog.strs, idx));
Gavin Howard01055ba2018-11-03 11:00:21 -06006333 c = str2[0];
6334 }
6335
6336 str = xmalloc(2);
6337 str[0] = c;
6338 str[1] = '\0';
6339
6340 str2 = xstrdup(str);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006341 bc_program_addFunc(str2, &idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006342
6343 if (idx != len + BC_PROG_REQ_FUNCS) {
6344
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006345 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6346 if (!strcmp(*((char **) bc_vec_item(&G.prog.strs, idx)), str)) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006347 len = idx;
6348 break;
6349 }
6350 }
6351
6352 free(str);
6353 }
6354 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006355 bc_vec_push(&G.prog.strs, &str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006356
6357 res.t = BC_RESULT_STR;
6358 res.d.id.idx = len;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006359 bc_vec_pop(&G.prog.results);
6360 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006361
6362 return BC_STATUS_SUCCESS;
6363
6364num_err:
6365 bc_num_free(&n);
6366 return s;
6367}
6368
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006369static BcStatus bc_program_printStream(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006370{
6371 BcStatus s;
6372 BcResult *r;
6373 BcNum *n = NULL;
6374 size_t idx;
6375 char *str;
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, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006382 if (s) return s;
6383
6384 if (BC_PROG_NUM(r, n))
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006385 s = bc_num_stream(n, &G.prog.strmb, &G.prog.nchars, G.prog.len);
Gavin Howard01055ba2018-11-03 11:00:21 -06006386 else {
6387 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006388 str = *((char **) bc_vec_item(&G.prog.strs, idx));
Denys Vlasenko00d77792018-11-30 23:13:42 +01006389 printf("%s", str);
Gavin Howard01055ba2018-11-03 11:00:21 -06006390 }
6391
6392 return s;
6393}
6394
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006395static BcStatus bc_program_nquit(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006396{
6397 BcStatus s;
6398 BcResult *opnd;
6399 BcNum *num = NULL;
6400 unsigned long val;
6401
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006402 s = bc_program_prep(&opnd, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006403 if (s) return s;
6404 s = bc_num_ulong(num, &val);
6405 if (s) return s;
6406
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006407 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006408
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006409 if (G.prog.stack.len < val)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006410 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006411 if (G.prog.stack.len == val) {
6412 if (ENABLE_FEATURE_CLEAN_UP)
6413 return BC_STATUS_FAILURE;
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006414 quit();
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006415 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006416
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006417 bc_vec_npop(&G.prog.stack, val);
Gavin Howard01055ba2018-11-03 11:00:21 -06006418
6419 return s;
6420}
6421
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006422static BcStatus bc_program_execStr(char *code, size_t *bgn,
Gavin Howard01055ba2018-11-03 11:00:21 -06006423 bool cond)
6424{
6425 BcStatus s = BC_STATUS_SUCCESS;
6426 BcResult *r;
6427 char **str;
6428 BcFunc *f;
6429 BcParse prs;
6430 BcInstPtr ip;
6431 size_t fidx, sidx;
6432 BcNum *n;
6433 bool exec;
6434
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006435 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006436 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006437
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006438 r = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006439
6440 if (cond) {
6441
Gavin Howard01055ba2018-11-03 11:00:21 -06006442 char *name, *then_name = bc_program_name(code, bgn), *else_name = NULL;
6443
6444 if (code[*bgn] == BC_PARSE_STREND)
6445 (*bgn) += 1;
6446 else
6447 else_name = bc_program_name(code, bgn);
6448
6449 exec = r->d.n.len != 0;
6450
6451 if (exec)
6452 name = then_name;
6453 else if (else_name != NULL) {
6454 exec = true;
6455 name = else_name;
6456 }
6457
6458 if (exec) {
Denys Vlasenkodf515392018-12-02 19:27:48 +01006459 BcVec *v;
6460 v = bc_program_search(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006461 n = bc_vec_top(v);
6462 }
6463
6464 free(then_name);
6465 free(else_name);
6466
6467 if (!exec) goto exit;
6468 if (!BC_PROG_STR(n)) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006469 s = bc_error_variable_is_wrong_type();
Gavin Howard01055ba2018-11-03 11:00:21 -06006470 goto exit;
6471 }
6472
6473 sidx = n->rdx;
6474 }
6475 else {
6476
6477 if (r->t == BC_RESULT_STR)
6478 sidx = r->d.id.idx;
6479 else if (r->t == BC_RESULT_VAR) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006480 s = bc_program_num(r, &n, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006481 if (s || !BC_PROG_STR(n)) goto exit;
6482 sidx = n->rdx;
6483 }
6484 else
6485 goto exit;
6486 }
6487
6488 fidx = sidx + BC_PROG_REQ_FUNCS;
6489
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006490 str = bc_vec_item(&G.prog.strs, sidx);
6491 f = bc_vec_item(&G.prog.fns, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006492
6493 if (f->code.len == 0) {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006494 common_parse_init(&prs, fidx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006495 s = bc_parse_text(&prs, *str);
6496 if (s) goto err;
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01006497 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006498 if (s) goto err;
6499
6500 if (prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006501 s = bc_error_bad_expression();
Gavin Howard01055ba2018-11-03 11:00:21 -06006502 goto err;
6503 }
6504
6505 bc_parse_free(&prs);
6506 }
6507
6508 ip.idx = 0;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006509 ip.len = G.prog.results.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006510 ip.func = fidx;
6511
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006512 bc_vec_pop(&G.prog.results);
6513 bc_vec_push(&G.prog.stack, &ip);
Gavin Howard01055ba2018-11-03 11:00:21 -06006514
6515 return BC_STATUS_SUCCESS;
6516
6517err:
6518 bc_parse_free(&prs);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006519 f = bc_vec_item(&G.prog.fns, fidx);
Denys Vlasenko7d628012018-12-04 21:46:47 +01006520 bc_vec_pop_all(&f->code);
Gavin Howard01055ba2018-11-03 11:00:21 -06006521exit:
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006522 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006523 return s;
6524}
6525#endif // ENABLE_DC
6526
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006527static void bc_program_pushGlobal(char inst)
Gavin Howard01055ba2018-11-03 11:00:21 -06006528{
Gavin Howard01055ba2018-11-03 11:00:21 -06006529 BcResult res;
6530 unsigned long val;
6531
6532 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6533 if (inst == BC_INST_IBASE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006534 val = (unsigned long) G.prog.ib_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006535 else if (inst == BC_INST_SCALE)
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006536 val = (unsigned long) G.prog.scale;
Gavin Howard01055ba2018-11-03 11:00:21 -06006537 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006538 val = (unsigned long) G.prog.ob_t;
Gavin Howard01055ba2018-11-03 11:00:21 -06006539
6540 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006541 bc_num_ulong2num(&res.d.n, val);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006542 bc_vec_push(&G.prog.results, &res);
Gavin Howard01055ba2018-11-03 11:00:21 -06006543}
6544
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006545static void bc_program_addFunc(char *name, size_t *idx)
Gavin Howard01055ba2018-11-03 11:00:21 -06006546{
Gavin Howard01055ba2018-11-03 11:00:21 -06006547 BcId entry, *entry_ptr;
6548 BcFunc f;
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006549 int inserted;
Gavin Howard01055ba2018-11-03 11:00:21 -06006550
6551 entry.name = name;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006552 entry.idx = G.prog.fns.len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006553
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006554 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6555 if (!inserted) free(name);
Gavin Howard01055ba2018-11-03 11:00:21 -06006556
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006557 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006558 *idx = entry_ptr->idx;
6559
Denys Vlasenkoa02f8442018-12-03 20:35:16 +01006560 if (!inserted) {
Gavin Howard01055ba2018-11-03 11:00:21 -06006561
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006562 BcFunc *func = bc_vec_item(&G.prog.fns, entry_ptr->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006563
6564 // We need to reset these, so the function can be repopulated.
6565 func->nparams = 0;
Denys Vlasenko7d628012018-12-04 21:46:47 +01006566 bc_vec_pop_all(&func->autos);
6567 bc_vec_pop_all(&func->code);
6568 bc_vec_pop_all(&func->labels);
Gavin Howard01055ba2018-11-03 11:00:21 -06006569 }
6570 else {
6571 bc_func_init(&f);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006572 bc_vec_push(&G.prog.fns, &f);
Gavin Howard01055ba2018-11-03 11:00:21 -06006573 }
6574}
6575
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006576static BcStatus bc_program_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006577{
6578 BcStatus s = BC_STATUS_SUCCESS;
6579 size_t idx;
6580 BcResult r, *ptr;
6581 BcNum *num;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006582 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6583 BcFunc *func = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006584 char *code = func->code.v;
6585 bool cond = false;
6586
6587 while (!s && ip->idx < func->code.len) {
6588
6589 char inst = code[(ip->idx)++];
6590
6591 switch (inst) {
6592
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006593#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006594 case BC_INST_JUMP_ZERO:
6595 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006596 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006597 if (s) return s;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006598 cond = !bc_num_cmp(num, &G.prog.zero);
6599 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006600 }
6601 // Fallthrough.
6602 case BC_INST_JUMP:
6603 {
6604 size_t *addr;
6605 idx = bc_program_index(code, &ip->idx);
6606 addr = bc_vec_item(&func->labels, idx);
6607 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6608 break;
6609 }
6610
6611 case BC_INST_CALL:
6612 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006613 s = bc_program_call(code, &ip->idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006614 break;
6615 }
6616
6617 case BC_INST_INC_PRE:
6618 case BC_INST_DEC_PRE:
6619 case BC_INST_INC_POST:
6620 case BC_INST_DEC_POST:
6621 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006622 s = bc_program_incdec(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006623 break;
6624 }
6625
6626 case BC_INST_HALT:
6627 {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006628 quit_or_return_for_exit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006629 break;
6630 }
6631
6632 case BC_INST_RET:
6633 case BC_INST_RET0:
6634 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006635 s = bc_program_return(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006636 break;
6637 }
6638
6639 case BC_INST_BOOL_OR:
6640 case BC_INST_BOOL_AND:
6641#endif // ENABLE_BC
6642 case BC_INST_REL_EQ:
6643 case BC_INST_REL_LE:
6644 case BC_INST_REL_GE:
6645 case BC_INST_REL_NE:
6646 case BC_INST_REL_LT:
6647 case BC_INST_REL_GT:
6648 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006649 s = bc_program_logical(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006650 break;
6651 }
6652
6653 case BC_INST_READ:
6654 {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006655 s = bc_program_read();
Gavin Howard01055ba2018-11-03 11:00:21 -06006656 break;
6657 }
6658
6659 case BC_INST_VAR:
6660 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006661 s = bc_program_pushVar(code, &ip->idx, false, false);
Gavin Howard01055ba2018-11-03 11:00:21 -06006662 break;
6663 }
6664
6665 case BC_INST_ARRAY_ELEM:
6666 case BC_INST_ARRAY:
6667 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006668 s = bc_program_pushArray(code, &ip->idx, inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006669 break;
6670 }
6671
6672 case BC_INST_LAST:
6673 {
6674 r.t = BC_RESULT_LAST;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006675 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006676 break;
6677 }
6678
6679 case BC_INST_IBASE:
6680 case BC_INST_SCALE:
6681 case BC_INST_OBASE:
6682 {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006683 bc_program_pushGlobal(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006684 break;
6685 }
6686
6687 case BC_INST_SCALE_FUNC:
6688 case BC_INST_LENGTH:
6689 case BC_INST_SQRT:
6690 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006691 s = bc_program_builtin(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006692 break;
6693 }
6694
6695 case BC_INST_NUM:
6696 {
6697 r.t = BC_RESULT_CONSTANT;
6698 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006699 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006700 break;
6701 }
6702
6703 case BC_INST_POP:
6704 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006705 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006706 s = bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006707 else
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006708 bc_vec_pop(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006709 break;
6710 }
6711
6712 case BC_INST_POP_EXEC:
6713 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006714 bc_vec_pop(&G.prog.stack);
Gavin Howard01055ba2018-11-03 11:00:21 -06006715 break;
6716 }
6717
6718 case BC_INST_PRINT:
6719 case BC_INST_PRINT_POP:
6720 case BC_INST_PRINT_STR:
6721 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006722 s = bc_program_print(inst, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06006723 break;
6724 }
6725
6726 case BC_INST_STR:
6727 {
6728 r.t = BC_RESULT_STR;
6729 r.d.id.idx = bc_program_index(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006730 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006731 break;
6732 }
6733
6734 case BC_INST_POWER:
6735 case BC_INST_MULTIPLY:
6736 case BC_INST_DIVIDE:
6737 case BC_INST_MODULUS:
6738 case BC_INST_PLUS:
6739 case BC_INST_MINUS:
6740 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006741 s = bc_program_op(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006742 break;
6743 }
6744
6745 case BC_INST_BOOL_NOT:
6746 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006747 s = bc_program_prep(&ptr, &num);
Gavin Howard01055ba2018-11-03 11:00:21 -06006748 if (s) return s;
6749
6750 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006751 (!bc_num_cmp(num, &G.prog.zero) ? bc_num_one : bc_num_zero)(&r.d.n);
6752 bc_program_retire(&r, BC_RESULT_TEMP);
Gavin Howard01055ba2018-11-03 11:00:21 -06006753
6754 break;
6755 }
6756
6757 case BC_INST_NEG:
6758 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006759 s = bc_program_negate();
Gavin Howard01055ba2018-11-03 11:00:21 -06006760 break;
6761 }
6762
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006763#if ENABLE_BC
Gavin Howard01055ba2018-11-03 11:00:21 -06006764 case BC_INST_ASSIGN_POWER:
6765 case BC_INST_ASSIGN_MULTIPLY:
6766 case BC_INST_ASSIGN_DIVIDE:
6767 case BC_INST_ASSIGN_MODULUS:
6768 case BC_INST_ASSIGN_PLUS:
6769 case BC_INST_ASSIGN_MINUS:
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006770#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06006771 case BC_INST_ASSIGN:
6772 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006773 s = bc_program_assign(inst);
Gavin Howard01055ba2018-11-03 11:00:21 -06006774 break;
6775 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006776#if ENABLE_DC
Gavin Howard01055ba2018-11-03 11:00:21 -06006777 case BC_INST_MODEXP:
6778 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006779 s = bc_program_modexp();
Gavin Howard01055ba2018-11-03 11:00:21 -06006780 break;
6781 }
6782
6783 case BC_INST_DIVMOD:
6784 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006785 s = bc_program_divmod();
Gavin Howard01055ba2018-11-03 11:00:21 -06006786 break;
6787 }
6788
6789 case BC_INST_EXECUTE:
6790 case BC_INST_EXEC_COND:
6791 {
6792 cond = inst == BC_INST_EXEC_COND;
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006793 s = bc_program_execStr(code, &ip->idx, cond);
Gavin Howard01055ba2018-11-03 11:00:21 -06006794 break;
6795 }
6796
6797 case BC_INST_PRINT_STACK:
6798 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006799 for (idx = 0; !s && idx < G.prog.results.len; ++idx)
6800 s = bc_program_print(BC_INST_PRINT, idx);
Gavin Howard01055ba2018-11-03 11:00:21 -06006801 break;
6802 }
6803
6804 case BC_INST_CLEAR_STACK:
6805 {
Denys Vlasenko7d628012018-12-04 21:46:47 +01006806 bc_vec_pop_all(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006807 break;
6808 }
6809
6810 case BC_INST_STACK_LEN:
6811 {
Denys Vlasenkoe3b4f232018-12-02 18:44:40 +01006812 bc_program_stackLen();
Gavin Howard01055ba2018-11-03 11:00:21 -06006813 break;
6814 }
6815
6816 case BC_INST_DUPLICATE:
6817 {
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006818 if (!BC_PROG_STACK(&G.prog.results, 1))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006819 return bc_error_stack_has_too_few_elements();
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006820 ptr = bc_vec_top(&G.prog.results);
Gavin Howard01055ba2018-11-03 11:00:21 -06006821 bc_result_copy(&r, ptr);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006822 bc_vec_push(&G.prog.results, &r);
Gavin Howard01055ba2018-11-03 11:00:21 -06006823 break;
6824 }
6825
6826 case BC_INST_SWAP:
6827 {
6828 BcResult *ptr2;
6829
Denys Vlasenko60cf7472018-12-04 20:05:28 +01006830 if (!BC_PROG_STACK(&G.prog.results, 2))
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01006831 return bc_error_stack_has_too_few_elements();
Gavin Howard01055ba2018-11-03 11:00:21 -06006832
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006833 ptr = bc_vec_item_rev(&G.prog.results, 0);
6834 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006835 memcpy(&r, ptr, sizeof(BcResult));
6836 memcpy(ptr, ptr2, sizeof(BcResult));
6837 memcpy(ptr2, &r, sizeof(BcResult));
6838
6839 break;
6840 }
6841
6842 case BC_INST_ASCIIFY:
6843 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006844 s = bc_program_asciify();
Gavin Howard01055ba2018-11-03 11:00:21 -06006845 break;
6846 }
6847
6848 case BC_INST_PRINT_STREAM:
6849 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006850 s = bc_program_printStream();
Gavin Howard01055ba2018-11-03 11:00:21 -06006851 break;
6852 }
6853
6854 case BC_INST_LOAD:
6855 case BC_INST_PUSH_VAR:
6856 {
6857 bool copy = inst == BC_INST_LOAD;
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006858 s = bc_program_pushVar(code, &ip->idx, true, copy);
Gavin Howard01055ba2018-11-03 11:00:21 -06006859 break;
6860 }
6861
6862 case BC_INST_PUSH_TO_VAR:
6863 {
6864 char *name = bc_program_name(code, &ip->idx);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006865 s = bc_program_copyToVar(name, true);
Gavin Howard01055ba2018-11-03 11:00:21 -06006866 free(name);
6867 break;
6868 }
6869
6870 case BC_INST_QUIT:
6871 {
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006872 if (G.prog.stack.len <= 2)
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01006873 quit_or_return_for_exit();
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01006874 bc_vec_npop(&G.prog.stack, 2);
Gavin Howard01055ba2018-11-03 11:00:21 -06006875 break;
6876 }
6877
6878 case BC_INST_NQUIT:
6879 {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01006880 s = bc_program_nquit();
Gavin Howard01055ba2018-11-03 11:00:21 -06006881 break;
6882 }
6883#endif // ENABLE_DC
6884 }
6885
Denys Vlasenkod38af482018-12-04 19:11:02 +01006886 if (s || G_interrupt) {
6887 bc_program_reset();
6888 break;
6889 }
Gavin Howard01055ba2018-11-03 11:00:21 -06006890
6891 // If the stack has changed, pointers may be invalid.
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01006892 ip = bc_vec_top(&G.prog.stack);
6893 func = bc_vec_item(&G.prog.fns, ip->func);
Gavin Howard01055ba2018-11-03 11:00:21 -06006894 code = func->code.v;
6895 }
6896
6897 return s;
6898}
6899
Denys Vlasenko54214c32018-12-06 09:07:06 +01006900static void bc_vm_info(void)
6901{
6902 printf("%s "BB_VER"\n"
6903 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6904 "Report bugs at: https://github.com/gavinhoward/bc\n"
6905 "This is free software with ABSOLUTELY NO WARRANTY\n"
6906 , applet_name);
6907}
6908
6909static void bc_args(char **argv)
6910{
6911 unsigned opts;
6912 int i;
6913
6914 GETOPT_RESET();
6915#if ENABLE_FEATURE_BC_LONG_OPTIONS
6916 opts = option_mask32 |= getopt32long(argv, "xwvsqli",
6917 "extended-register\0" No_argument "x"
6918 "warn\0" No_argument "w"
6919 "version\0" No_argument "v"
6920 "standard\0" No_argument "s"
6921 "quiet\0" No_argument "q"
6922 "mathlib\0" No_argument "l"
6923 "interactive\0" No_argument "i"
6924 );
6925#else
6926 opts = option_mask32 |= getopt32(argv, "xwvsqli");
6927#endif
6928 if (getenv("POSIXLY_CORRECT"))
6929 option_mask32 |= BC_FLAG_S;
6930
6931///should be in bc_vm_run() instead??
6932 if (opts & BC_FLAG_V) {
6933 bc_vm_info();
6934 exit(0);
6935 }
6936
6937 for (i = optind; argv[i]; ++i)
6938 bc_vec_push(&G.files, argv + i);
6939}
6940
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01006941#if ENABLE_BC
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006942static void bc_vm_envArgs(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06006943{
Gavin Howard01055ba2018-11-03 11:00:21 -06006944 BcVec v;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006945 char *buf;
Denys Vlasenko54214c32018-12-06 09:07:06 +01006946 char *env_args = getenv("BC_ENV_ARGS");
Gavin Howard01055ba2018-11-03 11:00:21 -06006947
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01006948 if (!env_args) return;
Gavin Howard01055ba2018-11-03 11:00:21 -06006949
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006950 G.env_args = xstrdup(env_args);
6951 buf = G.env_args;
Gavin Howard01055ba2018-11-03 11:00:21 -06006952
6953 bc_vec_init(&v, sizeof(char *), NULL);
Gavin Howard01055ba2018-11-03 11:00:21 -06006954
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006955 while (*(buf = skip_whitespace(buf)) != '\0') {
6956 bc_vec_push(&v, &buf);
6957 buf = skip_non_whitespace(buf);
6958 if (!*buf)
6959 break;
6960 *buf++ = '\0';
Gavin Howard01055ba2018-11-03 11:00:21 -06006961 }
6962
Denys Vlasenko54214c32018-12-06 09:07:06 +01006963 // NULL terminate, and pass argv[] so that first arg is argv[1]
6964 if (sizeof(int) == sizeof(char*)) {
6965 bc_vec_push(&v, &const_int_0);
6966 } else {
6967 static char *const nullptr = NULL;
6968 bc_vec_push(&v, &nullptr);
6969 }
6970 bc_args(((char **)v.v) - 1);
Gavin Howard01055ba2018-11-03 11:00:21 -06006971
6972 bc_vec_free(&v);
Gavin Howard01055ba2018-11-03 11:00:21 -06006973}
6974#endif // ENABLE_BC
6975
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006976static unsigned bc_vm_envLen(const char *var)
Gavin Howard01055ba2018-11-03 11:00:21 -06006977{
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006978 char *lenv;
6979 unsigned len;
Gavin Howard01055ba2018-11-03 11:00:21 -06006980
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006981 lenv = getenv(var);
6982 len = BC_NUM_PRINT_WIDTH;
Gavin Howard01055ba2018-11-03 11:00:21 -06006983 if (!lenv) return len;
6984
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01006985 len = bb_strtou(lenv, NULL, 10) - 1;
6986 if (errno || len < 2 || len >= INT_MAX)
Gavin Howard01055ba2018-11-03 11:00:21 -06006987 len = BC_NUM_PRINT_WIDTH;
6988
6989 return len;
6990}
6991
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006992static BcStatus bc_vm_process(const char *text)
Gavin Howard01055ba2018-11-03 11:00:21 -06006993{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006994 BcStatus s = bc_parse_text(&G.prs, text);
Gavin Howard01055ba2018-11-03 11:00:21 -06006995
Gavin Howard01055ba2018-11-03 11:00:21 -06006996 if (s) return s;
6997
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006998 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01006999 s = G.prs.parse(&G.prs);
Denys Vlasenkocfdc1332018-12-03 14:02:35 +01007000 if (s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007001 }
7002
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007003 if (BC_PARSE_CAN_EXEC(&G.prs)) {
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007004 s = bc_program_exec();
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01007005 fflush_and_check();
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007006 if (s)
Denys Vlasenkod38af482018-12-04 19:11:02 +01007007 bc_program_reset();
Gavin Howard01055ba2018-11-03 11:00:21 -06007008 }
7009
7010 return s;
7011}
7012
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007013static BcStatus bc_vm_file(const char *file)
Gavin Howard01055ba2018-11-03 11:00:21 -06007014{
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007015 const char *sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007016 char *data;
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007017 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007018 BcFunc *main_func;
7019 BcInstPtr *ip;
7020
Denys Vlasenkodf515392018-12-02 19:27:48 +01007021 data = bc_read_file(file);
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007022 if (!data) return bc_error_fmt("file '%s' is not text", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007023
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007024 sv_file = G.prog.file;
7025 G.prog.file = file;
7026 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007027 s = bc_vm_process(data);
Gavin Howard01055ba2018-11-03 11:00:21 -06007028 if (s) goto err;
7029
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007030 main_func = bc_vec_item(&G.prog.fns, BC_PROG_MAIN);
7031 ip = bc_vec_item(&G.prog.stack, 0);
Gavin Howard01055ba2018-11-03 11:00:21 -06007032
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007033 if (main_func->code.len < ip->idx)
Denys Vlasenko24fb2cd2018-12-05 16:03:46 +01007034 s = bc_error_fmt("file '%s' is not executable", file);
Gavin Howard01055ba2018-11-03 11:00:21 -06007035
7036err:
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007037 G.prog.file = sv_file;
Gavin Howard01055ba2018-11-03 11:00:21 -06007038 free(data);
7039 return s;
7040}
7041
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007042static BcStatus bc_vm_stdin(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007043{
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007044 BcStatus s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007045 BcVec buf, buffer;
Gavin Howard01055ba2018-11-03 11:00:21 -06007046 size_t len, i, str = 0;
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007047 bool comment = false;
Gavin Howard01055ba2018-11-03 11:00:21 -06007048
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007049 G.prog.file = NULL;
7050 bc_lex_file(&G.prs.l);
Gavin Howard01055ba2018-11-03 11:00:21 -06007051
Denys Vlasenko7d628012018-12-04 21:46:47 +01007052 bc_char_vec_init(&buffer);
7053 bc_char_vec_init(&buf);
Denys Vlasenko08c033c2018-12-05 16:55:08 +01007054 bc_vec_pushZeroByte(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007055
7056 // This loop is complex because the vm tries not to send any lines that end
7057 // with a backslash to the parser. The reason for that is because the parser
7058 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7059 // case, and for strings and comments, the parser will expect more stuff.
Denys Vlasenko657d6bb2018-12-05 20:25:03 +01007060 s = BC_STATUS_SUCCESS;
Denys Vlasenkod4744ad2018-12-03 14:28:51 +01007061 while (!G.eof && (s = bc_read_line(&buf, ">>> ")) == BC_STATUS_SUCCESS) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007062
7063 char *string = buf.v;
7064
7065 len = buf.len - 1;
7066
7067 if (len == 1) {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007068 if (str && buf.v[0] == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007069 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007070 else if (buf.v[0] == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007071 str += 1;
7072 }
7073 else if (len > 1 || comment) {
7074
7075 for (i = 0; i < len; ++i) {
7076
Denys Vlasenkoa0c421c2018-12-02 20:16:52 +01007077 bool notend = len > i + 1;
7078 char c = string[i];
Gavin Howard01055ba2018-11-03 11:00:21 -06007079
7080 if (i - 1 > len || string[i - 1] != '\\') {
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007081 if (G.sbgn == G.send)
7082 str ^= c == G.sbgn;
7083 else if (c == G.send)
Gavin Howard01055ba2018-11-03 11:00:21 -06007084 str -= 1;
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007085 else if (c == G.sbgn)
Gavin Howard01055ba2018-11-03 11:00:21 -06007086 str += 1;
7087 }
7088
7089 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7090 comment = true;
7091 break;
7092 }
7093 else if (c == '*' && notend && comment && string[i + 1] == '/')
7094 comment = false;
7095 }
7096
7097 if (str || comment || string[len - 2] == '\\') {
7098 bc_vec_concat(&buffer, buf.v);
7099 continue;
7100 }
7101 }
7102
7103 bc_vec_concat(&buffer, buf.v);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007104 s = bc_vm_process(buffer.v);
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007105 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007106 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007107 // Debug config, non-interactive mode:
7108 // return all the way back to main.
7109 // Non-debug builds do not come here, they exit.
7110 break;
7111 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007112 fflush_and_check();
7113 fputs("ready for more input\n", stderr);
7114 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007115
Denys Vlasenko7d628012018-12-04 21:46:47 +01007116 bc_vec_pop_all(&buffer);
Gavin Howard01055ba2018-11-03 11:00:21 -06007117 }
7118
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007119 if (str) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007120 s = bc_error("string end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007121 }
7122 else if (comment) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007123 s = bc_error("comment end could not be found");
Denys Vlasenko60cf7472018-12-04 20:05:28 +01007124 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007125
Gavin Howard01055ba2018-11-03 11:00:21 -06007126 bc_vec_free(&buf);
7127 bc_vec_free(&buffer);
7128 return s;
7129}
7130
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007131#if ENABLE_BC
7132static const char bc_lib[] = {
7133 "scale=20"
7134"\n" "define e(x){"
7135"\n" "auto b,s,n,r,d,i,p,f,v"
7136"\n" "b=ibase"
7137"\n" "ibase=A"
7138"\n" "if(x<0){"
7139"\n" "n=1"
7140"\n" "x=-x"
7141"\n" "}"
7142"\n" "s=scale"
7143"\n" "r=6+s+0.44*x"
7144"\n" "scale=scale(x)+1"
7145"\n" "while(x>1){"
7146"\n" "d+=1"
7147"\n" "x/=2"
7148"\n" "scale+=1"
7149"\n" "}"
7150"\n" "scale=r"
7151"\n" "r=x+1"
7152"\n" "p=x"
7153"\n" "f=v=1"
7154"\n" "for(i=2;v!=0;++i){"
7155"\n" "p*=x"
7156"\n" "f*=i"
7157"\n" "v=p/f"
7158"\n" "r+=v"
7159"\n" "}"
7160"\n" "while((d--)!=0)r*=r"
7161"\n" "scale=s"
7162"\n" "ibase=b"
7163"\n" "if(n!=0)return(1/r)"
7164"\n" "return(r/1)"
7165"\n" "}"
7166"\n" "define l(x){"
7167"\n" "auto b,s,r,p,a,q,i,v"
7168"\n" "b=ibase"
7169"\n" "ibase=A"
7170"\n" "if(x<=0){"
7171"\n" "r=(1-10^scale)/1"
7172"\n" "ibase=b"
7173"\n" "return(r)"
7174"\n" "}"
7175"\n" "s=scale"
7176"\n" "scale+=6"
7177"\n" "p=2"
7178"\n" "while(x>=2){"
7179"\n" "p*=2"
7180"\n" "x=sqrt(x)"
7181"\n" "}"
7182"\n" "while(x<=0.5){"
7183"\n" "p*=2"
7184"\n" "x=sqrt(x)"
7185"\n" "}"
7186"\n" "r=a=(x-1)/(x+1)"
7187"\n" "q=a*a"
7188"\n" "v=1"
7189"\n" "for(i=3;v!=0;i+=2){"
7190"\n" "a*=q"
7191"\n" "v=a/i"
7192"\n" "r+=v"
7193"\n" "}"
7194"\n" "r*=p"
7195"\n" "scale=s"
7196"\n" "ibase=b"
7197"\n" "return(r/1)"
7198"\n" "}"
7199"\n" "define s(x){"
7200"\n" "auto b,s,r,n,a,q,i"
7201"\n" "b=ibase"
7202"\n" "ibase=A"
7203"\n" "s=scale"
7204"\n" "scale=1.1*s+2"
7205"\n" "a=a(1)"
7206"\n" "if(x<0){"
7207"\n" "n=1"
7208"\n" "x=-x"
7209"\n" "}"
7210"\n" "scale=0"
7211"\n" "q=(x/a+2)/4"
7212"\n" "x=x-4*q*a"
7213"\n" "if(q%2!=0)x=-x"
7214"\n" "scale=s+2"
7215"\n" "r=a=x"
7216"\n" "q=-x*x"
7217"\n" "for(i=3;a!=0;i+=2){"
7218"\n" "a*=q/(i*(i-1))"
7219"\n" "r+=a"
7220"\n" "}"
7221"\n" "scale=s"
7222"\n" "ibase=b"
7223"\n" "if(n!=0)return(-r/1)"
7224"\n" "return(r/1)"
7225"\n" "}"
7226"\n" "define c(x){"
7227"\n" "auto b,s"
7228"\n" "b=ibase"
7229"\n" "ibase=A"
7230"\n" "s=scale"
7231"\n" "scale*=1.2"
7232"\n" "x=s(2*a(1)+x)"
7233"\n" "scale=s"
7234"\n" "ibase=b"
7235"\n" "return(x/1)"
7236"\n" "}"
7237"\n" "define a(x){"
7238"\n" "auto b,s,r,n,a,m,t,f,i,u"
7239"\n" "b=ibase"
7240"\n" "ibase=A"
7241"\n" "n=1"
7242"\n" "if(x<0){"
7243"\n" "n=-1"
7244"\n" "x=-x"
7245"\n" "}"
7246"\n" "if(x==1){"
7247"\n" "if(scale<65){"
7248"\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7249"\n" "}"
7250"\n" "}"
7251"\n" "if(x==.2){"
7252"\n" "if(scale<65){"
7253"\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7254"\n" "}"
7255"\n" "}"
7256"\n" "s=scale"
7257"\n" "if(x>.2){"
7258"\n" "scale+=5"
7259"\n" "a=a(.2)"
7260"\n" "}"
7261"\n" "scale=s+3"
7262"\n" "while(x>.2){"
7263"\n" "m+=1"
7264"\n" "x=(x-.2)/(1+.2*x)"
7265"\n" "}"
7266"\n" "r=u=x"
7267"\n" "f=-x*x"
7268"\n" "t=1"
7269"\n" "for(i=3;t!=0;i+=2){"
7270"\n" "u*=f"
7271"\n" "t=u/i"
7272"\n" "r+=t"
7273"\n" "}"
7274"\n" "scale=s"
7275"\n" "ibase=b"
7276"\n" "return((m*a+r)/n)"
7277"\n" "}"
7278"\n" "define j(n,x){"
7279"\n" "auto b,s,o,a,i,v,f"
7280"\n" "b=ibase"
7281"\n" "ibase=A"
7282"\n" "s=scale"
7283"\n" "scale=0"
7284"\n" "n/=1"
7285"\n" "if(n<0){"
7286"\n" "n=-n"
7287"\n" "if(n%2==1)o=1"
7288"\n" "}"
7289"\n" "a=1"
7290"\n" "for(i=2;i<=n;++i)a*=i"
7291"\n" "scale=1.5*s"
7292"\n" "a=(x^n)/2^n/a"
7293"\n" "r=v=1"
7294"\n" "f=-x*x/4"
7295"\n" "scale=scale+length(a)-scale(a)"
7296"\n" "for(i=1;v!=0;++i){"
7297"\n" "v=v*f/i/(n+i)"
7298"\n" "r+=v"
7299"\n" "}"
7300"\n" "scale=s"
7301"\n" "ibase=b"
7302"\n" "if(o!=0)a=-a"
7303"\n" "return(a*r/1)"
7304"\n" "}"
7305};
7306#endif // ENABLE_BC
7307
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007308static BcStatus bc_vm_exec(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007309{
7310 BcStatus s = BC_STATUS_SUCCESS;
7311 size_t i;
7312
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007313#if ENABLE_BC
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007314 if (option_mask32 & BC_FLAG_L) {
Gavin Howard01055ba2018-11-03 11:00:21 -06007315
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007316 // We know that internal library is not buggy,
7317 // thus error checking is normally disabled.
7318# define DEBUG_LIB 0
Denys Vlasenko0409ad32018-12-05 16:39:22 +01007319 bc_lex_file(&G.prs.l);
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007320 s = bc_parse_text(&G.prs, bc_lib);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007321 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007322
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007323 while (G.prs.l.t.t != BC_LEX_EOF) {
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007324 s = G.prs.parse(&G.prs);
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007325 if (DEBUG_LIB && s) return s;
7326 }
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007327 s = bc_program_exec();
Denys Vlasenko0ad36c42018-12-05 16:21:43 +01007328 if (DEBUG_LIB && s) return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007329 }
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007330#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007331
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007332 for (i = 0; !s && i < G.files.len; ++i)
7333 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007334 if (s) {
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007335 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007336 // Debug config, non-interactive mode:
7337 // return all the way back to main.
7338 // Non-debug builds do not come here, they exit.
7339 return s;
7340 }
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007341 fflush_and_check();
7342 fputs("ready for more input\n", stderr);
7343 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007344
Denys Vlasenko9b70f192018-12-04 20:51:40 +01007345 if (IS_BC || !G.files.len)
7346 s = bc_vm_stdin();
7347 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7348 s = bc_vm_process("");
Gavin Howard01055ba2018-11-03 11:00:21 -06007349
Denys Vlasenko00d77792018-11-30 23:13:42 +01007350 return s;
Gavin Howard01055ba2018-11-03 11:00:21 -06007351}
7352
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007353#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007354static void bc_program_free(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007355{
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007356 bc_num_free(&G.prog.ib);
7357 bc_num_free(&G.prog.ob);
7358 bc_num_free(&G.prog.hexb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007359# if ENABLE_DC
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007360 bc_num_free(&G.prog.strmb);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007361# endif
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007362 bc_vec_free(&G.prog.fns);
7363 bc_vec_free(&G.prog.fn_map);
7364 bc_vec_free(&G.prog.vars);
7365 bc_vec_free(&G.prog.var_map);
7366 bc_vec_free(&G.prog.arrs);
7367 bc_vec_free(&G.prog.arr_map);
7368 bc_vec_free(&G.prog.strs);
7369 bc_vec_free(&G.prog.consts);
7370 bc_vec_free(&G.prog.results);
7371 bc_vec_free(&G.prog.stack);
7372 bc_num_free(&G.prog.last);
7373 bc_num_free(&G.prog.zero);
7374 bc_num_free(&G.prog.one);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007375}
7376
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007377static void bc_vm_free(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007378{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007379 bc_vec_free(&G.files);
Denys Vlasenkoa1d3ca22018-12-02 18:26:38 +01007380 bc_program_free();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007381 bc_parse_free(&G.prs);
7382 free(G.env_args);
Gavin Howard01055ba2018-11-03 11:00:21 -06007383}
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007384#endif
7385
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007386static void bc_program_init(void)
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007387{
7388 size_t idx;
7389 BcInstPtr ip;
7390
7391 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7392 memset(&ip, 0, sizeof(BcInstPtr));
7393
7394 /* G.prog.nchars = G.prog.scale = 0; - already is */
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007395
7396 bc_num_init(&G.prog.ib, BC_NUM_DEF_SIZE);
7397 bc_num_ten(&G.prog.ib);
7398 G.prog.ib_t = 10;
7399
7400 bc_num_init(&G.prog.ob, BC_NUM_DEF_SIZE);
7401 bc_num_ten(&G.prog.ob);
7402 G.prog.ob_t = 10;
7403
7404 bc_num_init(&G.prog.hexb, BC_NUM_DEF_SIZE);
7405 bc_num_ten(&G.prog.hexb);
7406 G.prog.hexb.num[0] = 6;
7407
7408#if ENABLE_DC
7409 bc_num_init(&G.prog.strmb, BC_NUM_DEF_SIZE);
7410 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7411#endif
7412
7413 bc_num_init(&G.prog.last, BC_NUM_DEF_SIZE);
7414 bc_num_zero(&G.prog.last);
7415
7416 bc_num_init(&G.prog.zero, BC_NUM_DEF_SIZE);
7417 bc_num_zero(&G.prog.zero);
7418
7419 bc_num_init(&G.prog.one, BC_NUM_DEF_SIZE);
7420 bc_num_one(&G.prog.one);
7421
7422 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007423 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007424
Denys Vlasenko1f67e932018-12-03 00:08:59 +01007425 bc_program_addFunc(xstrdup("(main)"), &idx);
7426 bc_program_addFunc(xstrdup("(read)"), &idx);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007427
7428 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007429 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007430
7431 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
Denys Vlasenkocb9a99f2018-12-04 21:54:33 +01007432 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007433
7434 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7435 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7436 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7437 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7438 bc_vec_push(&G.prog.stack, &ip);
7439}
Gavin Howard01055ba2018-11-03 11:00:21 -06007440
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007441static void bc_vm_init(void)
Gavin Howard01055ba2018-11-03 11:00:21 -06007442{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007443 bc_vec_init(&G.files, sizeof(char *), NULL);
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007444 if (IS_BC)
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007445 IF_BC(bc_vm_envArgs();)
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007446 bc_program_init();
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007447 if (IS_BC) {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007448 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007449 } else {
Denys Vlasenko23c2e9f2018-12-06 11:43:17 +01007450 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
Denys Vlasenkof6c1da52018-12-02 17:36:00 +01007451 }
Gavin Howard01055ba2018-11-03 11:00:21 -06007452}
7453
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007454static BcStatus bc_vm_run(char **argv, const char *env_len)
Gavin Howard01055ba2018-11-03 11:00:21 -06007455{
7456 BcStatus st;
Gavin Howard01055ba2018-11-03 11:00:21 -06007457
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007458#if ENABLE_FEATURE_EDITING
7459 G.line_input_state = new_line_input_t(DO_HISTORY);
7460#endif
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007461 G.prog.len = bc_vm_envLen(env_len);
7462
7463 bc_vm_init();
7464 bc_args(argv);
Gavin Howard01055ba2018-11-03 11:00:21 -06007465
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007466 if (isatty(0)) {
Denys Vlasenkod38af482018-12-04 19:11:02 +01007467#if ENABLE_FEATURE_BC_SIGNALS
Denys Vlasenko1a6a4822018-12-06 09:20:32 +01007468 G_ttyin = 1;
Denys Vlasenko17c54722018-12-04 21:21:32 +01007469 // With SA_RESTART, most system calls will restart
7470 // (IOW: they won't fail with EINTR).
7471 // In particular, this means ^C won't cause
7472 // stdout to get into "error state" if SIGINT hits
7473 // within write() syscall.
7474 // The downside is that ^C while line input is taken
7475 // will only be handled after [Enter] since read()
7476 // from stdin is not interrupted by ^C either,
7477 // it restarts, thus fgetc() does not return on ^C.
7478 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7479
7480 // Without SA_RESTART, this exhibits a bug:
7481 // "while (1) print 1" and try ^C-ing it.
7482 // Intermittently, instead of returning to input line,
7483 // you'll get "output error: Interrupted system call"
7484 // and exit.
7485 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
Denys Vlasenkod38af482018-12-04 19:11:02 +01007486#endif
Denys Vlasenkod70d4a02018-12-04 20:58:40 +01007487 if (!(option_mask32 & BC_FLAG_Q))
Denys Vlasenkod38af482018-12-04 19:11:02 +01007488 bc_vm_info();
7489 }
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007490
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007491 st = bc_vm_exec();
Gavin Howard01055ba2018-11-03 11:00:21 -06007492
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007493#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007494 bc_vm_free();
Denys Vlasenko95f93bd2018-12-06 10:29:12 +01007495# if ENABLE_FEATURE_EDITING
7496 free_line_input_t(G.line_input_state);
7497# endif
Denys Vlasenkoe873ff92018-12-06 00:29:22 +01007498 FREE_G();
Denys Vlasenko785e4b32018-12-02 17:18:52 +01007499#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007500 return st;
7501}
7502
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007503#if ENABLE_BC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007504int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007505int bc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007506{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007507 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007508 G.sbgn = G.send = '"';
Gavin Howard01055ba2018-11-03 11:00:21 -06007509
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007510 return bc_vm_run(argv, "BC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007511}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007512#endif
Gavin Howard01055ba2018-11-03 11:00:21 -06007513
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007514#if ENABLE_DC
Denys Vlasenko5a9fef52018-12-02 14:35:32 +01007515int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007516int dc_main(int argc UNUSED_PARAM, char **argv)
Gavin Howard01055ba2018-11-03 11:00:21 -06007517{
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007518 INIT_G();
Denys Vlasenko6d9146a2018-12-02 15:48:37 +01007519 G.sbgn = '[';
7520 G.send = ']';
Gavin Howard01055ba2018-11-03 11:00:21 -06007521
Denys Vlasenko1ff1c702018-12-06 00:46:09 +01007522 return bc_vm_run(argv, "DC_LINE_LENGTH");
Gavin Howard01055ba2018-11-03 11:00:21 -06007523}
Denys Vlasenkoef869ec2018-12-02 18:49:16 +01007524#endif
Denys Vlasenko9ca9ef22018-12-06 11:31:14 +01007525
7526#endif // not DC_SMALL