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 BC_LEX_KW_ENTRY(a, b) \
522 { .name8 = a /*, .posix = b */ }
523 static const struct BcLexKeyword bc_lex_kws[20] = {
524 BC_LEX_KW_ENTRY("auto" , 1), // 0
525 BC_LEX_KW_ENTRY("break" , 1), // 1
526 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
527 BC_LEX_KW_ENTRY("define" , 1), // 3
528 BC_LEX_KW_ENTRY("else" , 0), // 4
529 BC_LEX_KW_ENTRY("for" , 1), // 5
530 BC_LEX_KW_ENTRY("halt" , 0), // 6
531 BC_LEX_KW_ENTRY("ibase" , 1), // 7
532 BC_LEX_KW_ENTRY("obase" , 1), // 8
533 BC_LEX_KW_ENTRY("if" , 1), // 9
534 BC_LEX_KW_ENTRY("last" , 0), // 10
535 BC_LEX_KW_ENTRY("length" , 1), // 11
536 BC_LEX_KW_ENTRY("limits" , 0), // 12
537 BC_LEX_KW_ENTRY("print" , 0), // 13
538 BC_LEX_KW_ENTRY("quit" , 1), // 14
539 BC_LEX_KW_ENTRY("read" , 0), // 15
540 BC_LEX_KW_ENTRY("return" , 1), // 16
541 BC_LEX_KW_ENTRY("scale" , 1), // 17
542 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
543 BC_LEX_KW_ENTRY("while" , 1), // 19
545 #undef BC_LEX_KW_ENTRY
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 bc_lex_kws_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 BcLex {
715 const char *lex_next_at; // last lex_next() was called at this string
720 smallint lex; // was BcLexType
721 smallint lex_last; // was BcLexType
725 #define BC_PARSE_STREND (0xff)
728 # define BC_PARSE_REL (1 << 0)
729 # define BC_PARSE_PRINT (1 << 1)
730 # define BC_PARSE_ARRAY (1 << 2)
731 # define BC_PARSE_NOCALL (1 << 3)
734 typedef struct BcParse {
741 const char *filename;
747 IF_BC(size_t in_funcdef;)
750 typedef struct BcProgram {
778 #define BC_PROG_MAIN (0)
779 #define BC_PROG_READ (1)
781 #define BC_PROG_REQ_FUNCS (2)
784 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
785 #define BC_PROG_NUM(r, n) \
786 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
788 #define BC_FLAG_W (1 << 0)
789 #define BC_FLAG_V (1 << 1)
790 #define BC_FLAG_S (1 << 2)
791 #define BC_FLAG_Q (1 << 3)
792 #define BC_FLAG_L (1 << 4)
793 #define BC_FLAG_I (1 << 5)
794 #define DC_FLAG_X (1 << 6)
796 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
797 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
799 #define BC_MAX_OBASE ((unsigned) 999)
800 #define BC_MAX_DIM ((unsigned) INT_MAX)
801 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
802 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
803 #define BC_MAX_NUM BC_MAX_STRING
804 // Unused apart from "limits" message. Just show a "biggish number" there.
805 //#define BC_MAX_NAME BC_MAX_STRING
806 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
807 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
808 #define BC_MAX_NAME_STR "999999999"
809 #define BC_MAX_EXP_STR "999999999"
810 #define BC_MAX_VARS_STR "999999999"
812 #define BC_MAX_OBASE_STR "999"
814 #if INT_MAX == 2147483647
815 # define BC_MAX_DIM_STR "2147483647"
816 #elif INT_MAX == 9223372036854775807
817 # define BC_MAX_DIM_STR "9223372036854775807"
819 # error Strange INT_MAX
822 #if UINT_MAX == 4294967295
823 # define BC_MAX_SCALE_STR "4294967295"
824 # define BC_MAX_STRING_STR "4294967294"
825 #elif UINT_MAX == 18446744073709551615
826 # define BC_MAX_SCALE_STR "18446744073709551615"
827 # define BC_MAX_STRING_STR "18446744073709551614"
829 # error Strange UINT_MAX
831 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
834 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
835 IF_FEATURE_CLEAN_UP(smallint exiting;)
840 // For error messages. Can be set to current parsed line,
841 // or [TODO] to current executing line (can be before last parsed one)
849 #if ENABLE_FEATURE_EDITING
850 line_input_t *line_input_state;
853 #define G (*ptr_to_globals)
854 #define INIT_G() do { \
855 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
857 #define FREE_G() do { \
858 FREE_PTR_TO_GLOBALS(); \
860 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
861 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
862 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
863 #if ENABLE_FEATURE_BC_SIGNALS
864 # define G_interrupt bb_got_signal
865 # define G_ttyin G.ttyin
867 # define G_interrupt 0
870 #if ENABLE_FEATURE_CLEAN_UP
871 # define G_exiting G.exiting
875 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
876 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
878 // In configurations where errors abort instead of propagating error
879 // return code up the call chain, functions returning BC_STATUS
880 // actually don't return anything, they always succeed and return "void".
881 // A macro wrapper is provided, which makes this statement work:
883 // and makes it visible to the compiler that s is always zero,
884 // allowing compiler to optimize dead code after the statement.
886 // To make code more readable, each such function has a "z"
887 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
889 #if ENABLE_FEATURE_BC_SIGNALS || ENABLE_FEATURE_CLEAN_UP
890 # define ERRORS_ARE_FATAL 0
891 # define ERRORFUNC /*nothing*/
892 # define IF_ERROR_RETURN_POSSIBLE(a) a
893 # define BC_STATUS BcStatus
894 # define RETURN_STATUS(v) return (v)
895 # define COMMA_SUCCESS /*nothing*/
897 # define ERRORS_ARE_FATAL 1
898 # define ERRORFUNC NORETURN
899 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
900 # define BC_STATUS void
901 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
902 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
909 static void fflush_and_check(void)
912 if (ferror(stdout) || ferror(stderr))
913 bb_perror_msg_and_die("output error");
916 #if ENABLE_FEATURE_CLEAN_UP
917 #define QUIT_OR_RETURN_TO_MAIN \
919 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
921 return BC_STATUS_FAILURE; \
924 #define QUIT_OR_RETURN_TO_MAIN quit()
927 static void quit(void) NORETURN;
928 static void quit(void)
931 bb_perror_msg_and_die("input error");
933 dbg_exec("quit(): exiting with exitcode SUCCESS");
937 static void bc_verror_msg(const char *fmt, va_list p)
939 const char *sv = sv; // for compiler
940 if (G.prs.filename) {
942 applet_name = xasprintf("%s: %s:%u", applet_name, G.prs.filename, G.err_line);
944 bb_verror_msg(fmt, p, NULL);
945 if (G.prs.filename) {
946 free((char*)applet_name);
951 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
956 bc_verror_msg(fmt, p);
959 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
960 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
965 static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
969 // Are non-POSIX constructs totally ok?
970 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
971 RETURN_STATUS(BC_STATUS_SUCCESS); // yes
974 bc_verror_msg(fmt, p);
977 // Do we treat non-POSIX constructs as errors?
978 if (!(option_mask32 & BC_FLAG_S))
979 RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
981 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
982 RETURN_STATUS(BC_STATUS_FAILURE);
985 #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
988 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
989 // This idiom begs for tail-call optimization, but for it to work,
990 // function must not have caller-cleaned parameters on stack.
991 // Unfortunately, vararg function API does exactly that on most arches.
992 // Thus, use these shims for the cases when we have no vararg PARAMS:
993 static ERRORFUNC int bc_error(const char *msg)
995 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
997 static ERRORFUNC int bc_error_bad_character(char c)
1000 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
1001 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
1003 static ERRORFUNC int bc_error_bad_expression(void)
1005 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
1007 static ERRORFUNC int bc_error_bad_token(void)
1009 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
1011 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1013 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1015 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1017 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1020 static BC_STATUS zbc_POSIX_requires(const char *msg)
1022 RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
1024 #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
1025 static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
1027 RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
1029 #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
1030 static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1032 RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; this is bad:", msg));
1034 #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)
1035 static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1037 RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in 'for()'", "POSIX does not allow ", msg));
1039 #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)
1042 static void bc_vec_grow(BcVec *v, size_t n)
1044 size_t cap = v->cap * 2;
1045 while (cap < v->len + n) cap *= 2;
1046 v->v = xrealloc(v->v, v->size * cap);
1050 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1053 v->cap = BC_VEC_START_CAP;
1056 v->v = xmalloc(esize * BC_VEC_START_CAP);
1059 static void bc_char_vec_init(BcVec *v)
1061 bc_vec_init(v, sizeof(char), NULL);
1064 static void bc_vec_expand(BcVec *v, size_t req)
1067 v->v = xrealloc(v->v, v->size * req);
1072 static void bc_vec_pop(BcVec *v)
1076 v->dtor(v->v + (v->size * v->len));
1079 static void bc_vec_npop(BcVec *v, size_t n)
1084 size_t len = v->len - n;
1085 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1089 static void bc_vec_pop_all(BcVec *v)
1091 bc_vec_npop(v, v->len);
1094 static size_t bc_vec_push(BcVec *v, const void *data)
1096 size_t len = v->len;
1097 if (len >= v->cap) bc_vec_grow(v, 1);
1098 memmove(v->v + (v->size * len), data, v->size);
1103 // G.prog.results often needs "pop old operand, push result" idiom.
1104 // Can do this without a few extra ops
1105 static size_t bc_result_pop_and_push(const void *data)
1107 BcVec *v = &G.prog.results;
1109 size_t len = v->len - 1;
1111 last = v->v + (v->size * len);
1114 memmove(last, data, v->size);
1118 static size_t bc_vec_pushByte(BcVec *v, char data)
1120 return bc_vec_push(v, &data);
1123 static size_t bc_vec_pushZeroByte(BcVec *v)
1125 //return bc_vec_pushByte(v, '\0');
1127 return bc_vec_push(v, &const_int_0);
1130 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1133 bc_vec_push(v, data);
1137 if (v->len == v->cap) bc_vec_grow(v, 1);
1139 ptr = v->v + v->size * idx;
1141 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1142 memmove(ptr, data, v->size);
1146 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1149 bc_vec_expand(v, len + 1);
1150 memcpy(v->v, str, len);
1153 bc_vec_pushZeroByte(v);
1156 #if ENABLE_FEATURE_BC_SIGNALS && ENABLE_FEATURE_EDITING
1157 static void bc_vec_concat(BcVec *v, const char *str)
1161 if (v->len == 0) bc_vec_pushZeroByte(v);
1164 len = v->len + slen;
1166 if (v->cap < len) bc_vec_grow(v, slen);
1167 strcpy(v->v + v->len - 1, str);
1173 static void *bc_vec_item(const BcVec *v, size_t idx)
1175 return v->v + v->size * idx;
1178 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1180 return v->v + v->size * (v->len - idx - 1);
1183 static void *bc_vec_top(const BcVec *v)
1185 return v->v + v->size * (v->len - 1);
1188 static FAST_FUNC void bc_vec_free(void *vec)
1190 BcVec *v = (BcVec *) vec;
1195 static BcFunc* bc_program_func(size_t idx)
1197 return bc_vec_item(&G.prog.fns, idx);
1199 // BC_PROG_MAIN is zeroth element, so:
1200 #define bc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1203 static BcFunc* bc_program_current_func(void)
1205 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1206 BcFunc *func = bc_program_func(ip->func);
1211 static char** bc_program_str(size_t idx)
1215 BcFunc *func = bc_program_current_func();
1216 return bc_vec_item(&func->strs, idx);
1219 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1222 static char** bc_program_const(size_t idx)
1226 BcFunc *func = bc_program_current_func();
1227 return bc_vec_item(&func->consts, idx);
1230 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1233 static int bc_id_cmp(const void *e1, const void *e2)
1235 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1238 static FAST_FUNC void bc_id_free(void *id)
1240 free(((BcId *) id)->name);
1243 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1245 size_t low = 0, high = v->len;
1247 while (low < high) {
1248 size_t mid = (low + high) / 2;
1249 BcId *id = bc_vec_item(v, mid);
1250 int result = bc_id_cmp(ptr, id);
1263 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1265 size_t n = *i = bc_map_find_ge(v, ptr);
1268 bc_vec_push(v, ptr);
1269 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1270 return 0; // "was not inserted"
1272 bc_vec_pushAt(v, ptr, n);
1273 return 1; // "was inserted"
1277 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1279 size_t i = bc_map_find_ge(v, ptr);
1280 if (i >= v->len) return BC_VEC_INVALID_IDX;
1281 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1285 static void bc_num_setToZero(BcNum *n, size_t scale)
1292 static void bc_num_zero(BcNum *n)
1294 bc_num_setToZero(n, 0);
1297 static void bc_num_one(BcNum *n)
1299 bc_num_setToZero(n, 0);
1304 // Note: this also sets BcNum to zero
1305 static void bc_num_init(BcNum *n, size_t req)
1307 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1308 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1309 n->num = xmalloc(req);
1316 static void bc_num_init_DEF_SIZE(BcNum *n)
1318 bc_num_init(n, BC_NUM_DEF_SIZE);
1321 static void bc_num_expand(BcNum *n, size_t req)
1323 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1325 n->num = xrealloc(n->num, req);
1330 static FAST_FUNC void bc_num_free(void *num)
1332 free(((BcNum *) num)->num);
1335 static void bc_num_copy(BcNum *d, BcNum *s)
1338 bc_num_expand(d, s->cap);
1342 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1346 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1349 unsigned long result;
1353 while (i > n->rdx) {
1354 unsigned long prev = result;
1355 result = result * 10 + n->num[--i];
1356 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1357 // 0x1ff00000 * 10 is 0x13f600000,
1358 // or 0x3f600000 truncated to 32 bits. Which is larger.
1359 // However, (N*10)/8 < N check is always correct.
1360 if ((result / 8) < prev)
1361 RETURN_STATUS(bc_error("overflow"));
1365 RETURN_STATUS(BC_STATUS_SUCCESS);
1367 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1369 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1371 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1373 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1375 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1377 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1378 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1379 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1380 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1382 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1383 // would not hit realloc() code path - not good if num[] is not malloced
1385 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1391 if (val == 0) return;
1393 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1400 if (val == 0) break;
1404 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1407 for (i = 0; i < len; ++i) {
1409 for (j = i; a[j] < 0;) {
1416 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1434 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1435 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1436 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1437 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1438 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1440 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1442 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1443 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1445 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1448 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1450 size_t i, min, a_int, b_int, diff;
1451 BcDig *max_num, *min_num;
1455 if (a == b) return 0;
1456 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1457 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1459 if (a->neg != b->neg) // signs of a and b differ
1460 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1461 return (int)b->neg - (int)a->neg;
1462 neg = a->neg; // 1 if both negative, 0 if both positive
1464 a_int = BC_NUM_INT(a);
1465 b_int = BC_NUM_INT(b);
1468 if (a_int != 0) return (ssize_t) a_int;
1470 a_max = (a->rdx > b->rdx);
1473 diff = a->rdx - b->rdx;
1474 max_num = a->num + diff;
1476 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1479 diff = b->rdx - a->rdx;
1480 max_num = b->num + diff;
1482 neg = !neg; // same as "neg = (a_max == neg)"
1485 cmp = bc_num_compare(max_num, min_num, b_int + min);
1486 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1488 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1489 if (max_num[i]) return BC_NUM_NEG(1, neg);
1495 static void bc_num_truncate(BcNum *n, size_t places)
1497 if (places == 0) return;
1503 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1507 static void bc_num_extend(BcNum *n, size_t places)
1509 size_t len = n->len + places;
1512 if (n->cap < len) bc_num_expand(n, len);
1514 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1515 memset(n->num, 0, sizeof(BcDig) * places);
1522 static void bc_num_clean(BcNum *n)
1524 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1527 else if (n->len < n->rdx)
1531 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1534 bc_num_extend(n, scale - n->rdx);
1536 bc_num_truncate(n, n->rdx - scale);
1539 if (n->len != 0) n->neg = !neg1 != !neg2;
1542 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1546 b->len = n->len - idx;
1548 a->rdx = b->rdx = 0;
1550 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1551 memcpy(a->num, n->num, idx * sizeof(BcDig));
1561 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1563 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1565 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1566 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1567 if (places + n->len > BC_MAX_NUM)
1568 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1571 if (n->rdx >= places)
1574 bc_num_extend(n, places - n->rdx);
1580 RETURN_STATUS(BC_STATUS_SUCCESS);
1582 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1584 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1586 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1587 BcNumBinaryOp op, size_t req)
1590 BcNum num2, *ptr_a, *ptr_b;
1595 memcpy(ptr_a, c, sizeof(BcNum));
1603 memcpy(ptr_b, c, sizeof(BcNum));
1610 bc_num_init(c, req);
1612 bc_num_expand(c, req);
1614 s = BC_STATUS_SUCCESS;
1615 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1617 if (init) bc_num_free(&num2);
1621 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1623 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1624 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1625 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1626 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1627 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1628 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1630 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1632 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1634 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1637 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1639 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1641 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1644 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1646 size_t req = BC_NUM_MREQ(a, b, scale);
1647 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1650 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1652 size_t req = BC_NUM_MREQ(a, b, scale);
1653 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1656 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1658 size_t req = BC_NUM_MREQ(a, b, scale);
1659 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1662 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1664 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1667 static const BcNumBinaryOp zbc_program_ops[] = {
1668 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1670 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1671 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1672 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1673 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1674 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1675 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1677 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1686 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1688 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1690 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1692 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1693 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1696 // Because this function doesn't need to use scale (per the bc spec),
1697 // I am hijacking it to say whether it's doing an add or a subtract.
1701 if (sub && c->len) c->neg = !c->neg;
1702 RETURN_STATUS(BC_STATUS_SUCCESS);
1706 RETURN_STATUS(BC_STATUS_SUCCESS);
1710 c->rdx = BC_MAX(a->rdx, b->rdx);
1711 min_rdx = BC_MIN(a->rdx, b->rdx);
1714 if (a->rdx > b->rdx) {
1715 diff = a->rdx - b->rdx;
1717 ptr_a = a->num + diff;
1720 diff = b->rdx - a->rdx;
1723 ptr_b = b->num + diff;
1727 for (i = 0; i < diff; ++i, ++c->len)
1731 a_int = BC_NUM_INT(a);
1732 b_int = BC_NUM_INT(b);
1734 if (a_int > b_int) {
1745 for (i = 0; i < min_rdx + min_int; ++i) {
1746 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1748 ptr_c[i] = (BcDig)(in % 10);
1750 for (; i < max + min_rdx; ++i) {
1751 unsigned in = (unsigned)ptr[i] + carry;
1753 ptr_c[i] = (BcDig)(in % 10);
1757 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1759 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1762 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1765 BcNum *minuend, *subtrahend;
1767 bool aneg, bneg, neg;
1769 // Because this function doesn't need to use scale (per the bc spec),
1770 // I am hijacking it to say whether it's doing an add or a subtract.
1774 if (sub && c->len) c->neg = !c->neg;
1775 RETURN_STATUS(BC_STATUS_SUCCESS);
1779 RETURN_STATUS(BC_STATUS_SUCCESS);
1784 a->neg = b->neg = false;
1786 cmp = bc_num_cmp(a, b);
1792 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1793 RETURN_STATUS(BC_STATUS_SUCCESS);
1801 if (sub) neg = !neg;
1806 bc_num_copy(c, minuend);
1809 if (c->rdx < subtrahend->rdx) {
1810 bc_num_extend(c, subtrahend->rdx - c->rdx);
1813 start = c->rdx - subtrahend->rdx;
1815 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1819 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1822 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1824 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1827 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1828 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1831 if (a->len == 0 || b->len == 0) {
1833 RETURN_STATUS(BC_STATUS_SUCCESS);
1835 aone = BC_NUM_ONE(a);
1836 if (aone || BC_NUM_ONE(b)) {
1837 bc_num_copy(c, aone ? b : a);
1838 RETURN_STATUS(BC_STATUS_SUCCESS);
1841 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1842 || a->len < BC_NUM_KARATSUBA_LEN
1843 || b->len < BC_NUM_KARATSUBA_LEN
1847 bc_num_expand(c, a->len + b->len + 1);
1849 memset(c->num, 0, sizeof(BcDig) * c->cap);
1852 for (i = 0; i < b->len; ++i) {
1854 for (j = 0; j < a->len; ++j) {
1855 unsigned in = c->num[i + j];
1856 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1857 // note: compilers prefer _unsigned_ div/const
1859 c->num[i + j] = (BcDig)(in % 10);
1862 c->num[i + j] += (BcDig) carry;
1863 len = BC_MAX(len, i + j + !!carry);
1865 #if ENABLE_FEATURE_BC_SIGNALS
1867 // a*a <- without check below, this will not be interruptible
1868 if (G_interrupt) return BC_STATUS_FAILURE;
1874 RETURN_STATUS(BC_STATUS_SUCCESS);
1877 bc_num_init(&l1, max);
1878 bc_num_init(&h1, max);
1879 bc_num_init(&l2, max);
1880 bc_num_init(&h2, max);
1881 bc_num_init(&m1, max);
1882 bc_num_init(&m2, max);
1883 bc_num_init(&z0, max);
1884 bc_num_init(&z1, max);
1885 bc_num_init(&z2, max);
1886 bc_num_init(&temp, max + max);
1888 bc_num_split(a, max2, &l1, &h1);
1889 bc_num_split(b, max2, &l2, &h2);
1891 s = zbc_num_add(&h1, &l1, &m1, 0);
1893 s = zbc_num_add(&h2, &l2, &m2, 0);
1896 s = zbc_num_k(&h1, &h2, &z0);
1898 s = zbc_num_k(&m1, &m2, &z1);
1900 s = zbc_num_k(&l1, &l2, &z2);
1903 s = zbc_num_sub(&z1, &z0, &temp, 0);
1905 s = zbc_num_sub(&temp, &z2, &z1, 0);
1908 s = zbc_num_shift(&z0, max2 * 2);
1910 s = zbc_num_shift(&z1, max2);
1912 s = zbc_num_add(&z0, &z1, &temp, 0);
1914 s = zbc_num_add(&temp, &z2, c, 0);
1929 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1933 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1935 scale = BC_MAX(scale, a->rdx);
1936 scale = BC_MAX(scale, b->rdx);
1937 scale = BC_MIN(a->rdx + b->rdx, scale);
1938 maxrdx = BC_MAX(maxrdx, scale);
1940 bc_num_init(&cpa, a->len);
1941 bc_num_init(&cpb, b->len);
1943 bc_num_copy(&cpa, a);
1944 bc_num_copy(&cpb, b);
1945 cpa.neg = cpb.neg = false;
1947 s = zbc_num_shift(&cpa, maxrdx);
1949 s = zbc_num_shift(&cpb, maxrdx);
1951 s = zbc_num_k(&cpa, &cpb, c);
1955 bc_num_expand(c, c->len + maxrdx);
1957 if (c->len < maxrdx) {
1958 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1963 bc_num_retireMul(c, scale, a->neg, b->neg);
1969 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1971 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1978 RETURN_STATUS(bc_error("divide by zero"));
1980 bc_num_setToZero(c, scale);
1981 RETURN_STATUS(BC_STATUS_SUCCESS);
1983 if (BC_NUM_ONE(b)) {
1985 bc_num_retireMul(c, scale, a->neg, b->neg);
1986 RETURN_STATUS(BC_STATUS_SUCCESS);
1989 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1990 bc_num_copy(&cp, a);
1994 bc_num_expand(&cp, len + 2);
1995 bc_num_extend(&cp, len - cp.len);
1998 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
2000 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
2002 if (b->rdx == b->len) {
2004 if (len == 0) break;
2006 if (b->num[len] != 0)
2012 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
2014 // We want an extra zero in front to make things simpler.
2015 cp.num[cp.len++] = 0;
2018 bc_num_expand(c, cp.len);
2021 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2025 s = BC_STATUS_SUCCESS;
2026 for (i = end - 1; i < end; --i) {
2029 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2030 bc_num_subArrays(n, b->num, len);
2032 #if ENABLE_FEATURE_BC_SIGNALS
2035 // 1/a <- without check below, this will not be interruptible
2037 s = BC_STATUS_FAILURE;
2043 bc_num_retireMul(c, scale, a->neg, b->neg);
2048 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2050 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2051 BcNum *restrict d, size_t scale, size_t ts)
2058 RETURN_STATUS(bc_error("divide by zero"));
2061 bc_num_setToZero(d, ts);
2062 RETURN_STATUS(BC_STATUS_SUCCESS);
2065 bc_num_init(&temp, d->cap);
2066 s = zbc_num_d(a, b, c, scale);
2069 if (scale != 0) scale = ts;
2071 s = zbc_num_m(c, b, &temp, scale);
2073 s = zbc_num_sub(a, &temp, d, scale);
2076 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2079 bc_num_retireMul(d, ts, a->neg, b->neg);
2085 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2087 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2091 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2093 bc_num_init(&c1, len);
2094 s = zbc_num_r(a, b, &c1, c, scale, ts);
2099 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2101 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2103 BcStatus s = BC_STATUS_SUCCESS;
2106 size_t i, powrdx, resrdx;
2109 // GNU bc does not allow 2^2.0 - we do
2110 for (i = 0; i < b->rdx; i++)
2112 RETURN_STATUS(bc_error("not an integer"));
2116 RETURN_STATUS(BC_STATUS_SUCCESS);
2119 bc_num_setToZero(c, scale);
2120 RETURN_STATUS(BC_STATUS_SUCCESS);
2122 if (BC_NUM_ONE(b)) {
2126 s = zbc_num_inv(a, c, scale);
2131 s = zbc_num_ulong_abs(b, &pow);
2132 if (s) RETURN_STATUS(s);
2133 // b is not used beyond this point
2135 bc_num_init(©, a->len);
2136 bc_num_copy(©, a);
2141 if (a->rdx * pow < scale)
2142 scale = a->rdx * pow;
2146 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2148 s = zbc_num_mul(©, ©, ©, powrdx);
2150 // Not needed: zbc_num_mul() has a check for ^C:
2151 //if (G_interrupt) {
2152 // s = BC_STATUS_FAILURE;
2157 bc_num_copy(c, ©);
2159 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2161 s = zbc_num_mul(©, ©, ©, powrdx);
2166 s = zbc_num_mul(c, ©, c, resrdx);
2169 // Not needed: zbc_num_mul() has a check for ^C:
2170 //if (G_interrupt) {
2171 // s = BC_STATUS_FAILURE;
2177 s = zbc_num_inv(c, c, scale);
2181 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2183 // We can't use bc_num_clean() here.
2184 for (i = 0; i < c->len; ++i)
2187 bc_num_setToZero(c, scale);
2194 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2196 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2199 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2200 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2201 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2203 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2204 bc_num_expand(b, req);
2207 bc_num_setToZero(b, scale);
2208 RETURN_STATUS(BC_STATUS_SUCCESS);
2211 RETURN_STATUS(bc_error("negative number"));
2213 if (BC_NUM_ONE(a)) {
2215 bc_num_extend(b, scale);
2216 RETURN_STATUS(BC_STATUS_SUCCESS);
2219 scale = BC_MAX(scale, a->rdx) + 1;
2220 len = a->len + scale;
2222 bc_num_init(&num1, len);
2223 bc_num_init(&num2, len);
2224 bc_num_init_DEF_SIZE(&half);
2230 bc_num_init(&f, len);
2231 bc_num_init(&fprime, len);
2237 pow = BC_NUM_INT(a);
2245 pow -= 2 - (pow & 1);
2247 bc_num_extend(x0, pow);
2249 // Make sure to move the radix back.
2253 x0->rdx = digs = digs1 = 0;
2255 len = BC_NUM_INT(x0) + resrdx - 1;
2257 while (cmp != 0 || digs < len) {
2258 s = zbc_num_div(a, x0, &f, resrdx);
2260 s = zbc_num_add(x0, &f, &fprime, resrdx);
2262 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2265 cmp = bc_num_cmp(x1, x0);
2266 digs = x1->len - (unsigned long long) llabs(cmp);
2268 if (cmp == cmp2 && digs == digs1)
2273 resrdx += times > 4;
2286 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2288 bc_num_free(&fprime);
2295 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2297 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2303 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2306 memcpy(&num2, c, sizeof(BcNum));
2308 bc_num_init(c, len);
2312 bc_num_expand(c, len);
2315 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2317 if (init) bc_num_free(&num2);
2321 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2324 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2327 BcNum base, exp, two, temp;
2331 RETURN_STATUS(bc_error("divide by zero"));
2332 if (a->rdx || b->rdx || c->rdx)
2333 RETURN_STATUS(bc_error("not an integer"));
2335 RETURN_STATUS(bc_error("negative number"));
2337 bc_num_expand(d, c->len);
2338 bc_num_init(&base, c->len);
2339 bc_num_init(&exp, b->len);
2340 bc_num_init(&temp, b->len);
2342 two.cap = ARRAY_SIZE(two_digs);
2349 s = zbc_num_rem(a, c, &base, 0);
2351 bc_num_copy(&exp, b);
2353 while (exp.len != 0) {
2354 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2357 if (BC_NUM_ONE(&temp)) {
2358 s = zbc_num_mul(d, &base, &temp, 0);
2360 s = zbc_num_rem(&temp, c, d, 0);
2364 s = zbc_num_mul(&base, &base, &temp, 0);
2366 s = zbc_num_rem(&temp, c, &base, 0);
2375 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2378 static FAST_FUNC void bc_string_free(void *string)
2380 free(*(char**)string);
2383 static void bc_func_init(BcFunc *f)
2385 bc_char_vec_init(&f->code);
2386 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2387 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2388 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2389 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2390 IF_BC(f->nparams = 0;)
2393 static FAST_FUNC void bc_func_free(void *func)
2395 BcFunc *f = (BcFunc *) func;
2396 bc_vec_free(&f->code);
2397 IF_BC(bc_vec_free(&f->labels);)
2398 IF_BC(bc_vec_free(&f->autos);)
2399 IF_BC(bc_vec_free(&f->strs);)
2400 IF_BC(bc_vec_free(&f->consts);)
2403 static void bc_array_expand(BcVec *a, size_t len);
2405 static void bc_array_init(BcVec *a, bool nums)
2408 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2410 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2411 bc_array_expand(a, 1);
2414 static void bc_array_expand(BcVec *a, size_t len)
2416 if (a->dtor == bc_num_free
2417 // && a->size == sizeof(BcNum) - always true
2420 while (len > a->len) {
2421 bc_num_init_DEF_SIZE(&n);
2426 while (len > a->len) {
2427 bc_array_init(&v, true);
2433 static void bc_array_copy(BcVec *d, const BcVec *s)
2439 bc_vec_expand(d, s->cap);
2444 for (i = 0; i < s->len; i++, dnum++, snum++) {
2445 bc_num_init(dnum, snum->len);
2446 bc_num_copy(dnum, snum);
2451 static void dc_result_copy(BcResult *d, BcResult *src)
2456 case XC_RESULT_TEMP:
2457 case XC_RESULT_IBASE:
2458 case XC_RESULT_SCALE:
2459 case XC_RESULT_OBASE:
2460 bc_num_init(&d->d.n, src->d.n.len);
2461 bc_num_copy(&d->d.n, &src->d.n);
2464 case XC_RESULT_ARRAY:
2465 case XC_RESULT_ARRAY_ELEM:
2466 d->d.id.name = xstrdup(src->d.id.name);
2468 case XC_RESULT_CONSTANT:
2469 IF_BC(case BC_RESULT_LAST:)
2470 IF_BC(case BC_RESULT_ONE:)
2472 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2478 static FAST_FUNC void bc_result_free(void *result)
2480 BcResult *r = (BcResult *) result;
2483 case XC_RESULT_TEMP:
2484 case XC_RESULT_IBASE:
2485 case XC_RESULT_SCALE:
2486 case XC_RESULT_OBASE:
2487 bc_num_free(&r->d.n);
2490 case XC_RESULT_ARRAY:
2491 case XC_RESULT_ARRAY_ELEM:
2500 static int bad_input_byte(char c)
2502 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2505 bc_error_fmt("illegal character 0x%02x", c);
2511 // Note: it _appends_ data from fp to vec.
2512 static void bc_read_line(BcVec *vec, FILE *fp)
2517 #if ENABLE_FEATURE_BC_SIGNALS
2518 if (G_interrupt) { // ^C was pressed
2521 // ^C while running a script (bc SCRIPT): die.
2522 // We do not return to interactive prompt:
2523 // user might be running us from a shell,
2524 // and SCRIPT might be intended to terminate
2525 // (e.g. contain a "halt" stmt).
2526 // ^C dropping user into a bc prompt instead of
2527 // the shell would be unexpected.
2530 // ^C while interactive input
2532 // GNU bc says "interrupted execution."
2533 // GNU dc says "Interrupt!"
2534 fputs("\ninterrupted execution\n", stderr);
2537 # if ENABLE_FEATURE_EDITING
2538 if (G_ttyin && fp == stdin) {
2540 # define line_buf bb_common_bufsiz1
2541 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2542 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2545 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2550 char c = line_buf[i++];
2552 if (bad_input_byte(c)) goto again;
2554 bc_vec_concat(vec, line_buf);
2562 size_t len = vec->len;
2565 #if ENABLE_FEATURE_BC_SIGNALS
2567 // ^C was pressed: ignore entire line, get another one
2572 do c = fgetc(fp); while (c == '\0');
2575 bb_perror_msg_and_die("input error");
2576 // Note: EOF does not append '\n'
2579 bad_chars |= bad_input_byte(c);
2580 bc_vec_pushByte(vec, (char)c);
2581 } while (c != '\n');
2584 // Bad chars on this line
2585 if (!G.prs.filename) { // stdin
2586 // ignore entire line, get another one
2590 bb_perror_msg_and_die("file '%s' is not text", G.prs.filename);
2592 bc_vec_pushZeroByte(vec);
2600 static bool bc_num_strValid(const char *val, size_t base)
2605 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2612 if (radix) return false;
2616 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2622 // Note: n is already "bc_num_zero()"ed,
2623 // leading zeroes in "val" are removed
2624 static void bc_num_parseDecimal(BcNum *n, const char *val)
2633 bc_num_expand(n, len);
2635 ptr = strchr(val, '.');
2639 n->rdx = (size_t)((val + len) - (ptr + 1));
2641 for (i = 0; val[i]; ++i) {
2642 if (val[i] != '0' && val[i] != '.') {
2643 // Not entirely zero value - convert it, and exit
2646 n->num[n->len] = val[i] - '0';
2650 if (val[--i] == '.') goto skip_dot;
2655 // if for() exits without hitting if(), the value is entirely zero
2658 // Note: n is already "bc_num_zero()"ed,
2659 // leading zeroes in "val" are removed
2660 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2663 BcNum temp, mult, result;
2665 BcDig base_digs[ULONG_NUM_BUFSIZE];
2670 for (i = 0; ; ++i) {
2673 if (val[i] != '.' && val[i] != '0')
2677 bc_num_init_DEF_SIZE(&temp);
2678 bc_num_init_DEF_SIZE(&mult);
2679 base.cap = ARRAY_SIZE(base_digs);
2680 base.num = base_digs;
2681 bc_num_ulong2num(&base, base_t);
2685 if (c == '\0') goto int_err;
2686 if (c == '.') break;
2688 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2690 s = zbc_num_mul(n, &base, &mult, 0);
2691 if (s) goto int_err;
2692 bc_num_ulong2num(&temp, v);
2693 s = zbc_num_add(&mult, &temp, n, 0);
2694 if (s) goto int_err;
2697 bc_num_init(&result, base.len);
2698 //bc_num_zero(&result); - already is
2704 if (c == '\0') break;
2707 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2709 s = zbc_num_mul(&result, &base, &result, 0);
2711 bc_num_ulong2num(&temp, v);
2712 s = zbc_num_add(&result, &temp, &result, 0);
2714 s = zbc_num_mul(&mult, &base, &mult, 0);
2718 s = zbc_num_div(&result, &mult, &result, digits);
2720 s = zbc_num_add(n, &result, n, digits);
2724 if (n->rdx < digits)
2725 bc_num_extend(n, digits - n->rdx);
2729 bc_num_free(&result);
2735 static BC_STATUS zbc_num_parse(BcNum *n, const char *val, unsigned base_t)
2737 if (!bc_num_strValid(val, base_t))
2738 RETURN_STATUS(bc_error("bad number string"));
2741 while (*val == '0') val++;
2744 bc_num_parseDecimal(n, val);
2746 bc_num_parseBase(n, val, base_t);
2748 RETURN_STATUS(BC_STATUS_SUCCESS);
2750 #define zbc_num_parse(...) (zbc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2752 static void bc_lex_lineComment(void)
2754 BcLex *l = &G.prs.l;
2755 // Try: echo -n '#foo' | bc
2757 l->lex = XC_LEX_WHITESPACE;
2759 while (i < l->len && l->buf[i] != '\n')
2764 static void bc_lex_whitespace(void)
2766 BcLex *l = &G.prs.l;
2767 l->lex = XC_LEX_WHITESPACE;
2769 char c = l->buf[l->i];
2770 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2778 static BC_STATUS zbc_lex_number(char start)
2780 BcLex *l = &G.prs.l;
2781 const char *buf = l->buf + l->i;
2782 size_t len, i, ccnt;
2785 pt = (start == '.');
2786 l->lex = XC_LEX_NUMBER;
2792 if (c == '\\' && buf[i + 1] == '\n') {
2794 //number_of_backslashes++ - see comment below
2797 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2798 if (c != '.') break;
2799 // if '.' was already seen, stop on second one:
2803 // buf[i] is one of "0-9A-F."
2808 //ccnt is the number of chars in the number string, excluding possible
2809 //trailing "[\<newline>].[\<newline>]" (with any number of \<NL> repetitions).
2810 //i is buf[i] index of the first not-yet-parsed char after that.
2813 // This might overestimate the size, if there are "\<NL>"'s
2814 // in the number. Subtracting number_of_backslashes*2 correctly
2815 // is not that easy: consider that in the case of "NNN.\<NL>"
2816 // loop above will count "\<NL>" before it realizes it is not
2817 // in fact *inside* the number:
2818 len = ccnt + 1; // +1 byte for NUL termination
2820 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2821 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2822 if (len > BC_MAX_NUM)
2823 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
2826 bc_vec_pop_all(&l->lex_buf);
2827 bc_vec_expand(&l->lex_buf, 1 + len);
2828 bc_vec_push(&l->lex_buf, &start);
2831 // If we have hit a backslash, skip it. We don't have
2832 // to check for a newline because it's guaranteed.
2838 bc_vec_push(&l->lex_buf, buf);
2843 bc_vec_pushZeroByte(&l->lex_buf);
2845 RETURN_STATUS(BC_STATUS_SUCCESS);
2847 #define zbc_lex_number(...) (zbc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2849 static void bc_lex_name(void)
2851 BcLex *l = &G.prs.l;
2855 l->lex = XC_LEX_NAME;
2858 buf = l->buf + l->i - 1;
2861 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2865 #if 0 // We do not protect against people with gigabyte-long names
2866 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2867 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2868 if (i > BC_MAX_STRING)
2869 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2872 bc_vec_string(&l->lex_buf, i, buf);
2874 // Increment the index. We minus 1 because it has already been incremented.
2877 //return BC_STATUS_SUCCESS;
2880 static void bc_lex_init(void)
2882 bc_char_vec_init(&G.prs.l.lex_buf);
2885 static void bc_lex_free(void)
2887 bc_vec_free(&G.prs.l.lex_buf);
2890 static void bc_lex_file(void)
2892 G.err_line = G.prs.l.line = 1;
2893 G.prs.l.newline = false;
2896 static bool bc_lex_more_input(void)
2898 BcLex *l = &G.prs.l;
2902 bc_vec_pop_all(&G.input_buffer);
2904 // This loop is complex because the vm tries not to send any lines that end
2905 // with a backslash to the parser. The reason for that is because the parser
2906 // treats a backslash+newline combo as whitespace, per the bc spec. In that
2907 // case, and for strings and comments, the parser will expect more stuff.
2911 size_t prevlen = G.input_buffer.len;
2914 bc_read_line(&G.input_buffer, G.prs.input_fp);
2915 // No more input means EOF
2916 if (G.input_buffer.len <= prevlen + 1) // (we expect +1 for NUL byte)
2919 string = G.input_buffer.v + prevlen;
2922 if (string == G.input_buffer.v || string[-1] != '\\') {
2933 if (c == '/' && *string == '*') {
2938 if (c == '*' && *string == '/') {
2943 if (str != 0 || comment) {
2944 G.input_buffer.len--; // backstep over the trailing NUL byte
2948 // Check for backslash+newline.
2949 // we do not check that last char is '\n' -
2950 // if it is not, then it's EOF, and looping back
2951 // to bc_read_line() will detect it:
2953 if (string >= G.input_buffer.v && *string == '\\') {
2954 G.input_buffer.len--;
2961 l->buf = G.input_buffer.v;
2963 // bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2964 l->len = G.input_buffer.len - 1; // do not include NUL
2969 IF_BC(static BC_STATUS zbc_lex_token(void);)
2970 IF_DC(static BC_STATUS zdc_lex_token(void);)
2971 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2972 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2974 static BC_STATUS zbc_lex_next(void)
2976 BcLex *l = &G.prs.l;
2979 l->lex_last = l->lex;
2980 if (l->lex_last == XC_LEX_EOF) RETURN_STATUS(bc_error("end of file"));
2982 l->line += l->newline;
2983 G.err_line = l->line;
2986 // Loop until failure or we don't have whitespace. This
2987 // is so the parser doesn't get inundated with whitespace.
2988 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2989 s = BC_STATUS_SUCCESS;
2991 if (l->i == l->len) {
2992 l->lex = XC_LEX_EOF;
2993 if (!G.prs.input_fp)
2994 RETURN_STATUS(BC_STATUS_SUCCESS);
2995 if (!bc_lex_more_input()) {
2996 G.prs.input_fp = NULL;
2997 RETURN_STATUS(BC_STATUS_SUCCESS);
2999 // here it's guaranteed that l->i is below l->len
3001 l->lex_next_at = l->buf + l->i;
3002 dbg_lex("next string to parse:'%.*s'",
3003 (int)(strchrnul(l->lex_next_at, '\n') - l->lex_next_at),
3007 IF_BC(s = zbc_lex_token());
3009 IF_DC(s = zdc_lex_token());
3011 } while (!s && l->lex == XC_LEX_WHITESPACE);
3012 dbg_lex("l->lex from string:%d", l->lex);
3016 #define zbc_lex_next(...) (zbc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
3019 static BC_STATUS zbc_lex_skip_if_at_NLINE(void)
3021 if (G.prs.l.lex == XC_LEX_NLINE)
3022 RETURN_STATUS(zbc_lex_next());
3023 RETURN_STATUS(BC_STATUS_SUCCESS);
3025 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3027 static BC_STATUS zbc_lex_next_and_skip_NLINE(void)
3031 if (s) RETURN_STATUS(s);
3032 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
3033 s = zbc_lex_skip_if_at_NLINE();
3036 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3039 static BC_STATUS zbc_lex_text_init(const char *text)
3043 G.prs.l.len = strlen(text);
3044 G.prs.l.lex = G.prs.l.lex_last = XC_LEX_INVALID;
3045 RETURN_STATUS(zbc_lex_next());
3047 #define zbc_lex_text_init(...) (zbc_lex_text_init(__VA_ARGS__) COMMA_SUCCESS)
3050 static BC_STATUS zbc_lex_identifier(void)
3052 BcLex *l = &G.prs.l;
3055 const char *buf = l->buf + l->i - 1;
3057 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3058 const char *keyword8 = bc_lex_kws[i].name8;
3060 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3062 if (j == 8) goto match;
3064 if (keyword8[j] != '\0')
3067 // buf starts with keyword bc_lex_kws[i]
3068 if (isalnum(buf[j]) || buf[j]=='_')
3069 continue; // "ifz" does not match "if" keyword, "if." does
3070 l->lex = BC_LEX_KEY_1st_keyword + i;
3071 if (!bc_lex_kws_POSIX(i)) {
3072 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3073 if (s) RETURN_STATUS(s);
3076 // We minus 1 because the index has already been incremented.
3078 RETURN_STATUS(BC_STATUS_SUCCESS);
3082 s = BC_STATUS_SUCCESS;
3084 if (l->lex_buf.len > 2) {
3087 // bc: POSIX only allows one character names; this is bad: 'qwe=1
3089 unsigned len = strchrnul(buf, '\n') - buf;
3090 s = zbc_posix_error_fmt("POSIX only allows one character names; this is bad: '%.*s'", len, buf);
3095 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3097 static BC_STATUS zbc_lex_string(void)
3099 BcLex *l = &G.prs.l;
3102 l->lex = XC_LEX_STR;
3110 RETURN_STATUS(bc_error("unterminated string"));
3119 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3120 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3121 if (len > BC_MAX_STRING)
3122 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3124 bc_vec_string(&l->lex_buf, len, l->buf + l->i);
3128 G.err_line = l->line;
3130 RETURN_STATUS(BC_STATUS_SUCCESS);
3132 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3134 static void bc_lex_assign(unsigned with_and_without)
3136 BcLex *l = &G.prs.l;
3137 if (l->buf[l->i] == '=') {
3139 with_and_without >>= 8; // store "with" value
3140 } // else store "without" value
3141 l->lex = (with_and_without & 0xff);
3143 #define bc_lex_assign(with, without) \
3144 bc_lex_assign(((with)<<8)|(without))
3146 static BC_STATUS zbc_lex_comment(void)
3148 BcLex *l = &G.prs.l;
3150 const char *buf = l->buf;
3152 l->lex = XC_LEX_WHITESPACE;
3153 i = l->i; /* here buf[l->i] is the '*' of opening comment delimiter */
3165 RETURN_STATUS(bc_error("unterminated comment"));
3172 G.err_line = l->line;
3174 RETURN_STATUS(BC_STATUS_SUCCESS);
3176 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3178 #undef zbc_lex_token
3179 static BC_STATUS zbc_lex_token(void)
3181 BcLex *l = &G.prs.l;
3182 BcStatus s = BC_STATUS_SUCCESS;
3183 char c = l->buf[l->i++], c2;
3185 // This is the workhorse of the lexer.
3187 // case '\0': // probably never reached
3189 // l->lex = XC_LEX_EOF;
3190 // l->newline = true;
3193 l->lex = XC_LEX_NLINE;
3201 bc_lex_whitespace();
3204 bc_lex_assign(XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3205 if (l->lex == BC_LEX_OP_BOOL_NOT) {
3206 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3207 if (s) RETURN_STATUS(s);
3211 s = zbc_lex_string();
3214 s = zbc_POSIX_does_not_allow("'#' script comments");
3215 if (s) RETURN_STATUS(s);
3216 bc_lex_lineComment();
3219 bc_lex_assign(BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3224 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3225 if (s) RETURN_STATUS(s);
3227 l->lex = BC_LEX_OP_BOOL_AND;
3229 l->lex = XC_LEX_INVALID;
3230 s = bc_error_bad_character('&');
3235 l->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3238 bc_lex_assign(BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3244 l->lex = BC_LEX_OP_INC;
3246 bc_lex_assign(BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3249 l->lex = BC_LEX_COMMA;
3255 l->lex = BC_LEX_OP_DEC;
3257 bc_lex_assign(BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3260 if (isdigit(l->buf[l->i]))
3261 s = zbc_lex_number(c);
3263 l->lex = BC_LEX_KEY_LAST;
3264 s = zbc_POSIX_does_not_allow("'.' as 'last'");
3270 s = zbc_lex_comment();
3272 bc_lex_assign(BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3290 s = zbc_lex_number(c);
3293 l->lex = BC_LEX_SCOLON;
3296 bc_lex_assign(XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3299 bc_lex_assign(XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3302 bc_lex_assign(XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3306 l->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3309 if (l->buf[l->i] == '\n') {
3310 l->lex = XC_LEX_WHITESPACE;
3313 s = bc_error_bad_character(c);
3316 bc_lex_assign(BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3344 s = zbc_lex_identifier();
3348 l->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3353 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3354 if (s) RETURN_STATUS(s);
3356 l->lex = BC_LEX_OP_BOOL_OR;
3358 l->lex = XC_LEX_INVALID;
3359 s = bc_error_bad_character(c);
3363 l->lex = XC_LEX_INVALID;
3364 s = bc_error_bad_character(c);
3370 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3374 static BC_STATUS zdc_lex_register(void)
3376 BcLex *l = &G.prs.l;
3377 if (G_exreg && isspace(l->buf[l->i])) {
3378 bc_lex_whitespace(); // eats whitespace (but not newline)
3379 l->i++; // bc_lex_name() expects this
3382 bc_vec_pop_all(&l->lex_buf);
3383 bc_vec_push(&l->lex_buf, &l->buf[l->i++]);
3384 bc_vec_pushZeroByte(&l->lex_buf);
3385 l->lex = XC_LEX_NAME;
3388 RETURN_STATUS(BC_STATUS_SUCCESS);
3390 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3392 static BC_STATUS zdc_lex_string(void)
3394 BcLex *l = &G.prs.l;
3395 size_t depth, nls, i;
3397 l->lex = XC_LEX_STR;
3398 bc_vec_pop_all(&l->lex_buf);
3407 RETURN_STATUS(bc_error("string end could not be found"));
3410 if (i == l->i || l->buf[i - 1] != '\\') {
3411 if (c == '[') depth++;
3416 bc_vec_push(&l->lex_buf, &l->buf[i]);
3421 bc_vec_pushZeroByte(&l->lex_buf);
3422 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3423 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3424 if (i - l->i > BC_MAX_STRING)
3425 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3430 G.err_line = l->line;
3432 RETURN_STATUS(BC_STATUS_SUCCESS);
3434 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3436 #undef zdc_lex_token
3437 static BC_STATUS zdc_lex_token(void)
3439 BcLex *l = &G.prs.l;
3440 static const //BcLexType - should be this type, but narrower type saves size:
3443 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3444 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3445 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3453 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3454 if (l->lex_last == dc_lex_regs[i])
3455 RETURN_STATUS(zdc_lex_register());
3458 s = BC_STATUS_SUCCESS;
3460 if (c >= '%' && c <= '~'
3461 && (l->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3466 // This is the workhorse of the lexer.
3468 // case '\0': // probably never reached
3469 // l->lex = XC_LEX_EOF;
3472 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3473 // (and "case '\n':" is not just empty here)
3474 // only to allow interactive dc have a way to exit
3475 // "parse" stage of "parse,execute" loop
3476 // on <enter>, not on _next_ token (which would mean
3477 // commands are not executed on pressing <enter>).
3478 // IOW: typing "1p<enter>" should print "1" _at once_,
3479 // not after some more input.
3480 l->lex = XC_LEX_NLINE;
3488 l->newline = 0; // was (c == '\n')
3489 bc_lex_whitespace();
3494 l->lex = XC_LEX_OP_REL_NE;
3496 l->lex = XC_LEX_OP_REL_LE;
3498 l->lex = XC_LEX_OP_REL_GE;
3500 RETURN_STATUS(bc_error_bad_character(c));
3504 bc_lex_lineComment();
3507 if (isdigit(l->buf[l->i]))
3508 s = zbc_lex_number(c);
3510 s = bc_error_bad_character(c);
3528 s = zbc_lex_number(c);
3531 s = zdc_lex_string();
3534 l->lex = XC_LEX_INVALID;
3535 s = bc_error_bad_character(c);
3541 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3544 static void bc_parse_push(char i)
3546 BcParse *p = &G.prs;
3547 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, p->func->code.len, i);
3548 bc_vec_pushByte(&p->func->code, i);
3551 static void bc_parse_pushName(char *name)
3554 bc_parse_push(*name++);
3555 bc_parse_push(BC_PARSE_STREND);
3558 static void bc_parse_pushIndex(size_t idx)
3563 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3564 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3567 if (idx & mask) break;
3575 bc_parse_push((unsigned char)idx);
3581 static void bc_parse_pushJUMP(size_t idx)
3583 bc_parse_push(BC_INST_JUMP);
3584 bc_parse_pushIndex(idx);
3587 static void bc_parse_pushJUMP_ZERO(size_t idx)
3589 bc_parse_push(BC_INST_JUMP_ZERO);
3590 bc_parse_pushIndex(idx);
3593 static BC_STATUS zbc_parse_pushSTR(void)
3595 BcParse *p = &G.prs;
3596 char *str = xstrdup(p->l.lex_buf.v);
3598 bc_parse_push(XC_INST_STR);
3599 bc_parse_pushIndex(p->func->strs.len);
3600 bc_vec_push(&p->func->strs, &str);
3602 RETURN_STATUS(zbc_lex_next());
3604 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3607 static void bc_parse_pushNUM(void)
3609 BcParse *p = &G.prs;
3610 char *num = xstrdup(p->l.lex_buf.v);
3611 #if ENABLE_BC && ENABLE_DC
3612 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3614 size_t idx = bc_vec_push(&p->func->consts, &num);
3616 size_t idx = bc_vec_push(&G.prog.consts, &num);
3618 bc_parse_push(XC_INST_NUM);
3619 bc_parse_pushIndex(idx);
3622 static BC_STATUS zbc_parse_text_init(const char *text)
3624 BcParse *p = &G.prs;
3625 p->func = bc_program_func(p->fidx);
3627 RETURN_STATUS(zbc_lex_text_init(text));
3629 #define zbc_parse_text_init(...) (zbc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3631 // Called when parsing or execution detects a failure,
3632 // resets execution structures.
3633 static void bc_program_reset(void)
3638 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3639 bc_vec_pop_all(&G.prog.results);
3641 f = bc_program_func_BC_PROG_MAIN();
3642 ip = bc_vec_top(&G.prog.exestack);
3643 ip->inst_idx = f->code.len;
3646 // Called when parsing code detects a failure,
3647 // resets parsing structures.
3648 static void bc_parse_reset(void)
3650 BcParse *p = &G.prs;
3651 if (p->fidx != BC_PROG_MAIN) {
3652 bc_func_free(p->func);
3653 bc_func_init(p->func);
3655 p->fidx = BC_PROG_MAIN;
3656 p->func = bc_program_func_BC_PROG_MAIN();
3660 p->l.lex = XC_LEX_EOF;
3662 IF_BC(bc_vec_pop_all(&p->exits);)
3663 IF_BC(bc_vec_pop_all(&p->conds);)
3664 IF_BC(bc_vec_pop_all(&p->ops);)
3669 static void bc_parse_free(void)
3671 BcParse *p = &G.prs;
3672 IF_BC(bc_vec_free(&p->exits);)
3673 IF_BC(bc_vec_free(&p->conds);)
3674 IF_BC(bc_vec_free(&p->ops);)
3678 static void bc_parse_create(size_t fidx)
3680 BcParse *p = &G.prs;
3681 memset(p, 0, sizeof(BcParse));
3684 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3685 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3686 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3689 p->func = bc_program_func(fidx);
3692 static void bc_program_add_fn(void)
3698 bc_vec_push(&G.prog.fns, &f);
3704 // Note: takes ownership of 'name' (must be malloced)
3705 static size_t bc_program_addFunc(char *name)
3708 BcId entry, *entry_ptr;
3712 entry.idx = G.prog.fns.len;
3714 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3715 if (!inserted) free(name);
3717 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3718 idx = entry_ptr->idx;
3721 // There is already a function with this name.
3722 // It'll be redefined now, clear old definition.
3723 BcFunc *func = bc_program_func(entry_ptr->idx);
3727 bc_program_add_fn();
3733 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3734 // We can calculate the conversion between tokens and exprs by subtracting the
3735 // position of the first operator in the lex enum and adding the position of the
3736 // first in the expr enum. Note: This only works for binary operators.
3737 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3739 static BcStatus bc_parse_expr_empty_ok(uint8_t flags);
3741 static BC_STATUS zbc_parse_expr(uint8_t flags)
3745 s = bc_parse_expr_empty_ok(flags);
3746 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3747 RETURN_STATUS(bc_error("empty expression"));
3750 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3752 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed);
3753 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3755 static BC_STATUS zbc_parse_stmt(void)
3757 RETURN_STATUS(zbc_parse_stmt_possibly_auto(false));
3759 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3761 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(const char *after_X)
3763 BcParse *p = &G.prs;
3764 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3765 // Same for "else", "while()", "for()".
3766 BcStatus s = zbc_lex_next_and_skip_NLINE();
3767 if (s) RETURN_STATUS(s);
3768 if (p->l.lex == XC_LEX_NLINE)
3769 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3771 RETURN_STATUS(zbc_parse_stmt());
3773 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3775 static void bc_parse_operator(BcLexType type, size_t start, size_t *nexprs)
3777 BcParse *p = &G.prs;
3778 char l, r = bc_parse_op_PREC(type - XC_LEX_1st_op);
3779 bool left = bc_parse_op_LEFT(type - XC_LEX_1st_op);
3781 while (p->ops.len > start) {
3782 BcLexType t = BC_PARSE_TOP_OP(p);
3783 if (t == BC_LEX_LPAREN) break;
3785 l = bc_parse_op_PREC(t - XC_LEX_1st_op);
3786 if (l >= r && (l != r || !left)) break;
3788 bc_parse_push(BC_TOKEN_2_INST(t));
3789 bc_vec_pop(&p->ops);
3790 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3793 bc_vec_push(&p->ops, &type);
3796 static BC_STATUS zbc_parse_rightParen(size_t ops_bgn, size_t *nexs)
3798 BcParse *p = &G.prs;
3801 if (p->ops.len <= ops_bgn)
3802 RETURN_STATUS(bc_error_bad_expression());
3803 top = BC_PARSE_TOP_OP(p);
3805 while (top != BC_LEX_LPAREN) {
3806 bc_parse_push(BC_TOKEN_2_INST(top));
3808 bc_vec_pop(&p->ops);
3809 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3811 if (p->ops.len <= ops_bgn)
3812 RETURN_STATUS(bc_error_bad_expression());
3813 top = BC_PARSE_TOP_OP(p);
3816 bc_vec_pop(&p->ops);
3818 RETURN_STATUS(BC_STATUS_SUCCESS);
3820 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3822 static BC_STATUS zbc_parse_params(uint8_t flags)
3824 BcParse *p = &G.prs;
3828 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
3829 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3832 if (s) RETURN_STATUS(s);
3835 if (p->l.lex != BC_LEX_RPAREN) {
3837 s = zbc_parse_expr(flags);
3838 if (s) RETURN_STATUS(s);
3840 if (p->l.lex != BC_LEX_COMMA) {
3841 if (p->l.lex == BC_LEX_RPAREN)
3843 RETURN_STATUS(bc_error_bad_token());
3846 if (s) RETURN_STATUS(s);
3850 bc_parse_push(BC_INST_CALL);
3851 bc_parse_pushIndex(nparams);
3853 RETURN_STATUS(BC_STATUS_SUCCESS);
3855 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3857 // Note: takes ownership of 'name' (must be malloced)
3858 static BC_STATUS zbc_parse_call(char *name, uint8_t flags)
3860 BcParse *p = &G.prs;
3862 BcId entry, *entry_ptr;
3867 s = zbc_parse_params(flags);
3870 if (p->l.lex != BC_LEX_RPAREN) {
3871 s = bc_error_bad_token();
3875 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3877 if (idx == BC_VEC_INVALID_IDX) {
3878 // No such function exists, create an empty one
3879 bc_program_addFunc(name);
3880 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3884 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3885 bc_parse_pushIndex(entry_ptr->idx);
3887 RETURN_STATUS(zbc_lex_next());
3892 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3894 static BC_STATUS zbc_parse_name(BcInst *type, uint8_t flags)
3896 BcParse *p = &G.prs;
3900 name = xstrdup(p->l.lex_buf.v);
3904 if (p->l.lex == BC_LEX_LBRACKET) {
3908 if (p->l.lex == BC_LEX_RBRACKET) {
3909 if (!(flags & BC_PARSE_ARRAY)) {
3910 s = bc_error_bad_expression();
3913 *type = XC_INST_ARRAY;
3915 *type = XC_INST_ARRAY_ELEM;
3916 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3917 s = zbc_parse_expr(flags);
3922 bc_parse_push(*type);
3923 bc_parse_pushName(name);
3925 } else if (p->l.lex == BC_LEX_LPAREN) {
3926 if (flags & BC_PARSE_NOCALL) {
3927 s = bc_error_bad_token();
3930 *type = BC_INST_CALL;
3931 s = zbc_parse_call(name, flags);
3933 *type = XC_INST_VAR;
3934 bc_parse_push(XC_INST_VAR);
3935 bc_parse_pushName(name);
3944 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3946 static BC_STATUS zbc_parse_read(void)
3948 BcParse *p = &G.prs;
3952 if (s) RETURN_STATUS(s);
3953 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3956 if (s) RETURN_STATUS(s);
3957 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3959 bc_parse_push(XC_INST_READ);
3963 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3965 static BC_STATUS zbc_parse_builtin(BcLexType type, uint8_t flags, BcInst *prev)
3967 BcParse *p = &G.prs;
3971 if (s) RETURN_STATUS(s);
3972 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3974 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3977 if (s) RETURN_STATUS(s);
3979 s = zbc_parse_expr(flags);
3980 if (s) RETURN_STATUS(s);
3982 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3984 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3985 bc_parse_push(*prev);
3989 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3991 static BC_STATUS zbc_parse_scale(BcInst *type, uint8_t flags)
3993 BcParse *p = &G.prs;
3997 if (s) RETURN_STATUS(s);
3999 if (p->l.lex != BC_LEX_LPAREN) {
4000 *type = XC_INST_SCALE;
4001 bc_parse_push(XC_INST_SCALE);
4002 RETURN_STATUS(BC_STATUS_SUCCESS);
4005 *type = XC_INST_SCALE_FUNC;
4006 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
4009 if (s) RETURN_STATUS(s);
4011 s = zbc_parse_expr(flags);
4012 if (s) RETURN_STATUS(s);
4013 if (p->l.lex != BC_LEX_RPAREN)
4014 RETURN_STATUS(bc_error_bad_token());
4015 bc_parse_push(XC_INST_SCALE_FUNC);
4017 RETURN_STATUS(zbc_lex_next());
4019 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
4021 static BC_STATUS zbc_parse_incdec(BcInst *prev, bool *paren_expr,
4022 size_t *nexprs, uint8_t flags)
4024 BcParse *p = &G.prs;
4028 BcInst etype = *prev;
4030 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
4031 || etype == XC_INST_SCALE || etype == BC_INST_LAST
4032 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
4034 *prev = inst = BC_INST_INC_POST + (p->l.lex != BC_LEX_OP_INC);
4035 bc_parse_push(inst);
4038 *prev = inst = BC_INST_INC_PRE + (p->l.lex != BC_LEX_OP_INC);
4042 if (s) RETURN_STATUS(s);
4045 // Because we parse the next part of the expression
4046 // right here, we need to increment this.
4047 *nexprs = *nexprs + 1;
4051 s = zbc_parse_name(prev, flags | BC_PARSE_NOCALL);
4053 case BC_LEX_KEY_IBASE:
4054 case BC_LEX_KEY_LAST:
4055 case BC_LEX_KEY_OBASE:
4056 bc_parse_push(type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4059 case BC_LEX_KEY_SCALE:
4061 if (s) RETURN_STATUS(s);
4062 if (p->l.lex == BC_LEX_LPAREN)
4063 s = bc_error_bad_token();
4065 bc_parse_push(XC_INST_SCALE);
4068 s = bc_error_bad_token();
4072 if (!s) bc_parse_push(inst);
4077 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4080 #define BC_PARSE_LEAF(p, rparen) \
4082 || ((p) >= XC_INST_NUM && (p) <= XC_INST_SQRT) \
4083 || (p) == BC_INST_INC_POST \
4084 || (p) == BC_INST_DEC_POST \
4087 static int ok_in_expr(BcInst p)
4089 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
4090 || p == BC_INST_INC_POST
4091 || p == BC_INST_DEC_POST
4094 #define BC_PARSE_LEAF(p, rparen) ((rparen) || ok_in_expr(p))
4097 static BC_STATUS zbc_parse_minus(BcInst *prev, size_t ops_bgn,
4098 bool rparen, size_t *nexprs)
4100 BcParse *p = &G.prs;
4103 BcInst etype = *prev;
4106 if (s) RETURN_STATUS(s);
4108 type = BC_PARSE_LEAF(etype, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
4109 *prev = BC_TOKEN_2_INST(type);
4111 // We can just push onto the op stack because this is the largest
4112 // precedence operator that gets pushed. Inc/dec does not.
4113 if (type != XC_LEX_OP_MINUS)
4114 bc_vec_push(&p->ops, &type);
4116 bc_parse_operator(type, ops_bgn, nexprs);
4120 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4122 static BC_STATUS zbc_parse_print(void)
4124 BcParse *p = &G.prs;
4130 if (s) RETURN_STATUS(s);
4132 if (type == XC_LEX_STR) {
4133 s = zbc_parse_pushSTR();
4135 s = zbc_parse_expr(0);
4137 if (s) RETURN_STATUS(s);
4138 bc_parse_push(XC_INST_PRINT_POP);
4139 if (p->l.lex != BC_LEX_COMMA)
4145 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4147 static BC_STATUS zbc_parse_return(void)
4149 BcParse *p = &G.prs;
4153 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4155 if (s) RETURN_STATUS(s);
4158 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON)
4159 bc_parse_push(BC_INST_RET0);
4161 bool paren = (t == BC_LEX_LPAREN);
4162 s = bc_parse_expr_empty_ok(0);
4163 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4164 bc_parse_push(BC_INST_RET0);
4167 if (s) RETURN_STATUS(s);
4169 if (!paren || p->l.lex_last != BC_LEX_RPAREN) {
4170 s = zbc_POSIX_requires("parentheses around return expressions");
4171 if (s) RETURN_STATUS(s);
4174 bc_parse_push(XC_INST_RET);
4177 dbg_lex_done("%s:%d done", __func__, __LINE__);
4180 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4182 static void rewrite_label_to_current(size_t idx)
4184 BcParse *p = &G.prs;
4185 size_t *label = bc_vec_item(&p->func->labels, idx);
4186 *label = p->func->code.len;
4189 static BC_STATUS zbc_parse_if(void)
4191 BcParse *p = &G.prs;
4195 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4197 if (s) RETURN_STATUS(s);
4198 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4201 if (s) RETURN_STATUS(s);
4202 s = zbc_parse_expr(BC_PARSE_REL);
4203 if (s) RETURN_STATUS(s);
4204 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4206 // Encode "if zero, jump to ..."
4207 // Pushed value (destination of the jump) is uninitialized,
4208 // will be rewritten to be address of "end of if()" or of "else".
4209 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4210 bc_parse_pushJUMP_ZERO(ip_idx);
4212 s = zbc_parse_stmt_allow_NLINE_before(STRING_if);
4213 if (s) RETURN_STATUS(s);
4215 dbg_lex("%s:%d in if after stmt: p->l.lex:%d", __func__, __LINE__, p->l.lex);
4216 if (p->l.lex == BC_LEX_KEY_ELSE) {
4219 // Encode "after then_stmt, jump to end of if()"
4220 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4221 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4222 bc_parse_pushJUMP(ip2_idx);
4224 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4225 rewrite_label_to_current(ip_idx);
4229 s = zbc_parse_stmt_allow_NLINE_before(STRING_else);
4230 if (s) RETURN_STATUS(s);
4233 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4234 rewrite_label_to_current(ip_idx);
4236 dbg_lex_done("%s:%d done", __func__, __LINE__);
4239 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4241 static BC_STATUS zbc_parse_while(void)
4243 BcParse *p = &G.prs;
4249 if (s) RETURN_STATUS(s);
4250 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4252 if (s) RETURN_STATUS(s);
4254 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4255 ip_idx = cond_idx + 1;
4256 bc_vec_push(&p->conds, &cond_idx);
4258 bc_vec_push(&p->exits, &ip_idx);
4259 bc_vec_push(&p->func->labels, &ip_idx);
4261 s = zbc_parse_expr(BC_PARSE_REL);
4262 if (s) RETURN_STATUS(s);
4263 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4265 bc_parse_pushJUMP_ZERO(ip_idx);
4267 s = zbc_parse_stmt_allow_NLINE_before(STRING_while);
4268 if (s) RETURN_STATUS(s);
4270 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4271 bc_parse_pushJUMP(cond_idx);
4273 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4274 rewrite_label_to_current(ip_idx);
4276 bc_vec_pop(&p->exits);
4277 bc_vec_pop(&p->conds);
4281 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4283 static BC_STATUS zbc_parse_for(void)
4285 BcParse *p = &G.prs;
4287 size_t cond_idx, exit_idx, body_idx, update_idx;
4289 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
4291 if (s) RETURN_STATUS(s);
4292 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4294 if (s) RETURN_STATUS(s);
4296 if (p->l.lex != BC_LEX_SCOLON) {
4297 s = zbc_parse_expr(0);
4298 bc_parse_push(XC_INST_POP);
4299 if (s) RETURN_STATUS(s);
4301 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4302 if (s) RETURN_STATUS(s);
4305 if (p->l.lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4307 if (s) RETURN_STATUS(s);
4309 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4310 update_idx = cond_idx + 1;
4311 body_idx = update_idx + 1;
4312 exit_idx = body_idx + 1;
4314 if (p->l.lex != BC_LEX_SCOLON)
4315 s = zbc_parse_expr(BC_PARSE_REL);
4317 // Set this for the next call to bc_parse_pushNUM().
4318 // This is safe to set because the current token is a semicolon,
4319 // which has no string requirement.
4320 bc_vec_string(&p->l.lex_buf, 1, "1");
4322 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4324 if (s) RETURN_STATUS(s);
4326 if (p->l.lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4329 if (s) RETURN_STATUS(s);
4331 bc_parse_pushJUMP_ZERO(exit_idx);
4332 bc_parse_pushJUMP(body_idx);
4334 bc_vec_push(&p->conds, &update_idx);
4335 bc_vec_push(&p->func->labels, &p->func->code.len);
4337 if (p->l.lex != BC_LEX_RPAREN) {
4338 s = zbc_parse_expr(0);
4339 if (s) RETURN_STATUS(s);
4340 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4341 bc_parse_push(XC_INST_POP);
4343 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4344 if (s) RETURN_STATUS(s);
4347 bc_parse_pushJUMP(cond_idx);
4348 bc_vec_push(&p->func->labels, &p->func->code.len);
4350 bc_vec_push(&p->exits, &exit_idx);
4351 bc_vec_push(&p->func->labels, &exit_idx);
4353 s = zbc_parse_stmt_allow_NLINE_before(STRING_for);
4354 if (s) RETURN_STATUS(s);
4356 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4357 bc_parse_pushJUMP(update_idx);
4359 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4360 rewrite_label_to_current(exit_idx);
4362 bc_vec_pop(&p->exits);
4363 bc_vec_pop(&p->conds);
4365 RETURN_STATUS(BC_STATUS_SUCCESS);
4367 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4369 static BC_STATUS zbc_parse_break_or_continue(BcLexType type)
4371 BcParse *p = &G.prs;
4374 if (type == BC_LEX_KEY_BREAK) {
4375 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4376 RETURN_STATUS(bc_error_bad_token());
4377 i = *(size_t*)bc_vec_top(&p->exits);
4379 i = *(size_t*)bc_vec_top(&p->conds);
4381 bc_parse_pushJUMP(i);
4383 RETURN_STATUS(zbc_lex_next());
4385 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4387 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4393 autoid = (void*)f->autos.v;
4394 for (i = 0; i < f->autos.len; i++, autoid++) {
4395 if (strcmp(name, autoid->name) == 0)
4396 RETURN_STATUS(bc_error("duplicate function parameter or auto name"));
4402 bc_vec_push(&f->autos, &a);
4404 RETURN_STATUS(BC_STATUS_SUCCESS);
4406 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4408 static BC_STATUS zbc_parse_funcdef(void)
4410 BcParse *p = &G.prs;
4412 bool var, comma = false;
4415 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4417 if (s) RETURN_STATUS(s);
4418 if (p->l.lex != XC_LEX_NAME)
4419 RETURN_STATUS(bc_error("bad function definition"));
4421 name = xstrdup(p->l.lex_buf.v);
4422 p->fidx = bc_program_addFunc(name);
4423 p->func = bc_program_func(p->fidx);
4426 if (s) RETURN_STATUS(s);
4427 if (p->l.lex != BC_LEX_LPAREN)
4428 RETURN_STATUS(bc_error("bad function definition"));
4430 if (s) RETURN_STATUS(s);
4432 while (p->l.lex != BC_LEX_RPAREN) {
4433 if (p->l.lex != XC_LEX_NAME)
4434 RETURN_STATUS(bc_error("bad function definition"));
4438 name = xstrdup(p->l.lex_buf.v);
4442 var = p->l.lex != BC_LEX_LBRACKET;
4448 if (p->l.lex != BC_LEX_RBRACKET) {
4449 s = bc_error("bad function definition");
4457 comma = p->l.lex == BC_LEX_COMMA;
4463 s = zbc_func_insert(p->func, name, var);
4467 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4470 if (s) RETURN_STATUS(s);
4472 if (p->l.lex != BC_LEX_LBRACE) {
4473 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4474 if (s) RETURN_STATUS(s);
4477 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4478 s = zbc_lex_skip_if_at_NLINE();
4479 if (s) RETURN_STATUS(s);
4480 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4481 if (p->l.lex != BC_LEX_LBRACE)
4482 RETURN_STATUS(bc_error("function { body } expected"));
4484 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4485 s = zbc_parse_stmt_possibly_auto(true);
4487 if (s) RETURN_STATUS(s);
4489 bc_parse_push(BC_INST_RET0);
4491 // Subsequent code generation is into main program
4492 p->fidx = BC_PROG_MAIN;
4493 p->func = bc_program_func_BC_PROG_MAIN();
4495 dbg_lex_done("%s:%d done", __func__, __LINE__);
4498 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4502 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4504 static BC_STATUS zbc_parse_auto(void)
4506 BcParse *p = &G.prs;
4510 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4512 if (s) RETURN_STATUS(s);
4517 if (p->l.lex != XC_LEX_NAME)
4518 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4520 name = xstrdup(p->l.lex_buf.v);
4524 var = (p->l.lex != BC_LEX_LBRACKET);
4529 if (p->l.lex != BC_LEX_RBRACKET) {
4530 s = bc_error("bad 'auto' syntax");
4537 s = zbc_func_insert(p->func, name, var);
4540 if (p->l.lex == XC_LEX_NLINE
4541 || p->l.lex == BC_LEX_SCOLON
4542 //|| p->l.lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4546 if (p->l.lex != BC_LEX_COMMA)
4547 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4548 s = zbc_lex_next(); // skip comma
4549 if (s) RETURN_STATUS(s);
4552 dbg_lex_done("%s:%d done", __func__, __LINE__);
4553 RETURN_STATUS(BC_STATUS_SUCCESS);
4556 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4559 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4561 #undef zbc_parse_stmt_possibly_auto
4562 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed)
4564 BcParse *p = &G.prs;
4565 BcStatus s = BC_STATUS_SUCCESS;
4567 dbg_lex_enter("%s:%d entered, p->l.lex:%d", __func__, __LINE__, p->l.lex);
4569 if (p->l.lex == XC_LEX_NLINE) {
4570 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4571 RETURN_STATUS(zbc_lex_next());
4573 if (p->l.lex == BC_LEX_SCOLON) {
4574 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4575 RETURN_STATUS(zbc_lex_next());
4578 if (p->l.lex == BC_LEX_LBRACE) {
4579 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4582 if (s) RETURN_STATUS(s);
4583 } while (p->l.lex == XC_LEX_NLINE);
4584 if (auto_allowed && p->l.lex == BC_LEX_KEY_AUTO) {
4585 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4586 s = zbc_parse_auto();
4587 if (s) RETURN_STATUS(s);
4589 while (p->l.lex != BC_LEX_RBRACE) {
4590 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4591 s = zbc_parse_stmt();
4592 if (s) RETURN_STATUS(s);
4595 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4599 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
4601 case XC_LEX_OP_MINUS:
4604 case BC_LEX_OP_BOOL_NOT:
4608 case BC_LEX_KEY_IBASE:
4609 case BC_LEX_KEY_LAST:
4610 case BC_LEX_KEY_LENGTH:
4611 case BC_LEX_KEY_OBASE:
4612 case BC_LEX_KEY_READ:
4613 case BC_LEX_KEY_SCALE:
4614 case BC_LEX_KEY_SQRT:
4615 s = zbc_parse_expr(BC_PARSE_PRINT);
4618 s = zbc_parse_pushSTR();
4619 bc_parse_push(XC_INST_PRINT_STR);
4621 case BC_LEX_KEY_BREAK:
4622 case BC_LEX_KEY_CONTINUE:
4623 s = zbc_parse_break_or_continue(p->l.lex);
4625 case BC_LEX_KEY_FOR:
4626 s = zbc_parse_for();
4628 case BC_LEX_KEY_HALT:
4629 bc_parse_push(BC_INST_HALT);
4635 case BC_LEX_KEY_LIMITS:
4636 // "limits" is a compile-time command,
4637 // the output is produced at _parse time_.
4639 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4640 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4641 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4642 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4643 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4644 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4645 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4646 "Number of vars = "BC_MAX_VARS_STR "\n"
4650 case BC_LEX_KEY_PRINT:
4651 s = zbc_parse_print();
4653 case BC_LEX_KEY_QUIT:
4654 // "quit" is a compile-time command. For example,
4655 // "if (0 == 1) quit" terminates when parsing the statement,
4656 // not when it is executed
4657 QUIT_OR_RETURN_TO_MAIN;
4658 case BC_LEX_KEY_RETURN:
4660 RETURN_STATUS(bc_error("'return' not in a function"));
4661 s = zbc_parse_return();
4663 case BC_LEX_KEY_WHILE:
4664 s = zbc_parse_while();
4667 s = bc_error_bad_token();
4671 dbg_lex_done("%s:%d done", __func__, __LINE__);
4674 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4676 static BC_STATUS zbc_parse_stmt_or_funcdef(void)
4678 BcParse *p = &G.prs;
4681 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4682 if (p->l.lex == XC_LEX_EOF)
4683 s = bc_error("end of file");
4684 else if (p->l.lex == BC_LEX_KEY_DEFINE) {
4685 dbg_lex("%s:%d p->l.lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4686 s = zbc_parse_funcdef();
4688 dbg_lex("%s:%d p->l.lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->l.lex);
4689 s = zbc_parse_stmt();
4692 dbg_lex_done("%s:%d done", __func__, __LINE__);
4695 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4697 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4698 static BcStatus bc_parse_expr_empty_ok(uint8_t flags)
4700 BcParse *p = &G.prs;
4701 BcInst prev = XC_INST_PRINT;
4702 size_t nexprs = 0, ops_bgn = p->ops.len;
4703 unsigned nparens, nrelops;
4704 bool paren_first, paren_expr, rprn, assign, bin_last;
4706 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4707 paren_first = (p->l.lex == BC_LEX_LPAREN);
4708 nparens = nrelops = 0;
4709 paren_expr = rprn = assign = false;
4715 BcLexType t = p->l.lex;
4717 if (!lex_allowed_in_bc_expr(t))
4720 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4722 s = BC_STATUS_SUCCESS;
4726 s = zbc_parse_incdec(&prev, &paren_expr, &nexprs, flags);
4727 rprn = bin_last = false;
4728 //get_token = false; - already is
4730 case XC_LEX_OP_MINUS:
4731 s = zbc_parse_minus(&prev, ops_bgn, rprn, &nexprs);
4733 //get_token = false; - already is
4734 bin_last = (prev == XC_INST_MINUS);
4736 case BC_LEX_OP_ASSIGN_POWER:
4737 case BC_LEX_OP_ASSIGN_MULTIPLY:
4738 case BC_LEX_OP_ASSIGN_DIVIDE:
4739 case BC_LEX_OP_ASSIGN_MODULUS:
4740 case BC_LEX_OP_ASSIGN_PLUS:
4741 case BC_LEX_OP_ASSIGN_MINUS:
4742 case BC_LEX_OP_ASSIGN:
4743 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4744 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4745 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4747 return bc_error("bad assignment:"
4748 " left side must be variable"
4750 ); // note: shared string
4753 case XC_LEX_OP_POWER:
4754 case XC_LEX_OP_MULTIPLY:
4755 case XC_LEX_OP_DIVIDE:
4756 case XC_LEX_OP_MODULUS:
4757 case XC_LEX_OP_PLUS:
4758 case XC_LEX_OP_REL_EQ:
4759 case XC_LEX_OP_REL_LE:
4760 case XC_LEX_OP_REL_GE:
4761 case XC_LEX_OP_REL_NE:
4762 case XC_LEX_OP_REL_LT:
4763 case XC_LEX_OP_REL_GT:
4764 case BC_LEX_OP_BOOL_NOT:
4765 case BC_LEX_OP_BOOL_OR:
4766 case BC_LEX_OP_BOOL_AND:
4767 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4768 || (t != BC_LEX_OP_BOOL_NOT && prev == XC_INST_BOOL_NOT)
4770 return bc_error_bad_expression();
4772 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4773 prev = BC_TOKEN_2_INST(t);
4774 bc_parse_operator(t, ops_bgn, &nexprs);
4777 //get_token = false; - already is
4778 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4781 if (BC_PARSE_LEAF(prev, rprn))
4782 return bc_error_bad_expression();
4783 bc_vec_push(&p->ops, &t);
4787 rprn = bin_last = false;
4790 if (bin_last || prev == XC_INST_BOOL_NOT)
4791 return bc_error_bad_expression();
4796 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4797 return BC_STATUS_PARSE_EMPTY_EXP;
4799 s = zbc_parse_rightParen(ops_bgn, &nexprs);
4802 paren_expr = rprn = true;
4806 if (BC_PARSE_LEAF(prev, rprn))
4807 return bc_error_bad_expression();
4808 s = zbc_parse_name(&prev, flags & ~BC_PARSE_NOCALL);
4810 rprn = bin_last = false;
4811 //get_token = false; - already is
4815 if (BC_PARSE_LEAF(prev, rprn))
4816 return bc_error_bad_expression();
4821 rprn = bin_last = false;
4824 case BC_LEX_KEY_IBASE:
4825 case BC_LEX_KEY_LAST:
4826 case BC_LEX_KEY_OBASE:
4827 if (BC_PARSE_LEAF(prev, rprn))
4828 return bc_error_bad_expression();
4829 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4830 bc_parse_push((char) prev);
4833 rprn = bin_last = false;
4836 case BC_LEX_KEY_LENGTH:
4837 case BC_LEX_KEY_SQRT:
4838 if (BC_PARSE_LEAF(prev, rprn))
4839 return bc_error_bad_expression();
4840 s = zbc_parse_builtin(t, flags, &prev);
4843 rprn = bin_last = false;
4846 case BC_LEX_KEY_READ:
4847 if (BC_PARSE_LEAF(prev, rprn))
4848 return bc_error_bad_expression();
4849 s = zbc_parse_read();
4850 prev = XC_INST_READ;
4853 rprn = bin_last = false;
4856 case BC_LEX_KEY_SCALE:
4857 if (BC_PARSE_LEAF(prev, rprn))
4858 return bc_error_bad_expression();
4859 s = zbc_parse_scale(&prev, flags);
4860 prev = XC_INST_SCALE;
4861 //get_token = false; - already is
4863 rprn = bin_last = false;
4867 return bc_error_bad_token();
4870 if (s || G_interrupt) // error, or ^C: stop parsing
4871 return BC_STATUS_FAILURE;
4879 while (p->ops.len > ops_bgn) {
4880 BcLexType top = BC_PARSE_TOP_OP(p);
4881 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4883 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4884 return bc_error_bad_expression();
4886 bc_parse_push(BC_TOKEN_2_INST(top));
4888 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4889 bc_vec_pop(&p->ops);
4892 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4893 return bc_error_bad_expression();
4895 if (!(flags & BC_PARSE_REL) && nrelops) {
4897 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4899 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4901 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4905 if (flags & BC_PARSE_PRINT) {
4906 if (paren_first || !assign)
4907 bc_parse_push(XC_INST_PRINT);
4908 bc_parse_push(XC_INST_POP);
4911 dbg_lex_done("%s:%d done", __func__, __LINE__);
4912 return BC_STATUS_SUCCESS;
4919 static BC_STATUS zdc_parse_register(void)
4921 BcParse *p = &G.prs;
4925 if (s) RETURN_STATUS(s);
4926 if (p->l.lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4928 bc_parse_pushName(p->l.lex_buf.v);
4932 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4934 static void dc_parse_string(void)
4936 BcParse *p = &G.prs;
4938 size_t len = G.prog.strs.len;
4940 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4942 str = xstrdup(p->l.lex_buf.v);
4943 bc_parse_push(XC_INST_STR);
4944 bc_parse_pushIndex(len);
4945 bc_vec_push(&G.prog.strs, &str);
4947 // Explanation needed here
4948 bc_program_add_fn();
4949 p->func = bc_program_func(p->fidx);
4951 dbg_lex_done("%s:%d done", __func__, __LINE__);
4954 static BC_STATUS zdc_parse_mem(uint8_t inst, bool name, bool store)
4958 bc_parse_push(inst);
4960 s = zdc_parse_register();
4961 if (s) RETURN_STATUS(s);
4965 bc_parse_push(DC_INST_SWAP);
4966 bc_parse_push(XC_INST_ASSIGN);
4967 bc_parse_push(XC_INST_POP);
4970 RETURN_STATUS(BC_STATUS_SUCCESS);
4972 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4974 static BC_STATUS zdc_parse_cond(uint8_t inst)
4976 BcParse *p = &G.prs;
4979 bc_parse_push(inst);
4980 bc_parse_push(DC_INST_EXEC_COND);
4982 s = zdc_parse_register();
4983 if (s) RETURN_STATUS(s);
4986 if (s) RETURN_STATUS(s);
4988 // Note that 'else' part can not be on the next line:
4989 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4990 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4991 if (p->l.lex == DC_LEX_ELSE) {
4992 s = zdc_parse_register();
4993 if (s) RETURN_STATUS(s);
4996 bc_parse_push(BC_PARSE_STREND);
5001 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
5003 static BC_STATUS zdc_parse_token(BcLexType t)
5007 bool assign, get_token;
5009 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
5010 s = BC_STATUS_SUCCESS;
5013 case XC_LEX_OP_REL_EQ:
5014 case XC_LEX_OP_REL_LE:
5015 case XC_LEX_OP_REL_GE:
5016 case XC_LEX_OP_REL_NE:
5017 case XC_LEX_OP_REL_LT:
5018 case XC_LEX_OP_REL_GT:
5019 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
5020 s = zdc_parse_cond(t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
5025 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
5026 s = zdc_parse_mem(XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
5029 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
5033 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
5035 if (s) RETURN_STATUS(s);
5036 if (G.prs.l.lex != XC_LEX_NUMBER)
5037 RETURN_STATUS(bc_error_bad_token());
5039 bc_parse_push(XC_INST_NEG);
5042 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
5046 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
5047 bc_parse_push(XC_INST_READ);
5049 case DC_LEX_OP_ASSIGN:
5050 case DC_LEX_STORE_PUSH:
5051 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
5052 assign = (t == DC_LEX_OP_ASSIGN);
5053 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
5054 s = zdc_parse_mem(inst, true, assign);
5057 case DC_LEX_LOAD_POP:
5058 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
5059 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
5060 s = zdc_parse_mem(inst, true, false);
5062 case DC_LEX_STORE_IBASE:
5063 case DC_LEX_STORE_SCALE:
5064 case DC_LEX_STORE_OBASE:
5065 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
5066 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
5067 s = zdc_parse_mem(inst, false, true);
5070 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
5071 RETURN_STATUS(bc_error_bad_token());
5074 if (!s && get_token) s = zbc_lex_next();
5076 dbg_lex_done("%s:%d done", __func__, __LINE__);
5079 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
5081 static BC_STATUS zdc_parse_expr(void)
5083 BcParse *p = &G.prs;
5086 i = (int)p->l.lex - (int)XC_LEX_OP_POWER;
5088 BcInst inst = dc_LEX_to_INST[i];
5089 if (inst != DC_INST_INVALID) {
5090 bc_parse_push(inst);
5091 RETURN_STATUS(zbc_lex_next());
5094 RETURN_STATUS(zdc_parse_token(p->l.lex));
5096 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
5098 static BC_STATUS zdc_parse_exprs_until_eof(void)
5100 BcParse *p = &G.prs;
5101 dbg_lex_enter("%s:%d entered, p->l.lex:%d", __func__, __LINE__, p->l.lex);
5102 while (p->l.lex != XC_LEX_EOF) {
5103 BcStatus s = zdc_parse_expr();
5104 if (s) RETURN_STATUS(s);
5107 dbg_lex_done("%s:%d done", __func__, __LINE__);
5108 RETURN_STATUS(BC_STATUS_SUCCESS);
5110 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5118 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5119 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5121 static BcVec* bc_program_search(char *id, bool var)
5128 v = var ? &G.prog.vars : &G.prog.arrs;
5129 map = var ? &G.prog.var_map : &G.prog.arr_map;
5133 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5137 bc_array_init(&v2, var);
5138 bc_vec_push(v, &v2);
5141 ptr = bc_vec_item(map, i);
5142 if (new) ptr->name = xstrdup(e.name);
5143 return bc_vec_item(v, ptr->idx);
5146 // 'num' need not be initialized on entry
5147 static BC_STATUS zbc_program_num(BcResult *r, BcNum **num, bool hex)
5151 case XC_RESULT_TEMP:
5152 case XC_RESULT_IBASE:
5153 case XC_RESULT_SCALE:
5154 case XC_RESULT_OBASE:
5157 case XC_RESULT_CONSTANT: {
5163 str = *bc_program_const(r->d.id.idx);
5166 bc_num_init(&r->d.n, len);
5168 hex = hex && len == 1;
5169 base_t = hex ? 16 : G.prog.ib_t;
5170 s = zbc_num_parse(&r->d.n, str, base_t);
5172 bc_num_free(&r->d.n);
5176 r->t = XC_RESULT_TEMP;
5180 case XC_RESULT_ARRAY:
5181 case XC_RESULT_ARRAY_ELEM: {
5184 v = bc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5186 if (r->t == XC_RESULT_ARRAY_ELEM) {
5188 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5189 *num = bc_vec_item(v, r->d.id.idx);
5191 *num = bc_vec_top(v);
5195 case BC_RESULT_LAST:
5196 *num = &G.prog.last;
5204 // Testing the theory that dc does not reach LAST/ONE
5205 bb_error_msg_and_die("BUG:%d", r->t);
5209 RETURN_STATUS(BC_STATUS_SUCCESS);
5211 #define zbc_program_num(...) (zbc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5213 static BC_STATUS zbc_program_binOpPrep(BcResult **l, BcNum **ln,
5214 BcResult **r, BcNum **rn, bool assign)
5218 BcResultType lt, rt;
5220 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5221 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5223 *r = bc_vec_item_rev(&G.prog.results, 0);
5224 *l = bc_vec_item_rev(&G.prog.results, 1);
5228 hex = assign && (lt == XC_RESULT_IBASE || lt == XC_RESULT_OBASE);
5230 s = zbc_program_num(*l, ln, false);
5231 if (s) RETURN_STATUS(s);
5232 s = zbc_program_num(*r, rn, hex);
5233 if (s) RETURN_STATUS(s);
5235 // We run this again under these conditions in case any vector has been
5236 // reallocated out from under the BcNums or arrays we had.
5237 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5238 s = zbc_program_num(*l, ln, false);
5239 if (s) RETURN_STATUS(s);
5242 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5243 RETURN_STATUS(bc_error_variable_is_wrong_type());
5244 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5245 RETURN_STATUS(bc_error_variable_is_wrong_type());
5249 #define zbc_program_binOpPrep(...) (zbc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5251 static void bc_program_binOpRetire(BcResult *r)
5253 r->t = XC_RESULT_TEMP;
5254 bc_vec_pop(&G.prog.results);
5255 bc_result_pop_and_push(r);
5258 // Note: *r and *n need not be initialized by caller
5259 static BC_STATUS zbc_program_prep(BcResult **r, BcNum **n)
5263 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5264 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5265 *r = bc_vec_top(&G.prog.results);
5267 s = zbc_program_num(*r, n, false);
5268 if (s) RETURN_STATUS(s);
5270 if (!BC_PROG_NUM((*r), (*n)))
5271 RETURN_STATUS(bc_error_variable_is_wrong_type());
5275 #define zbc_program_prep(...) (zbc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5277 static void bc_program_retire(BcResult *r, BcResultType t)
5280 bc_result_pop_and_push(r);
5283 static BC_STATUS zbc_program_op(char inst)
5286 BcResult *opd1, *opd2, res;
5289 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5290 if (s) RETURN_STATUS(s);
5291 bc_num_init_DEF_SIZE(&res.d.n);
5293 s = BC_STATUS_SUCCESS;
5294 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5296 bc_program_binOpRetire(&res);
5300 bc_num_free(&res.d.n);
5303 #define zbc_program_op(...) (zbc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5305 static BC_STATUS zbc_program_read(void)
5313 bc_char_vec_init(&buf);
5314 bc_read_line(&buf, stdin);
5316 f = bc_program_func(BC_PROG_READ);
5317 bc_vec_pop_all(&f->code);
5319 sv_parse = G.prs; // struct copy
5320 bc_parse_create(BC_PROG_READ);
5321 //bc_lex_file(&G.prs.l); - not needed, error line info is not printed for read()
5323 s = zbc_parse_text_init(buf.v);
5324 if (s) goto exec_err;
5326 IF_BC(s = zbc_parse_expr(0));
5328 IF_DC(s = zdc_parse_exprs_until_eof());
5330 if (s) goto exec_err;
5332 if (G.prs.l.lex != XC_LEX_NLINE && G.prs.l.lex != XC_LEX_EOF) {
5333 s = bc_error("bad read() expression");
5337 ip.func = BC_PROG_READ;
5339 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5341 bc_parse_push(XC_INST_RET);
5342 bc_vec_push(&G.prog.exestack, &ip);
5346 G.prs = sv_parse; // struct copy
5350 #define zbc_program_read(...) (zbc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5352 static size_t bc_program_index(char *code, size_t *bgn)
5354 unsigned char *bytes = (void*)(code + *bgn);
5364 for (i = 0; i < amt; i += 8)
5365 res |= (size_t)(*bytes++) << i;
5370 static char *bc_program_name(char *code, size_t *bgn)
5376 s = xmalloc(strchr(code, BC_PARSE_STREND) - code + 1);
5380 if (c == BC_PARSE_STREND)
5390 static void bc_program_printString(const char *str)
5394 // Example: echo '[]ap' | dc
5395 // should print two bytes: 0x00, 0x0A
5402 if (c != '\\' || !*str)
5422 G.prog.nchars = SIZE_MAX;
5434 // Just print the backslash and following character.
5445 static void bc_num_printNewline(void)
5447 if (G.prog.nchars == G.prog.len - 1) {
5455 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5458 bb_putchar((char) num);
5459 G.prog.nchars += width;
5463 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5467 bc_num_printNewline();
5468 bb_putchar(radix ? '.' : ' ');
5471 bc_num_printNewline();
5472 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5475 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5477 bc_num_printNewline();
5480 bb_putchar(((char) dig) + '0');
5484 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5487 bc_num_printNewline();
5492 bc_num_printNewline();
5493 bb_putchar(bb_hexdigits_upcase[num]);
5494 G.prog.nchars += width;
5497 static void bc_num_printDecimal(BcNum *n)
5499 size_t i, rdx = n->rdx - 1;
5506 for (i = n->len - 1; i < n->len; --i)
5507 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5510 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5512 static BC_STATUS zbc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5517 BcDig base_digs[ULONG_NUM_BUFSIZE];
5518 BcNum intp, fracp, digit, frac_len;
5519 unsigned long dig, *ptr;
5524 print(0, width, false);
5525 RETURN_STATUS(BC_STATUS_SUCCESS);
5528 bc_vec_init(&stack, sizeof(long), NULL);
5529 bc_num_init(&intp, n->len);
5530 bc_num_init(&fracp, n->rdx);
5531 bc_num_init(&digit, width);
5532 bc_num_init(&frac_len, BC_NUM_INT(n));
5533 bc_num_copy(&intp, n);
5534 bc_num_one(&frac_len);
5535 base.cap = ARRAY_SIZE(base_digs);
5536 base.num = base_digs;
5537 bc_num_ulong2num(&base, base_t);
5539 bc_num_truncate(&intp, intp.rdx);
5540 s = zbc_num_sub(n, &intp, &fracp, 0);
5543 while (intp.len != 0) {
5544 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5546 s = zbc_num_ulong(&digit, &dig);
5548 bc_vec_push(&stack, &dig);
5551 for (i = 0; i < stack.len; ++i) {
5552 ptr = bc_vec_item_rev(&stack, i);
5553 print(*ptr, width, false);
5556 if (!n->rdx) goto err;
5558 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5559 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5561 s = zbc_num_ulong(&fracp, &dig);
5563 bc_num_ulong2num(&intp, dig);
5564 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5566 print(dig, width, radix);
5567 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5571 bc_num_free(&frac_len);
5572 bc_num_free(&digit);
5573 bc_num_free(&fracp);
5575 bc_vec_free(&stack);
5578 #define zbc_num_printNum(...) (zbc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5580 static BC_STATUS zbc_num_printBase(BcNum *n)
5594 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5596 print = bc_num_printHex;
5598 unsigned i = G.prog.ob_t - 1;
5606 print = bc_num_printDigits;
5609 s = zbc_num_printNum(n, G.prog.ob_t, width, print);
5614 #define zbc_num_printBase(...) (zbc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5616 static BC_STATUS zbc_num_print(BcNum *n, bool newline)
5618 BcStatus s = BC_STATUS_SUCCESS;
5620 bc_num_printNewline();
5625 } else if (G.prog.ob_t == 10)
5626 bc_num_printDecimal(n);
5628 s = zbc_num_printBase(n);
5637 #define zbc_num_print(...) (zbc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5639 static BC_STATUS zbc_program_print(char inst, size_t idx)
5644 bool pop = (inst != XC_INST_PRINT);
5646 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5647 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5649 r = bc_vec_item_rev(&G.prog.results, idx);
5650 s = zbc_program_num(r, &num, false);
5651 if (s) RETURN_STATUS(s);
5653 if (BC_PROG_NUM(r, num)) {
5654 s = zbc_num_print(num, !pop);
5656 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5661 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5662 str = *bc_program_str(idx);
5664 if (inst == XC_INST_PRINT_STR) {
5667 if (c == '\0') break;
5670 if (c == '\n') G.prog.nchars = 0;
5673 bc_program_printString(str);
5674 if (inst == XC_INST_PRINT) bb_putchar('\n');
5678 if (!s && pop) bc_vec_pop(&G.prog.results);
5682 #define zbc_program_print(...) (zbc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5684 static BC_STATUS zbc_program_negate(void)
5690 s = zbc_program_prep(&ptr, &num);
5691 if (s) RETURN_STATUS(s);
5693 bc_num_init(&res.d.n, num->len);
5694 bc_num_copy(&res.d.n, num);
5695 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5697 bc_program_retire(&res, XC_RESULT_TEMP);
5701 #define zbc_program_negate(...) (zbc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5703 static BC_STATUS zbc_program_logical(char inst)
5706 BcResult *opd1, *opd2, res;
5710 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5711 if (s) RETURN_STATUS(s);
5713 bc_num_init_DEF_SIZE(&res.d.n);
5715 if (inst == XC_INST_BOOL_AND)
5716 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5717 else if (inst == XC_INST_BOOL_OR)
5718 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5720 cond = bc_num_cmp(n1, n2);
5722 case XC_INST_REL_EQ:
5725 case XC_INST_REL_LE:
5728 case XC_INST_REL_GE:
5731 case XC_INST_REL_LT:
5734 case XC_INST_REL_GT:
5737 default: // = case XC_INST_REL_NE:
5738 //cond = (cond != 0); - not needed
5743 if (cond) bc_num_one(&res.d.n);
5744 //else bc_num_zero(&res.d.n); - already is
5746 bc_program_binOpRetire(&res);
5750 #define zbc_program_logical(...) (zbc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5753 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5758 memset(&n2, 0, sizeof(BcNum));
5759 n2.rdx = res.d.id.idx = r->d.id.idx;
5760 res.t = XC_RESULT_STR;
5763 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5764 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5766 bc_vec_pop(&G.prog.results);
5769 bc_result_pop_and_push(&res);
5770 bc_vec_push(v, &n2);
5772 RETURN_STATUS(BC_STATUS_SUCCESS);
5774 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5777 static BC_STATUS zbc_program_copyToVar(char *name, bool var)
5784 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5785 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5787 ptr = bc_vec_top(&G.prog.results);
5788 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5789 RETURN_STATUS(bc_error_variable_is_wrong_type());
5790 v = bc_program_search(name, var);
5793 if (ptr->t == XC_RESULT_STR && !var)
5794 RETURN_STATUS(bc_error_variable_is_wrong_type());
5795 if (ptr->t == XC_RESULT_STR)
5796 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5799 s = zbc_program_num(ptr, &n, false);
5800 if (s) RETURN_STATUS(s);
5802 // Do this once more to make sure that pointers were not invalidated.
5803 v = bc_program_search(name, var);
5806 bc_num_init_DEF_SIZE(&r.d.n);
5807 bc_num_copy(&r.d.n, n);
5809 bc_array_init(&r.d.v, true);
5810 bc_array_copy(&r.d.v, (BcVec *) n);
5813 bc_vec_push(v, &r.d);
5814 bc_vec_pop(&G.prog.results);
5818 #define zbc_program_copyToVar(...) (zbc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5820 static BC_STATUS zbc_program_assign(char inst)
5823 BcResult *left, *right, res;
5825 bool assign = (inst == XC_INST_ASSIGN);
5828 s = zbc_program_binOpPrep(&left, &l, &right, &r, assign);
5829 if (s) RETURN_STATUS(s);
5831 ib = left->t == XC_RESULT_IBASE;
5832 sc = left->t == XC_RESULT_SCALE;
5835 if (right->t == XC_RESULT_STR) {
5838 if (left->t != XC_RESULT_VAR)
5839 RETURN_STATUS(bc_error_variable_is_wrong_type());
5840 v = bc_program_search(left->d.id.name, true);
5842 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5846 if (left->t == XC_RESULT_CONSTANT || left->t == XC_RESULT_TEMP)
5847 RETURN_STATUS(bc_error("bad assignment:"
5848 " left side must be variable"
5850 )); // note: shared string
5853 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5854 RETURN_STATUS(bc_error("divide by zero"));
5859 s = BC_STATUS_SUCCESS;
5860 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5862 if (s) RETURN_STATUS(s);
5867 if (ib || sc || left->t == XC_RESULT_OBASE) {
5868 static const char *const msg[] = {
5869 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5870 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5871 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5877 s = zbc_num_ulong(l, &val);
5878 if (s) RETURN_STATUS(s);
5879 s = left->t - XC_RESULT_IBASE;
5882 ptr = &G.prog.scale;
5885 RETURN_STATUS(bc_error(msg[s]));
5886 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5887 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5891 RETURN_STATUS(bc_error(msg[s]));
5893 *ptr = (size_t) val;
5894 s = BC_STATUS_SUCCESS;
5897 bc_num_init(&res.d.n, l->len);
5898 bc_num_copy(&res.d.n, l);
5899 bc_program_binOpRetire(&res);
5903 #define zbc_program_assign(...) (zbc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5906 #define bc_program_pushVar(code, bgn, pop, copy) \
5907 bc_program_pushVar(code, bgn)
5908 // for bc, 'pop' and 'copy' are always false
5910 static BC_STATUS bc_program_pushVar(char *code, size_t *bgn,
5911 bool pop, bool copy)
5914 char *name = bc_program_name(code, bgn);
5916 r.t = XC_RESULT_VAR;
5921 BcVec *v = bc_program_search(name, true);
5922 BcNum *num = bc_vec_top(v);
5925 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5926 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5929 if (!BC_PROG_STR(num)) {
5930 r.t = XC_RESULT_TEMP;
5931 bc_num_init_DEF_SIZE(&r.d.n);
5932 bc_num_copy(&r.d.n, num);
5934 r.t = XC_RESULT_STR;
5935 r.d.id.idx = num->rdx;
5938 if (!copy) bc_vec_pop(v);
5942 bc_vec_push(&G.prog.results, &r);
5944 RETURN_STATUS(BC_STATUS_SUCCESS);
5946 #define zbc_program_pushVar(...) (bc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5948 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5950 BcStatus s = BC_STATUS_SUCCESS;
5954 r.d.id.name = bc_program_name(code, bgn);
5956 if (inst == XC_INST_ARRAY) {
5957 r.t = XC_RESULT_ARRAY;
5958 bc_vec_push(&G.prog.results, &r);
5963 s = zbc_program_prep(&operand, &num);
5965 s = zbc_num_ulong(num, &temp);
5968 if (temp > BC_MAX_DIM) {
5969 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5973 r.d.id.idx = (size_t) temp;
5974 bc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5977 if (s) free(r.d.id.name);
5980 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5983 static BC_STATUS zbc_program_incdec(char inst)
5986 BcResult *ptr, res, copy;
5990 s = zbc_program_prep(&ptr, &num);
5991 if (s) RETURN_STATUS(s);
5993 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5994 copy.t = XC_RESULT_TEMP;
5995 bc_num_init(©.d.n, num->len);
5996 bc_num_copy(©.d.n, num);
5999 res.t = BC_RESULT_ONE;
6000 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
6001 ? BC_INST_ASSIGN_PLUS
6002 : BC_INST_ASSIGN_MINUS;
6004 bc_vec_push(&G.prog.results, &res);
6005 s = zbc_program_assign(inst);
6006 if (s) RETURN_STATUS(s);
6008 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
6009 bc_result_pop_and_push(©);
6014 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
6016 static BC_STATUS zbc_program_call(char *code, size_t *idx)
6024 nparams = bc_program_index(code, idx);
6026 ip.func = bc_program_index(code, idx);
6027 func = bc_program_func(ip.func);
6029 if (func->code.len == 0) {
6030 RETURN_STATUS(bc_error("undefined function"));
6032 if (nparams != func->nparams) {
6033 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
6035 ip.results_len_before_call = G.prog.results.len - nparams;
6037 for (i = 0; i < nparams; ++i) {
6040 a = bc_vec_item(&func->autos, nparams - 1 - i);
6041 arg = bc_vec_top(&G.prog.results);
6043 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) || arg->t == XC_RESULT_STR)
6044 RETURN_STATUS(bc_error_variable_is_wrong_type());
6046 s = zbc_program_copyToVar(a->name, a->idx);
6047 if (s) RETURN_STATUS(s);
6050 a = bc_vec_item(&func->autos, i);
6051 for (; i < func->autos.len; i++, a++) {
6054 v = bc_program_search(a->name, a->idx);
6057 bc_num_init_DEF_SIZE(&n2);
6058 bc_vec_push(v, &n2);
6061 bc_array_init(&v2, true);
6062 bc_vec_push(v, &v2);
6066 bc_vec_push(&G.prog.exestack, &ip);
6068 RETURN_STATUS(BC_STATUS_SUCCESS);
6070 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
6072 static BC_STATUS zbc_program_return(char inst)
6078 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6080 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == XC_INST_RET)))
6081 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6083 f = bc_program_func(ip->func);
6084 res.t = XC_RESULT_TEMP;
6086 if (inst == XC_INST_RET) {
6089 BcResult *operand = bc_vec_top(&G.prog.results);
6091 s = zbc_program_num(operand, &num, false);
6092 if (s) RETURN_STATUS(s);
6093 bc_num_init(&res.d.n, num->len);
6094 bc_num_copy(&res.d.n, num);
6096 bc_num_init_DEF_SIZE(&res.d.n);
6097 //bc_num_zero(&res.d.n); - already is
6100 // We need to pop arguments as well, so this takes that into account.
6101 a = (void*)f->autos.v;
6102 for (i = 0; i < f->autos.len; i++, a++) {
6104 v = bc_program_search(a->name, a->idx);
6108 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
6109 bc_vec_push(&G.prog.results, &res);
6110 bc_vec_pop(&G.prog.exestack);
6112 RETURN_STATUS(BC_STATUS_SUCCESS);
6114 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6117 static unsigned long bc_program_scale(BcNum *n)
6119 return (unsigned long) n->rdx;
6122 static unsigned long bc_program_len(BcNum *n)
6124 size_t len = n->len;
6126 if (n->rdx != len) return len;
6128 if (len == 0) break;
6130 if (n->num[len] != 0) break;
6135 static BC_STATUS zbc_program_builtin(char inst)
6141 bool len = (inst == XC_INST_LENGTH);
6143 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6144 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6145 opnd = bc_vec_top(&G.prog.results);
6147 s = zbc_program_num(opnd, &num, false);
6148 if (s) RETURN_STATUS(s);
6151 if (!BC_PROG_NUM(opnd, num) && !len)
6152 RETURN_STATUS(bc_error_variable_is_wrong_type());
6155 bc_num_init_DEF_SIZE(&res.d.n);
6157 if (inst == XC_INST_SQRT)
6158 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6160 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6161 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6165 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6167 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6169 str = bc_program_str(idx);
6170 bc_num_ulong2num(&res.d.n, strlen(*str));
6174 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6177 bc_program_retire(&res, XC_RESULT_TEMP);
6181 #define zbc_program_builtin(...) (zbc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6184 static BC_STATUS zdc_program_divmod(void)
6187 BcResult *opd1, *opd2, res, res2;
6190 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6191 if (s) RETURN_STATUS(s);
6193 bc_num_init_DEF_SIZE(&res.d.n);
6194 bc_num_init(&res2.d.n, n2->len);
6196 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6199 bc_program_binOpRetire(&res2);
6200 res.t = XC_RESULT_TEMP;
6201 bc_vec_push(&G.prog.results, &res);
6205 bc_num_free(&res2.d.n);
6206 bc_num_free(&res.d.n);
6209 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6211 static BC_STATUS zdc_program_modexp(void)
6214 BcResult *r1, *r2, *r3, res;
6215 BcNum *n1, *n2, *n3;
6217 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6218 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6219 s = zbc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6220 if (s) RETURN_STATUS(s);
6222 r1 = bc_vec_item_rev(&G.prog.results, 2);
6223 s = zbc_program_num(r1, &n1, false);
6224 if (s) RETURN_STATUS(s);
6225 if (!BC_PROG_NUM(r1, n1))
6226 RETURN_STATUS(bc_error_variable_is_wrong_type());
6228 // Make sure that the values have their pointers updated, if necessary.
6229 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6230 if (r1->t == r2->t) {
6231 s = zbc_program_num(r2, &n2, false);
6232 if (s) RETURN_STATUS(s);
6234 if (r1->t == r3->t) {
6235 s = zbc_program_num(r3, &n3, false);
6236 if (s) RETURN_STATUS(s);
6240 bc_num_init(&res.d.n, n3->len);
6241 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6244 bc_vec_pop(&G.prog.results);
6245 bc_program_binOpRetire(&res);
6249 bc_num_free(&res.d.n);
6252 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6254 static void dc_program_stackLen(void)
6257 size_t len = G.prog.results.len;
6259 res.t = XC_RESULT_TEMP;
6261 bc_num_init_DEF_SIZE(&res.d.n);
6262 bc_num_ulong2num(&res.d.n, len);
6263 bc_vec_push(&G.prog.results, &res);
6266 static BC_STATUS zdc_program_asciify(void)
6276 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6277 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6278 r = bc_vec_top(&G.prog.results);
6280 s = zbc_program_num(r, &num, false);
6281 if (s) RETURN_STATUS(s);
6283 if (BC_PROG_NUM(r, num)) {
6286 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6288 bc_num_init_DEF_SIZE(&n);
6289 bc_num_copy(&n, num);
6290 bc_num_truncate(&n, n.rdx);
6292 strmb.cap = ARRAY_SIZE(strmb_digs);
6293 strmb.num = strmb_digs;
6294 bc_num_ulong2num(&strmb, 0x100);
6295 s = zbc_num_mod(&n, &strmb, &n, 0);
6297 if (s) goto num_err;
6298 s = zbc_num_ulong(&n, &val);
6299 if (s) goto num_err;
6306 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6307 sp = *bc_program_str(idx);
6311 strs = (void*)G.prog.strs.v;
6312 for (idx = 0; idx < G.prog.strs.len; idx++) {
6313 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6319 //str[1] = '\0'; - already is
6320 bc_vec_push(&G.prog.strs, &str);
6322 res.t = XC_RESULT_STR;
6324 bc_result_pop_and_push(&res);
6326 RETURN_STATUS(BC_STATUS_SUCCESS);
6331 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6333 static BC_STATUS zdc_program_printStream(void)
6340 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6341 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6342 r = bc_vec_top(&G.prog.results);
6344 s = zbc_program_num(r, &n, false);
6345 if (s) RETURN_STATUS(s);
6347 if (BC_PROG_NUM(r, n)) {
6348 s = zbc_num_printNum(n, 0x100, 1, dc_num_printChar);
6351 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6352 str = *bc_program_str(idx);
6358 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6360 static BC_STATUS zdc_program_nquit(void)
6367 s = zbc_program_prep(&opnd, &num);
6368 if (s) RETURN_STATUS(s);
6369 s = zbc_num_ulong(num, &val);
6370 if (s) RETURN_STATUS(s);
6372 bc_vec_pop(&G.prog.results);
6374 if (G.prog.exestack.len < val)
6375 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6376 if (G.prog.exestack.len == val) {
6377 QUIT_OR_RETURN_TO_MAIN;
6380 bc_vec_npop(&G.prog.exestack, val);
6384 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6386 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6388 BcStatus s = BC_STATUS_SUCCESS;
6394 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6395 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6397 r = bc_vec_top(&G.prog.results);
6400 BcNum *n = n; // for compiler
6403 char *then_name = bc_program_name(code, bgn);
6404 char *else_name = NULL;
6406 if (code[*bgn] == BC_PARSE_STREND)
6409 else_name = bc_program_name(code, bgn);
6411 exec = r->d.n.len != 0;
6413 if (!exec && else_name != NULL) {
6420 v = bc_program_search(name, true);
6427 if (!exec) goto exit;
6428 if (!BC_PROG_STR(n)) {
6429 s = bc_error_variable_is_wrong_type();
6435 if (r->t == XC_RESULT_STR) {
6437 } else if (r->t == XC_RESULT_VAR) {
6439 s = zbc_program_num(r, &n, false);
6440 if (s || !BC_PROG_STR(n)) goto exit;
6446 fidx = sidx + BC_PROG_REQ_FUNCS;
6448 f = bc_program_func(fidx);
6450 if (f->code.len == 0) {
6454 sv_parse = G.prs; // struct copy
6455 bc_parse_create(fidx);
6456 str = *bc_program_str(sidx);
6457 s = zbc_parse_text_init(str);
6460 s = zdc_parse_exprs_until_eof();
6462 bc_parse_push(DC_INST_POP_EXEC);
6463 if (G.prs.l.lex != XC_LEX_EOF)
6464 s = bc_error_bad_expression();
6466 G.prs = sv_parse; // struct copy
6469 bc_vec_pop_all(&f->code);
6477 bc_vec_pop(&G.prog.results);
6478 bc_vec_push(&G.prog.exestack, &ip);
6480 RETURN_STATUS(BC_STATUS_SUCCESS);
6482 bc_vec_pop(&G.prog.results);
6485 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6488 static void bc_program_pushGlobal(char inst)
6493 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6494 if (inst == XC_INST_IBASE)
6495 val = (unsigned long) G.prog.ib_t;
6496 else if (inst == XC_INST_SCALE)
6497 val = (unsigned long) G.prog.scale;
6499 val = (unsigned long) G.prog.ob_t;
6501 bc_num_init_DEF_SIZE(&res.d.n);
6502 bc_num_ulong2num(&res.d.n, val);
6503 bc_vec_push(&G.prog.results, &res);
6506 static BC_STATUS zbc_program_exec(void)
6509 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6510 BcFunc *func = bc_program_func(ip->func);
6511 char *code = func->code.v;
6513 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6514 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6515 while (ip->inst_idx < func->code.len) {
6516 BcStatus s = BC_STATUS_SUCCESS;
6517 char inst = code[ip->inst_idx++];
6519 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6522 case BC_INST_JUMP_ZERO: {
6525 dbg_exec("BC_INST_JUMP_ZERO:");
6526 s = zbc_program_prep(&ptr, &num);
6527 if (s) RETURN_STATUS(s);
6528 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6529 bc_vec_pop(&G.prog.results);
6531 bc_program_index(code, &ip->inst_idx);
6534 // else: fall through
6536 case BC_INST_JUMP: {
6537 size_t idx = bc_program_index(code, &ip->inst_idx);
6538 size_t *addr = bc_vec_item(&func->labels, idx);
6539 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6540 ip->inst_idx = *addr;
6544 dbg_exec("BC_INST_CALL:");
6545 s = zbc_program_call(code, &ip->inst_idx);
6546 goto read_updated_ip;
6547 case BC_INST_INC_PRE:
6548 case BC_INST_DEC_PRE:
6549 case BC_INST_INC_POST:
6550 case BC_INST_DEC_POST:
6551 dbg_exec("BC_INST_INCDEC:");
6552 s = zbc_program_incdec(inst);
6555 dbg_exec("BC_INST_HALT:");
6556 QUIT_OR_RETURN_TO_MAIN;
6560 dbg_exec("BC_INST_RET[0]:");
6561 s = zbc_program_return(inst);
6562 goto read_updated_ip;
6563 case XC_INST_BOOL_OR:
6564 case XC_INST_BOOL_AND:
6566 case XC_INST_REL_EQ:
6567 case XC_INST_REL_LE:
6568 case XC_INST_REL_GE:
6569 case XC_INST_REL_NE:
6570 case XC_INST_REL_LT:
6571 case XC_INST_REL_GT:
6572 dbg_exec("BC_INST_BOOL:");
6573 s = zbc_program_logical(inst);
6576 dbg_exec("XC_INST_READ:");
6577 s = zbc_program_read();
6578 goto read_updated_ip;
6580 dbg_exec("XC_INST_VAR:");
6581 s = zbc_program_pushVar(code, &ip->inst_idx, false, false);
6583 case XC_INST_ARRAY_ELEM:
6585 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6586 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6590 dbg_exec("BC_INST_LAST:");
6591 r.t = BC_RESULT_LAST;
6592 bc_vec_push(&G.prog.results, &r);
6598 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6599 bc_program_pushGlobal(inst);
6601 case XC_INST_SCALE_FUNC:
6602 case XC_INST_LENGTH:
6604 dbg_exec("BC_INST_builtin:");
6605 s = zbc_program_builtin(inst);
6608 dbg_exec("XC_INST_NUM:");
6609 r.t = XC_RESULT_CONSTANT;
6610 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6611 bc_vec_push(&G.prog.results, &r);
6614 dbg_exec("XC_INST_POP:");
6615 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6616 s = bc_error_stack_has_too_few_elements();
6618 bc_vec_pop(&G.prog.results);
6621 case XC_INST_PRINT_POP:
6622 case XC_INST_PRINT_STR:
6623 dbg_exec("XC_INST_PRINTxyz:");
6624 s = zbc_program_print(inst, 0);
6627 dbg_exec("XC_INST_STR:");
6628 r.t = XC_RESULT_STR;
6629 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6630 bc_vec_push(&G.prog.results, &r);
6633 case XC_INST_MULTIPLY:
6634 case XC_INST_DIVIDE:
6635 case XC_INST_MODULUS:
6638 dbg_exec("BC_INST_binaryop:");
6639 s = zbc_program_op(inst);
6641 case XC_INST_BOOL_NOT: {
6643 dbg_exec("XC_INST_BOOL_NOT:");
6644 s = zbc_program_prep(&ptr, &num);
6645 if (s) RETURN_STATUS(s);
6646 bc_num_init_DEF_SIZE(&r.d.n);
6647 if (bc_num_cmp(num, &G.prog.zero) == 0)
6649 //else bc_num_zero(&r.d.n); - already is
6650 bc_program_retire(&r, XC_RESULT_TEMP);
6654 dbg_exec("XC_INST_NEG:");
6655 s = zbc_program_negate();
6658 case BC_INST_ASSIGN_POWER:
6659 case BC_INST_ASSIGN_MULTIPLY:
6660 case BC_INST_ASSIGN_DIVIDE:
6661 case BC_INST_ASSIGN_MODULUS:
6662 case BC_INST_ASSIGN_PLUS:
6663 case BC_INST_ASSIGN_MINUS:
6665 case XC_INST_ASSIGN:
6666 dbg_exec("BC_INST_ASSIGNxyz:");
6667 s = zbc_program_assign(inst);
6670 case DC_INST_POP_EXEC:
6671 dbg_exec("DC_INST_POP_EXEC:");
6672 bc_vec_pop(&G.prog.exestack);
6673 goto read_updated_ip;
6674 case DC_INST_MODEXP:
6675 dbg_exec("DC_INST_MODEXP:");
6676 s = zdc_program_modexp();
6678 case DC_INST_DIVMOD:
6679 dbg_exec("DC_INST_DIVMOD:");
6680 s = zdc_program_divmod();
6682 case DC_INST_EXECUTE:
6683 case DC_INST_EXEC_COND:
6684 dbg_exec("DC_INST_EXEC[_COND]:");
6685 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6686 goto read_updated_ip;
6687 case DC_INST_PRINT_STACK: {
6689 dbg_exec("DC_INST_PRINT_STACK:");
6690 for (idx = 0; idx < G.prog.results.len; ++idx) {
6691 s = zbc_program_print(XC_INST_PRINT, idx);
6696 case DC_INST_CLEAR_STACK:
6697 dbg_exec("DC_INST_CLEAR_STACK:");
6698 bc_vec_pop_all(&G.prog.results);
6700 case DC_INST_STACK_LEN:
6701 dbg_exec("DC_INST_STACK_LEN:");
6702 dc_program_stackLen();
6704 case DC_INST_DUPLICATE:
6705 dbg_exec("DC_INST_DUPLICATE:");
6706 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6707 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6708 ptr = bc_vec_top(&G.prog.results);
6709 dc_result_copy(&r, ptr);
6710 bc_vec_push(&G.prog.results, &r);
6712 case DC_INST_SWAP: {
6714 dbg_exec("DC_INST_SWAP:");
6715 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6716 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6717 ptr = bc_vec_item_rev(&G.prog.results, 0);
6718 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6719 memcpy(&r, ptr, sizeof(BcResult));
6720 memcpy(ptr, ptr2, sizeof(BcResult));
6721 memcpy(ptr2, &r, sizeof(BcResult));
6724 case DC_INST_ASCIIFY:
6725 dbg_exec("DC_INST_ASCIIFY:");
6726 s = zdc_program_asciify();
6728 case DC_INST_PRINT_STREAM:
6729 dbg_exec("DC_INST_PRINT_STREAM:");
6730 s = zdc_program_printStream();
6733 case DC_INST_PUSH_VAR: {
6734 bool copy = inst == DC_INST_LOAD;
6735 s = zbc_program_pushVar(code, &ip->inst_idx, true, copy);
6738 case DC_INST_PUSH_TO_VAR: {
6739 char *name = bc_program_name(code, &ip->inst_idx);
6740 s = zbc_program_copyToVar(name, true);
6745 dbg_exec("DC_INST_QUIT:");
6746 if (G.prog.exestack.len <= 2)
6747 QUIT_OR_RETURN_TO_MAIN;
6748 bc_vec_npop(&G.prog.exestack, 2);
6749 goto read_updated_ip;
6751 dbg_exec("DC_INST_NQUIT:");
6752 s = zdc_program_nquit();
6753 //goto read_updated_ip; - just fall through to it
6756 // Instruction stack has changed, read new pointers
6757 ip = bc_vec_top(&G.prog.exestack);
6758 func = bc_program_func(ip->func);
6759 code = func->code.v;
6760 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6763 if (s || G_interrupt) {
6771 RETURN_STATUS(BC_STATUS_SUCCESS);
6773 #define zbc_program_exec(...) (zbc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6775 static unsigned bc_vm_envLen(const char *var)
6781 len = BC_NUM_PRINT_WIDTH;
6782 if (!lenv) return len;
6784 len = bb_strtou(lenv, NULL, 10) - 1;
6785 if (errno || len < 2 || len >= INT_MAX)
6786 len = BC_NUM_PRINT_WIDTH;
6791 static BC_STATUS zbc_vm_process(const char *text)
6795 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6796 s = zbc_parse_text_init(text); // does the first zbc_lex_next()
6797 if (s) RETURN_STATUS(s);
6800 while (G.prs.l.lex != XC_LEX_EOF) {
6804 dbg_lex("%s:%d G.prs.l.lex:%d, parsing...", __func__, __LINE__, G.prs.l.lex);
6807 if (G.prs.l.lex == BC_LEX_SCOLON
6808 || G.prs.l.lex == XC_LEX_NLINE
6815 s = zbc_parse_stmt_or_funcdef();
6818 // Check that next token is a correct stmt delimiter -
6819 // disallows "print 1 print 2" and such.
6820 if (G.prs.l.lex != BC_LEX_SCOLON
6821 && G.prs.l.lex != XC_LEX_NLINE
6822 && G.prs.l.lex != XC_LEX_EOF
6825 //TODO: commonalize for other parse errors:
6826 err_at = G.prs.l.lex_next_at ? G.prs.l.lex_next_at : "UNKNOWN";
6827 bc_error_fmt("bad statement terminator at '%.*s'",
6828 (int)(strchrnul(err_at, '\n') - err_at),
6833 // The above logic is fragile. Check these examples:
6834 // - interative read() still works
6838 // Most of dc parsing assumes all whitespace,
6839 // including '\n', is eaten.
6840 while (G.prs.l.lex == XC_LEX_NLINE) {
6843 if (G.prs.l.lex == XC_LEX_EOF)
6846 s = zdc_parse_expr();
6849 if (s || G_interrupt) {
6851 bc_parse_reset(); // includes bc_program_reset()
6852 RETURN_STATUS(BC_STATUS_FAILURE);
6855 dbg_lex("%s:%d executing...", __func__, __LINE__);
6856 s = zbc_program_exec();
6862 ip = (void*)G.prog.exestack.v;
6864 if (G.prog.exestack.len != 1) // should have only main's IP
6865 bb_error_msg_and_die("BUG:call stack");
6866 if (ip->func != BC_PROG_MAIN)
6867 bb_error_msg_and_die("BUG:not MAIN");
6869 f = bc_program_func_BC_PROG_MAIN();
6870 // bc discards strings, constants and code after each
6871 // top-level statement in the "main program".
6872 // This prevents "yes 1 | bc" from growing its memory
6873 // without bound. This can be done because data stack
6874 // is empty and thus can't hold any references to
6875 // strings or constants, there is no generated code
6876 // which can hold references (after we discard one
6877 // we just executed). Code of functions can have references,
6878 // but bc stores function strings/constants in per-function
6882 if (G.prog.results.len != 0) // should be empty
6883 bb_error_msg_and_die("BUG:data stack");
6885 IF_BC(bc_vec_pop_all(&f->strs);)
6886 IF_BC(bc_vec_pop_all(&f->consts);)
6888 if (G.prog.results.len == 0
6889 && G.prog.vars.len == 0
6891 // If stack is empty and no registers exist (TODO: or they are all empty),
6892 // we can get rid of accumulated strings and constants.
6893 // In this example dc process should not grow
6894 // its memory consumption with time:
6896 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6897 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6899 // The code is discarded always (below), thus this example
6900 // should also not grow its memory consumption with time,
6901 // even though its data stack is not empty:
6902 // { echo 1; yes dk; } | dc
6904 // We drop generated and executed code for both bc and dc:
6905 bc_vec_pop_all(&f->code);
6909 dbg_lex_done("%s:%d done", __func__, __LINE__);
6912 #define zbc_vm_process(...) (zbc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6914 static BC_STATUS zbc_vm_execute_FILE(FILE *fp, const char *filename)
6916 // So far bc/dc have no way to include a file from another file,
6917 // therefore we know G.prs.filename == NULL on entry
6918 //const char *sv_file;
6921 G.prs.filename = filename;
6922 G.prs.input_fp = fp;
6926 s = zbc_vm_process("");
6927 // We do not stop looping on errors here if reading stdin.
6928 // Example: start interactive bc and enter "return".
6929 // It should say "'return' not in a function"
6930 // but should not exit.
6931 } while (G.prs.input_fp == stdin);
6932 G.prs.filename = NULL;
6935 #define zbc_vm_execute_FILE(...) (zbc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6937 static BC_STATUS zbc_vm_file(const char *file)
6942 fp = xfopen_for_read(file);
6943 s = zbc_vm_execute_FILE(fp, file);
6948 #define zbc_vm_file(...) (zbc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6951 static void bc_vm_info(void)
6953 printf("%s "BB_VER"\n"
6954 "Adapted from https://github.com/gavinhoward/bc\n"
6955 "Original code (c) 2018 Gavin D. Howard and contributors\n"
6959 static void bc_args(char **argv)
6965 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6966 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6967 "warn\0" No_argument "w"
6968 "version\0" No_argument "v"
6969 "standard\0" No_argument "s"
6970 "quiet\0" No_argument "q"
6971 "mathlib\0" No_argument "l"
6972 "interactive\0" No_argument "i"
6975 opts = option_mask32 |= getopt32(argv, "wvsqli");
6977 if (getenv("POSIXLY_CORRECT"))
6978 option_mask32 |= BC_FLAG_S;
6980 if (opts & BC_FLAG_V) {
6985 for (i = optind; argv[i]; ++i)
6986 bc_vec_push(&G.files, argv + i);
6989 static void bc_vm_envArgs(void)
6993 char *env_args = getenv("BC_ENV_ARGS");
6995 if (!env_args) return;
6997 G.env_args = xstrdup(env_args);
7000 bc_vec_init(&v, sizeof(char *), NULL);
7002 while (*(buf = skip_whitespace(buf)) != '\0') {
7003 bc_vec_push(&v, &buf);
7004 buf = skip_non_whitespace(buf);
7010 // NULL terminate, and pass argv[] so that first arg is argv[1]
7011 if (sizeof(int) == sizeof(char*)) {
7012 bc_vec_push(&v, &const_int_0);
7014 static char *const nullptr = NULL;
7015 bc_vec_push(&v, &nullptr);
7017 bc_args(((char **)v.v) - 1);
7022 static const char bc_lib[] ALIGN1 = {
7025 "\n" "auto b,s,n,r,d,i,p,f,v"
7026 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
7027 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
7028 //e(-.998896): GNU:.36828580434569428695
7029 // above code:.36828580434569428696
7030 // actual value:.3682858043456942869594...
7031 // but for now let's be "GNU compatible"
7040 "\n" "scale=scale(x)+1"
7050 "\n" "for(i=2;v;++i){"
7056 "\n" "while(d--)r*=r"
7059 "\n" "if(n)return(1/r)"
7063 "\n" "auto b,s,r,p,a,q,i,v"
7067 "\n" "r=(1-10^scale)/1"
7078 "\n" "while(x<=.5){"
7082 "\n" "r=a=(x-1)/(x+1)"
7085 "\n" "for(i=3;v;i+=2){"
7096 "\n" "auto b,s,r,a,q,i"
7097 "\n" "if(x<0)return(-s(-x))"
7101 "\n" "scale=1.1*s+2"
7110 "\n" "for(i=3;a;i+=2){"
7111 "\n" "a*=q/(i*(i-1))"
7124 "\n" "x=s(2*a(1)+x)"
7130 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7138 "\n" "if(scale<65){"
7139 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7140 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7150 "\n" "x=(x-.2)/(1+.2*x)"
7155 "\n" "for(i=3;t;i+=2){"
7162 "\n" "return((m*a+r)/n)"
7164 "\n" "define j(n,x){"
7165 "\n" "auto b,s,o,a,i,v,f"
7176 "\n" "for(i=2;i<=n;++i)a*=i"
7178 "\n" "a=(x^n)/2^n/a"
7181 "\n" "scale+=length(a)-scale(a)"
7182 "\n" "for(i=1;v;++i){"
7183 "\n" "v=v*f/i/(n+i)"
7189 "\n" "return(a*r/1)"
7194 static BC_STATUS zbc_vm_exec(void)
7201 if (option_mask32 & BC_FLAG_L) {
7202 // We know that internal library is not buggy,
7203 // thus error checking is normally disabled.
7204 # define DEBUG_LIB 0
7206 s = zbc_vm_process(bc_lib);
7207 if (DEBUG_LIB && s) RETURN_STATUS(s);
7211 s = BC_STATUS_SUCCESS;
7212 fname = (void*)G.files.v;
7213 for (i = 0; i < G.files.len; i++) {
7214 s = zbc_vm_file(*fname++);
7215 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7216 // Debug config, non-interactive mode:
7217 // return all the way back to main.
7218 // Non-debug builds do not come here
7219 // in non-interactive mode, they exit.
7224 if (IS_BC || (option_mask32 & BC_FLAG_I))
7225 s = zbc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7229 #define zbc_vm_exec(...) (zbc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7231 #if ENABLE_FEATURE_CLEAN_UP
7232 static void bc_program_free(void)
7234 bc_vec_free(&G.prog.fns);
7235 IF_BC(bc_vec_free(&G.prog.fn_map);)
7236 bc_vec_free(&G.prog.vars);
7237 bc_vec_free(&G.prog.var_map);
7238 bc_vec_free(&G.prog.arrs);
7239 bc_vec_free(&G.prog.arr_map);
7240 IF_DC(bc_vec_free(&G.prog.strs);)
7241 IF_DC(bc_vec_free(&G.prog.consts);)
7242 bc_vec_free(&G.prog.results);
7243 bc_vec_free(&G.prog.exestack);
7244 IF_BC(bc_num_free(&G.prog.last);)
7245 IF_BC(bc_num_free(&G.prog.zero);)
7246 IF_BC(bc_num_free(&G.prog.one);)
7247 bc_vec_free(&G.input_buffer);
7250 static void bc_vm_free(void)
7252 bc_vec_free(&G.files);
7259 static void bc_program_init(void)
7263 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7264 memset(&ip, 0, sizeof(BcInstPtr));
7266 // G.prog.nchars = G.prog.scale = 0; - already is
7270 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7271 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7273 bc_num_init_DEF_SIZE(&G.prog.zero);
7274 //bc_num_zero(&G.prog.zero); - already is
7276 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7277 IF_BC(bc_num_one(&G.prog.one);)
7279 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7280 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7283 // Names are chosen simply to be distinct and never match
7284 // a valid function name (and be short)
7285 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7286 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7288 // in dc, functions have no names
7289 bc_program_add_fn();
7290 bc_program_add_fn();
7293 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7294 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7296 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7297 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7299 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7300 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7301 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7302 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7303 bc_vec_push(&G.prog.exestack, &ip);
7305 bc_char_vec_init(&G.input_buffer);
7308 static int bc_vm_init(const char *env_len)
7310 #if ENABLE_FEATURE_EDITING
7311 G.line_input_state = new_line_input_t(DO_HISTORY);
7313 G.prog.len = bc_vm_envLen(env_len);
7315 bc_vec_init(&G.files, sizeof(char *), NULL);
7316 IF_BC(if (IS_BC) bc_vm_envArgs();)
7318 bc_parse_create(BC_PROG_MAIN);
7320 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7321 //-i option unconditionally enables this regardless of isatty():
7323 #if ENABLE_FEATURE_BC_SIGNALS
7325 // With SA_RESTART, most system calls will restart
7326 // (IOW: they won't fail with EINTR).
7327 // In particular, this means ^C won't cause
7328 // stdout to get into "error state" if SIGINT hits
7329 // within write() syscall.
7331 // The downside is that ^C while tty input is taken
7332 // will only be handled after [Enter] since read()
7333 // from stdin is not interrupted by ^C either,
7334 // it restarts, thus fgetc() does not return on ^C.
7335 // (This problem manifests only if line editing is disabled)
7336 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7338 // Without SA_RESTART, this exhibits a bug:
7339 // "while (1) print 1" and try ^C-ing it.
7340 // Intermittently, instead of returning to input line,
7341 // you'll get "output error: Interrupted system call"
7343 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7347 return 0; // "not a tty"
7350 static BcStatus bc_vm_run(void)
7352 BcStatus st = zbc_vm_exec();
7353 #if ENABLE_FEATURE_CLEAN_UP
7354 if (G_exiting) // it was actually "halt" or "quit"
7357 # if ENABLE_FEATURE_EDITING
7358 free_line_input_t(G.line_input_state);
7362 dbg_exec("exiting with exitcode %d", st);
7367 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7368 int bc_main(int argc UNUSED_PARAM, char **argv)
7374 is_tty = bc_vm_init("BC_LINE_LENGTH");
7378 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7386 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7387 int dc_main(int argc UNUSED_PARAM, char **argv)
7393 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7394 // 1 char wider than bc from the same package.
7395 // Both default width, and xC_LINE_LENGTH=N are wider:
7396 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7399 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7402 // Do the same, or it's a bug?
7403 bc_vm_init("DC_LINE_LENGTH");
7405 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7406 noscript = BC_FLAG_I;
7408 int n = getopt(argc, argv, "e:f:x");
7414 n = zbc_vm_process(optarg);
7419 n = zbc_vm_file(optarg);
7423 option_mask32 |= DC_FLAG_X;
7433 bc_vec_push(&G.files, argv++);
7436 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7442 #endif // not DC_SMALL