1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Adapted from https://github.com/gavinhoward/bc
5 * Original code copyright (c) 2018 Gavin D. Howard and contributors.
8 //config: bool "bc (45 kb; 49 kb when combined with dc)"
11 //config: bc is a command-line, arbitrary-precision calculator with a
12 //config: Turing-complete language. See the GNU bc manual
13 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
14 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
16 //config: This bc has five differences to the GNU bc:
17 //config: 1) The period (.) is a shortcut for "last", as in the BSD bc.
18 //config: 2) Arrays are copied before being passed as arguments to
19 //config: functions. This behavior is required by the bc spec.
20 //config: 3) Arrays can be passed to the builtin "length" function to get
21 //config: the number of elements in the array. This prints "1":
22 //config: a[0] = 0; length(a[])
23 //config: 4) The precedence of the boolean "not" operator (!) is equal to
24 //config: that of the unary minus (-) negation operator. This still
25 //config: allows POSIX-compliant scripts to work while somewhat
26 //config: preserving expected behavior (versus C) and making parsing
28 //config: 5) "read()" accepts expressions, not only numeric literals.
31 //config: -i --interactive force interactive mode
32 //config: -q --quiet don't print version and copyright
33 //config: -s --standard error if any non-POSIX extensions are used
34 //config: -w --warn warn if any non-POSIX extensions are used
35 //config: -l --mathlib use predefined math routines:
36 //config: s(expr) sine in radians
37 //config: c(expr) cosine in radians
38 //config: a(expr) arctangent, returning radians
39 //config: l(expr) natural log
40 //config: e(expr) raises e to the power of expr
41 //config: j(n, x) Bessel function of integer order n of x
44 //config: bool "dc (38 kb; 49 kb when combined with bc)"
47 //config: dc is a reverse-polish notation command-line calculator which
48 //config: supports unlimited precision arithmetic. See the FreeBSD man page
49 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
50 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
52 //config: This dc has a few differences from the two above:
53 //config: 1) When printing a byte stream (command "P"), this dc follows what
54 //config: the FreeBSD dc does.
55 //config: 2) Implements the GNU extensions for divmod ("~") and
56 //config: modular exponentiation ("|").
57 //config: 3) Implements all FreeBSD extensions, except for "J" and "M".
58 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
59 //config: However, they are implemented differently. When it encounters
60 //config: whitespace where a register should be, it skips the whitespace.
61 //config: If the character following is not a lowercase letter, an error
62 //config: is issued. Otherwise, the register name is parsed by the
63 //config: following regex:
64 //config: [a-z][a-z0-9_]*
65 //config: This generally means that register names will be surrounded by
66 //config: whitespace. Examples:
67 //config: l idx s temp L index S temp2 < do_thing
68 //config: Also note that, like the FreeBSD dc, extended registers are not
69 //config: allowed unless the "-x" option is given.
71 //config:config FEATURE_DC_SMALL
72 //config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
73 //config: depends on DC && !BC
76 //config:config FEATURE_DC_LIBM
77 //config: bool "Enable power and exp functions (requires libm)"
79 //config: depends on FEATURE_DC_SMALL
81 //config: Enable power and exp functions.
82 //config: NOTE: This will require libm to be present for linking.
84 //config:config FEATURE_BC_SIGNALS
85 //config: bool "Interactive mode (+4kb)"
87 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
89 //config: Enable interactive mode: when started on a tty,
90 //config: ^C interrupts execution and returns to command line,
91 //config: errors also return to command line instead of exiting,
92 //config: line editing with history is available.
94 //config: With this option off, input can still be taken from tty,
95 //config: but all errors are fatal, ^C is fatal,
96 //config: tty is treated exactly the same as any other
97 //config: standard input (IOW: no line editing).
99 //config:config FEATURE_BC_LONG_OPTIONS
100 //config: bool "Enable bc/dc long options"
102 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
104 //config: Enable long options for bc and dc.
106 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
107 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
109 //kbuild:lib-$(CONFIG_BC) += bc.o
110 //kbuild:lib-$(CONFIG_DC) += bc.o
112 //See www.gnu.org/software/bc/manual/bc.html
113 //usage:#define bc_trivial_usage
114 //usage: "[-sqlw] FILE..."
116 //usage:#define bc_full_usage "\n"
117 //usage: "\nArbitrary precision calculator"
119 ///////: "\n -i Interactive" - has no effect for now
120 //usage: "\n -q Quiet"
121 //usage: "\n -l Load standard math library"
122 //usage: "\n -s Be POSIX compatible"
123 //usage: "\n -w Warn if extensions are used"
124 ///////: "\n -v Version"
126 //usage: "\n$BC_LINE_LENGTH changes output width"
128 //usage:#define bc_example_usage
129 //usage: "3 + 4.129\n"
130 //usage: "1903 - 2893\n"
131 //usage: "-129 * 213.28935\n"
132 //usage: "12 / -1932\n"
134 //usage: "34 ^ 189\n"
135 //usage: "scale = 13\n"
136 //usage: "ibase = 2\n"
137 //usage: "obase = A\n"
139 //usage:#define dc_trivial_usage
140 //usage: IF_NOT_FEATURE_DC_SMALL("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
142 //usage:#define dc_full_usage "\n"
143 //usage: "\nTiny RPN calculator. Operations:"
144 //usage: "\n+, -, *, /, %, ~, ^," IF_NOT_FEATURE_DC_SMALL(" |,")
145 //usage: "\np - print top of the stack without popping"
146 //usage: "\nf - print entire stack"
147 //usage: "\nk - pop the value and set the precision"
148 //usage: "\ni - pop the value and set input radix"
149 //usage: "\no - pop the value and set output radix"
150 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
152 //usage:#define dc_example_usage
153 //usage: "$ dc -e'2 2 + p'\n"
155 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
157 //usage: "$ dc -e'0 1 & p'\n"
159 //usage: "$ dc -e'0 1 | p'\n"
161 //usage: "$ echo '72 9 / 8 * p' | dc\n"
165 #include "common_bufsiz.h"
167 #if ENABLE_FEATURE_DC_SMALL
171 #define DEBUG_LEXER 0
172 #define DEBUG_COMPILE 0
174 // This can be left enabled for production as well:
175 #define SANITY_CHECKS 1
178 static uint8_t lex_indent;
179 #define dbg_lex(...) \
181 fprintf(stderr, "%*s", lex_indent, ""); \
182 bb_error_msg(__VA_ARGS__); \
184 #define dbg_lex_enter(...) \
186 dbg_lex(__VA_ARGS__); \
189 #define dbg_lex_done(...) \
192 dbg_lex(__VA_ARGS__); \
195 # define dbg_lex(...) ((void)0)
196 # define dbg_lex_enter(...) ((void)0)
197 # define dbg_lex_done(...) ((void)0)
201 # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
203 # define dbg_compile(...) ((void)0)
207 # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
209 # define dbg_exec(...) ((void)0)
212 typedef enum BcStatus {
213 BC_STATUS_SUCCESS = 0,
214 BC_STATUS_FAILURE = 1,
215 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr_empty_ok() uses this
218 #define BC_VEC_INVALID_IDX ((size_t) -1)
219 #define BC_VEC_START_CAP (1 << 5)
221 typedef void (*BcVecFree)(void *) FAST_FUNC;
223 typedef struct BcVec {
231 typedef signed char BcDig;
233 typedef struct BcNum {
241 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
242 // larger value might speed up BIGNUM calculations a bit:
243 #define BC_NUM_DEF_SIZE (16)
244 #define BC_NUM_PRINT_WIDTH (69)
246 #define BC_NUM_KARATSUBA_LEN (32)
248 typedef enum BcInst {
255 XC_INST_NEG, // order
257 XC_INST_REL_EQ, // should
258 XC_INST_REL_LE, // match
259 XC_INST_REL_GE, // LEX
260 XC_INST_REL_NE, // constants
261 XC_INST_REL_LT, // for
262 XC_INST_REL_GT, // these
264 XC_INST_POWER, // operations
265 XC_INST_MULTIPLY, // |
267 XC_INST_MODULUS, // |
271 XC_INST_BOOL_NOT, // |
272 XC_INST_BOOL_OR, // |
273 XC_INST_BOOL_AND, // |
275 BC_INST_ASSIGN_POWER, // |
276 BC_INST_ASSIGN_MULTIPLY,// |
277 BC_INST_ASSIGN_DIVIDE, // |
278 BC_INST_ASSIGN_MODULUS, // |
279 BC_INST_ASSIGN_PLUS, // |
280 BC_INST_ASSIGN_MINUS, // |
290 XC_INST_IBASE, // order of these constans should match other enums
291 XC_INST_OBASE, // order of these constans should match other enums
292 XC_INST_SCALE, // order of these constans should match other enums
293 IF_BC(BC_INST_LAST,) // order of these constans should match other enums
324 DC_INST_PRINT_STREAM,
339 DC_INST_INVALID = -1,
343 typedef struct BcId {
348 typedef struct BcFunc {
354 IF_BC(size_t nparams;)
357 typedef enum BcResultType {
361 XC_RESULT_ARRAY_ELEM,
366 //code uses "inst - XC_INST_IBASE + XC_RESULT_IBASE" construct,
367 XC_RESULT_IBASE, // relative order should match for: XC_INST_IBASE
368 XC_RESULT_OBASE, // relative order should match for: XC_INST_OBASE
369 XC_RESULT_SCALE, // relative order should match for: XC_INST_SCALE
370 IF_BC(BC_RESULT_LAST,) // relative order should match for: BC_INST_LAST
372 IF_BC(BC_RESULT_ONE,)
375 typedef union BcResultData {
381 typedef struct BcResult {
386 typedef struct BcInstPtr {
389 IF_BC(size_t results_len_before_call;)
392 typedef enum BcLexType {
403 XC_LEX_NEG = XC_LEX_1st_op, // order
405 XC_LEX_OP_REL_EQ, // should
406 XC_LEX_OP_REL_LE, // match
407 XC_LEX_OP_REL_GE, // INST
408 XC_LEX_OP_REL_NE, // constants
409 XC_LEX_OP_REL_LT, // for
410 XC_LEX_OP_REL_GT, // these
412 XC_LEX_OP_POWER, // operations
413 XC_LEX_OP_MULTIPLY, // |
414 XC_LEX_OP_DIVIDE, // |
415 XC_LEX_OP_MODULUS, // |
417 XC_LEX_OP_MINUS, // |
418 XC_LEX_OP_last = XC_LEX_OP_MINUS,
420 BC_LEX_OP_BOOL_NOT, // |
421 BC_LEX_OP_BOOL_OR, // |
422 BC_LEX_OP_BOOL_AND, // |
424 BC_LEX_OP_ASSIGN_POWER, // |
425 BC_LEX_OP_ASSIGN_MULTIPLY, // |
426 BC_LEX_OP_ASSIGN_DIVIDE, // |
427 BC_LEX_OP_ASSIGN_MODULUS, // |
428 BC_LEX_OP_ASSIGN_PLUS, // |
429 BC_LEX_OP_ASSIGN_MINUS, // |
431 BC_LEX_OP_ASSIGN, // V
436 BC_LEX_LPAREN, // () are 0x28 and 0x29
437 BC_LEX_RPAREN, // must be LPAREN+1: code uses (c - '(' + BC_LEX_LPAREN)
439 BC_LEX_LBRACKET, // [] are 0x5B and 5D
441 BC_LEX_RBRACKET, // must be LBRACKET+2: code uses (c - '[' + BC_LEX_LBRACKET)
443 BC_LEX_LBRACE, // {} are 0x7B and 0x7D
445 BC_LEX_RBRACE, // must be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
447 BC_LEX_KEY_1st_keyword,
448 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
455 // code uses "type - BC_LEX_KEY_IBASE + XC_INST_IBASE" construct,
456 BC_LEX_KEY_IBASE, // relative order should match for: XC_INST_IBASE
457 BC_LEX_KEY_OBASE, // relative order should match for: XC_INST_OBASE
459 IF_BC(BC_LEX_KEY_LAST,) // relative order should match for: BC_INST_LAST
472 DC_LEX_OP_BOOL_NOT = XC_LEX_OP_last + 1,
504 // code uses "t - DC_LEX_STORE_IBASE + XC_INST_IBASE" construct,
505 DC_LEX_STORE_IBASE, // relative order should match for: XC_INST_IBASE
506 DC_LEX_STORE_OBASE, // relative order should match for: XC_INST_OBASE
507 DC_LEX_STORE_SCALE, // relative order should match for: XC_INST_SCALE
516 // must match order of BC_LEX_KEY_foo etc above
518 struct BcLexKeyword {
521 #define LEX_KW_ENTRY(a, b) \
522 { .name8 = a /*, .posix = b */ }
523 static const struct BcLexKeyword bc_lex_kws[20] = {
524 LEX_KW_ENTRY("auto" , 1), // 0
525 LEX_KW_ENTRY("break" , 1), // 1
526 LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
527 LEX_KW_ENTRY("define" , 1), // 3
528 LEX_KW_ENTRY("else" , 0), // 4
529 LEX_KW_ENTRY("for" , 1), // 5
530 LEX_KW_ENTRY("halt" , 0), // 6
531 LEX_KW_ENTRY("ibase" , 1), // 7
532 LEX_KW_ENTRY("obase" , 1), // 8
533 LEX_KW_ENTRY("if" , 1), // 9
534 LEX_KW_ENTRY("last" , 0), // 10
535 LEX_KW_ENTRY("length" , 1), // 11
536 LEX_KW_ENTRY("limits" , 0), // 12
537 LEX_KW_ENTRY("print" , 0), // 13
538 LEX_KW_ENTRY("quit" , 1), // 14
539 LEX_KW_ENTRY("read" , 0), // 15
540 LEX_KW_ENTRY("return" , 1), // 16
541 LEX_KW_ENTRY("scale" , 1), // 17
542 LEX_KW_ENTRY("sqrt" , 1), // 18
543 LEX_KW_ENTRY("while" , 1), // 19
546 #define STRING_else (bc_lex_kws[4].name8)
547 #define STRING_for (bc_lex_kws[5].name8)
548 #define STRING_if (bc_lex_kws[9].name8)
549 #define STRING_while (bc_lex_kws[19].name8)
573 #define keyword_is_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
575 // This is a bit array that corresponds to token types. An entry is
576 // true if the token is valid in an expression, false otherwise.
577 // Used to figure out when expr parsing should stop *without error message*
578 // - 0 element indicates this condition. 1 means "this token is to be eaten
579 // as part of the expression", it can then still be determined to be invalid
580 // by later processing.
582 #define EXBITS(a,b,c,d,e,f,g,h) \
583 ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
584 BC_PARSE_EXPRS_BITS = 0 // corresponding BC_LEX_xyz:
585 + (EXBITS(0,0,0,0,0,1,1,1) << (0*8)) // 0: EOF INVAL NL WS STR NAME NUM -
586 + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: == <= >= != < > ^ *
587 + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: / % + - ! || && ^=
588 + (EXBITS(1,1,1,1,1,1,1,1) << (3*8)) // 24: *= /= %= += -= = ++ --
589 + (EXBITS(1,1,0,0,0,0,0,0) << (4*8)) // 32: ( ) [ , ] { ; }
590 + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
591 + (EXBITS(1,0,1,1,0,0,0,1) << (6*8)) // 48: obase if last length limits print quit read
592 + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
595 static ALWAYS_INLINE long lex_allowed_in_bc_expr(unsigned i)
597 #if ULONG_MAX > 0xffffffff
598 // 64-bit version (will not work correctly for 32-bit longs!)
599 return BC_PARSE_EXPRS_BITS & (1UL << i);
602 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
604 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
607 return m & (1UL << i);
611 // This is an array of data for operators that correspond to
612 // [XC_LEX_1st_op...] token types.
613 static const uint8_t bc_parse_ops[] = {
614 #define OP(p,l) ((int)(l) * 0x10 + (p))
616 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
618 OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
619 OP(4, true ), OP( 4, true ), // + -
621 OP(7, true ), OP( 7, true ), // or and
622 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
623 OP(5, false), OP( 5, false ), // -= =
624 OP(0, false), OP( 0, false ), // inc dec
627 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
628 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
632 static const //BcLexType - should be this type
636 XC_LEX_OP_MODULUS, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_LPAREN,
638 XC_LEX_INVALID, XC_LEX_OP_MULTIPLY, XC_LEX_OP_PLUS, XC_LEX_INVALID,
640 XC_LEX_OP_MINUS, XC_LEX_INVALID, XC_LEX_OP_DIVIDE,
642 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
643 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
644 XC_LEX_INVALID, XC_LEX_INVALID,
646 DC_LEX_COLON, DC_LEX_SCOLON, XC_LEX_OP_REL_GT, XC_LEX_OP_REL_EQ,
647 XC_LEX_OP_REL_LT, DC_LEX_READ, XC_LEX_INVALID,
649 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
650 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_EQ_NO_REG, XC_LEX_INVALID,
652 DC_LEX_IBASE, XC_LEX_INVALID, DC_LEX_SCALE, DC_LEX_LOAD_POP,
653 XC_LEX_INVALID, DC_LEX_OP_BOOL_NOT, DC_LEX_OBASE, DC_LEX_PRINT_STREAM,
655 DC_LEX_NQUIT, DC_LEX_POP, DC_LEX_STORE_PUSH, XC_LEX_INVALID, XC_LEX_INVALID,
656 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_SCALE_FACTOR, XC_LEX_INVALID,
658 DC_LEX_LENGTH, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
660 XC_LEX_OP_POWER, XC_LEX_NEG, XC_LEX_INVALID,
662 DC_LEX_ASCIIFY, XC_LEX_INVALID, DC_LEX_CLEAR_STACK, DC_LEX_DUPLICATE,
663 DC_LEX_ELSE, DC_LEX_PRINT_STACK, XC_LEX_INVALID, XC_LEX_INVALID,
665 DC_LEX_STORE_IBASE, XC_LEX_INVALID, DC_LEX_STORE_SCALE, DC_LEX_LOAD,
666 XC_LEX_INVALID, DC_LEX_PRINT_POP, DC_LEX_STORE_OBASE, DC_LEX_PRINT,
668 DC_LEX_QUIT, DC_LEX_SWAP, DC_LEX_OP_ASSIGN, XC_LEX_INVALID,
669 XC_LEX_INVALID, DC_LEX_SQRT, XC_LEX_INVALID, DC_LEX_EXECUTE,
671 XC_LEX_INVALID, DC_LEX_STACK_LEVEL,
673 DC_LEX_LBRACE, DC_LEX_OP_MODEXP, XC_LEX_INVALID, DC_LEX_OP_DIVMOD,
675 static const //BcInst - should be this type. Using signed narrow type since DC_INST_INVALID is -1
677 dc_LEX_to_INST[] = { // starts at XC_LEX_OP_POWER // corresponding XC/DC_LEX_xyz:
678 XC_INST_POWER, XC_INST_MULTIPLY, // OP_POWER OP_MULTIPLY
679 XC_INST_DIVIDE, XC_INST_MODULUS, // OP_DIVIDE OP_MODULUS
680 XC_INST_PLUS, XC_INST_MINUS, // OP_PLUS OP_MINUS
681 XC_INST_BOOL_NOT, // DC_LEX_OP_BOOL_NOT
682 DC_INST_INVALID, // DC_LEX_OP_ASSIGN
683 XC_INST_REL_GT, // DC_LEX_LPAREN
684 DC_INST_INVALID, // DC_LEX_SCOLON
685 DC_INST_INVALID, // DC_LEX_READ
686 XC_INST_IBASE, // DC_LEX_IBASE
687 XC_INST_SCALE, // DC_LEX_SCALE
688 XC_INST_OBASE, // DC_LEX_OBASE
689 XC_INST_LENGTH, // DC_LEX_LENGTH
690 XC_INST_PRINT, // DC_LEX_PRINT
691 DC_INST_QUIT, // DC_LEX_QUIT
692 XC_INST_SQRT, // DC_LEX_SQRT
693 XC_INST_REL_GE, // DC_LEX_LBRACE
694 XC_INST_REL_EQ, // DC_LEX_EQ_NO_REG
695 DC_INST_MODEXP, DC_INST_DIVMOD, // OP_MODEXP OP_DIVMOD
696 DC_INST_INVALID, DC_INST_INVALID, // COLON ELSE
697 DC_INST_EXECUTE, // EXECUTE
698 DC_INST_PRINT_STACK, DC_INST_CLEAR_STACK, // PRINT_STACK CLEAR_STACK
699 DC_INST_STACK_LEN, DC_INST_DUPLICATE, // STACK_LEVEL DUPLICATE
700 DC_INST_SWAP, XC_INST_POP, // SWAP POP
701 DC_INST_ASCIIFY, DC_INST_PRINT_STREAM, // ASCIIFY PRINT_STREAM
702 DC_INST_INVALID, DC_INST_INVALID, // STORE_IBASE STORE_OBASE
703 DC_INST_INVALID, DC_INST_INVALID, // STORE_SCALE LOAD
704 DC_INST_INVALID, DC_INST_INVALID, // LOAD_POP STORE_PUSH
705 XC_INST_PRINT, DC_INST_NQUIT, // PRINT_POP NQUIT
706 XC_INST_SCALE_FUNC, // SCALE_FACTOR
707 // DC_INST_INVALID in this table either means that corresponding LEX
708 // is not possible for dc, or that it does not compile one-to-one
713 typedef struct BcParse {
714 smallint lex; // was BcLexType // first member is most used
715 smallint lex_last; // was BcLexType
717 const char *lex_inbuf;
718 const char *lex_next_at; // last lex_next() was called at this string
719 const char *lex_filename;
725 IF_BC(size_t in_funcdef;)
731 typedef struct BcProgram {
760 BcParse prs; // first member is most used
762 // For error messages. Can be set to current parsed line,
763 // or [TODO] to current executing line (can be before last parsed one)
768 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
769 IF_FEATURE_CLEAN_UP(smallint exiting;)
777 #if ENABLE_FEATURE_EDITING
778 line_input_t *line_input_state;
781 #define G (*ptr_to_globals)
782 #define INIT_G() do { \
783 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
785 #define FREE_G() do { \
786 FREE_PTR_TO_GLOBALS(); \
788 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
789 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
790 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
791 #if ENABLE_FEATURE_BC_SIGNALS
792 # define G_interrupt bb_got_signal
793 # define G_ttyin G.ttyin
795 # define G_interrupt 0
798 #if ENABLE_FEATURE_CLEAN_UP
799 # define G_exiting G.exiting
803 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
804 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
807 # define BC_PARSE_REL (1 << 0)
808 # define BC_PARSE_PRINT (1 << 1)
809 # define BC_PARSE_ARRAY (1 << 2)
810 # define BC_PARSE_NOCALL (1 << 3)
813 #define BC_PROG_MAIN (0)
814 #define BC_PROG_READ (1)
816 #define BC_PROG_REQ_FUNCS (2)
819 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
820 #define BC_PROG_NUM(r, n) \
821 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
823 #define BC_FLAG_W (1 << 0)
824 #define BC_FLAG_V (1 << 1)
825 #define BC_FLAG_S (1 << 2)
826 #define BC_FLAG_Q (1 << 3)
827 #define BC_FLAG_L (1 << 4)
828 #define BC_FLAG_I (1 << 5)
829 #define DC_FLAG_X (1 << 6)
831 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
832 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
834 #define BC_MAX_OBASE ((unsigned) 999)
835 #define BC_MAX_DIM ((unsigned) INT_MAX)
836 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
837 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
838 #define BC_MAX_NUM BC_MAX_STRING
839 // Unused apart from "limits" message. Just show a "biggish number" there.
840 //#define BC_MAX_NAME BC_MAX_STRING
841 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
842 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
843 #define BC_MAX_NAME_STR "999999999"
844 #define BC_MAX_EXP_STR "999999999"
845 #define BC_MAX_VARS_STR "999999999"
847 #define BC_MAX_OBASE_STR "999"
849 #if INT_MAX == 2147483647
850 # define BC_MAX_DIM_STR "2147483647"
851 #elif INT_MAX == 9223372036854775807
852 # define BC_MAX_DIM_STR "9223372036854775807"
854 # error Strange INT_MAX
857 #if UINT_MAX == 4294967295
858 # define BC_MAX_SCALE_STR "4294967295"
859 # define BC_MAX_STRING_STR "4294967294"
860 #elif UINT_MAX == 18446744073709551615
861 # define BC_MAX_SCALE_STR "18446744073709551615"
862 # define BC_MAX_STRING_STR "18446744073709551614"
864 # error Strange UINT_MAX
866 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
868 // In configurations where errors abort instead of propagating error
869 // return code up the call chain, functions returning BC_STATUS
870 // actually don't return anything, they always succeed and return "void".
871 // A macro wrapper is provided, which makes this statement work:
873 // and makes it visible to the compiler that s is always zero,
874 // allowing compiler to optimize dead code after the statement.
876 // To make code more readable, each such function has a "z"
877 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
879 #if ENABLE_FEATURE_BC_SIGNALS || ENABLE_FEATURE_CLEAN_UP
880 # define ERRORS_ARE_FATAL 0
881 # define ERRORFUNC /*nothing*/
882 # define IF_ERROR_RETURN_POSSIBLE(a) a
883 # define BC_STATUS BcStatus
884 # define RETURN_STATUS(v) return (v)
885 # define COMMA_SUCCESS /*nothing*/
887 # define ERRORS_ARE_FATAL 1
888 # define ERRORFUNC NORETURN
889 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
890 # define BC_STATUS void
891 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
892 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
899 static void fflush_and_check(void)
902 if (ferror(stdout) || ferror(stderr))
903 bb_perror_msg_and_die("output error");
906 #if ENABLE_FEATURE_CLEAN_UP
907 #define QUIT_OR_RETURN_TO_MAIN \
909 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
911 return BC_STATUS_FAILURE; \
914 #define QUIT_OR_RETURN_TO_MAIN quit()
917 static void quit(void) NORETURN;
918 static void quit(void)
921 bb_perror_msg_and_die("input error");
923 dbg_exec("quit(): exiting with exitcode SUCCESS");
927 static void bc_verror_msg(const char *fmt, va_list p)
929 const char *sv = sv; // for compiler
930 if (G.prs.lex_filename) {
932 applet_name = xasprintf("%s: %s:%u", applet_name, G.prs.lex_filename, G.err_line);
934 bb_verror_msg(fmt, p, NULL);
935 if (G.prs.lex_filename) {
936 free((char*)applet_name);
941 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
946 bc_verror_msg(fmt, p);
949 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
950 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
955 static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
959 // Are non-POSIX constructs totally ok?
960 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
961 RETURN_STATUS(BC_STATUS_SUCCESS); // yes
964 bc_verror_msg(fmt, p);
967 // Do we treat non-POSIX constructs as errors?
968 if (!(option_mask32 & BC_FLAG_S))
969 RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
971 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
972 RETURN_STATUS(BC_STATUS_FAILURE);
975 #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
978 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
979 // This idiom begs for tail-call optimization, but for it to work,
980 // function must not have caller-cleaned parameters on stack.
981 // Unfortunately, vararg function API does exactly that on most arches.
982 // Thus, use these shims for the cases when we have no vararg PARAMS:
983 static ERRORFUNC int bc_error(const char *msg)
985 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
987 static ERRORFUNC int bc_error_bad_character(char c)
990 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
991 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
993 static ERRORFUNC int bc_error_bad_expression(void)
995 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
997 static ERRORFUNC int bc_error_bad_token(void)
999 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
1001 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1003 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1005 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1007 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1010 static BC_STATUS zbc_POSIX_requires(const char *msg)
1012 RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
1014 #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
1015 static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
1017 RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
1019 #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
1020 static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1022 RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; this is bad:", msg));
1024 #define zbc_POSIX_does_not_allow_bool_ops_this_is_bad(...) (zbc_POSIX_does_not_allow_bool_ops_this_is_bad(__VA_ARGS__) COMMA_SUCCESS)
1025 static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1027 RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in 'for()'", "POSIX does not allow ", msg));
1029 #define zbc_POSIX_does_not_allow_empty_X_expression_in_for(...) (zbc_POSIX_does_not_allow_empty_X_expression_in_for(__VA_ARGS__) COMMA_SUCCESS)
1032 static void bc_vec_grow(BcVec *v, size_t n)
1034 size_t cap = v->cap * 2;
1035 while (cap < v->len + n) cap *= 2;
1036 v->v = xrealloc(v->v, v->size * cap);
1040 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1043 v->cap = BC_VEC_START_CAP;
1046 v->v = xmalloc(esize * BC_VEC_START_CAP);
1049 static void bc_char_vec_init(BcVec *v)
1051 bc_vec_init(v, sizeof(char), NULL);
1054 static void bc_vec_expand(BcVec *v, size_t req)
1057 v->v = xrealloc(v->v, v->size * req);
1062 static void bc_vec_pop(BcVec *v)
1066 v->dtor(v->v + (v->size * v->len));
1069 static void bc_vec_npop(BcVec *v, size_t n)
1074 size_t len = v->len - n;
1075 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1079 static void bc_vec_pop_all(BcVec *v)
1081 bc_vec_npop(v, v->len);
1084 static size_t bc_vec_push(BcVec *v, const void *data)
1086 size_t len = v->len;
1087 if (len >= v->cap) bc_vec_grow(v, 1);
1088 memmove(v->v + (v->size * len), data, v->size);
1093 // G.prog.results often needs "pop old operand, push result" idiom.
1094 // Can do this without a few extra ops
1095 static size_t bc_result_pop_and_push(const void *data)
1097 BcVec *v = &G.prog.results;
1099 size_t len = v->len - 1;
1101 last = v->v + (v->size * len);
1104 memmove(last, data, v->size);
1108 static size_t bc_vec_pushByte(BcVec *v, char data)
1110 return bc_vec_push(v, &data);
1113 static size_t bc_vec_pushZeroByte(BcVec *v)
1115 //return bc_vec_pushByte(v, '\0');
1117 return bc_vec_push(v, &const_int_0);
1120 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1123 bc_vec_push(v, data);
1127 if (v->len == v->cap) bc_vec_grow(v, 1);
1129 ptr = v->v + v->size * idx;
1131 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1132 memmove(ptr, data, v->size);
1136 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1139 bc_vec_expand(v, len + 1);
1140 memcpy(v->v, str, len);
1143 bc_vec_pushZeroByte(v);
1146 static void *bc_vec_item(const BcVec *v, size_t idx)
1148 return v->v + v->size * idx;
1151 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1153 return v->v + v->size * (v->len - idx - 1);
1156 static void *bc_vec_top(const BcVec *v)
1158 return v->v + v->size * (v->len - 1);
1161 static FAST_FUNC void bc_vec_free(void *vec)
1163 BcVec *v = (BcVec *) vec;
1168 static BcFunc* bc_program_func(size_t idx)
1170 return bc_vec_item(&G.prog.fns, idx);
1172 // BC_PROG_MAIN is zeroth element, so:
1173 #define bc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1176 static BcFunc* bc_program_current_func(void)
1178 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1179 BcFunc *func = bc_program_func(ip->func);
1184 static char** bc_program_str(size_t idx)
1188 BcFunc *func = bc_program_current_func();
1189 return bc_vec_item(&func->strs, idx);
1192 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1195 static char** bc_program_const(size_t idx)
1199 BcFunc *func = bc_program_current_func();
1200 return bc_vec_item(&func->consts, idx);
1203 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1206 static int bc_id_cmp(const void *e1, const void *e2)
1208 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1211 static FAST_FUNC void bc_id_free(void *id)
1213 free(((BcId *) id)->name);
1216 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1218 size_t low = 0, high = v->len;
1220 while (low < high) {
1221 size_t mid = (low + high) / 2;
1222 BcId *id = bc_vec_item(v, mid);
1223 int result = bc_id_cmp(ptr, id);
1236 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1238 size_t n = *i = bc_map_find_ge(v, ptr);
1241 bc_vec_push(v, ptr);
1242 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1243 return 0; // "was not inserted"
1245 bc_vec_pushAt(v, ptr, n);
1246 return 1; // "was inserted"
1250 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1252 size_t i = bc_map_find_ge(v, ptr);
1253 if (i >= v->len) return BC_VEC_INVALID_IDX;
1254 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1258 static void bc_num_setToZero(BcNum *n, size_t scale)
1265 static void bc_num_zero(BcNum *n)
1267 bc_num_setToZero(n, 0);
1270 static void bc_num_one(BcNum *n)
1272 bc_num_setToZero(n, 0);
1277 // Note: this also sets BcNum to zero
1278 static void bc_num_init(BcNum *n, size_t req)
1280 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1281 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1282 n->num = xmalloc(req);
1289 static void bc_num_init_DEF_SIZE(BcNum *n)
1291 bc_num_init(n, BC_NUM_DEF_SIZE);
1294 static void bc_num_expand(BcNum *n, size_t req)
1296 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1298 n->num = xrealloc(n->num, req);
1303 static FAST_FUNC void bc_num_free(void *num)
1305 free(((BcNum *) num)->num);
1308 static void bc_num_copy(BcNum *d, BcNum *s)
1311 bc_num_expand(d, s->cap);
1315 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1319 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1322 unsigned long result;
1326 while (i > n->rdx) {
1327 unsigned long prev = result;
1328 result = result * 10 + n->num[--i];
1329 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1330 // 0x1ff00000 * 10 is 0x13f600000,
1331 // or 0x3f600000 truncated to 32 bits. Which is larger.
1332 // However, (N*10)/8 < N check is always correct.
1333 if ((result / 8) < prev)
1334 RETURN_STATUS(bc_error("overflow"));
1338 RETURN_STATUS(BC_STATUS_SUCCESS);
1340 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1342 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1344 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1346 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1348 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1350 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1351 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1352 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1353 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1355 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1356 // would not hit realloc() code path - not good if num[] is not malloced
1358 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1364 if (val == 0) return;
1366 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1373 if (val == 0) break;
1377 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1380 for (i = 0; i < len; ++i) {
1382 for (j = i; a[j] < 0;) {
1389 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1407 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1408 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1409 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1410 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1411 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1413 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1415 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1416 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1418 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1421 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1423 size_t i, min, a_int, b_int, diff;
1424 BcDig *max_num, *min_num;
1428 if (a == b) return 0;
1429 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1430 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1432 if (a->neg != b->neg) // signs of a and b differ
1433 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1434 return (int)b->neg - (int)a->neg;
1435 neg = a->neg; // 1 if both negative, 0 if both positive
1437 a_int = BC_NUM_INT(a);
1438 b_int = BC_NUM_INT(b);
1441 if (a_int != 0) return (ssize_t) a_int;
1443 a_max = (a->rdx > b->rdx);
1446 diff = a->rdx - b->rdx;
1447 max_num = a->num + diff;
1449 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1452 diff = b->rdx - a->rdx;
1453 max_num = b->num + diff;
1455 neg = !neg; // same as "neg = (a_max == neg)"
1458 cmp = bc_num_compare(max_num, min_num, b_int + min);
1459 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1461 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1462 if (max_num[i]) return BC_NUM_NEG(1, neg);
1468 static void bc_num_truncate(BcNum *n, size_t places)
1470 if (places == 0) return;
1476 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1480 static void bc_num_extend(BcNum *n, size_t places)
1482 size_t len = n->len + places;
1485 if (n->cap < len) bc_num_expand(n, len);
1487 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1488 memset(n->num, 0, sizeof(BcDig) * places);
1495 static void bc_num_clean(BcNum *n)
1497 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1500 else if (n->len < n->rdx)
1504 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1507 bc_num_extend(n, scale - n->rdx);
1509 bc_num_truncate(n, n->rdx - scale);
1512 if (n->len != 0) n->neg = !neg1 != !neg2;
1515 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1519 b->len = n->len - idx;
1521 a->rdx = b->rdx = 0;
1523 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1524 memcpy(a->num, n->num, idx * sizeof(BcDig));
1534 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1536 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1538 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1539 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1540 if (places + n->len > BC_MAX_NUM)
1541 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1544 if (n->rdx >= places)
1547 bc_num_extend(n, places - n->rdx);
1553 RETURN_STATUS(BC_STATUS_SUCCESS);
1555 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1557 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1559 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1560 BcNumBinaryOp op, size_t req)
1563 BcNum num2, *ptr_a, *ptr_b;
1568 memcpy(ptr_a, c, sizeof(BcNum));
1576 memcpy(ptr_b, c, sizeof(BcNum));
1583 bc_num_init(c, req);
1585 bc_num_expand(c, req);
1587 s = BC_STATUS_SUCCESS;
1588 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1590 if (init) bc_num_free(&num2);
1594 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1596 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1597 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1598 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1599 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1600 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1601 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1603 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1605 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1607 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1610 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1612 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1614 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1617 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1619 size_t req = BC_NUM_MREQ(a, b, scale);
1620 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1623 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1625 size_t req = BC_NUM_MREQ(a, b, scale);
1626 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1629 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1631 size_t req = BC_NUM_MREQ(a, b, scale);
1632 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1635 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1637 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1640 static const BcNumBinaryOp zbc_program_ops[] = {
1641 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1643 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1644 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1645 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1646 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1647 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1648 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1650 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1659 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1661 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1663 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1665 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1666 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1669 // Because this function doesn't need to use scale (per the bc spec),
1670 // I am hijacking it to say whether it's doing an add or a subtract.
1674 if (sub && c->len) c->neg = !c->neg;
1675 RETURN_STATUS(BC_STATUS_SUCCESS);
1679 RETURN_STATUS(BC_STATUS_SUCCESS);
1683 c->rdx = BC_MAX(a->rdx, b->rdx);
1684 min_rdx = BC_MIN(a->rdx, b->rdx);
1687 if (a->rdx > b->rdx) {
1688 diff = a->rdx - b->rdx;
1690 ptr_a = a->num + diff;
1693 diff = b->rdx - a->rdx;
1696 ptr_b = b->num + diff;
1700 for (i = 0; i < diff; ++i, ++c->len)
1704 a_int = BC_NUM_INT(a);
1705 b_int = BC_NUM_INT(b);
1707 if (a_int > b_int) {
1718 for (i = 0; i < min_rdx + min_int; ++i) {
1719 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1721 ptr_c[i] = (BcDig)(in % 10);
1723 for (; i < max + min_rdx; ++i) {
1724 unsigned in = (unsigned)ptr[i] + carry;
1726 ptr_c[i] = (BcDig)(in % 10);
1730 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1732 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1735 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1738 BcNum *minuend, *subtrahend;
1740 bool aneg, bneg, neg;
1742 // Because this function doesn't need to use scale (per the bc spec),
1743 // I am hijacking it to say whether it's doing an add or a subtract.
1747 if (sub && c->len) c->neg = !c->neg;
1748 RETURN_STATUS(BC_STATUS_SUCCESS);
1752 RETURN_STATUS(BC_STATUS_SUCCESS);
1757 a->neg = b->neg = false;
1759 cmp = bc_num_cmp(a, b);
1765 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1766 RETURN_STATUS(BC_STATUS_SUCCESS);
1774 if (sub) neg = !neg;
1779 bc_num_copy(c, minuend);
1782 if (c->rdx < subtrahend->rdx) {
1783 bc_num_extend(c, subtrahend->rdx - c->rdx);
1786 start = c->rdx - subtrahend->rdx;
1788 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1792 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1795 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1797 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1800 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1801 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1804 if (a->len == 0 || b->len == 0) {
1806 RETURN_STATUS(BC_STATUS_SUCCESS);
1808 aone = BC_NUM_ONE(a);
1809 if (aone || BC_NUM_ONE(b)) {
1810 bc_num_copy(c, aone ? b : a);
1811 RETURN_STATUS(BC_STATUS_SUCCESS);
1814 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1815 || a->len < BC_NUM_KARATSUBA_LEN
1816 || b->len < BC_NUM_KARATSUBA_LEN
1820 bc_num_expand(c, a->len + b->len + 1);
1822 memset(c->num, 0, sizeof(BcDig) * c->cap);
1825 for (i = 0; i < b->len; ++i) {
1827 for (j = 0; j < a->len; ++j) {
1828 unsigned in = c->num[i + j];
1829 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1830 // note: compilers prefer _unsigned_ div/const
1832 c->num[i + j] = (BcDig)(in % 10);
1835 c->num[i + j] += (BcDig) carry;
1836 len = BC_MAX(len, i + j + !!carry);
1838 #if ENABLE_FEATURE_BC_SIGNALS
1840 // a*a <- without check below, this will not be interruptible
1841 if (G_interrupt) return BC_STATUS_FAILURE;
1847 RETURN_STATUS(BC_STATUS_SUCCESS);
1850 bc_num_init(&l1, max);
1851 bc_num_init(&h1, max);
1852 bc_num_init(&l2, max);
1853 bc_num_init(&h2, max);
1854 bc_num_init(&m1, max);
1855 bc_num_init(&m2, max);
1856 bc_num_init(&z0, max);
1857 bc_num_init(&z1, max);
1858 bc_num_init(&z2, max);
1859 bc_num_init(&temp, max + max);
1861 bc_num_split(a, max2, &l1, &h1);
1862 bc_num_split(b, max2, &l2, &h2);
1864 s = zbc_num_add(&h1, &l1, &m1, 0);
1866 s = zbc_num_add(&h2, &l2, &m2, 0);
1869 s = zbc_num_k(&h1, &h2, &z0);
1871 s = zbc_num_k(&m1, &m2, &z1);
1873 s = zbc_num_k(&l1, &l2, &z2);
1876 s = zbc_num_sub(&z1, &z0, &temp, 0);
1878 s = zbc_num_sub(&temp, &z2, &z1, 0);
1881 s = zbc_num_shift(&z0, max2 * 2);
1883 s = zbc_num_shift(&z1, max2);
1885 s = zbc_num_add(&z0, &z1, &temp, 0);
1887 s = zbc_num_add(&temp, &z2, c, 0);
1902 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1906 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1908 scale = BC_MAX(scale, a->rdx);
1909 scale = BC_MAX(scale, b->rdx);
1910 scale = BC_MIN(a->rdx + b->rdx, scale);
1911 maxrdx = BC_MAX(maxrdx, scale);
1913 bc_num_init(&cpa, a->len);
1914 bc_num_init(&cpb, b->len);
1916 bc_num_copy(&cpa, a);
1917 bc_num_copy(&cpb, b);
1918 cpa.neg = cpb.neg = false;
1920 s = zbc_num_shift(&cpa, maxrdx);
1922 s = zbc_num_shift(&cpb, maxrdx);
1924 s = zbc_num_k(&cpa, &cpb, c);
1928 bc_num_expand(c, c->len + maxrdx);
1930 if (c->len < maxrdx) {
1931 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1936 bc_num_retireMul(c, scale, a->neg, b->neg);
1942 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1944 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1951 RETURN_STATUS(bc_error("divide by zero"));
1953 bc_num_setToZero(c, scale);
1954 RETURN_STATUS(BC_STATUS_SUCCESS);
1956 if (BC_NUM_ONE(b)) {
1958 bc_num_retireMul(c, scale, a->neg, b->neg);
1959 RETURN_STATUS(BC_STATUS_SUCCESS);
1962 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1963 bc_num_copy(&cp, a);
1967 bc_num_expand(&cp, len + 2);
1968 bc_num_extend(&cp, len - cp.len);
1971 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1973 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1975 if (b->rdx == b->len) {
1977 if (len == 0) break;
1979 if (b->num[len] != 0)
1985 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1987 // We want an extra zero in front to make things simpler.
1988 cp.num[cp.len++] = 0;
1991 bc_num_expand(c, cp.len);
1994 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1998 s = BC_STATUS_SUCCESS;
1999 for (i = end - 1; i < end; --i) {
2002 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2003 bc_num_subArrays(n, b->num, len);
2005 #if ENABLE_FEATURE_BC_SIGNALS
2008 // 1/a <- without check below, this will not be interruptible
2010 s = BC_STATUS_FAILURE;
2016 bc_num_retireMul(c, scale, a->neg, b->neg);
2021 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2023 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2024 BcNum *restrict d, size_t scale, size_t ts)
2031 RETURN_STATUS(bc_error("divide by zero"));
2034 bc_num_setToZero(d, ts);
2035 RETURN_STATUS(BC_STATUS_SUCCESS);
2038 bc_num_init(&temp, d->cap);
2039 s = zbc_num_d(a, b, c, scale);
2042 if (scale != 0) scale = ts;
2044 s = zbc_num_m(c, b, &temp, scale);
2046 s = zbc_num_sub(a, &temp, d, scale);
2049 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2052 bc_num_retireMul(d, ts, a->neg, b->neg);
2058 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2060 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2064 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2066 bc_num_init(&c1, len);
2067 s = zbc_num_r(a, b, &c1, c, scale, ts);
2072 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2074 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2076 BcStatus s = BC_STATUS_SUCCESS;
2079 size_t i, powrdx, resrdx;
2082 // GNU bc does not allow 2^2.0 - we do
2083 for (i = 0; i < b->rdx; i++)
2085 RETURN_STATUS(bc_error("not an integer"));
2089 RETURN_STATUS(BC_STATUS_SUCCESS);
2092 bc_num_setToZero(c, scale);
2093 RETURN_STATUS(BC_STATUS_SUCCESS);
2095 if (BC_NUM_ONE(b)) {
2099 s = zbc_num_inv(a, c, scale);
2104 s = zbc_num_ulong_abs(b, &pow);
2105 if (s) RETURN_STATUS(s);
2106 // b is not used beyond this point
2108 bc_num_init(©, a->len);
2109 bc_num_copy(©, a);
2114 if (a->rdx * pow < scale)
2115 scale = a->rdx * pow;
2119 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2121 s = zbc_num_mul(©, ©, ©, powrdx);
2123 // Not needed: zbc_num_mul() has a check for ^C:
2124 //if (G_interrupt) {
2125 // s = BC_STATUS_FAILURE;
2130 bc_num_copy(c, ©);
2132 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2134 s = zbc_num_mul(©, ©, ©, powrdx);
2139 s = zbc_num_mul(c, ©, c, resrdx);
2142 // Not needed: zbc_num_mul() has a check for ^C:
2143 //if (G_interrupt) {
2144 // s = BC_STATUS_FAILURE;
2150 s = zbc_num_inv(c, c, scale);
2154 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2156 // We can't use bc_num_clean() here.
2157 for (i = 0; i < c->len; ++i)
2160 bc_num_setToZero(c, scale);
2167 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2169 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2172 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2173 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2174 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2176 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2177 bc_num_expand(b, req);
2180 bc_num_setToZero(b, scale);
2181 RETURN_STATUS(BC_STATUS_SUCCESS);
2184 RETURN_STATUS(bc_error("negative number"));
2186 if (BC_NUM_ONE(a)) {
2188 bc_num_extend(b, scale);
2189 RETURN_STATUS(BC_STATUS_SUCCESS);
2192 scale = BC_MAX(scale, a->rdx) + 1;
2193 len = a->len + scale;
2195 bc_num_init(&num1, len);
2196 bc_num_init(&num2, len);
2197 bc_num_init_DEF_SIZE(&half);
2203 bc_num_init(&f, len);
2204 bc_num_init(&fprime, len);
2210 pow = BC_NUM_INT(a);
2218 pow -= 2 - (pow & 1);
2220 bc_num_extend(x0, pow);
2222 // Make sure to move the radix back.
2226 x0->rdx = digs = digs1 = 0;
2228 len = BC_NUM_INT(x0) + resrdx - 1;
2230 while (cmp != 0 || digs < len) {
2231 s = zbc_num_div(a, x0, &f, resrdx);
2233 s = zbc_num_add(x0, &f, &fprime, resrdx);
2235 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2238 cmp = bc_num_cmp(x1, x0);
2239 digs = x1->len - (unsigned long long) llabs(cmp);
2241 if (cmp == cmp2 && digs == digs1)
2246 resrdx += times > 4;
2259 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2261 bc_num_free(&fprime);
2268 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2270 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2276 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2279 memcpy(&num2, c, sizeof(BcNum));
2281 bc_num_init(c, len);
2285 bc_num_expand(c, len);
2288 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2290 if (init) bc_num_free(&num2);
2294 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2297 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2300 BcNum base, exp, two, temp;
2304 RETURN_STATUS(bc_error("divide by zero"));
2305 if (a->rdx || b->rdx || c->rdx)
2306 RETURN_STATUS(bc_error("not an integer"));
2308 RETURN_STATUS(bc_error("negative number"));
2310 bc_num_expand(d, c->len);
2311 bc_num_init(&base, c->len);
2312 bc_num_init(&exp, b->len);
2313 bc_num_init(&temp, b->len);
2315 two.cap = ARRAY_SIZE(two_digs);
2322 s = zbc_num_rem(a, c, &base, 0);
2324 bc_num_copy(&exp, b);
2326 while (exp.len != 0) {
2327 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2330 if (BC_NUM_ONE(&temp)) {
2331 s = zbc_num_mul(d, &base, &temp, 0);
2333 s = zbc_num_rem(&temp, c, d, 0);
2337 s = zbc_num_mul(&base, &base, &temp, 0);
2339 s = zbc_num_rem(&temp, c, &base, 0);
2348 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2351 static FAST_FUNC void bc_string_free(void *string)
2353 free(*(char**)string);
2356 static void bc_func_init(BcFunc *f)
2358 bc_char_vec_init(&f->code);
2359 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2360 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2361 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2362 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2363 IF_BC(f->nparams = 0;)
2366 static FAST_FUNC void bc_func_free(void *func)
2368 BcFunc *f = (BcFunc *) func;
2369 bc_vec_free(&f->code);
2370 IF_BC(bc_vec_free(&f->labels);)
2371 IF_BC(bc_vec_free(&f->autos);)
2372 IF_BC(bc_vec_free(&f->strs);)
2373 IF_BC(bc_vec_free(&f->consts);)
2376 static void bc_array_expand(BcVec *a, size_t len);
2378 static void bc_array_init(BcVec *a, bool nums)
2381 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2383 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2384 bc_array_expand(a, 1);
2387 static void bc_array_expand(BcVec *a, size_t len)
2389 if (a->dtor == bc_num_free
2390 // && a->size == sizeof(BcNum) - always true
2393 while (len > a->len) {
2394 bc_num_init_DEF_SIZE(&n);
2399 while (len > a->len) {
2400 bc_array_init(&v, true);
2406 static void bc_array_copy(BcVec *d, const BcVec *s)
2412 bc_vec_expand(d, s->cap);
2417 for (i = 0; i < s->len; i++, dnum++, snum++) {
2418 bc_num_init(dnum, snum->len);
2419 bc_num_copy(dnum, snum);
2424 static void dc_result_copy(BcResult *d, BcResult *src)
2429 case XC_RESULT_TEMP:
2430 case XC_RESULT_IBASE:
2431 case XC_RESULT_SCALE:
2432 case XC_RESULT_OBASE:
2433 bc_num_init(&d->d.n, src->d.n.len);
2434 bc_num_copy(&d->d.n, &src->d.n);
2437 case XC_RESULT_ARRAY:
2438 case XC_RESULT_ARRAY_ELEM:
2439 d->d.id.name = xstrdup(src->d.id.name);
2441 case XC_RESULT_CONSTANT:
2442 IF_BC(case BC_RESULT_LAST:)
2443 IF_BC(case BC_RESULT_ONE:)
2445 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2451 static FAST_FUNC void bc_result_free(void *result)
2453 BcResult *r = (BcResult *) result;
2456 case XC_RESULT_TEMP:
2457 case XC_RESULT_IBASE:
2458 case XC_RESULT_SCALE:
2459 case XC_RESULT_OBASE:
2460 bc_num_free(&r->d.n);
2463 case XC_RESULT_ARRAY:
2464 case XC_RESULT_ARRAY_ELEM:
2473 static int bad_input_byte(char c)
2475 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2478 bc_error_fmt("illegal character 0x%02x", c);
2484 static void bc_read_line(BcVec *vec, FILE *fp)
2487 bc_vec_pop_all(vec);
2490 #if ENABLE_FEATURE_BC_SIGNALS
2491 if (G_interrupt) { // ^C was pressed
2494 // ^C while running a script (bc SCRIPT): die.
2495 // We do not return to interactive prompt:
2496 // user might be running us from a shell,
2497 // and SCRIPT might be intended to terminate
2498 // (e.g. contain a "halt" stmt).
2499 // ^C dropping user into a bc prompt instead of
2500 // the shell would be unexpected.
2503 // ^C while interactive input
2505 // GNU bc says "interrupted execution."
2506 // GNU dc says "Interrupt!"
2507 fputs("\ninterrupted execution\n", stderr);
2510 # if ENABLE_FEATURE_EDITING
2511 if (G_ttyin && fp == stdin) {
2513 # define line_buf bb_common_bufsiz1
2514 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2515 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2518 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2523 char c = line_buf[i++];
2525 if (bad_input_byte(c)) goto again;
2527 bc_vec_string(vec, n, line_buf);
2537 #if ENABLE_FEATURE_BC_SIGNALS
2539 // ^C was pressed: ignore entire line, get another one
2540 bc_vec_pop_all(vec);
2544 do c = fgetc(fp); while (c == '\0');
2547 bb_perror_msg_and_die("input error");
2548 // Note: EOF does not append '\n'
2551 bad_chars |= bad_input_byte(c);
2552 bc_vec_pushByte(vec, (char)c);
2553 } while (c != '\n');
2556 // Bad chars on this line
2557 if (!G.prs.lex_filename) { // stdin
2558 // ignore entire line, get another one
2561 bb_perror_msg_and_die("file '%s' is not text", G.prs.lex_filename);
2563 bc_vec_pushZeroByte(vec);
2571 static bool bc_num_strValid(const char *val, size_t base)
2576 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2583 if (radix) return false;
2587 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2593 // Note: n is already "bc_num_zero()"ed,
2594 // leading zeroes in "val" are removed
2595 static void bc_num_parseDecimal(BcNum *n, const char *val)
2604 bc_num_expand(n, len);
2606 ptr = strchr(val, '.');
2610 n->rdx = (size_t)((val + len) - (ptr + 1));
2612 for (i = 0; val[i]; ++i) {
2613 if (val[i] != '0' && val[i] != '.') {
2614 // Not entirely zero value - convert it, and exit
2617 n->num[n->len] = val[i] - '0';
2621 if (val[--i] == '.') goto skip_dot;
2626 // if for() exits without hitting if(), the value is entirely zero
2629 // Note: n is already "bc_num_zero()"ed,
2630 // leading zeroes in "val" are removed
2631 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2634 BcNum temp, mult, result;
2636 BcDig base_digs[ULONG_NUM_BUFSIZE];
2641 for (i = 0; ; ++i) {
2644 if (val[i] != '.' && val[i] != '0')
2648 bc_num_init_DEF_SIZE(&temp);
2649 bc_num_init_DEF_SIZE(&mult);
2650 base.cap = ARRAY_SIZE(base_digs);
2651 base.num = base_digs;
2652 bc_num_ulong2num(&base, base_t);
2656 if (c == '\0') goto int_err;
2657 if (c == '.') break;
2659 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2661 s = zbc_num_mul(n, &base, &mult, 0);
2662 if (s) goto int_err;
2663 bc_num_ulong2num(&temp, v);
2664 s = zbc_num_add(&mult, &temp, n, 0);
2665 if (s) goto int_err;
2668 bc_num_init(&result, base.len);
2669 //bc_num_zero(&result); - already is
2675 if (c == '\0') break;
2678 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2680 s = zbc_num_mul(&result, &base, &result, 0);
2682 bc_num_ulong2num(&temp, v);
2683 s = zbc_num_add(&result, &temp, &result, 0);
2685 s = zbc_num_mul(&mult, &base, &mult, 0);
2689 s = zbc_num_div(&result, &mult, &result, digits);
2691 s = zbc_num_add(n, &result, n, digits);
2695 if (n->rdx < digits)
2696 bc_num_extend(n, digits - n->rdx);
2700 bc_num_free(&result);
2706 static BC_STATUS zbc_num_parse(BcNum *n, const char *val, unsigned base_t)
2708 if (!bc_num_strValid(val, base_t))
2709 RETURN_STATUS(bc_error("bad number string"));
2712 while (*val == '0') val++;
2715 bc_num_parseDecimal(n, val);
2717 bc_num_parseBase(n, val, base_t);
2719 RETURN_STATUS(BC_STATUS_SUCCESS);
2721 #define zbc_num_parse(...) (zbc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2723 static bool bc_lex_more_input(void)
2725 BcParse *p = &G.prs;
2727 bc_vec_pop_all(&G.input_buffer);
2729 bc_read_line(&G.input_buffer, G.prs.lex_input_fp);
2731 p->lex_inbuf = G.input_buffer.v;
2732 // bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2734 return G.input_buffer.len > 1;
2737 // p->lex_inbuf points to the current string to be parsed.
2738 // if p->lex_inbuf points to '\0', it's either EOF or it points after
2739 // last processed line's terminating '\n' (and more reading needs to be done
2740 // to get next character).
2742 // If you are in a situation where that is a possibility, call peek_inbuf().
2743 // If necessary, it performs more reading and changes p->lex_inbuf,
2744 // then it returns *p->lex_inbuf (which will be '\0' only if it's EOF).
2745 // After it, just referencing *p->lex_inbuf is valid, and if it wasn't '\0',
2746 // it's ok to do p->lex_inbuf++ once without end-of-buffer checking.
2748 // eat_inbuf() is equvalent to "peek_inbuf(); if (c) p->lex_inbuf++":
2749 // it returns current char and advances the pointer (if not EOF).
2750 // After eat_inbuf(), referencing p->lex_inbuf[-1] and *p->lex_inbuf is valid.
2752 // In many cases, you can use fast *p->lex_inbuf instead of peek_inbuf():
2753 // unless prev char might have been '\n', *p->lex_inbuf is '\0' ONLY
2754 // on real EOF, not end-of-buffer.
2756 // bc cases to test interactively:
2757 // 1 #comment\ - prints "1<newline>" at once (comment is not continued)
2758 // 1 #comment/* - prints "1<newline>" at once
2759 // 1 #comment" - prints "1<newline>" at once
2760 // 1\#comment - error at once (\ is not a line continuation)
2761 // 1 + /*"*/2 - prints "3<newline>" at once
2762 // 1 + /*#*/2 - prints "3<newline>" at once
2763 // "str\" - prints "str\" at once
2764 // "str#" - prints "str#" at once
2765 // "str/*" - prints "str/*" at once
2766 // "str#\ - waits for second line
2767 // end" - ...prints "str#\<newline>end"
2768 static char peek_inbuf(void)
2770 if (*G.prs.lex_inbuf == '\0') {
2771 if (G.prs.lex_input_fp)
2772 if (!bc_lex_more_input())
2773 G.prs.lex_input_fp = NULL;
2775 return *G.prs.lex_inbuf;
2777 static char eat_inbuf(void)
2779 char c = peek_inbuf();
2780 if (c) G.prs.lex_inbuf++;
2784 static void bc_lex_lineComment(void)
2786 BcParse *p = &G.prs;
2789 // Try: echo -n '#foo' | bc
2790 p->lex = XC_LEX_WHITESPACE;
2792 // We depend here on input being done in whole lines:
2793 // '\0' which isn't the EOF can only be seen after '\n'.
2794 while ((c = *p->lex_inbuf) != '\n' && c != '\0')
2798 static void bc_lex_whitespace(void)
2800 BcParse *p = &G.prs;
2802 p->lex = XC_LEX_WHITESPACE;
2804 // We depend here on input being done in whole lines:
2805 // '\0' which isn't the EOF can only be seen after '\n'.
2806 char c = *p->lex_inbuf;
2807 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2815 static BC_STATUS zbc_lex_number(char last)
2817 BcParse *p = &G.prs;
2820 bc_vec_pop_all(&p->lex_strnumbuf);
2821 bc_vec_pushByte(&p->lex_strnumbuf, last);
2824 p->lex = XC_LEX_NUMBER;
2826 // We depend here on input being done in whole lines:
2827 // '\0' which isn't the EOF can only be seen after '\n'.
2828 char c = *p->lex_inbuf;
2832 if (c == '\\' && p->lex_inbuf[1] == '\n') {
2835 c = peek_inbuf(); // force next line to be read
2838 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2839 if (c != '.') break;
2840 // if '.' was already seen, stop on second one:
2844 // c is one of "0-9A-F."
2846 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
2849 if (last == '.') // remove trailing '.' if any
2850 bc_vec_pop(&p->lex_strnumbuf);
2851 bc_vec_pushZeroByte(&p->lex_strnumbuf);
2853 G.err_line = G.prs.lex_line;
2854 RETURN_STATUS(BC_STATUS_SUCCESS);
2856 #define zbc_lex_number(...) (zbc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2858 static void bc_lex_name(void)
2860 BcParse *p = &G.prs;
2864 p->lex = XC_LEX_NAME;
2866 // Since names can't cross lines with \<newline>,
2867 // we depend on the fact that whole line is in the buffer
2869 buf = p->lex_inbuf - 1;
2872 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2876 #if 0 // We do not protect against people with gigabyte-long names
2877 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2878 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2879 if (i > BC_MAX_STRING)
2880 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2883 bc_vec_string(&p->lex_strnumbuf, i, buf);
2885 // Increment the index. We minus 1 because it has already been incremented.
2886 p->lex_inbuf += i - 1;
2888 //return BC_STATUS_SUCCESS;
2891 IF_BC(static BC_STATUS zbc_lex_token(void);)
2892 IF_DC(static BC_STATUS zdc_lex_token(void);)
2893 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2894 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2896 static BC_STATUS zbc_lex_next(void)
2898 BcParse *p = &G.prs;
2901 p->lex_last = p->lex;
2903 // if (p->lex_last == XC_LEX_EOF)
2904 // RETURN_STATUS(bc_error("end of file"));
2906 // Loop until failure or we don't have whitespace. This
2907 // is so the parser doesn't get inundated with whitespace.
2908 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2909 s = BC_STATUS_SUCCESS;
2911 if (*p->lex_inbuf == '\0') {
2912 p->lex = XC_LEX_EOF;
2913 if (peek_inbuf() == '\0')
2914 RETURN_STATUS(BC_STATUS_SUCCESS);
2916 p->lex_next_at = p->lex_inbuf;
2917 dbg_lex("next string to parse:'%.*s'",
2918 (int)(strchrnul(p->lex_next_at, '\n') - p->lex_next_at),
2922 IF_BC(s = zbc_lex_token());
2924 IF_DC(s = zdc_lex_token());
2926 } while (!s && p->lex == XC_LEX_WHITESPACE);
2927 dbg_lex("p->lex from string:%d", p->lex);
2931 #define zbc_lex_next(...) (zbc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
2934 static BC_STATUS zbc_lex_skip_if_at_NLINE(void)
2936 if (G.prs.lex == XC_LEX_NLINE)
2937 RETURN_STATUS(zbc_lex_next());
2938 RETURN_STATUS(BC_STATUS_SUCCESS);
2940 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2942 static BC_STATUS zbc_lex_next_and_skip_NLINE(void)
2946 if (s) RETURN_STATUS(s);
2947 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
2948 s = zbc_lex_skip_if_at_NLINE();
2951 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2954 static BC_STATUS zbc_lex_text_init(const char *text)
2956 G.prs.lex_inbuf = text;
2957 G.prs.lex = G.prs.lex_last = XC_LEX_INVALID;
2958 RETURN_STATUS(zbc_lex_next());
2960 #define zbc_lex_text_init(...) (zbc_lex_text_init(__VA_ARGS__) COMMA_SUCCESS)
2963 static BC_STATUS zbc_lex_identifier(void)
2965 BcParse *p = &G.prs;
2968 const char *buf = p->lex_inbuf - 1;
2970 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2971 const char *keyword8 = bc_lex_kws[i].name8;
2973 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2975 if (j == 8) goto match;
2977 if (keyword8[j] != '\0')
2980 // buf starts with keyword bc_lex_kws[i]
2981 if (isalnum(buf[j]) || buf[j]=='_')
2982 continue; // "ifz" does not match "if" keyword, "if." does
2983 p->lex = BC_LEX_KEY_1st_keyword + i;
2984 if (!keyword_is_POSIX(i)) {
2985 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
2986 if (s) RETURN_STATUS(s);
2989 // We minus 1 because the index has already been incremented.
2990 p->lex_inbuf += j - 1;
2991 RETURN_STATUS(BC_STATUS_SUCCESS);
2995 s = BC_STATUS_SUCCESS;
2997 if (p->lex_strnumbuf.len > 2) {
3000 // bc: POSIX only allows one character names; this is bad: 'qwe=1
3002 unsigned len = strchrnul(buf, '\n') - buf;
3003 s = zbc_posix_error_fmt("POSIX only allows one character names; this is bad: '%.*s'", len, buf);
3008 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3010 static BC_STATUS zbc_lex_string(void)
3012 BcParse *p = &G.prs;
3014 p->lex = XC_LEX_STR;
3015 bc_vec_pop_all(&p->lex_strnumbuf);
3017 char c = peek_inbuf(); // strings can cross lines
3019 RETURN_STATUS(bc_error("unterminated string1"));
3025 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3028 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3031 G.err_line = p->lex_line;
3032 RETURN_STATUS(BC_STATUS_SUCCESS);
3034 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3036 static void parse_lex_by_checking_eq_sign(unsigned with_and_without)
3038 BcParse *p = &G.prs;
3039 if (*p->lex_inbuf == '=') {
3040 // ^^^ not using peek_inbuf() since '==' etc can't be split across lines
3042 with_and_without >>= 8; // store "with" value
3043 } // else store "without" value
3044 p->lex = (with_and_without & 0xff);
3046 #define parse_lex_by_checking_eq_sign(with, without) \
3047 parse_lex_by_checking_eq_sign(((with)<<8)|(without))
3049 static BC_STATUS zbc_lex_comment(void)
3051 BcParse *p = &G.prs;
3053 p->lex = XC_LEX_WHITESPACE;
3054 // here lex_inbuf is at '*' of opening comment delimiter
3069 RETURN_STATUS(bc_error("unterminated comment"));
3074 p->lex_inbuf++; // skip trailing '/'
3076 G.err_line = p->lex_line;
3077 RETURN_STATUS(BC_STATUS_SUCCESS);
3079 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3081 #undef zbc_lex_token
3082 static BC_STATUS zbc_lex_token(void)
3084 BcParse *p = &G.prs;
3085 BcStatus s = BC_STATUS_SUCCESS;
3086 char c = eat_inbuf();
3089 // This is the workhorse of the lexer.
3091 // case '\0': // probably never reached
3093 // p->lex = XC_LEX_EOF;
3097 p->lex = XC_LEX_NLINE;
3104 bc_lex_whitespace();
3107 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3108 if (p->lex == BC_LEX_OP_BOOL_NOT) {
3109 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3110 if (s) RETURN_STATUS(s);
3114 s = zbc_lex_string();
3117 s = zbc_POSIX_does_not_allow("'#' script comments");
3118 if (s) RETURN_STATUS(s);
3119 bc_lex_lineComment();
3122 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3127 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3128 if (s) RETURN_STATUS(s);
3130 p->lex = BC_LEX_OP_BOOL_AND;
3132 p->lex = XC_LEX_INVALID;
3133 s = bc_error_bad_character('&');
3138 p->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3141 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3147 p->lex = BC_LEX_OP_INC;
3149 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3152 p->lex = BC_LEX_COMMA;
3158 p->lex = BC_LEX_OP_DEC;
3160 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3163 if (isdigit(*p->lex_inbuf))
3164 s = zbc_lex_number(c);
3166 p->lex = BC_LEX_KEY_LAST;
3167 s = zbc_POSIX_does_not_allow("'.' as 'last'");
3173 s = zbc_lex_comment();
3175 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3193 s = zbc_lex_number(c);
3196 p->lex = BC_LEX_SCOLON;
3199 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3202 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3205 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3209 p->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3212 if (*p->lex_inbuf == '\n') {
3213 p->lex = XC_LEX_WHITESPACE;
3216 s = bc_error_bad_character(c);
3219 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3247 s = zbc_lex_identifier();
3251 p->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3256 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3257 if (s) RETURN_STATUS(s);
3259 p->lex = BC_LEX_OP_BOOL_OR;
3261 p->lex = XC_LEX_INVALID;
3262 s = bc_error_bad_character(c);
3266 p->lex = XC_LEX_INVALID;
3267 s = bc_error_bad_character(c);
3273 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3277 static BC_STATUS zdc_lex_register(void)
3279 BcParse *p = &G.prs;
3280 if (G_exreg && isspace(*p->lex_inbuf)) {
3281 bc_lex_whitespace(); // eats whitespace (but not newline)
3282 p->lex_inbuf++; // bc_lex_name() expects this
3285 bc_vec_pop_all(&p->lex_strnumbuf);
3286 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf++);
3287 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3288 p->lex = XC_LEX_NAME;
3291 RETURN_STATUS(BC_STATUS_SUCCESS);
3293 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3295 static BC_STATUS zdc_lex_string(void)
3297 BcParse *p = &G.prs;
3300 p->lex = XC_LEX_STR;
3301 bc_vec_pop_all(&p->lex_strnumbuf);
3305 char c = peek_inbuf();
3307 RETURN_STATUS(bc_error("unterminated string"));
3309 if (c == '[') depth++;
3315 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3318 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3319 p->lex_inbuf++; // skip trailing ']'
3321 G.err_line = p->lex_line;
3322 RETURN_STATUS(BC_STATUS_SUCCESS);
3324 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3326 #undef zdc_lex_token
3327 static BC_STATUS zdc_lex_token(void)
3329 BcParse *p = &G.prs;
3330 static const //BcLexType - should be this type, but narrower type saves size:
3333 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3334 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3335 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3343 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3344 if (p->lex_last == dc_lex_regs[i])
3345 RETURN_STATUS(zdc_lex_register());
3348 s = BC_STATUS_SUCCESS;
3350 if (c >= '%' && c <= '~'
3351 && (p->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3356 // This is the workhorse of the lexer.
3358 // case '\0': // probably never reached
3359 // p->lex = XC_LEX_EOF;
3362 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3363 // (and "case '\n':" is not just empty here)
3364 // only to allow interactive dc have a way to exit
3365 // "parse" stage of "parse,execute" loop
3366 // on <enter>, not on _next_ token (which would mean
3367 // commands are not executed on pressing <enter>).
3368 // IOW: typing "1p<enter>" should print "1" _at once_,
3369 // not after some more input.
3371 p->lex = XC_LEX_NLINE;
3378 bc_lex_whitespace();
3383 p->lex = XC_LEX_OP_REL_NE;
3385 p->lex = XC_LEX_OP_REL_LE;
3387 p->lex = XC_LEX_OP_REL_GE;
3389 RETURN_STATUS(bc_error_bad_character(c));
3393 bc_lex_lineComment();
3396 if (isdigit(*p->lex_inbuf))
3397 s = zbc_lex_number(c);
3399 s = bc_error_bad_character(c);
3417 s = zbc_lex_number(c);
3420 s = zdc_lex_string();
3423 p->lex = XC_LEX_INVALID;
3424 s = bc_error_bad_character(c);
3430 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3433 static void bc_parse_push(char i)
3435 BcVec *code = &G.prs.func->code;
3436 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, code->len, i);
3437 bc_vec_pushByte(code, i);
3440 static void bc_parse_pushName(char *name)
3443 BcVec *code = &G.prs.func->code;
3444 size_t pos = code->len;
3445 size_t len = strlen(name) + 1;
3447 bc_vec_expand(code, pos + len);
3448 strcpy(code->v + pos, name);
3449 code->len = pos + len;
3451 // Smaller code, but way slow:
3453 bc_parse_push(*name);
3458 // Indexes < 0xfc are encoded verbatim, else first byte is
3459 // 0xfc, 0xfd, 0xfe or 0xff, encoding "1..4 bytes",
3460 // followed by that many bytes, lsb first.
3461 // (The above describes 32-bit case).
3462 #define SMALL_INDEX_LIMIT (0x100 - sizeof(size_t))
3464 static void bc_parse_pushIndex(size_t idx)
3469 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3470 if (idx < SMALL_INDEX_LIMIT) {
3474 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3477 if (idx & mask) break;
3482 bc_parse_push(SMALL_INDEX_LIMIT + amt);
3486 bc_parse_push((unsigned char)idx);
3492 static void bc_parse_pushJUMP(size_t idx)
3494 bc_parse_push(BC_INST_JUMP);
3495 bc_parse_pushIndex(idx);
3498 static void bc_parse_pushJUMP_ZERO(size_t idx)
3500 bc_parse_push(BC_INST_JUMP_ZERO);
3501 bc_parse_pushIndex(idx);
3504 static BC_STATUS zbc_parse_pushSTR(void)
3506 BcParse *p = &G.prs;
3507 char *str = xstrdup(p->lex_strnumbuf.v);
3509 bc_parse_push(XC_INST_STR);
3510 bc_parse_pushIndex(p->func->strs.len);
3511 bc_vec_push(&p->func->strs, &str);
3513 RETURN_STATUS(zbc_lex_next());
3515 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3518 static void bc_parse_pushNUM(void)
3520 BcParse *p = &G.prs;
3521 char *num = xstrdup(p->lex_strnumbuf.v);
3522 #if ENABLE_BC && ENABLE_DC
3523 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3525 size_t idx = bc_vec_push(&p->func->consts, &num);
3527 size_t idx = bc_vec_push(&G.prog.consts, &num);
3529 bc_parse_push(XC_INST_NUM);
3530 bc_parse_pushIndex(idx);
3533 static BC_STATUS zbc_parse_text_init(const char *text)
3535 BcParse *p = &G.prs;
3536 p->func = bc_program_func(p->fidx);
3538 RETURN_STATUS(zbc_lex_text_init(text));
3540 #define zbc_parse_text_init(...) (zbc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3542 // Called when parsing or execution detects a failure,
3543 // resets execution structures.
3544 static void bc_program_reset(void)
3549 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3550 bc_vec_pop_all(&G.prog.results);
3552 f = bc_program_func_BC_PROG_MAIN();
3553 ip = bc_vec_top(&G.prog.exestack);
3554 ip->inst_idx = f->code.len;
3557 // Called when parsing code detects a failure,
3558 // resets parsing structures.
3559 static void bc_parse_reset(void)
3561 BcParse *p = &G.prs;
3562 if (p->fidx != BC_PROG_MAIN) {
3563 bc_func_free(p->func);
3564 bc_func_init(p->func);
3566 p->fidx = BC_PROG_MAIN;
3567 p->func = bc_program_func_BC_PROG_MAIN();
3570 p->lex_inbuf += strlen(p->lex_inbuf);
3571 p->lex = XC_LEX_EOF;
3573 IF_BC(bc_vec_pop_all(&p->exits);)
3574 IF_BC(bc_vec_pop_all(&p->conds);)
3575 IF_BC(bc_vec_pop_all(&p->ops);)
3580 static void bc_parse_free(void)
3582 IF_BC(bc_vec_free(&G.prs.exits);)
3583 IF_BC(bc_vec_free(&G.prs.conds);)
3584 IF_BC(bc_vec_free(&G.prs.ops);)
3585 bc_vec_free(&G.prs.lex_strnumbuf);
3588 static void bc_parse_create(size_t fidx)
3590 BcParse *p = &G.prs;
3591 memset(p, 0, sizeof(BcParse));
3593 bc_char_vec_init(&p->lex_strnumbuf);
3594 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3595 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3596 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3599 p->func = bc_program_func(fidx);
3602 static void bc_program_add_fn(void)
3608 bc_vec_push(&G.prog.fns, &f);
3614 // Note: takes ownership of 'name' (must be malloced)
3615 static size_t bc_program_addFunc(char *name)
3618 BcId entry, *entry_ptr;
3622 entry.idx = G.prog.fns.len;
3624 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3625 if (!inserted) free(name);
3627 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3628 idx = entry_ptr->idx;
3631 // There is already a function with this name.
3632 // It'll be redefined now, clear old definition.
3633 BcFunc *func = bc_program_func(entry_ptr->idx);
3637 bc_program_add_fn();
3643 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3644 // We can calculate the conversion between tokens and exprs by subtracting the
3645 // position of the first operator in the lex enum and adding the position of the
3646 // first in the expr enum. Note: This only works for binary operators.
3647 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3649 static BcStatus bc_parse_expr_empty_ok(uint8_t flags);
3651 static BC_STATUS zbc_parse_expr(uint8_t flags)
3655 s = bc_parse_expr_empty_ok(flags);
3656 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3657 RETURN_STATUS(bc_error("empty expression"));
3660 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3662 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed);
3663 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3665 static BC_STATUS zbc_parse_stmt(void)
3667 RETURN_STATUS(zbc_parse_stmt_possibly_auto(false));
3669 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3671 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(const char *after_X)
3673 BcParse *p = &G.prs;
3674 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3675 // Same for "else", "while()", "for()".
3676 BcStatus s = zbc_lex_next_and_skip_NLINE();
3677 if (s) RETURN_STATUS(s);
3678 if (p->lex == XC_LEX_NLINE)
3679 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3681 RETURN_STATUS(zbc_parse_stmt());
3683 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3685 static void bc_parse_operator(BcLexType type, size_t start, size_t *nexprs)
3687 BcParse *p = &G.prs;
3688 char l, r = bc_parse_op_PREC(type - XC_LEX_1st_op);
3689 bool left = bc_parse_op_LEFT(type - XC_LEX_1st_op);
3691 while (p->ops.len > start) {
3692 BcLexType t = BC_PARSE_TOP_OP(p);
3693 if (t == BC_LEX_LPAREN) break;
3695 l = bc_parse_op_PREC(t - XC_LEX_1st_op);
3696 if (l >= r && (l != r || !left)) break;
3698 bc_parse_push(BC_TOKEN_2_INST(t));
3699 bc_vec_pop(&p->ops);
3700 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3703 bc_vec_push(&p->ops, &type);
3706 static BC_STATUS zbc_parse_rightParen(size_t ops_bgn, size_t *nexs)
3708 BcParse *p = &G.prs;
3711 if (p->ops.len <= ops_bgn)
3712 RETURN_STATUS(bc_error_bad_expression());
3713 top = BC_PARSE_TOP_OP(p);
3715 while (top != BC_LEX_LPAREN) {
3716 bc_parse_push(BC_TOKEN_2_INST(top));
3718 bc_vec_pop(&p->ops);
3719 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3721 if (p->ops.len <= ops_bgn)
3722 RETURN_STATUS(bc_error_bad_expression());
3723 top = BC_PARSE_TOP_OP(p);
3726 bc_vec_pop(&p->ops);
3728 RETURN_STATUS(BC_STATUS_SUCCESS);
3730 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3732 static BC_STATUS zbc_parse_params(uint8_t flags)
3734 BcParse *p = &G.prs;
3738 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
3739 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3742 if (s) RETURN_STATUS(s);
3745 if (p->lex != BC_LEX_RPAREN) {
3747 s = zbc_parse_expr(flags);
3748 if (s) RETURN_STATUS(s);
3750 if (p->lex != BC_LEX_COMMA) {
3751 if (p->lex == BC_LEX_RPAREN)
3753 RETURN_STATUS(bc_error_bad_token());
3756 if (s) RETURN_STATUS(s);
3760 bc_parse_push(BC_INST_CALL);
3761 bc_parse_pushIndex(nparams);
3763 RETURN_STATUS(BC_STATUS_SUCCESS);
3765 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3767 // Note: takes ownership of 'name' (must be malloced)
3768 static BC_STATUS zbc_parse_call(char *name, uint8_t flags)
3770 BcParse *p = &G.prs;
3772 BcId entry, *entry_ptr;
3777 s = zbc_parse_params(flags);
3780 if (p->lex != BC_LEX_RPAREN) {
3781 s = bc_error_bad_token();
3785 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3787 if (idx == BC_VEC_INVALID_IDX) {
3788 // No such function exists, create an empty one
3789 bc_program_addFunc(name);
3790 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3794 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3795 bc_parse_pushIndex(entry_ptr->idx);
3797 RETURN_STATUS(zbc_lex_next());
3802 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3804 static BC_STATUS zbc_parse_name(BcInst *type, uint8_t flags)
3806 BcParse *p = &G.prs;
3810 name = xstrdup(p->lex_strnumbuf.v);
3814 if (p->lex == BC_LEX_LBRACKET) {
3818 if (p->lex == BC_LEX_RBRACKET) {
3819 if (!(flags & BC_PARSE_ARRAY)) {
3820 s = bc_error_bad_expression();
3823 *type = XC_INST_ARRAY;
3825 *type = XC_INST_ARRAY_ELEM;
3826 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3827 s = zbc_parse_expr(flags);
3832 bc_parse_push(*type);
3833 bc_parse_pushName(name);
3835 } else if (p->lex == BC_LEX_LPAREN) {
3836 if (flags & BC_PARSE_NOCALL) {
3837 s = bc_error_bad_token();
3840 *type = BC_INST_CALL;
3841 s = zbc_parse_call(name, flags);
3843 *type = XC_INST_VAR;
3844 bc_parse_push(XC_INST_VAR);
3845 bc_parse_pushName(name);
3854 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3856 static BC_STATUS zbc_parse_read(void)
3858 BcParse *p = &G.prs;
3862 if (s) RETURN_STATUS(s);
3863 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3866 if (s) RETURN_STATUS(s);
3867 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3869 bc_parse_push(XC_INST_READ);
3873 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3875 static BC_STATUS zbc_parse_builtin(BcLexType type, uint8_t flags, BcInst *prev)
3877 BcParse *p = &G.prs;
3881 if (s) RETURN_STATUS(s);
3882 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3884 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3887 if (s) RETURN_STATUS(s);
3889 s = zbc_parse_expr(flags);
3890 if (s) RETURN_STATUS(s);
3892 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3894 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3895 bc_parse_push(*prev);
3899 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3901 static BC_STATUS zbc_parse_scale(BcInst *type, uint8_t flags)
3903 BcParse *p = &G.prs;
3907 if (s) RETURN_STATUS(s);
3909 if (p->lex != BC_LEX_LPAREN) {
3910 *type = XC_INST_SCALE;
3911 bc_parse_push(XC_INST_SCALE);
3912 RETURN_STATUS(BC_STATUS_SUCCESS);
3915 *type = XC_INST_SCALE_FUNC;
3916 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3919 if (s) RETURN_STATUS(s);
3921 s = zbc_parse_expr(flags);
3922 if (s) RETURN_STATUS(s);
3923 if (p->lex != BC_LEX_RPAREN)
3924 RETURN_STATUS(bc_error_bad_token());
3925 bc_parse_push(XC_INST_SCALE_FUNC);
3927 RETURN_STATUS(zbc_lex_next());
3929 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3931 static BC_STATUS zbc_parse_incdec(BcInst *prev, bool *paren_expr,
3932 size_t *nexprs, uint8_t flags)
3934 BcParse *p = &G.prs;
3938 BcInst etype = *prev;
3940 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
3941 || etype == XC_INST_SCALE || etype == BC_INST_LAST
3942 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
3944 *prev = inst = BC_INST_INC_POST + (p->lex != BC_LEX_OP_INC);
3945 bc_parse_push(inst);
3948 *prev = inst = BC_INST_INC_PRE + (p->lex != BC_LEX_OP_INC);
3952 if (s) RETURN_STATUS(s);
3955 // Because we parse the next part of the expression
3956 // right here, we need to increment this.
3957 *nexprs = *nexprs + 1;
3961 s = zbc_parse_name(prev, flags | BC_PARSE_NOCALL);
3963 case BC_LEX_KEY_IBASE:
3964 case BC_LEX_KEY_LAST:
3965 case BC_LEX_KEY_OBASE:
3966 bc_parse_push(type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
3969 case BC_LEX_KEY_SCALE:
3971 if (s) RETURN_STATUS(s);
3972 if (p->lex == BC_LEX_LPAREN)
3973 s = bc_error_bad_token();
3975 bc_parse_push(XC_INST_SCALE);
3978 s = bc_error_bad_token();
3982 if (!s) bc_parse_push(inst);
3987 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
3990 #define BC_PARSE_LEAF(p, rparen) \
3992 || ((p) >= XC_INST_NUM && (p) <= XC_INST_SQRT) \
3993 || (p) == BC_INST_INC_POST \
3994 || (p) == BC_INST_DEC_POST \
3997 static int ok_in_expr(BcInst p)
3999 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
4000 || p == BC_INST_INC_POST
4001 || p == BC_INST_DEC_POST
4004 #define BC_PARSE_LEAF(p, rparen) ((rparen) || ok_in_expr(p))
4007 static BC_STATUS zbc_parse_minus(BcInst *prev, size_t ops_bgn,
4008 bool rparen, size_t *nexprs)
4010 BcParse *p = &G.prs;
4013 BcInst etype = *prev;
4016 if (s) RETURN_STATUS(s);
4018 type = BC_PARSE_LEAF(etype, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
4019 *prev = BC_TOKEN_2_INST(type);
4021 // We can just push onto the op stack because this is the largest
4022 // precedence operator that gets pushed. Inc/dec does not.
4023 if (type != XC_LEX_OP_MINUS)
4024 bc_vec_push(&p->ops, &type);
4026 bc_parse_operator(type, ops_bgn, nexprs);
4030 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4032 static BC_STATUS zbc_parse_print(void)
4034 BcParse *p = &G.prs;
4040 if (s) RETURN_STATUS(s);
4042 if (type == XC_LEX_STR) {
4043 s = zbc_parse_pushSTR();
4045 s = zbc_parse_expr(0);
4047 if (s) RETURN_STATUS(s);
4048 bc_parse_push(XC_INST_PRINT_POP);
4049 if (p->lex != BC_LEX_COMMA)
4055 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4057 static BC_STATUS zbc_parse_return(void)
4059 BcParse *p = &G.prs;
4063 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4065 if (s) RETURN_STATUS(s);
4068 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON)
4069 bc_parse_push(BC_INST_RET0);
4071 bool paren = (t == BC_LEX_LPAREN);
4072 s = bc_parse_expr_empty_ok(0);
4073 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4074 bc_parse_push(BC_INST_RET0);
4077 if (s) RETURN_STATUS(s);
4079 if (!paren || p->lex_last != BC_LEX_RPAREN) {
4080 s = zbc_POSIX_requires("parentheses around return expressions");
4081 if (s) RETURN_STATUS(s);
4084 bc_parse_push(XC_INST_RET);
4087 dbg_lex_done("%s:%d done", __func__, __LINE__);
4090 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4092 static void rewrite_label_to_current(size_t idx)
4094 BcParse *p = &G.prs;
4095 size_t *label = bc_vec_item(&p->func->labels, idx);
4096 *label = p->func->code.len;
4099 static BC_STATUS zbc_parse_if(void)
4101 BcParse *p = &G.prs;
4105 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4107 if (s) RETURN_STATUS(s);
4108 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4111 if (s) RETURN_STATUS(s);
4112 s = zbc_parse_expr(BC_PARSE_REL);
4113 if (s) RETURN_STATUS(s);
4114 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4116 // Encode "if zero, jump to ..."
4117 // Pushed value (destination of the jump) is uninitialized,
4118 // will be rewritten to be address of "end of if()" or of "else".
4119 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4120 bc_parse_pushJUMP_ZERO(ip_idx);
4122 s = zbc_parse_stmt_allow_NLINE_before(STRING_if);
4123 if (s) RETURN_STATUS(s);
4125 dbg_lex("%s:%d in if after stmt: p->lex:%d", __func__, __LINE__, p->lex);
4126 if (p->lex == BC_LEX_KEY_ELSE) {
4129 // Encode "after then_stmt, jump to end of if()"
4130 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4131 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4132 bc_parse_pushJUMP(ip2_idx);
4134 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4135 rewrite_label_to_current(ip_idx);
4139 s = zbc_parse_stmt_allow_NLINE_before(STRING_else);
4140 if (s) RETURN_STATUS(s);
4143 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4144 rewrite_label_to_current(ip_idx);
4146 dbg_lex_done("%s:%d done", __func__, __LINE__);
4149 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4151 static BC_STATUS zbc_parse_while(void)
4153 BcParse *p = &G.prs;
4159 if (s) RETURN_STATUS(s);
4160 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4162 if (s) RETURN_STATUS(s);
4164 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4165 ip_idx = cond_idx + 1;
4166 bc_vec_push(&p->conds, &cond_idx);
4168 bc_vec_push(&p->exits, &ip_idx);
4169 bc_vec_push(&p->func->labels, &ip_idx);
4171 s = zbc_parse_expr(BC_PARSE_REL);
4172 if (s) RETURN_STATUS(s);
4173 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4175 bc_parse_pushJUMP_ZERO(ip_idx);
4177 s = zbc_parse_stmt_allow_NLINE_before(STRING_while);
4178 if (s) RETURN_STATUS(s);
4180 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4181 bc_parse_pushJUMP(cond_idx);
4183 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4184 rewrite_label_to_current(ip_idx);
4186 bc_vec_pop(&p->exits);
4187 bc_vec_pop(&p->conds);
4191 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4193 static BC_STATUS zbc_parse_for(void)
4195 BcParse *p = &G.prs;
4197 size_t cond_idx, exit_idx, body_idx, update_idx;
4199 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4201 if (s) RETURN_STATUS(s);
4202 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4204 if (s) RETURN_STATUS(s);
4206 if (p->lex != BC_LEX_SCOLON) {
4207 s = zbc_parse_expr(0);
4208 bc_parse_push(XC_INST_POP);
4209 if (s) RETURN_STATUS(s);
4211 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4212 if (s) RETURN_STATUS(s);
4215 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4217 if (s) RETURN_STATUS(s);
4219 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4220 update_idx = cond_idx + 1;
4221 body_idx = update_idx + 1;
4222 exit_idx = body_idx + 1;
4224 if (p->lex != BC_LEX_SCOLON)
4225 s = zbc_parse_expr(BC_PARSE_REL);
4227 // Set this for the next call to bc_parse_pushNUM().
4228 // This is safe to set because the current token is a semicolon,
4229 // which has no string requirement.
4230 bc_vec_string(&p->lex_strnumbuf, 1, "1");
4232 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4234 if (s) RETURN_STATUS(s);
4236 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4239 if (s) RETURN_STATUS(s);
4241 bc_parse_pushJUMP_ZERO(exit_idx);
4242 bc_parse_pushJUMP(body_idx);
4244 bc_vec_push(&p->conds, &update_idx);
4245 bc_vec_push(&p->func->labels, &p->func->code.len);
4247 if (p->lex != BC_LEX_RPAREN) {
4248 s = zbc_parse_expr(0);
4249 if (s) RETURN_STATUS(s);
4250 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4251 bc_parse_push(XC_INST_POP);
4253 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4254 if (s) RETURN_STATUS(s);
4257 bc_parse_pushJUMP(cond_idx);
4258 bc_vec_push(&p->func->labels, &p->func->code.len);
4260 bc_vec_push(&p->exits, &exit_idx);
4261 bc_vec_push(&p->func->labels, &exit_idx);
4263 s = zbc_parse_stmt_allow_NLINE_before(STRING_for);
4264 if (s) RETURN_STATUS(s);
4266 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4267 bc_parse_pushJUMP(update_idx);
4269 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4270 rewrite_label_to_current(exit_idx);
4272 bc_vec_pop(&p->exits);
4273 bc_vec_pop(&p->conds);
4275 RETURN_STATUS(BC_STATUS_SUCCESS);
4277 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4279 static BC_STATUS zbc_parse_break_or_continue(BcLexType type)
4281 BcParse *p = &G.prs;
4284 if (type == BC_LEX_KEY_BREAK) {
4285 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4286 RETURN_STATUS(bc_error_bad_token());
4287 i = *(size_t*)bc_vec_top(&p->exits);
4289 i = *(size_t*)bc_vec_top(&p->conds);
4291 bc_parse_pushJUMP(i);
4293 RETURN_STATUS(zbc_lex_next());
4295 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4297 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4303 autoid = (void*)f->autos.v;
4304 for (i = 0; i < f->autos.len; i++, autoid++) {
4305 if (strcmp(name, autoid->name) == 0)
4306 RETURN_STATUS(bc_error("duplicate function parameter or auto name"));
4312 bc_vec_push(&f->autos, &a);
4314 RETURN_STATUS(BC_STATUS_SUCCESS);
4316 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4318 static BC_STATUS zbc_parse_funcdef(void)
4320 BcParse *p = &G.prs;
4322 bool var, comma = false;
4325 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4327 if (s) RETURN_STATUS(s);
4328 if (p->lex != XC_LEX_NAME)
4329 RETURN_STATUS(bc_error("bad function definition"));
4331 name = xstrdup(p->lex_strnumbuf.v);
4332 p->fidx = bc_program_addFunc(name);
4333 p->func = bc_program_func(p->fidx);
4336 if (s) RETURN_STATUS(s);
4337 if (p->lex != BC_LEX_LPAREN)
4338 RETURN_STATUS(bc_error("bad function definition"));
4340 if (s) RETURN_STATUS(s);
4342 while (p->lex != BC_LEX_RPAREN) {
4343 if (p->lex != XC_LEX_NAME)
4344 RETURN_STATUS(bc_error("bad function definition"));
4348 name = xstrdup(p->lex_strnumbuf.v);
4352 var = p->lex != BC_LEX_LBRACKET;
4358 if (p->lex != BC_LEX_RBRACKET) {
4359 s = bc_error("bad function definition");
4367 comma = p->lex == BC_LEX_COMMA;
4373 s = zbc_func_insert(p->func, name, var);
4377 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4380 if (s) RETURN_STATUS(s);
4382 if (p->lex != BC_LEX_LBRACE) {
4383 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4384 if (s) RETURN_STATUS(s);
4387 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4388 s = zbc_lex_skip_if_at_NLINE();
4389 if (s) RETURN_STATUS(s);
4390 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4391 if (p->lex != BC_LEX_LBRACE)
4392 RETURN_STATUS(bc_error("function { body } expected"));
4394 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4395 s = zbc_parse_stmt_possibly_auto(true);
4397 if (s) RETURN_STATUS(s);
4399 bc_parse_push(BC_INST_RET0);
4401 // Subsequent code generation is into main program
4402 p->fidx = BC_PROG_MAIN;
4403 p->func = bc_program_func_BC_PROG_MAIN();
4405 dbg_lex_done("%s:%d done", __func__, __LINE__);
4408 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4412 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4414 static BC_STATUS zbc_parse_auto(void)
4416 BcParse *p = &G.prs;
4420 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4422 if (s) RETURN_STATUS(s);
4427 if (p->lex != XC_LEX_NAME)
4428 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4430 name = xstrdup(p->lex_strnumbuf.v);
4434 var = (p->lex != BC_LEX_LBRACKET);
4439 if (p->lex != BC_LEX_RBRACKET) {
4440 s = bc_error("bad 'auto' syntax");
4447 s = zbc_func_insert(p->func, name, var);
4450 if (p->lex == XC_LEX_NLINE
4451 || p->lex == BC_LEX_SCOLON
4452 //|| p->lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4456 if (p->lex != BC_LEX_COMMA)
4457 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4458 s = zbc_lex_next(); // skip comma
4459 if (s) RETURN_STATUS(s);
4462 dbg_lex_done("%s:%d done", __func__, __LINE__);
4463 RETURN_STATUS(BC_STATUS_SUCCESS);
4466 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4469 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4471 #undef zbc_parse_stmt_possibly_auto
4472 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed)
4474 BcParse *p = &G.prs;
4475 BcStatus s = BC_STATUS_SUCCESS;
4477 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
4479 if (p->lex == XC_LEX_NLINE) {
4480 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4481 RETURN_STATUS(zbc_lex_next());
4483 if (p->lex == BC_LEX_SCOLON) {
4484 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4485 RETURN_STATUS(zbc_lex_next());
4488 if (p->lex == BC_LEX_LBRACE) {
4489 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4492 if (s) RETURN_STATUS(s);
4493 } while (p->lex == XC_LEX_NLINE);
4494 if (auto_allowed && p->lex == BC_LEX_KEY_AUTO) {
4495 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4496 s = zbc_parse_auto();
4497 if (s) RETURN_STATUS(s);
4499 while (p->lex != BC_LEX_RBRACE) {
4500 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4501 s = zbc_parse_stmt();
4502 if (s) RETURN_STATUS(s);
4505 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4509 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4511 case XC_LEX_OP_MINUS:
4514 case BC_LEX_OP_BOOL_NOT:
4518 case BC_LEX_KEY_IBASE:
4519 case BC_LEX_KEY_LAST:
4520 case BC_LEX_KEY_LENGTH:
4521 case BC_LEX_KEY_OBASE:
4522 case BC_LEX_KEY_READ:
4523 case BC_LEX_KEY_SCALE:
4524 case BC_LEX_KEY_SQRT:
4525 s = zbc_parse_expr(BC_PARSE_PRINT);
4528 s = zbc_parse_pushSTR();
4529 bc_parse_push(XC_INST_PRINT_STR);
4531 case BC_LEX_KEY_BREAK:
4532 case BC_LEX_KEY_CONTINUE:
4533 s = zbc_parse_break_or_continue(p->lex);
4535 case BC_LEX_KEY_FOR:
4536 s = zbc_parse_for();
4538 case BC_LEX_KEY_HALT:
4539 bc_parse_push(BC_INST_HALT);
4545 case BC_LEX_KEY_LIMITS:
4546 // "limits" is a compile-time command,
4547 // the output is produced at _parse time_.
4549 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4550 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4551 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4552 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4553 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4554 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4555 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4556 "Number of vars = "BC_MAX_VARS_STR "\n"
4560 case BC_LEX_KEY_PRINT:
4561 s = zbc_parse_print();
4563 case BC_LEX_KEY_QUIT:
4564 // "quit" is a compile-time command. For example,
4565 // "if (0 == 1) quit" terminates when parsing the statement,
4566 // not when it is executed
4567 QUIT_OR_RETURN_TO_MAIN;
4568 case BC_LEX_KEY_RETURN:
4570 RETURN_STATUS(bc_error("'return' not in a function"));
4571 s = zbc_parse_return();
4573 case BC_LEX_KEY_WHILE:
4574 s = zbc_parse_while();
4577 s = bc_error_bad_token();
4581 dbg_lex_done("%s:%d done", __func__, __LINE__);
4584 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4586 static BC_STATUS zbc_parse_stmt_or_funcdef(void)
4588 BcParse *p = &G.prs;
4591 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4592 if (p->lex == XC_LEX_EOF)
4593 s = bc_error("end of file");
4594 else if (p->lex == BC_LEX_KEY_DEFINE) {
4595 dbg_lex("%s:%d p->lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4596 s = zbc_parse_funcdef();
4598 dbg_lex("%s:%d p->lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->lex);
4599 s = zbc_parse_stmt();
4602 dbg_lex_done("%s:%d done", __func__, __LINE__);
4605 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4607 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4608 static BcStatus bc_parse_expr_empty_ok(uint8_t flags)
4610 BcParse *p = &G.prs;
4611 BcInst prev = XC_INST_PRINT;
4612 size_t nexprs = 0, ops_bgn = p->ops.len;
4613 unsigned nparens, nrelops;
4614 bool paren_first, paren_expr, rprn, assign, bin_last;
4616 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4617 paren_first = (p->lex == BC_LEX_LPAREN);
4618 nparens = nrelops = 0;
4619 paren_expr = rprn = assign = false;
4625 BcLexType t = p->lex;
4627 if (!lex_allowed_in_bc_expr(t))
4630 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4632 s = BC_STATUS_SUCCESS;
4636 dbg_lex("%s:%d LEX_OP_INC/DEC", __func__, __LINE__);
4637 s = zbc_parse_incdec(&prev, &paren_expr, &nexprs, flags);
4638 rprn = bin_last = false;
4639 //get_token = false; - already is
4641 case XC_LEX_OP_MINUS:
4642 dbg_lex("%s:%d LEX_OP_MINUS", __func__, __LINE__);
4643 s = zbc_parse_minus(&prev, ops_bgn, rprn, &nexprs);
4645 //get_token = false; - already is
4646 bin_last = (prev == XC_INST_MINUS);
4648 case BC_LEX_OP_ASSIGN_POWER:
4649 case BC_LEX_OP_ASSIGN_MULTIPLY:
4650 case BC_LEX_OP_ASSIGN_DIVIDE:
4651 case BC_LEX_OP_ASSIGN_MODULUS:
4652 case BC_LEX_OP_ASSIGN_PLUS:
4653 case BC_LEX_OP_ASSIGN_MINUS:
4654 case BC_LEX_OP_ASSIGN:
4655 dbg_lex("%s:%d LEX_ASSIGNxyz", __func__, __LINE__);
4656 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4657 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4658 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4660 return bc_error("bad assignment:"
4661 " left side must be variable"
4663 ); // note: shared string
4666 case XC_LEX_OP_POWER:
4667 case XC_LEX_OP_MULTIPLY:
4668 case XC_LEX_OP_DIVIDE:
4669 case XC_LEX_OP_MODULUS:
4670 case XC_LEX_OP_PLUS:
4671 case XC_LEX_OP_REL_EQ:
4672 case XC_LEX_OP_REL_LE:
4673 case XC_LEX_OP_REL_GE:
4674 case XC_LEX_OP_REL_NE:
4675 case XC_LEX_OP_REL_LT:
4676 case XC_LEX_OP_REL_GT:
4677 case BC_LEX_OP_BOOL_NOT:
4678 case BC_LEX_OP_BOOL_OR:
4679 case BC_LEX_OP_BOOL_AND:
4680 dbg_lex("%s:%d LEX_OP_xyz", __func__, __LINE__);
4681 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4682 || (t != BC_LEX_OP_BOOL_NOT && prev == XC_INST_BOOL_NOT)
4684 return bc_error_bad_expression();
4686 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4687 prev = BC_TOKEN_2_INST(t);
4688 bc_parse_operator(t, ops_bgn, &nexprs);
4691 //get_token = false; - already is
4692 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4695 dbg_lex("%s:%d LEX_LPAREN", __func__, __LINE__);
4696 if (BC_PARSE_LEAF(prev, rprn))
4697 return bc_error_bad_expression();
4698 bc_vec_push(&p->ops, &t);
4702 rprn = bin_last = false;
4705 dbg_lex("%s:%d LEX_RPAREN", __func__, __LINE__);
4706 if (bin_last || prev == XC_INST_BOOL_NOT)
4707 return bc_error_bad_expression();
4712 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4713 return BC_STATUS_PARSE_EMPTY_EXP;
4715 s = zbc_parse_rightParen(ops_bgn, &nexprs);
4718 paren_expr = rprn = true;
4722 dbg_lex("%s:%d LEX_NAME", __func__, __LINE__);
4723 if (BC_PARSE_LEAF(prev, rprn))
4724 return bc_error_bad_expression();
4725 s = zbc_parse_name(&prev, flags & ~BC_PARSE_NOCALL);
4727 rprn = bin_last = false;
4728 //get_token = false; - already is
4732 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4733 if (BC_PARSE_LEAF(prev, rprn))
4734 return bc_error_bad_expression();
4739 rprn = bin_last = false;
4742 case BC_LEX_KEY_IBASE:
4743 case BC_LEX_KEY_LAST:
4744 case BC_LEX_KEY_OBASE:
4745 dbg_lex("%s:%d LEX_IBASE/LAST/OBASE", __func__, __LINE__);
4746 if (BC_PARSE_LEAF(prev, rprn))
4747 return bc_error_bad_expression();
4748 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4749 bc_parse_push((char) prev);
4752 rprn = bin_last = false;
4755 case BC_LEX_KEY_LENGTH:
4756 case BC_LEX_KEY_SQRT:
4757 dbg_lex("%s:%d LEX_LEN/SQRT", __func__, __LINE__);
4758 if (BC_PARSE_LEAF(prev, rprn))
4759 return bc_error_bad_expression();
4760 s = zbc_parse_builtin(t, flags, &prev);
4763 rprn = bin_last = false;
4766 case BC_LEX_KEY_READ:
4767 dbg_lex("%s:%d LEX_READ", __func__, __LINE__);
4768 if (BC_PARSE_LEAF(prev, rprn))
4769 return bc_error_bad_expression();
4770 s = zbc_parse_read();
4771 prev = XC_INST_READ;
4774 rprn = bin_last = false;
4777 case BC_LEX_KEY_SCALE:
4778 dbg_lex("%s:%d LEX_SCALE", __func__, __LINE__);
4779 if (BC_PARSE_LEAF(prev, rprn))
4780 return bc_error_bad_expression();
4781 s = zbc_parse_scale(&prev, flags);
4782 prev = XC_INST_SCALE;
4783 //get_token = false; - already is
4785 rprn = bin_last = false;
4789 return bc_error_bad_token();
4792 if (s || G_interrupt) // error, or ^C: stop parsing
4793 return BC_STATUS_FAILURE;
4801 while (p->ops.len > ops_bgn) {
4802 BcLexType top = BC_PARSE_TOP_OP(p);
4803 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4805 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4806 return bc_error_bad_expression();
4808 bc_parse_push(BC_TOKEN_2_INST(top));
4810 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4811 bc_vec_pop(&p->ops);
4814 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4815 return bc_error_bad_expression();
4817 if (!(flags & BC_PARSE_REL) && nrelops) {
4819 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4821 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4823 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4827 if (flags & BC_PARSE_PRINT) {
4828 if (paren_first || !assign)
4829 bc_parse_push(XC_INST_PRINT);
4830 bc_parse_push(XC_INST_POP);
4833 dbg_lex_done("%s:%d done", __func__, __LINE__);
4834 return BC_STATUS_SUCCESS;
4841 static BC_STATUS zdc_parse_register(void)
4843 BcParse *p = &G.prs;
4847 if (s) RETURN_STATUS(s);
4848 if (p->lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4850 bc_parse_pushName(p->lex_strnumbuf.v);
4854 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4856 static void dc_parse_string(void)
4858 BcParse *p = &G.prs;
4860 size_t len = G.prog.strs.len;
4862 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4864 str = xstrdup(p->lex_strnumbuf.v);
4865 bc_parse_push(XC_INST_STR);
4866 bc_parse_pushIndex(len);
4867 bc_vec_push(&G.prog.strs, &str);
4869 // Explanation needed here
4870 bc_program_add_fn();
4871 p->func = bc_program_func(p->fidx);
4873 dbg_lex_done("%s:%d done", __func__, __LINE__);
4876 static BC_STATUS zdc_parse_mem(uint8_t inst, bool name, bool store)
4880 bc_parse_push(inst);
4882 s = zdc_parse_register();
4883 if (s) RETURN_STATUS(s);
4887 bc_parse_push(DC_INST_SWAP);
4888 bc_parse_push(XC_INST_ASSIGN);
4889 bc_parse_push(XC_INST_POP);
4892 RETURN_STATUS(BC_STATUS_SUCCESS);
4894 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4896 static BC_STATUS zdc_parse_cond(uint8_t inst)
4898 BcParse *p = &G.prs;
4901 bc_parse_push(inst);
4902 bc_parse_push(DC_INST_EXEC_COND);
4904 s = zdc_parse_register();
4905 if (s) RETURN_STATUS(s);
4908 if (s) RETURN_STATUS(s);
4910 // Note that 'else' part can not be on the next line:
4911 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4912 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4913 if (p->lex == DC_LEX_ELSE) {
4914 s = zdc_parse_register();
4915 if (s) RETURN_STATUS(s);
4918 bc_parse_push('\0');
4923 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4925 static BC_STATUS zdc_parse_token(BcLexType t)
4929 bool assign, get_token;
4931 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4932 s = BC_STATUS_SUCCESS;
4935 case XC_LEX_OP_REL_EQ:
4936 case XC_LEX_OP_REL_LE:
4937 case XC_LEX_OP_REL_GE:
4938 case XC_LEX_OP_REL_NE:
4939 case XC_LEX_OP_REL_LT:
4940 case XC_LEX_OP_REL_GT:
4941 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
4942 s = zdc_parse_cond(t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
4947 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
4948 s = zdc_parse_mem(XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
4951 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
4955 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
4957 if (s) RETURN_STATUS(s);
4958 if (G.prs.lex != XC_LEX_NUMBER)
4959 RETURN_STATUS(bc_error_bad_token());
4961 bc_parse_push(XC_INST_NEG);
4964 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4968 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
4969 bc_parse_push(XC_INST_READ);
4971 case DC_LEX_OP_ASSIGN:
4972 case DC_LEX_STORE_PUSH:
4973 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
4974 assign = (t == DC_LEX_OP_ASSIGN);
4975 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
4976 s = zdc_parse_mem(inst, true, assign);
4979 case DC_LEX_LOAD_POP:
4980 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
4981 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
4982 s = zdc_parse_mem(inst, true, false);
4984 case DC_LEX_STORE_IBASE:
4985 case DC_LEX_STORE_SCALE:
4986 case DC_LEX_STORE_OBASE:
4987 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
4988 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
4989 s = zdc_parse_mem(inst, false, true);
4992 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
4993 RETURN_STATUS(bc_error_bad_token());
4996 if (!s && get_token) s = zbc_lex_next();
4998 dbg_lex_done("%s:%d done", __func__, __LINE__);
5001 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
5003 static BC_STATUS zdc_parse_expr(void)
5005 BcParse *p = &G.prs;
5008 i = (int)p->lex - (int)XC_LEX_OP_POWER;
5010 BcInst inst = dc_LEX_to_INST[i];
5011 if (inst != DC_INST_INVALID) {
5012 bc_parse_push(inst);
5013 RETURN_STATUS(zbc_lex_next());
5016 RETURN_STATUS(zdc_parse_token(p->lex));
5018 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
5020 static BC_STATUS zdc_parse_exprs_until_eof(void)
5022 BcParse *p = &G.prs;
5023 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
5024 while (p->lex != XC_LEX_EOF) {
5025 BcStatus s = zdc_parse_expr();
5026 if (s) RETURN_STATUS(s);
5029 dbg_lex_done("%s:%d done", __func__, __LINE__);
5030 RETURN_STATUS(BC_STATUS_SUCCESS);
5032 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5040 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5041 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5043 static BcVec* bc_program_search(char *id, bool var)
5050 v = var ? &G.prog.vars : &G.prog.arrs;
5051 map = var ? &G.prog.var_map : &G.prog.arr_map;
5055 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5059 bc_array_init(&v2, var);
5060 bc_vec_push(v, &v2);
5063 ptr = bc_vec_item(map, i);
5064 if (new) ptr->name = xstrdup(e.name);
5065 return bc_vec_item(v, ptr->idx);
5068 // 'num' need not be initialized on entry
5069 static BC_STATUS zbc_program_num(BcResult *r, BcNum **num, bool hex)
5073 case XC_RESULT_TEMP:
5074 case XC_RESULT_IBASE:
5075 case XC_RESULT_SCALE:
5076 case XC_RESULT_OBASE:
5079 case XC_RESULT_CONSTANT: {
5085 str = *bc_program_const(r->d.id.idx);
5088 bc_num_init(&r->d.n, len);
5090 hex = hex && len == 1;
5091 base_t = hex ? 16 : G.prog.ib_t;
5092 s = zbc_num_parse(&r->d.n, str, base_t);
5094 bc_num_free(&r->d.n);
5098 r->t = XC_RESULT_TEMP;
5102 case XC_RESULT_ARRAY:
5103 case XC_RESULT_ARRAY_ELEM: {
5106 v = bc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5108 if (r->t == XC_RESULT_ARRAY_ELEM) {
5110 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5111 *num = bc_vec_item(v, r->d.id.idx);
5113 *num = bc_vec_top(v);
5117 case BC_RESULT_LAST:
5118 *num = &G.prog.last;
5126 // Testing the theory that dc does not reach LAST/ONE
5127 bb_error_msg_and_die("BUG:%d", r->t);
5131 RETURN_STATUS(BC_STATUS_SUCCESS);
5133 #define zbc_program_num(...) (zbc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5135 static BC_STATUS zbc_program_binOpPrep(BcResult **l, BcNum **ln,
5136 BcResult **r, BcNum **rn, bool assign)
5140 BcResultType lt, rt;
5142 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5143 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5145 *r = bc_vec_item_rev(&G.prog.results, 0);
5146 *l = bc_vec_item_rev(&G.prog.results, 1);
5150 hex = assign && (lt == XC_RESULT_IBASE || lt == XC_RESULT_OBASE);
5152 s = zbc_program_num(*l, ln, false);
5153 if (s) RETURN_STATUS(s);
5154 s = zbc_program_num(*r, rn, hex);
5155 if (s) RETURN_STATUS(s);
5157 // We run this again under these conditions in case any vector has been
5158 // reallocated out from under the BcNums or arrays we had.
5159 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5160 s = zbc_program_num(*l, ln, false);
5161 if (s) RETURN_STATUS(s);
5164 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5165 RETURN_STATUS(bc_error_variable_is_wrong_type());
5166 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5167 RETURN_STATUS(bc_error_variable_is_wrong_type());
5171 #define zbc_program_binOpPrep(...) (zbc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5173 static void bc_program_binOpRetire(BcResult *r)
5175 r->t = XC_RESULT_TEMP;
5176 bc_vec_pop(&G.prog.results);
5177 bc_result_pop_and_push(r);
5180 // Note: *r and *n need not be initialized by caller
5181 static BC_STATUS zbc_program_prep(BcResult **r, BcNum **n)
5185 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5186 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5187 *r = bc_vec_top(&G.prog.results);
5189 s = zbc_program_num(*r, n, false);
5190 if (s) RETURN_STATUS(s);
5192 if (!BC_PROG_NUM((*r), (*n)))
5193 RETURN_STATUS(bc_error_variable_is_wrong_type());
5197 #define zbc_program_prep(...) (zbc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5199 static void bc_program_retire(BcResult *r, BcResultType t)
5202 bc_result_pop_and_push(r);
5205 static BC_STATUS zbc_program_op(char inst)
5208 BcResult *opd1, *opd2, res;
5211 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5212 if (s) RETURN_STATUS(s);
5213 bc_num_init_DEF_SIZE(&res.d.n);
5215 s = BC_STATUS_SUCCESS;
5216 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5218 bc_program_binOpRetire(&res);
5222 bc_num_free(&res.d.n);
5225 #define zbc_program_op(...) (zbc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5227 static BC_STATUS zbc_program_read(void)
5235 bc_char_vec_init(&buf);
5236 bc_read_line(&buf, stdin);
5238 f = bc_program_func(BC_PROG_READ);
5239 bc_vec_pop_all(&f->code);
5241 sv_parse = G.prs; // struct copy
5242 bc_parse_create(BC_PROG_READ);
5243 //G.err_line = G.prs.lex_line = 1; - not needed, error line info is not printed for read()
5245 s = zbc_parse_text_init(buf.v);
5246 if (s) goto exec_err;
5248 IF_BC(s = zbc_parse_expr(0));
5250 IF_DC(s = zdc_parse_exprs_until_eof());
5252 if (s) goto exec_err;
5254 if (G.prs.lex != XC_LEX_NLINE && G.prs.lex != XC_LEX_EOF) {
5255 s = bc_error("bad read() expression");
5259 ip.func = BC_PROG_READ;
5261 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5263 bc_parse_push(XC_INST_RET);
5264 bc_vec_push(&G.prog.exestack, &ip);
5268 G.prs = sv_parse; // struct copy
5272 #define zbc_program_read(...) (zbc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5274 static size_t bc_program_index(char *code, size_t *bgn)
5276 unsigned char *bytes = (void*)(code + *bgn);
5282 if (amt < SMALL_INDEX_LIMIT) {
5286 amt -= SMALL_INDEX_LIMIT;
5291 for (i = 0; i < amt; i += 8)
5292 res |= (size_t)(*bytes++) << i;
5297 static char *bc_program_name(char *code, size_t *bgn)
5300 *bgn += strlen(code) + 1;
5302 return xstrdup(code);
5305 static void bc_program_printString(const char *str)
5309 // Example: echo '[]ap' | dc
5310 // should print two bytes: 0x00, 0x0A
5317 if (c != '\\' || !*str)
5337 G.prog.nchars = SIZE_MAX;
5349 // Just print the backslash and following character.
5360 static void bc_num_printNewline(void)
5362 if (G.prog.nchars == G.prog.len - 1) {
5370 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5373 bb_putchar((char) num);
5374 G.prog.nchars += width;
5378 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5382 bc_num_printNewline();
5383 bb_putchar(radix ? '.' : ' ');
5386 bc_num_printNewline();
5387 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5390 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5392 bc_num_printNewline();
5395 bb_putchar(((char) dig) + '0');
5399 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5402 bc_num_printNewline();
5407 bc_num_printNewline();
5408 bb_putchar(bb_hexdigits_upcase[num]);
5409 G.prog.nchars += width;
5412 static void bc_num_printDecimal(BcNum *n)
5414 size_t i, rdx = n->rdx - 1;
5421 for (i = n->len - 1; i < n->len; --i)
5422 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5425 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5427 static BC_STATUS zbc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5432 BcDig base_digs[ULONG_NUM_BUFSIZE];
5433 BcNum intp, fracp, digit, frac_len;
5434 unsigned long dig, *ptr;
5439 print(0, width, false);
5440 RETURN_STATUS(BC_STATUS_SUCCESS);
5443 bc_vec_init(&stack, sizeof(long), NULL);
5444 bc_num_init(&intp, n->len);
5445 bc_num_init(&fracp, n->rdx);
5446 bc_num_init(&digit, width);
5447 bc_num_init(&frac_len, BC_NUM_INT(n));
5448 bc_num_copy(&intp, n);
5449 bc_num_one(&frac_len);
5450 base.cap = ARRAY_SIZE(base_digs);
5451 base.num = base_digs;
5452 bc_num_ulong2num(&base, base_t);
5454 bc_num_truncate(&intp, intp.rdx);
5455 s = zbc_num_sub(n, &intp, &fracp, 0);
5458 while (intp.len != 0) {
5459 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5461 s = zbc_num_ulong(&digit, &dig);
5463 bc_vec_push(&stack, &dig);
5466 for (i = 0; i < stack.len; ++i) {
5467 ptr = bc_vec_item_rev(&stack, i);
5468 print(*ptr, width, false);
5471 if (!n->rdx) goto err;
5473 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5474 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5476 s = zbc_num_ulong(&fracp, &dig);
5478 bc_num_ulong2num(&intp, dig);
5479 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5481 print(dig, width, radix);
5482 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5486 bc_num_free(&frac_len);
5487 bc_num_free(&digit);
5488 bc_num_free(&fracp);
5490 bc_vec_free(&stack);
5493 #define zbc_num_printNum(...) (zbc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5495 static BC_STATUS zbc_num_printBase(BcNum *n)
5509 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5511 print = bc_num_printHex;
5513 unsigned i = G.prog.ob_t - 1;
5521 print = bc_num_printDigits;
5524 s = zbc_num_printNum(n, G.prog.ob_t, width, print);
5529 #define zbc_num_printBase(...) (zbc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5531 static BC_STATUS zbc_num_print(BcNum *n, bool newline)
5533 BcStatus s = BC_STATUS_SUCCESS;
5535 bc_num_printNewline();
5540 } else if (G.prog.ob_t == 10)
5541 bc_num_printDecimal(n);
5543 s = zbc_num_printBase(n);
5552 #define zbc_num_print(...) (zbc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5554 static BC_STATUS zbc_program_print(char inst, size_t idx)
5559 bool pop = (inst != XC_INST_PRINT);
5561 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5562 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5564 r = bc_vec_item_rev(&G.prog.results, idx);
5565 s = zbc_program_num(r, &num, false);
5566 if (s) RETURN_STATUS(s);
5568 if (BC_PROG_NUM(r, num)) {
5569 s = zbc_num_print(num, !pop);
5571 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5576 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5577 str = *bc_program_str(idx);
5579 if (inst == XC_INST_PRINT_STR) {
5582 if (c == '\0') break;
5585 if (c == '\n') G.prog.nchars = 0;
5588 bc_program_printString(str);
5589 if (inst == XC_INST_PRINT) bb_putchar('\n');
5593 if (!s && pop) bc_vec_pop(&G.prog.results);
5597 #define zbc_program_print(...) (zbc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5599 static BC_STATUS zbc_program_negate(void)
5605 s = zbc_program_prep(&ptr, &num);
5606 if (s) RETURN_STATUS(s);
5608 bc_num_init(&res.d.n, num->len);
5609 bc_num_copy(&res.d.n, num);
5610 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5612 bc_program_retire(&res, XC_RESULT_TEMP);
5616 #define zbc_program_negate(...) (zbc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5618 static BC_STATUS zbc_program_logical(char inst)
5621 BcResult *opd1, *opd2, res;
5625 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5626 if (s) RETURN_STATUS(s);
5628 bc_num_init_DEF_SIZE(&res.d.n);
5630 if (inst == XC_INST_BOOL_AND)
5631 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5632 else if (inst == XC_INST_BOOL_OR)
5633 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5635 cond = bc_num_cmp(n1, n2);
5637 case XC_INST_REL_EQ:
5640 case XC_INST_REL_LE:
5643 case XC_INST_REL_GE:
5646 case XC_INST_REL_LT:
5649 case XC_INST_REL_GT:
5652 default: // = case XC_INST_REL_NE:
5653 //cond = (cond != 0); - not needed
5658 if (cond) bc_num_one(&res.d.n);
5659 //else bc_num_zero(&res.d.n); - already is
5661 bc_program_binOpRetire(&res);
5665 #define zbc_program_logical(...) (zbc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5668 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5673 memset(&n2, 0, sizeof(BcNum));
5674 n2.rdx = res.d.id.idx = r->d.id.idx;
5675 res.t = XC_RESULT_STR;
5678 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5679 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5681 bc_vec_pop(&G.prog.results);
5684 bc_result_pop_and_push(&res);
5685 bc_vec_push(v, &n2);
5687 RETURN_STATUS(BC_STATUS_SUCCESS);
5689 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5692 static BC_STATUS zbc_program_copyToVar(char *name, bool var)
5699 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5700 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5702 ptr = bc_vec_top(&G.prog.results);
5703 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5704 RETURN_STATUS(bc_error_variable_is_wrong_type());
5705 v = bc_program_search(name, var);
5708 if (ptr->t == XC_RESULT_STR && !var)
5709 RETURN_STATUS(bc_error_variable_is_wrong_type());
5710 if (ptr->t == XC_RESULT_STR)
5711 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5714 s = zbc_program_num(ptr, &n, false);
5715 if (s) RETURN_STATUS(s);
5717 // Do this once more to make sure that pointers were not invalidated.
5718 v = bc_program_search(name, var);
5721 bc_num_init_DEF_SIZE(&r.d.n);
5722 bc_num_copy(&r.d.n, n);
5724 bc_array_init(&r.d.v, true);
5725 bc_array_copy(&r.d.v, (BcVec *) n);
5728 bc_vec_push(v, &r.d);
5729 bc_vec_pop(&G.prog.results);
5733 #define zbc_program_copyToVar(...) (zbc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5735 static BC_STATUS zbc_program_assign(char inst)
5738 BcResult *left, *right, res;
5740 bool assign = (inst == XC_INST_ASSIGN);
5743 s = zbc_program_binOpPrep(&left, &l, &right, &r, assign);
5744 if (s) RETURN_STATUS(s);
5746 ib = left->t == XC_RESULT_IBASE;
5747 sc = left->t == XC_RESULT_SCALE;
5750 if (right->t == XC_RESULT_STR) {
5753 if (left->t != XC_RESULT_VAR)
5754 RETURN_STATUS(bc_error_variable_is_wrong_type());
5755 v = bc_program_search(left->d.id.name, true);
5757 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5761 if (left->t == XC_RESULT_CONSTANT || left->t == XC_RESULT_TEMP)
5762 RETURN_STATUS(bc_error("bad assignment:"
5763 " left side must be variable"
5765 )); // note: shared string
5768 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5769 RETURN_STATUS(bc_error("divide by zero"));
5774 s = BC_STATUS_SUCCESS;
5775 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5777 if (s) RETURN_STATUS(s);
5782 if (ib || sc || left->t == XC_RESULT_OBASE) {
5783 static const char *const msg[] = {
5784 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5785 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5786 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5792 s = zbc_num_ulong(l, &val);
5793 if (s) RETURN_STATUS(s);
5794 s = left->t - XC_RESULT_IBASE;
5797 ptr = &G.prog.scale;
5800 RETURN_STATUS(bc_error(msg[s]));
5801 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5802 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5806 RETURN_STATUS(bc_error(msg[s]));
5808 *ptr = (size_t) val;
5809 s = BC_STATUS_SUCCESS;
5812 bc_num_init(&res.d.n, l->len);
5813 bc_num_copy(&res.d.n, l);
5814 bc_program_binOpRetire(&res);
5818 #define zbc_program_assign(...) (zbc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5821 #define bc_program_pushVar(code, bgn, pop, copy) \
5822 bc_program_pushVar(code, bgn)
5823 // for bc, 'pop' and 'copy' are always false
5825 static BC_STATUS bc_program_pushVar(char *code, size_t *bgn,
5826 bool pop, bool copy)
5829 char *name = bc_program_name(code, bgn);
5831 r.t = XC_RESULT_VAR;
5836 BcVec *v = bc_program_search(name, true);
5837 BcNum *num = bc_vec_top(v);
5840 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5841 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5844 if (!BC_PROG_STR(num)) {
5845 r.t = XC_RESULT_TEMP;
5846 bc_num_init_DEF_SIZE(&r.d.n);
5847 bc_num_copy(&r.d.n, num);
5849 r.t = XC_RESULT_STR;
5850 r.d.id.idx = num->rdx;
5853 if (!copy) bc_vec_pop(v);
5857 bc_vec_push(&G.prog.results, &r);
5859 RETURN_STATUS(BC_STATUS_SUCCESS);
5861 #define zbc_program_pushVar(...) (bc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5863 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5865 BcStatus s = BC_STATUS_SUCCESS;
5869 r.d.id.name = bc_program_name(code, bgn);
5871 if (inst == XC_INST_ARRAY) {
5872 r.t = XC_RESULT_ARRAY;
5873 bc_vec_push(&G.prog.results, &r);
5878 s = zbc_program_prep(&operand, &num);
5880 s = zbc_num_ulong(num, &temp);
5883 if (temp > BC_MAX_DIM) {
5884 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5888 r.d.id.idx = (size_t) temp;
5889 bc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5892 if (s) free(r.d.id.name);
5895 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5898 static BC_STATUS zbc_program_incdec(char inst)
5901 BcResult *ptr, res, copy;
5905 s = zbc_program_prep(&ptr, &num);
5906 if (s) RETURN_STATUS(s);
5908 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5909 copy.t = XC_RESULT_TEMP;
5910 bc_num_init(©.d.n, num->len);
5911 bc_num_copy(©.d.n, num);
5914 res.t = BC_RESULT_ONE;
5915 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
5916 ? BC_INST_ASSIGN_PLUS
5917 : BC_INST_ASSIGN_MINUS;
5919 bc_vec_push(&G.prog.results, &res);
5920 s = zbc_program_assign(inst);
5921 if (s) RETURN_STATUS(s);
5923 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5924 bc_result_pop_and_push(©);
5929 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5931 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5939 nparams = bc_program_index(code, idx);
5941 ip.func = bc_program_index(code, idx);
5942 func = bc_program_func(ip.func);
5944 if (func->code.len == 0) {
5945 RETURN_STATUS(bc_error("undefined function"));
5947 if (nparams != func->nparams) {
5948 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5950 ip.results_len_before_call = G.prog.results.len - nparams;
5952 for (i = 0; i < nparams; ++i) {
5955 a = bc_vec_item(&func->autos, nparams - 1 - i);
5956 arg = bc_vec_top(&G.prog.results);
5958 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) || arg->t == XC_RESULT_STR)
5959 RETURN_STATUS(bc_error_variable_is_wrong_type());
5961 s = zbc_program_copyToVar(a->name, a->idx);
5962 if (s) RETURN_STATUS(s);
5965 a = bc_vec_item(&func->autos, i);
5966 for (; i < func->autos.len; i++, a++) {
5969 v = bc_program_search(a->name, a->idx);
5972 bc_num_init_DEF_SIZE(&n2);
5973 bc_vec_push(v, &n2);
5976 bc_array_init(&v2, true);
5977 bc_vec_push(v, &v2);
5981 bc_vec_push(&G.prog.exestack, &ip);
5983 RETURN_STATUS(BC_STATUS_SUCCESS);
5985 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
5987 static BC_STATUS zbc_program_return(char inst)
5993 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
5995 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == XC_INST_RET)))
5996 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5998 f = bc_program_func(ip->func);
5999 res.t = XC_RESULT_TEMP;
6001 if (inst == XC_INST_RET) {
6004 BcResult *operand = bc_vec_top(&G.prog.results);
6006 s = zbc_program_num(operand, &num, false);
6007 if (s) RETURN_STATUS(s);
6008 bc_num_init(&res.d.n, num->len);
6009 bc_num_copy(&res.d.n, num);
6011 bc_num_init_DEF_SIZE(&res.d.n);
6012 //bc_num_zero(&res.d.n); - already is
6015 // We need to pop arguments as well, so this takes that into account.
6016 a = (void*)f->autos.v;
6017 for (i = 0; i < f->autos.len; i++, a++) {
6019 v = bc_program_search(a->name, a->idx);
6023 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
6024 bc_vec_push(&G.prog.results, &res);
6025 bc_vec_pop(&G.prog.exestack);
6027 RETURN_STATUS(BC_STATUS_SUCCESS);
6029 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6032 static unsigned long bc_program_scale(BcNum *n)
6034 return (unsigned long) n->rdx;
6037 static unsigned long bc_program_len(BcNum *n)
6039 size_t len = n->len;
6041 if (n->rdx != len) return len;
6043 if (len == 0) break;
6045 if (n->num[len] != 0) break;
6050 static BC_STATUS zbc_program_builtin(char inst)
6056 bool len = (inst == XC_INST_LENGTH);
6058 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6059 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6060 opnd = bc_vec_top(&G.prog.results);
6062 s = zbc_program_num(opnd, &num, false);
6063 if (s) RETURN_STATUS(s);
6066 if (!BC_PROG_NUM(opnd, num) && !len)
6067 RETURN_STATUS(bc_error_variable_is_wrong_type());
6070 bc_num_init_DEF_SIZE(&res.d.n);
6072 if (inst == XC_INST_SQRT)
6073 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6075 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6076 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6080 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6082 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6084 str = bc_program_str(idx);
6085 bc_num_ulong2num(&res.d.n, strlen(*str));
6089 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6092 bc_program_retire(&res, XC_RESULT_TEMP);
6096 #define zbc_program_builtin(...) (zbc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6099 static BC_STATUS zdc_program_divmod(void)
6102 BcResult *opd1, *opd2, res, res2;
6105 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6106 if (s) RETURN_STATUS(s);
6108 bc_num_init_DEF_SIZE(&res.d.n);
6109 bc_num_init(&res2.d.n, n2->len);
6111 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6114 bc_program_binOpRetire(&res2);
6115 res.t = XC_RESULT_TEMP;
6116 bc_vec_push(&G.prog.results, &res);
6120 bc_num_free(&res2.d.n);
6121 bc_num_free(&res.d.n);
6124 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6126 static BC_STATUS zdc_program_modexp(void)
6129 BcResult *r1, *r2, *r3, res;
6130 BcNum *n1, *n2, *n3;
6132 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6133 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6134 s = zbc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6135 if (s) RETURN_STATUS(s);
6137 r1 = bc_vec_item_rev(&G.prog.results, 2);
6138 s = zbc_program_num(r1, &n1, false);
6139 if (s) RETURN_STATUS(s);
6140 if (!BC_PROG_NUM(r1, n1))
6141 RETURN_STATUS(bc_error_variable_is_wrong_type());
6143 // Make sure that the values have their pointers updated, if necessary.
6144 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6145 if (r1->t == r2->t) {
6146 s = zbc_program_num(r2, &n2, false);
6147 if (s) RETURN_STATUS(s);
6149 if (r1->t == r3->t) {
6150 s = zbc_program_num(r3, &n3, false);
6151 if (s) RETURN_STATUS(s);
6155 bc_num_init(&res.d.n, n3->len);
6156 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6159 bc_vec_pop(&G.prog.results);
6160 bc_program_binOpRetire(&res);
6164 bc_num_free(&res.d.n);
6167 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6169 static void dc_program_stackLen(void)
6172 size_t len = G.prog.results.len;
6174 res.t = XC_RESULT_TEMP;
6176 bc_num_init_DEF_SIZE(&res.d.n);
6177 bc_num_ulong2num(&res.d.n, len);
6178 bc_vec_push(&G.prog.results, &res);
6181 static BC_STATUS zdc_program_asciify(void)
6191 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6192 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6193 r = bc_vec_top(&G.prog.results);
6195 s = zbc_program_num(r, &num, false);
6196 if (s) RETURN_STATUS(s);
6198 if (BC_PROG_NUM(r, num)) {
6201 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6203 bc_num_init_DEF_SIZE(&n);
6204 bc_num_copy(&n, num);
6205 bc_num_truncate(&n, n.rdx);
6207 strmb.cap = ARRAY_SIZE(strmb_digs);
6208 strmb.num = strmb_digs;
6209 bc_num_ulong2num(&strmb, 0x100);
6210 s = zbc_num_mod(&n, &strmb, &n, 0);
6212 if (s) goto num_err;
6213 s = zbc_num_ulong(&n, &val);
6214 if (s) goto num_err;
6221 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6222 sp = *bc_program_str(idx);
6226 strs = (void*)G.prog.strs.v;
6227 for (idx = 0; idx < G.prog.strs.len; idx++) {
6228 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6234 //str[1] = '\0'; - already is
6235 bc_vec_push(&G.prog.strs, &str);
6237 res.t = XC_RESULT_STR;
6239 bc_result_pop_and_push(&res);
6241 RETURN_STATUS(BC_STATUS_SUCCESS);
6246 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6248 static BC_STATUS zdc_program_printStream(void)
6255 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6256 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6257 r = bc_vec_top(&G.prog.results);
6259 s = zbc_program_num(r, &n, false);
6260 if (s) RETURN_STATUS(s);
6262 if (BC_PROG_NUM(r, n)) {
6263 s = zbc_num_printNum(n, 0x100, 1, dc_num_printChar);
6266 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6267 str = *bc_program_str(idx);
6273 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6275 static BC_STATUS zdc_program_nquit(void)
6282 s = zbc_program_prep(&opnd, &num);
6283 if (s) RETURN_STATUS(s);
6284 s = zbc_num_ulong(num, &val);
6285 if (s) RETURN_STATUS(s);
6287 bc_vec_pop(&G.prog.results);
6289 if (G.prog.exestack.len < val)
6290 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6291 if (G.prog.exestack.len == val) {
6292 QUIT_OR_RETURN_TO_MAIN;
6295 bc_vec_npop(&G.prog.exestack, val);
6299 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6301 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6303 BcStatus s = BC_STATUS_SUCCESS;
6309 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6310 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6312 r = bc_vec_top(&G.prog.results);
6315 BcNum *n = n; // for compiler
6318 char *then_name = bc_program_name(code, bgn);
6319 char *else_name = NULL;
6321 if (code[*bgn] == '\0')
6324 else_name = bc_program_name(code, bgn);
6326 exec = r->d.n.len != 0;
6328 if (!exec && else_name != NULL) {
6335 v = bc_program_search(name, true);
6342 if (!exec) goto exit;
6343 if (!BC_PROG_STR(n)) {
6344 s = bc_error_variable_is_wrong_type();
6350 if (r->t == XC_RESULT_STR) {
6352 } else if (r->t == XC_RESULT_VAR) {
6354 s = zbc_program_num(r, &n, false);
6355 if (s || !BC_PROG_STR(n)) goto exit;
6361 fidx = sidx + BC_PROG_REQ_FUNCS;
6363 f = bc_program_func(fidx);
6365 if (f->code.len == 0) {
6369 sv_parse = G.prs; // struct copy
6370 bc_parse_create(fidx);
6371 str = *bc_program_str(sidx);
6372 s = zbc_parse_text_init(str);
6375 s = zdc_parse_exprs_until_eof();
6377 bc_parse_push(DC_INST_POP_EXEC);
6378 if (G.prs.lex != XC_LEX_EOF)
6379 s = bc_error_bad_expression();
6381 G.prs = sv_parse; // struct copy
6384 bc_vec_pop_all(&f->code);
6392 bc_vec_pop(&G.prog.results);
6393 bc_vec_push(&G.prog.exestack, &ip);
6395 RETURN_STATUS(BC_STATUS_SUCCESS);
6397 bc_vec_pop(&G.prog.results);
6400 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6403 static void bc_program_pushGlobal(char inst)
6408 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6409 if (inst == XC_INST_IBASE)
6410 val = (unsigned long) G.prog.ib_t;
6411 else if (inst == XC_INST_SCALE)
6412 val = (unsigned long) G.prog.scale;
6414 val = (unsigned long) G.prog.ob_t;
6416 bc_num_init_DEF_SIZE(&res.d.n);
6417 bc_num_ulong2num(&res.d.n, val);
6418 bc_vec_push(&G.prog.results, &res);
6421 static BC_STATUS zbc_program_exec(void)
6424 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6425 BcFunc *func = bc_program_func(ip->func);
6426 char *code = func->code.v;
6428 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6429 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6430 while (ip->inst_idx < func->code.len) {
6431 BcStatus s = BC_STATUS_SUCCESS;
6432 char inst = code[ip->inst_idx++];
6434 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6437 case BC_INST_JUMP_ZERO: {
6440 dbg_exec("BC_INST_JUMP_ZERO:");
6441 s = zbc_program_prep(&ptr, &num);
6442 if (s) RETURN_STATUS(s);
6443 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6444 bc_vec_pop(&G.prog.results);
6446 bc_program_index(code, &ip->inst_idx);
6449 // else: fall through
6451 case BC_INST_JUMP: {
6452 size_t idx = bc_program_index(code, &ip->inst_idx);
6453 size_t *addr = bc_vec_item(&func->labels, idx);
6454 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6455 ip->inst_idx = *addr;
6459 dbg_exec("BC_INST_CALL:");
6460 s = zbc_program_call(code, &ip->inst_idx);
6461 goto read_updated_ip;
6462 case BC_INST_INC_PRE:
6463 case BC_INST_DEC_PRE:
6464 case BC_INST_INC_POST:
6465 case BC_INST_DEC_POST:
6466 dbg_exec("BC_INST_INCDEC:");
6467 s = zbc_program_incdec(inst);
6470 dbg_exec("BC_INST_HALT:");
6471 QUIT_OR_RETURN_TO_MAIN;
6475 dbg_exec("BC_INST_RET[0]:");
6476 s = zbc_program_return(inst);
6477 goto read_updated_ip;
6478 case XC_INST_BOOL_OR:
6479 case XC_INST_BOOL_AND:
6481 case XC_INST_REL_EQ:
6482 case XC_INST_REL_LE:
6483 case XC_INST_REL_GE:
6484 case XC_INST_REL_NE:
6485 case XC_INST_REL_LT:
6486 case XC_INST_REL_GT:
6487 dbg_exec("BC_INST_BOOL:");
6488 s = zbc_program_logical(inst);
6491 dbg_exec("XC_INST_READ:");
6492 s = zbc_program_read();
6493 goto read_updated_ip;
6495 dbg_exec("XC_INST_VAR:");
6496 s = zbc_program_pushVar(code, &ip->inst_idx, false, false);
6498 case XC_INST_ARRAY_ELEM:
6500 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6501 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6505 dbg_exec("BC_INST_LAST:");
6506 r.t = BC_RESULT_LAST;
6507 bc_vec_push(&G.prog.results, &r);
6513 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6514 bc_program_pushGlobal(inst);
6516 case XC_INST_SCALE_FUNC:
6517 case XC_INST_LENGTH:
6519 dbg_exec("BC_INST_builtin:");
6520 s = zbc_program_builtin(inst);
6523 dbg_exec("XC_INST_NUM:");
6524 r.t = XC_RESULT_CONSTANT;
6525 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6526 bc_vec_push(&G.prog.results, &r);
6529 dbg_exec("XC_INST_POP:");
6530 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6531 s = bc_error_stack_has_too_few_elements();
6533 bc_vec_pop(&G.prog.results);
6536 case XC_INST_PRINT_POP:
6537 case XC_INST_PRINT_STR:
6538 dbg_exec("XC_INST_PRINTxyz:");
6539 s = zbc_program_print(inst, 0);
6542 dbg_exec("XC_INST_STR:");
6543 r.t = XC_RESULT_STR;
6544 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6545 bc_vec_push(&G.prog.results, &r);
6548 case XC_INST_MULTIPLY:
6549 case XC_INST_DIVIDE:
6550 case XC_INST_MODULUS:
6553 dbg_exec("BC_INST_binaryop:");
6554 s = zbc_program_op(inst);
6556 case XC_INST_BOOL_NOT: {
6558 dbg_exec("XC_INST_BOOL_NOT:");
6559 s = zbc_program_prep(&ptr, &num);
6560 if (s) RETURN_STATUS(s);
6561 bc_num_init_DEF_SIZE(&r.d.n);
6562 if (bc_num_cmp(num, &G.prog.zero) == 0)
6564 //else bc_num_zero(&r.d.n); - already is
6565 bc_program_retire(&r, XC_RESULT_TEMP);
6569 dbg_exec("XC_INST_NEG:");
6570 s = zbc_program_negate();
6573 case BC_INST_ASSIGN_POWER:
6574 case BC_INST_ASSIGN_MULTIPLY:
6575 case BC_INST_ASSIGN_DIVIDE:
6576 case BC_INST_ASSIGN_MODULUS:
6577 case BC_INST_ASSIGN_PLUS:
6578 case BC_INST_ASSIGN_MINUS:
6580 case XC_INST_ASSIGN:
6581 dbg_exec("BC_INST_ASSIGNxyz:");
6582 s = zbc_program_assign(inst);
6585 case DC_INST_POP_EXEC:
6586 dbg_exec("DC_INST_POP_EXEC:");
6587 bc_vec_pop(&G.prog.exestack);
6588 goto read_updated_ip;
6589 case DC_INST_MODEXP:
6590 dbg_exec("DC_INST_MODEXP:");
6591 s = zdc_program_modexp();
6593 case DC_INST_DIVMOD:
6594 dbg_exec("DC_INST_DIVMOD:");
6595 s = zdc_program_divmod();
6597 case DC_INST_EXECUTE:
6598 case DC_INST_EXEC_COND:
6599 dbg_exec("DC_INST_EXEC[_COND]:");
6600 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6601 goto read_updated_ip;
6602 case DC_INST_PRINT_STACK: {
6604 dbg_exec("DC_INST_PRINT_STACK:");
6605 for (idx = 0; idx < G.prog.results.len; ++idx) {
6606 s = zbc_program_print(XC_INST_PRINT, idx);
6611 case DC_INST_CLEAR_STACK:
6612 dbg_exec("DC_INST_CLEAR_STACK:");
6613 bc_vec_pop_all(&G.prog.results);
6615 case DC_INST_STACK_LEN:
6616 dbg_exec("DC_INST_STACK_LEN:");
6617 dc_program_stackLen();
6619 case DC_INST_DUPLICATE:
6620 dbg_exec("DC_INST_DUPLICATE:");
6621 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6622 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6623 ptr = bc_vec_top(&G.prog.results);
6624 dc_result_copy(&r, ptr);
6625 bc_vec_push(&G.prog.results, &r);
6627 case DC_INST_SWAP: {
6629 dbg_exec("DC_INST_SWAP:");
6630 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6631 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6632 ptr = bc_vec_item_rev(&G.prog.results, 0);
6633 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6634 memcpy(&r, ptr, sizeof(BcResult));
6635 memcpy(ptr, ptr2, sizeof(BcResult));
6636 memcpy(ptr2, &r, sizeof(BcResult));
6639 case DC_INST_ASCIIFY:
6640 dbg_exec("DC_INST_ASCIIFY:");
6641 s = zdc_program_asciify();
6643 case DC_INST_PRINT_STREAM:
6644 dbg_exec("DC_INST_PRINT_STREAM:");
6645 s = zdc_program_printStream();
6648 case DC_INST_PUSH_VAR: {
6649 bool copy = inst == DC_INST_LOAD;
6650 s = zbc_program_pushVar(code, &ip->inst_idx, true, copy);
6653 case DC_INST_PUSH_TO_VAR: {
6654 char *name = bc_program_name(code, &ip->inst_idx);
6655 s = zbc_program_copyToVar(name, true);
6660 dbg_exec("DC_INST_QUIT:");
6661 if (G.prog.exestack.len <= 2)
6662 QUIT_OR_RETURN_TO_MAIN;
6663 bc_vec_npop(&G.prog.exestack, 2);
6664 goto read_updated_ip;
6666 dbg_exec("DC_INST_NQUIT:");
6667 s = zdc_program_nquit();
6668 //goto read_updated_ip; - just fall through to it
6671 // Instruction stack has changed, read new pointers
6672 ip = bc_vec_top(&G.prog.exestack);
6673 func = bc_program_func(ip->func);
6674 code = func->code.v;
6675 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6678 if (s || G_interrupt) {
6686 RETURN_STATUS(BC_STATUS_SUCCESS);
6688 #define zbc_program_exec(...) (zbc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6690 static unsigned bc_vm_envLen(const char *var)
6696 len = BC_NUM_PRINT_WIDTH;
6697 if (!lenv) return len;
6699 len = bb_strtou(lenv, NULL, 10) - 1;
6700 if (errno || len < 2 || len >= INT_MAX)
6701 len = BC_NUM_PRINT_WIDTH;
6706 static BC_STATUS zbc_vm_process(const char *text)
6710 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6711 s = zbc_parse_text_init(text); // does the first zbc_lex_next()
6712 if (s) RETURN_STATUS(s);
6715 while (G.prs.lex != XC_LEX_EOF) {
6719 dbg_lex("%s:%d G.prs.lex:%d, parsing...", __func__, __LINE__, G.prs.lex);
6722 if (G.prs.lex == BC_LEX_SCOLON
6723 || G.prs.lex == XC_LEX_NLINE
6730 s = zbc_parse_stmt_or_funcdef();
6733 // Check that next token is a correct stmt delimiter -
6734 // disallows "print 1 print 2" and such.
6735 if (G.prs.lex != BC_LEX_SCOLON
6736 && G.prs.lex != XC_LEX_NLINE
6737 && G.prs.lex != XC_LEX_EOF
6740 //TODO: commonalize for other parse errors:
6741 err_at = G.prs.lex_next_at ? G.prs.lex_next_at : "UNKNOWN";
6742 bc_error_fmt("bad statement terminator at '%.*s'",
6743 (int)(strchrnul(err_at, '\n') - err_at),
6748 // The above logic is fragile. Check these examples:
6749 // - interative read() still works
6753 // Most of dc parsing assumes all whitespace,
6754 // including '\n', is eaten.
6755 while (G.prs.lex == XC_LEX_NLINE) {
6758 if (G.prs.lex == XC_LEX_EOF)
6761 s = zdc_parse_expr();
6764 if (s || G_interrupt) {
6766 bc_parse_reset(); // includes bc_program_reset()
6767 RETURN_STATUS(BC_STATUS_FAILURE);
6770 dbg_lex("%s:%d executing...", __func__, __LINE__);
6771 s = zbc_program_exec();
6777 ip = (void*)G.prog.exestack.v;
6779 if (G.prog.exestack.len != 1) // should have only main's IP
6780 bb_error_msg_and_die("BUG:call stack");
6781 if (ip->func != BC_PROG_MAIN)
6782 bb_error_msg_and_die("BUG:not MAIN");
6784 f = bc_program_func_BC_PROG_MAIN();
6785 // bc discards strings, constants and code after each
6786 // top-level statement in the "main program".
6787 // This prevents "yes 1 | bc" from growing its memory
6788 // without bound. This can be done because data stack
6789 // is empty and thus can't hold any references to
6790 // strings or constants, there is no generated code
6791 // which can hold references (after we discard one
6792 // we just executed). Code of functions can have references,
6793 // but bc stores function strings/constants in per-function
6797 if (G.prog.results.len != 0) // should be empty
6798 bb_error_msg_and_die("BUG:data stack");
6800 IF_BC(bc_vec_pop_all(&f->strs);)
6801 IF_BC(bc_vec_pop_all(&f->consts);)
6803 if (G.prog.results.len == 0
6804 && G.prog.vars.len == 0
6806 // If stack is empty and no registers exist (TODO: or they are all empty),
6807 // we can get rid of accumulated strings and constants.
6808 // In this example dc process should not grow
6809 // its memory consumption with time:
6811 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6812 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6814 // The code is discarded always (below), thus this example
6815 // should also not grow its memory consumption with time,
6816 // even though its data stack is not empty:
6817 // { echo 1; yes dk; } | dc
6819 // We drop generated and executed code for both bc and dc:
6820 bc_vec_pop_all(&f->code);
6824 dbg_lex_done("%s:%d done", __func__, __LINE__);
6827 #define zbc_vm_process(...) (zbc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6829 static BC_STATUS zbc_vm_execute_FILE(FILE *fp, const char *filename)
6831 // So far bc/dc have no way to include a file from another file,
6832 // therefore we know G.prs.lex_filename == NULL on entry
6833 //const char *sv_file;
6836 G.prs.lex_filename = filename;
6837 G.prs.lex_input_fp = fp;
6838 G.err_line = G.prs.lex_line = 1;
6841 s = zbc_vm_process("");
6842 // We do not stop looping on errors here if reading stdin.
6843 // Example: start interactive bc and enter "return".
6844 // It should say "'return' not in a function"
6845 // but should not exit.
6846 } while (G.prs.lex_input_fp == stdin);
6847 G.prs.lex_filename = NULL;
6850 #define zbc_vm_execute_FILE(...) (zbc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6852 static BC_STATUS zbc_vm_file(const char *file)
6857 fp = xfopen_for_read(file);
6858 s = zbc_vm_execute_FILE(fp, file);
6863 #define zbc_vm_file(...) (zbc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6866 static void bc_vm_info(void)
6868 printf("%s "BB_VER"\n"
6869 "Adapted from https://github.com/gavinhoward/bc\n"
6870 "Original code (c) 2018 Gavin D. Howard and contributors\n"
6874 static void bc_args(char **argv)
6880 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6881 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6882 "warn\0" No_argument "w"
6883 "version\0" No_argument "v"
6884 "standard\0" No_argument "s"
6885 "quiet\0" No_argument "q"
6886 "mathlib\0" No_argument "l"
6887 "interactive\0" No_argument "i"
6890 opts = option_mask32 |= getopt32(argv, "wvsqli");
6892 if (getenv("POSIXLY_CORRECT"))
6893 option_mask32 |= BC_FLAG_S;
6895 if (opts & BC_FLAG_V) {
6900 for (i = optind; argv[i]; ++i)
6901 bc_vec_push(&G.files, argv + i);
6904 static void bc_vm_envArgs(void)
6908 char *env_args = getenv("BC_ENV_ARGS");
6910 if (!env_args) return;
6912 G.env_args = xstrdup(env_args);
6915 bc_vec_init(&v, sizeof(char *), NULL);
6917 while (*(buf = skip_whitespace(buf)) != '\0') {
6918 bc_vec_push(&v, &buf);
6919 buf = skip_non_whitespace(buf);
6925 // NULL terminate, and pass argv[] so that first arg is argv[1]
6926 if (sizeof(int) == sizeof(char*)) {
6927 bc_vec_push(&v, &const_int_0);
6929 static char *const nullptr = NULL;
6930 bc_vec_push(&v, &nullptr);
6932 bc_args(((char **)v.v) - 1);
6937 static const char bc_lib[] ALIGN1 = {
6940 "\n" "auto b,s,n,r,d,i,p,f,v"
6941 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6942 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6943 //e(-.998896): GNU:.36828580434569428695
6944 // above code:.36828580434569428696
6945 // actual value:.3682858043456942869594...
6946 // but for now let's be "GNU compatible"
6955 "\n" "scale=scale(x)+1"
6965 "\n" "for(i=2;v;++i){"
6971 "\n" "while(d--)r*=r"
6974 "\n" "if(n)return(1/r)"
6978 "\n" "auto b,s,r,p,a,q,i,v"
6982 "\n" "r=(1-10^scale)/1"
6993 "\n" "while(x<=.5){"
6997 "\n" "r=a=(x-1)/(x+1)"
7000 "\n" "for(i=3;v;i+=2){"
7011 "\n" "auto b,s,r,a,q,i"
7012 "\n" "if(x<0)return(-s(-x))"
7016 "\n" "scale=1.1*s+2"
7025 "\n" "for(i=3;a;i+=2){"
7026 "\n" "a*=q/(i*(i-1))"
7039 "\n" "x=s(2*a(1)+x)"
7045 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7053 "\n" "if(scale<65){"
7054 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7055 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7065 "\n" "x=(x-.2)/(1+.2*x)"
7070 "\n" "for(i=3;t;i+=2){"
7077 "\n" "return((m*a+r)/n)"
7079 "\n" "define j(n,x){"
7080 "\n" "auto b,s,o,a,i,v,f"
7091 "\n" "for(i=2;i<=n;++i)a*=i"
7093 "\n" "a=(x^n)/2^n/a"
7096 "\n" "scale+=length(a)-scale(a)"
7097 "\n" "for(i=1;v;++i){"
7098 "\n" "v=v*f/i/(n+i)"
7104 "\n" "return(a*r/1)"
7109 static BC_STATUS zbc_vm_exec(void)
7116 if (option_mask32 & BC_FLAG_L) {
7117 // We know that internal library is not buggy,
7118 // thus error checking is normally disabled.
7119 # define DEBUG_LIB 0
7120 s = zbc_vm_process(bc_lib);
7121 if (DEBUG_LIB && s) RETURN_STATUS(s);
7125 s = BC_STATUS_SUCCESS;
7126 fname = (void*)G.files.v;
7127 for (i = 0; i < G.files.len; i++) {
7128 s = zbc_vm_file(*fname++);
7129 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7130 // Debug config, non-interactive mode:
7131 // return all the way back to main.
7132 // Non-debug builds do not come here
7133 // in non-interactive mode, they exit.
7138 if (IS_BC || (option_mask32 & BC_FLAG_I))
7139 s = zbc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7143 #define zbc_vm_exec(...) (zbc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7145 #if ENABLE_FEATURE_CLEAN_UP
7146 static void bc_program_free(void)
7148 bc_vec_free(&G.prog.fns);
7149 IF_BC(bc_vec_free(&G.prog.fn_map);)
7150 bc_vec_free(&G.prog.vars);
7151 bc_vec_free(&G.prog.var_map);
7152 bc_vec_free(&G.prog.arrs);
7153 bc_vec_free(&G.prog.arr_map);
7154 IF_DC(bc_vec_free(&G.prog.strs);)
7155 IF_DC(bc_vec_free(&G.prog.consts);)
7156 bc_vec_free(&G.prog.results);
7157 bc_vec_free(&G.prog.exestack);
7158 IF_BC(bc_num_free(&G.prog.last);)
7159 IF_BC(bc_num_free(&G.prog.zero);)
7160 IF_BC(bc_num_free(&G.prog.one);)
7161 bc_vec_free(&G.input_buffer);
7164 static void bc_vm_free(void)
7166 bc_vec_free(&G.files);
7173 static void bc_program_init(void)
7177 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7178 memset(&ip, 0, sizeof(BcInstPtr));
7180 // G.prog.nchars = G.prog.scale = 0; - already is
7184 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7185 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7187 bc_num_init_DEF_SIZE(&G.prog.zero);
7188 //bc_num_zero(&G.prog.zero); - already is
7190 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7191 IF_BC(bc_num_one(&G.prog.one);)
7193 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7194 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7197 // Names are chosen simply to be distinct and never match
7198 // a valid function name (and be short)
7199 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7200 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7202 // in dc, functions have no names
7203 bc_program_add_fn();
7204 bc_program_add_fn();
7207 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7208 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7210 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7211 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7213 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7214 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7215 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7216 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7217 bc_vec_push(&G.prog.exestack, &ip);
7219 bc_char_vec_init(&G.input_buffer);
7222 static int bc_vm_init(const char *env_len)
7224 #if ENABLE_FEATURE_EDITING
7225 G.line_input_state = new_line_input_t(DO_HISTORY);
7227 G.prog.len = bc_vm_envLen(env_len);
7229 bc_vec_init(&G.files, sizeof(char *), NULL);
7230 IF_BC(if (IS_BC) bc_vm_envArgs();)
7232 bc_parse_create(BC_PROG_MAIN);
7234 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7235 //-i option unconditionally enables this regardless of isatty():
7237 #if ENABLE_FEATURE_BC_SIGNALS
7239 // With SA_RESTART, most system calls will restart
7240 // (IOW: they won't fail with EINTR).
7241 // In particular, this means ^C won't cause
7242 // stdout to get into "error state" if SIGINT hits
7243 // within write() syscall.
7245 // The downside is that ^C while tty input is taken
7246 // will only be handled after [Enter] since read()
7247 // from stdin is not interrupted by ^C either,
7248 // it restarts, thus fgetc() does not return on ^C.
7249 // (This problem manifests only if line editing is disabled)
7250 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7252 // Without SA_RESTART, this exhibits a bug:
7253 // "while (1) print 1" and try ^C-ing it.
7254 // Intermittently, instead of returning to input line,
7255 // you'll get "output error: Interrupted system call"
7257 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7261 return 0; // "not a tty"
7264 static BcStatus bc_vm_run(void)
7266 BcStatus st = zbc_vm_exec();
7267 #if ENABLE_FEATURE_CLEAN_UP
7268 if (G_exiting) // it was actually "halt" or "quit"
7271 # if ENABLE_FEATURE_EDITING
7272 free_line_input_t(G.line_input_state);
7276 dbg_exec("exiting with exitcode %d", st);
7281 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7282 int bc_main(int argc UNUSED_PARAM, char **argv)
7288 is_tty = bc_vm_init("BC_LINE_LENGTH");
7292 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7300 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7301 int dc_main(int argc UNUSED_PARAM, char **argv)
7307 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7308 // 1 char wider than bc from the same package.
7309 // Both default width, and xC_LINE_LENGTH=N are wider:
7310 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7313 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7316 // Do the same, or it's a bug?
7317 bc_vm_init("DC_LINE_LENGTH");
7319 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7320 noscript = BC_FLAG_I;
7322 int n = getopt(argc, argv, "e:f:x");
7328 n = zbc_vm_process(optarg);
7333 n = zbc_vm_file(optarg);
7337 option_mask32 |= DC_FLAG_X;
7347 bc_vec_push(&G.files, argv++);
7350 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7356 #endif // not DC_SMALL