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.
7 //TODO: GNU extensions:
8 // support "define void f()..."
9 // support "define f(*param[])" - "pass array by reference" syntax
12 #define DEBUG_COMPILE 0
14 // This can be left enabled for production as well:
15 #define SANITY_CHECKS 1
18 //config: bool "bc (45 kb)"
20 //config: select FEATURE_DC_BIG
22 //config: bc is a command-line, arbitrary-precision calculator with a
23 //config: Turing-complete language. See the GNU bc manual
24 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
25 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
27 //config: This bc has five differences to the GNU bc:
28 //config: 1) The period (.) is a shortcut for "last", as in the BSD bc.
29 //config: 2) Arrays are copied before being passed as arguments to
30 //config: functions. This behavior is required by the bc spec.
31 //config: 3) Arrays can be passed to the builtin "length" function to get
32 //config: the number of elements in the array. This prints "1":
33 //config: a[0] = 0; length(a[])
34 //config: 4) The precedence of the boolean "not" operator (!) is equal to
35 //config: that of the unary minus (-) negation operator. This still
36 //config: allows POSIX-compliant scripts to work while somewhat
37 //config: preserving expected behavior (versus C) and making parsing
39 //config: 5) "read()" accepts expressions, not only numeric literals.
42 //config: bool "dc (36 kb)"
45 //config: dc is a reverse-polish notation command-line calculator which
46 //config: supports unlimited precision arithmetic. See the FreeBSD man page
47 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
48 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
50 //config: This dc has a few differences from the two above:
51 //config: 1) When printing a byte stream (command "P"), this dc follows what
52 //config: the FreeBSD dc does.
53 //config: 2) Implements the GNU extensions for divmod ("~") and
54 //config: modular exponentiation ("|").
55 //config: 3) Implements all FreeBSD extensions, except for "J" and "M".
56 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
57 //config: However, they are implemented differently. When it encounters
58 //config: whitespace where a register should be, it skips the whitespace.
59 //config: If the character following is not a lowercase letter, an error
60 //config: is issued. Otherwise, the register name is parsed by the
61 //config: following regex: [a-z][a-z0-9_]*
62 //config: This generally means that register names will be surrounded by
63 //config: whitespace. Examples:
64 //config: l idx s temp L index S temp2 < do_thing
65 //config: Also note that, like the FreeBSD dc, extended registers are not
66 //config: allowed unless the "-x" option is given.
68 //config:if BC || DC # for menuconfig indenting
70 //config:config FEATURE_DC_BIG
71 //config: bool "Use bc code base for dc (larger, more features)"
74 //config:config FEATURE_DC_LIBM
75 //config: bool "Enable power and exp functions (requires libm)"
77 //config: depends on DC && !BC && !FEATURE_DC_BIG
79 //config: Enable power and exp functions.
80 //config: NOTE: This will require libm to be present for linking.
82 //config:config FEATURE_BC_INTERACTIVE
83 //config: bool "Interactive mode (+4kb)"
85 //config: depends on BC || (DC && FEATURE_DC_BIG)
87 //config: Enable interactive mode: when started on a tty,
88 //config: ^C interrupts execution and returns to command line,
89 //config: errors also return to command line instead of exiting,
90 //config: line editing with history is available.
92 //config: With this option off, input can still be taken from tty,
93 //config: but all errors are fatal, ^C is fatal,
94 //config: tty is treated exactly the same as any other
95 //config: standard input (IOW: no line editing).
97 //config:config FEATURE_BC_LONG_OPTIONS
98 //config: bool "Enable bc/dc long options"
100 //config: depends on BC || (DC && FEATURE_DC_BIG)
104 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
105 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
107 //kbuild:lib-$(CONFIG_BC) += bc.o
108 //kbuild:lib-$(CONFIG_DC) += bc.o
110 //See www.gnu.org/software/bc/manual/bc.html
111 //usage:#define bc_trivial_usage
112 //usage: "[-sqlw] FILE..."
114 //usage:#define bc_full_usage "\n"
115 //usage: "\nArbitrary precision calculator"
117 ///////: "\n -i Interactive" - has no effect for now
118 //usage: "\n -q Quiet"
119 //usage: "\n -l Load standard math library"
120 //usage: "\n -s Be POSIX compatible"
121 //usage: "\n -w Warn if extensions are used"
122 ///////: "\n -v Version"
124 //usage: "\n$BC_LINE_LENGTH changes output width"
126 //usage:#define bc_example_usage
127 //usage: "3 + 4.129\n"
128 //usage: "1903 - 2893\n"
129 //usage: "-129 * 213.28935\n"
130 //usage: "12 / -1932\n"
132 //usage: "34 ^ 189\n"
133 //usage: "scale = 13\n"
134 //usage: "ibase = 2\n"
135 //usage: "obase = A\n"
137 //usage:#define dc_trivial_usage
138 //usage: IF_FEATURE_DC_BIG("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
140 //usage:#define dc_full_usage "\n"
141 //usage: "\nTiny RPN calculator. Operations:"
142 //usage: "\n+, -, *, /, %, ~, ^," IF_FEATURE_DC_BIG(" |,")
143 //usage: "\np - print top of the stack without popping"
144 //usage: "\nf - print entire stack"
145 //usage: "\nk - pop the value and set the precision"
146 //usage: "\ni - pop the value and set input radix"
147 //usage: "\no - pop the value and set output radix"
148 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
150 //usage:#define dc_example_usage
151 //usage: "$ dc -e'2 2 + p'\n"
153 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
155 //usage: "$ dc -e'0 1 & p'\n"
157 //usage: "$ dc -e'0 1 | p'\n"
159 //usage: "$ echo '72 9 / 8 * p' | dc\n"
163 #include "common_bufsiz.h"
165 #if !ENABLE_BC && !ENABLE_FEATURE_DC_BIG
170 static uint8_t lex_indent;
171 #define dbg_lex(...) \
173 fprintf(stderr, "%*s", lex_indent, ""); \
174 bb_error_msg(__VA_ARGS__); \
176 #define dbg_lex_enter(...) \
178 dbg_lex(__VA_ARGS__); \
181 #define dbg_lex_done(...) \
184 dbg_lex(__VA_ARGS__); \
187 # define dbg_lex(...) ((void)0)
188 # define dbg_lex_enter(...) ((void)0)
189 # define dbg_lex_done(...) ((void)0)
193 # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
195 # define dbg_compile(...) ((void)0)
199 # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
201 # define dbg_exec(...) ((void)0)
204 typedef enum BcStatus {
205 BC_STATUS_SUCCESS = 0,
206 BC_STATUS_FAILURE = 1,
207 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr_empty_ok() uses this
210 #define BC_VEC_INVALID_IDX ((size_t) -1)
211 #define BC_VEC_START_CAP (1 << 5)
213 typedef void (*BcVecFree)(void *) FAST_FUNC;
215 typedef struct BcVec {
223 typedef signed char BcDig;
225 typedef struct BcNum {
233 #define BC_NUM_MAX_IBASE 36
234 // larger value might speed up BIGNUM calculations a bit:
235 #define BC_NUM_DEF_SIZE 16
236 #define BC_NUM_PRINT_WIDTH 69
238 #define BC_NUM_KARATSUBA_LEN 32
240 typedef enum BcInst {
247 XC_INST_NEG, // order
249 XC_INST_REL_EQ, // should
250 XC_INST_REL_LE, // match
251 XC_INST_REL_GE, // LEX
252 XC_INST_REL_NE, // constants
253 XC_INST_REL_LT, // for
254 XC_INST_REL_GT, // these
256 XC_INST_POWER, // operations
257 XC_INST_MULTIPLY, // |
259 XC_INST_MODULUS, // |
263 XC_INST_BOOL_NOT, // |
264 XC_INST_BOOL_OR, // |
265 XC_INST_BOOL_AND, // |
267 BC_INST_ASSIGN_POWER, // |
268 BC_INST_ASSIGN_MULTIPLY,// |
269 BC_INST_ASSIGN_DIVIDE, // |
270 BC_INST_ASSIGN_MODULUS, // |
271 BC_INST_ASSIGN_PLUS, // |
272 BC_INST_ASSIGN_MINUS, // |
282 XC_INST_IBASE, // order of these constans should match other enums
283 XC_INST_OBASE, // order of these constans should match other enums
284 XC_INST_SCALE, // order of these constans should match other enums
285 IF_BC(BC_INST_LAST,) // order of these constans should match other enums
316 DC_INST_PRINT_STREAM,
331 DC_INST_INVALID = -1,
335 typedef struct BcId {
340 typedef struct BcFunc {
346 IF_BC(size_t nparams;)
349 typedef enum BcResultType {
353 XC_RESULT_ARRAY_ELEM,
358 //code uses "inst - XC_INST_IBASE + XC_RESULT_IBASE" construct,
359 XC_RESULT_IBASE, // relative order should match for: XC_INST_IBASE
360 XC_RESULT_OBASE, // relative order should match for: XC_INST_OBASE
361 XC_RESULT_SCALE, // relative order should match for: XC_INST_SCALE
362 IF_BC(BC_RESULT_LAST,) // relative order should match for: BC_INST_LAST
364 IF_BC(BC_RESULT_ONE,)
367 typedef union BcResultData {
373 typedef struct BcResult {
378 typedef struct BcInstPtr {
381 IF_BC(size_t results_len_before_call;)
384 typedef enum BcLexType {
395 XC_LEX_NEG = XC_LEX_1st_op, // order
397 XC_LEX_OP_REL_EQ, // should
398 XC_LEX_OP_REL_LE, // match
399 XC_LEX_OP_REL_GE, // INST
400 XC_LEX_OP_REL_NE, // constants
401 XC_LEX_OP_REL_LT, // for
402 XC_LEX_OP_REL_GT, // these
404 XC_LEX_OP_POWER, // operations
405 XC_LEX_OP_MULTIPLY, // |
406 XC_LEX_OP_DIVIDE, // |
407 XC_LEX_OP_MODULUS, // |
409 XC_LEX_OP_MINUS, // |
410 XC_LEX_OP_last = XC_LEX_OP_MINUS,
412 BC_LEX_OP_BOOL_NOT, // |
413 BC_LEX_OP_BOOL_OR, // |
414 BC_LEX_OP_BOOL_AND, // |
416 BC_LEX_OP_ASSIGN_POWER, // |
417 BC_LEX_OP_ASSIGN_MULTIPLY, // |
418 BC_LEX_OP_ASSIGN_DIVIDE, // |
419 BC_LEX_OP_ASSIGN_MODULUS, // |
420 BC_LEX_OP_ASSIGN_PLUS, // |
421 BC_LEX_OP_ASSIGN_MINUS, // |
423 BC_LEX_OP_ASSIGN, // V
428 BC_LEX_LPAREN, // () are 0x28 and 0x29
429 BC_LEX_RPAREN, // must be LPAREN+1: code uses (c - '(' + BC_LEX_LPAREN)
431 BC_LEX_LBRACKET, // [] are 0x5B and 0x5D
433 BC_LEX_RBRACKET, // must be LBRACKET+2: code uses (c - '[' + BC_LEX_LBRACKET)
435 BC_LEX_LBRACE, // {} are 0x7B and 0x7D
437 BC_LEX_RBRACE, // must be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
439 BC_LEX_KEY_1st_keyword,
440 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
447 // code uses "type - BC_LEX_KEY_IBASE + XC_INST_IBASE" construct,
448 BC_LEX_KEY_IBASE, // relative order should match for: XC_INST_IBASE
449 BC_LEX_KEY_OBASE, // relative order should match for: XC_INST_OBASE
451 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
464 DC_LEX_OP_BOOL_NOT = XC_LEX_OP_last + 1,
496 // code uses "t - DC_LEX_STORE_IBASE + XC_INST_IBASE" construct,
497 DC_LEX_STORE_IBASE, // relative order should match for: XC_INST_IBASE
498 DC_LEX_STORE_OBASE, // relative order should match for: XC_INST_OBASE
499 DC_LEX_STORE_SCALE, // relative order should match for: XC_INST_SCALE
508 // must match order of BC_LEX_KEY_foo etc above
510 struct BcLexKeyword {
513 #define LEX_KW_ENTRY(a, b) \
514 { .name8 = a /*, .posix = b */ }
515 static const struct BcLexKeyword bc_lex_kws[20] = {
516 LEX_KW_ENTRY("auto" , 1), // 0
517 LEX_KW_ENTRY("break" , 1), // 1
518 LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
519 LEX_KW_ENTRY("define" , 1), // 3
520 LEX_KW_ENTRY("else" , 0), // 4
521 LEX_KW_ENTRY("for" , 1), // 5
522 LEX_KW_ENTRY("halt" , 0), // 6
523 LEX_KW_ENTRY("ibase" , 1), // 7
524 LEX_KW_ENTRY("obase" , 1), // 8
525 LEX_KW_ENTRY("if" , 1), // 9
526 LEX_KW_ENTRY("last" , 0), // 10
527 LEX_KW_ENTRY("length" , 1), // 11
528 LEX_KW_ENTRY("limits" , 0), // 12
529 LEX_KW_ENTRY("print" , 0), // 13
530 LEX_KW_ENTRY("quit" , 1), // 14
531 LEX_KW_ENTRY("read" , 0), // 15
532 LEX_KW_ENTRY("return" , 1), // 16
533 LEX_KW_ENTRY("scale" , 1), // 17
534 LEX_KW_ENTRY("sqrt" , 1), // 18
535 LEX_KW_ENTRY("while" , 1), // 19
538 #define STRING_else (bc_lex_kws[4].name8)
539 #define STRING_for (bc_lex_kws[5].name8)
540 #define STRING_if (bc_lex_kws[9].name8)
541 #define STRING_while (bc_lex_kws[19].name8)
565 #define keyword_is_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
567 // This is a bit array that corresponds to token types. An entry is
568 // true if the token is valid in an expression, false otherwise.
569 // Used to figure out when expr parsing should stop *without error message*
570 // - 0 element indicates this condition. 1 means "this token is to be eaten
571 // as part of the expression", it can then still be determined to be invalid
572 // by later processing.
574 #define EXBITS(a,b,c,d,e,f,g,h) \
575 ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
576 BC_PARSE_EXPRS_BITS = 0 // corresponding BC_LEX_xyz:
577 + (EXBITS(0,0,0,0,0,1,1,1) << (0*8)) // 0: EOF INVAL NL WS STR NAME NUM -
578 + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: == <= >= != < > ^ *
579 + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: / % + - ! || && ^=
580 + (EXBITS(1,1,1,1,1,1,1,1) << (3*8)) // 24: *= /= %= += -= = ++ --
581 + (EXBITS(1,1,0,0,0,0,0,0) << (4*8)) // 32: ( ) [ , ] { ; }
582 + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
583 + (EXBITS(1,0,1,1,0,0,0,1) << (6*8)) // 48: obase if last length limits print quit read
584 + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
587 static ALWAYS_INLINE long lex_allowed_in_bc_expr(unsigned i)
589 #if ULONG_MAX > 0xffffffff
590 // 64-bit version (will not work correctly for 32-bit longs!)
591 return BC_PARSE_EXPRS_BITS & (1UL << i);
594 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
596 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
599 return m & (1UL << i);
603 // This is an array of data for operators that correspond to
604 // [XC_LEX_1st_op...] token types.
605 static const uint8_t bc_ops_prec_and_assoc[] ALIGN1 = {
606 #define OP(p,l) ((int)(l) * 0x10 + (p))
608 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
610 OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
611 OP(4, true ), OP( 4, true ), // + -
613 OP(7, true ), OP( 7, true ), // or and
614 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
615 OP(5, false), OP( 5, false ), // -= =
616 OP(0, false), OP( 0, false ), // inc dec
619 #define bc_operation_PREC(i) (bc_ops_prec_and_assoc[i] & 0x0f)
620 #define bc_operation_LEFT(i) (bc_ops_prec_and_assoc[i] & 0x10)
624 static const //BcLexType - should be this type
626 dc_char_to_LEX[] ALIGN1 = {
628 XC_LEX_OP_MODULUS, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_LPAREN,
630 XC_LEX_INVALID, XC_LEX_OP_MULTIPLY, XC_LEX_OP_PLUS, XC_LEX_INVALID,
632 XC_LEX_OP_MINUS, XC_LEX_INVALID, XC_LEX_OP_DIVIDE,
634 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
635 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
636 XC_LEX_INVALID, XC_LEX_INVALID,
638 DC_LEX_COLON, DC_LEX_SCOLON, XC_LEX_OP_REL_GT, XC_LEX_OP_REL_EQ,
639 XC_LEX_OP_REL_LT, DC_LEX_READ, XC_LEX_INVALID,
641 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
642 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_EQ_NO_REG, XC_LEX_INVALID,
644 DC_LEX_IBASE, XC_LEX_INVALID, DC_LEX_SCALE, DC_LEX_LOAD_POP,
645 XC_LEX_INVALID, DC_LEX_OP_BOOL_NOT, DC_LEX_OBASE, DC_LEX_PRINT_STREAM,
647 DC_LEX_NQUIT, DC_LEX_POP, DC_LEX_STORE_PUSH, XC_LEX_INVALID, XC_LEX_INVALID,
648 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_SCALE_FACTOR, XC_LEX_INVALID,
650 DC_LEX_LENGTH, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
652 XC_LEX_OP_POWER, XC_LEX_NEG, XC_LEX_INVALID,
654 DC_LEX_ASCIIFY, XC_LEX_INVALID, DC_LEX_CLEAR_STACK, DC_LEX_DUPLICATE,
655 DC_LEX_ELSE, DC_LEX_PRINT_STACK, XC_LEX_INVALID, XC_LEX_INVALID,
657 DC_LEX_STORE_IBASE, XC_LEX_INVALID, DC_LEX_STORE_SCALE, DC_LEX_LOAD,
658 XC_LEX_INVALID, DC_LEX_PRINT_POP, DC_LEX_STORE_OBASE, DC_LEX_PRINT,
660 DC_LEX_QUIT, DC_LEX_SWAP, DC_LEX_OP_ASSIGN, XC_LEX_INVALID,
661 XC_LEX_INVALID, DC_LEX_SQRT, XC_LEX_INVALID, DC_LEX_EXECUTE,
663 XC_LEX_INVALID, DC_LEX_STACK_LEVEL,
665 DC_LEX_LBRACE, DC_LEX_OP_MODEXP, XC_LEX_INVALID, DC_LEX_OP_DIVMOD,
667 static const //BcInst - should be this type. Using signed narrow type since DC_INST_INVALID is -1
669 dc_LEX_to_INST[] ALIGN1 = { //starts at XC_LEX_OP_POWER // corresponding XC/DC_LEX_xyz:
670 XC_INST_POWER, XC_INST_MULTIPLY, // XC_LEX_OP_POWER XC_LEX_OP_MULTIPLY
671 XC_INST_DIVIDE, XC_INST_MODULUS, // XC_LEX_OP_DIVIDE XC_LEX_OP_MODULUS
672 XC_INST_PLUS, XC_INST_MINUS, // XC_LEX_OP_PLUS XC_LEX_OP_MINUS
673 XC_INST_BOOL_NOT, // DC_LEX_OP_BOOL_NOT
674 DC_INST_INVALID, // DC_LEX_OP_ASSIGN
675 XC_INST_REL_GT, // DC_LEX_LPAREN
676 DC_INST_INVALID, // DC_LEX_SCOLON
677 DC_INST_INVALID, // DC_LEX_READ
678 XC_INST_IBASE, // DC_LEX_IBASE
679 XC_INST_SCALE, // DC_LEX_SCALE
680 XC_INST_OBASE, // DC_LEX_OBASE
681 XC_INST_LENGTH, // DC_LEX_LENGTH
682 XC_INST_PRINT, // DC_LEX_PRINT
683 DC_INST_QUIT, // DC_LEX_QUIT
684 XC_INST_SQRT, // DC_LEX_SQRT
685 XC_INST_REL_GE, // DC_LEX_LBRACE
686 XC_INST_REL_EQ, // DC_LEX_EQ_NO_REG
687 DC_INST_MODEXP, DC_INST_DIVMOD, // DC_LEX_OP_MODEXP DC_LEX_OP_DIVMOD
688 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_COLON DC_LEX_ELSE
689 DC_INST_EXECUTE, // DC_LEX_EXECUTE
690 DC_INST_PRINT_STACK, DC_INST_CLEAR_STACK, // DC_LEX_PRINT_STACK DC_LEX_CLEAR_STACK
691 DC_INST_STACK_LEN, DC_INST_DUPLICATE, // DC_LEX_STACK_LEVEL DC_LEX_DUPLICATE
692 DC_INST_SWAP, XC_INST_POP, // DC_LEX_SWAP DC_LEX_POP
693 DC_INST_ASCIIFY, DC_INST_PRINT_STREAM, // DC_LEX_ASCIIFY DC_LEX_PRINT_STREAM
694 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_IBASE DC_LEX_STORE_OBASE
695 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_SCALE DC_LEX_LOAD
696 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_LOAD_POP DC_LEX_STORE_PUSH
697 XC_INST_PRINT, DC_INST_NQUIT, // DC_LEX_PRINT_POP DC_LEX_NQUIT
698 XC_INST_SCALE_FUNC, // DC_LEX_SCALE_FACTOR
699 // DC_INST_INVALID in this table either means that corresponding LEX
700 // is not possible for dc, or that it does not compile one-to-one
705 typedef struct BcParse {
706 smallint lex; // was BcLexType // first member is most used
707 smallint lex_last; // was BcLexType
709 const char *lex_inbuf;
710 const char *lex_next_at; // last lex_next() was called at this string
711 const char *lex_filename;
717 IF_BC(size_t in_funcdef;)
723 typedef struct BcProgram {
752 BcParse prs; // first member is most used
754 // For error messages. Can be set to current parsed line,
755 // or [TODO] to current executing line (can be before last parsed one)
760 IF_FEATURE_BC_INTERACTIVE(smallint ttyin;)
761 IF_FEATURE_CLEAN_UP(smallint exiting;)
769 #if ENABLE_FEATURE_EDITING
770 line_input_t *line_input_state;
773 #define G (*ptr_to_globals)
774 #define INIT_G() do { \
775 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
777 #define FREE_G() do { \
778 FREE_PTR_TO_GLOBALS(); \
780 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
781 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
782 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
783 #if ENABLE_FEATURE_BC_INTERACTIVE
784 # define G_interrupt bb_got_signal
785 # define G_ttyin G.ttyin
787 # define G_interrupt 0
790 #if ENABLE_FEATURE_CLEAN_UP
791 # define G_exiting G.exiting
795 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
796 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
799 # define BC_PARSE_REL (1 << 0)
800 # define BC_PARSE_PRINT (1 << 1)
801 # define BC_PARSE_ARRAY (1 << 2)
802 # define BC_PARSE_NOCALL (1 << 3)
805 #define BC_PROG_MAIN 0
806 #define BC_PROG_READ 1
808 #define BC_PROG_REQ_FUNCS 2
811 #define BC_FLAG_W (1 << 0)
812 #define BC_FLAG_V (1 << 1)
813 #define BC_FLAG_S (1 << 2)
814 #define BC_FLAG_Q (1 << 3)
815 #define BC_FLAG_L (1 << 4)
816 #define BC_FLAG_I ((1 << 5) * ENABLE_DC)
817 #define DC_FLAG_X ((1 << 6) * ENABLE_DC)
819 #define BC_MAX_OBASE ((unsigned) 999)
820 #define BC_MAX_DIM ((unsigned) INT_MAX)
821 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
822 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
823 #define BC_MAX_NUM BC_MAX_STRING
824 // Unused apart from "limits" message. Just show a "biggish number" there.
825 //#define BC_MAX_NAME BC_MAX_STRING
826 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
827 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
828 #define BC_MAX_NAME_STR "999999999"
829 #define BC_MAX_EXP_STR "999999999"
830 #define BC_MAX_VARS_STR "999999999"
832 #define BC_MAX_OBASE_STR "999"
834 #if INT_MAX == 2147483647
835 # define BC_MAX_DIM_STR "2147483647"
836 #elif INT_MAX == 9223372036854775807
837 # define BC_MAX_DIM_STR "9223372036854775807"
839 # error Strange INT_MAX
842 #if UINT_MAX == 4294967295
843 # define BC_MAX_SCALE_STR "4294967295"
844 # define BC_MAX_STRING_STR "4294967294"
845 #elif UINT_MAX == 18446744073709551615
846 # define BC_MAX_SCALE_STR "18446744073709551615"
847 # define BC_MAX_STRING_STR "18446744073709551614"
849 # error Strange UINT_MAX
851 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
853 // In configurations where errors abort instead of propagating error
854 // return code up the call chain, functions returning BC_STATUS
855 // actually don't return anything, they always succeed and return "void".
856 // A macro wrapper is provided, which makes this statement work:
858 // and makes it visible to the compiler that s is always zero,
859 // allowing compiler to optimize dead code after the statement.
861 // To make code more readable, each such function has a "z"
862 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
864 #if ENABLE_FEATURE_BC_INTERACTIVE || ENABLE_FEATURE_CLEAN_UP
865 # define ERRORS_ARE_FATAL 0
866 # define ERRORFUNC /*nothing*/
867 # define IF_ERROR_RETURN_POSSIBLE(a) a
868 # define BC_STATUS BcStatus
869 # define RETURN_STATUS(v) return (v)
870 # define COMMA_SUCCESS /*nothing*/
872 # define ERRORS_ARE_FATAL 1
873 # define ERRORFUNC NORETURN
874 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
875 # define BC_STATUS void
876 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
877 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
884 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
885 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
887 static void fflush_and_check(void)
890 if (ferror(stdout) || ferror(stderr))
891 bb_perror_msg_and_die("output error");
894 #if ENABLE_FEATURE_CLEAN_UP
895 #define QUIT_OR_RETURN_TO_MAIN \
897 IF_FEATURE_BC_INTERACTIVE(G_ttyin = 0;) /* do not loop in main loop anymore */ \
899 return BC_STATUS_FAILURE; \
902 static void quit(void) NORETURN;
903 static void quit(void)
906 bb_perror_msg_and_die("input error");
908 dbg_exec("quit(): exiting with exitcode SUCCESS");
911 #define QUIT_OR_RETURN_TO_MAIN quit()
914 static void bc_verror_msg(const char *fmt, va_list p)
916 const char *sv = sv; // for compiler
917 if (G.prs.lex_filename) {
919 applet_name = xasprintf("%s: %s:%u", applet_name, G.prs.lex_filename, G.err_line);
921 bb_verror_msg(fmt, p, NULL);
922 if (G.prs.lex_filename) {
923 free((char*)applet_name);
928 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
933 bc_verror_msg(fmt, p);
936 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
937 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
942 static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
946 // Are non-POSIX constructs totally ok?
947 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
948 RETURN_STATUS(BC_STATUS_SUCCESS); // yes
951 bc_verror_msg(fmt, p);
954 // Do we treat non-POSIX constructs as errors?
955 if (!(option_mask32 & BC_FLAG_S))
956 RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
958 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
959 RETURN_STATUS(BC_STATUS_FAILURE);
962 #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
965 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
966 // This idiom begs for tail-call optimization, but for it to work,
967 // function must not have caller-cleaned parameters on stack.
968 // Unfortunately, vararg function API does exactly that on most arches.
969 // Thus, use these shims for the cases when we have no vararg PARAMS:
970 static ERRORFUNC int bc_error(const char *msg)
972 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
974 static ERRORFUNC int bc_error_at(const char *msg)
976 const char *err_at = G.prs.lex_next_at;
978 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt(
981 (int)(strchrnul(err_at, '\n') - err_at),
985 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
987 static ERRORFUNC int bc_error_bad_character(char c)
990 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
991 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
993 static ERRORFUNC int bc_error_bad_function_definition(void)
995 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad function definition");
997 static ERRORFUNC int bc_error_bad_expression(void)
999 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad expression");
1001 static ERRORFUNC int bc_error_bad_assignment(void)
1003 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at(
1004 "bad assignment: left side must be variable or array element"
1007 static ERRORFUNC int bc_error_bad_token(void)
1009 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("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 static void *bc_vec_item(const BcVec *v, size_t idx)
1158 return v->v + v->size * idx;
1161 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1163 return v->v + v->size * (v->len - idx - 1);
1166 static void *bc_vec_top(const BcVec *v)
1168 return v->v + v->size * (v->len - 1);
1171 static FAST_FUNC void bc_vec_free(void *vec)
1173 BcVec *v = (BcVec *) vec;
1178 static BcFunc* xc_program_func(size_t idx)
1180 return bc_vec_item(&G.prog.fns, idx);
1182 // BC_PROG_MAIN is zeroth element, so:
1183 #define xc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1186 static BcFunc* bc_program_current_func(void)
1188 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1189 BcFunc *func = xc_program_func(ip->func);
1194 static char** xc_program_str(size_t idx)
1198 BcFunc *func = bc_program_current_func();
1199 return bc_vec_item(&func->strs, idx);
1202 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1205 static char** xc_program_const(size_t idx)
1209 BcFunc *func = bc_program_current_func();
1210 return bc_vec_item(&func->consts, idx);
1213 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1216 static int bc_id_cmp(const void *e1, const void *e2)
1218 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1221 static FAST_FUNC void bc_id_free(void *id)
1223 free(((BcId *) id)->name);
1226 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1228 size_t low = 0, high = v->len;
1230 while (low < high) {
1231 size_t mid = (low + high) / 2;
1232 BcId *id = bc_vec_item(v, mid);
1233 int result = bc_id_cmp(ptr, id);
1246 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1248 size_t n = *i = bc_map_find_ge(v, ptr);
1251 bc_vec_push(v, ptr);
1252 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1253 return 0; // "was not inserted"
1255 bc_vec_pushAt(v, ptr, n);
1256 return 1; // "was inserted"
1260 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1262 size_t i = bc_map_find_ge(v, ptr);
1263 if (i >= v->len) return BC_VEC_INVALID_IDX;
1264 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1268 static void bc_num_setToZero(BcNum *n, size_t scale)
1275 static void bc_num_zero(BcNum *n)
1277 bc_num_setToZero(n, 0);
1280 static void bc_num_one(BcNum *n)
1282 bc_num_setToZero(n, 0);
1287 // Note: this also sets BcNum to zero
1288 static void bc_num_init(BcNum *n, size_t req)
1290 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1291 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1292 n->num = xmalloc(req);
1299 static void bc_num_init_DEF_SIZE(BcNum *n)
1301 bc_num_init(n, BC_NUM_DEF_SIZE);
1304 static void bc_num_expand(BcNum *n, size_t req)
1306 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1308 n->num = xrealloc(n->num, req);
1313 static FAST_FUNC void bc_num_free(void *num)
1315 free(((BcNum *) num)->num);
1318 static void bc_num_copy(BcNum *d, BcNum *s)
1321 bc_num_expand(d, s->cap);
1325 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1329 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1332 unsigned long result;
1336 while (i > n->rdx) {
1337 unsigned long prev = result;
1338 result = result * 10 + n->num[--i];
1339 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1340 // 0x1ff00000 * 10 is 0x13f600000,
1341 // or 0x3f600000 truncated to 32 bits. Which is larger.
1342 // However, (N*10)/8 < N check is always correct.
1343 if ((result / 8) < prev)
1344 RETURN_STATUS(bc_error("overflow"));
1348 RETURN_STATUS(BC_STATUS_SUCCESS);
1350 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1352 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1354 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1356 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1358 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1360 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1361 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1362 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1363 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1365 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1366 // would not hit realloc() code path - not good if num[] is not malloced
1368 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1374 if (val == 0) return;
1376 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1383 if (val == 0) break;
1387 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1390 for (i = 0; i < len; ++i) {
1392 for (j = i; a[j] < 0;) {
1399 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1417 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1418 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1419 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1420 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1421 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1423 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1425 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1426 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1428 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1431 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1433 size_t i, min, a_int, b_int, diff;
1434 BcDig *max_num, *min_num;
1438 if (a == b) return 0;
1439 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1440 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1442 if (a->neg != b->neg) // signs of a and b differ
1443 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1444 return (int)b->neg - (int)a->neg;
1445 neg = a->neg; // 1 if both negative, 0 if both positive
1447 a_int = BC_NUM_INT(a);
1448 b_int = BC_NUM_INT(b);
1451 if (a_int != 0) return (ssize_t) a_int;
1453 a_max = (a->rdx > b->rdx);
1456 diff = a->rdx - b->rdx;
1457 max_num = a->num + diff;
1459 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1462 diff = b->rdx - a->rdx;
1463 max_num = b->num + diff;
1465 neg = !neg; // same as "neg = (a_max == neg)"
1468 cmp = bc_num_compare(max_num, min_num, b_int + min);
1469 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1471 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1472 if (max_num[i]) return BC_NUM_NEG(1, neg);
1478 static void bc_num_truncate(BcNum *n, size_t places)
1480 if (places == 0) return;
1486 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1490 static void bc_num_extend(BcNum *n, size_t places)
1492 size_t len = n->len + places;
1495 if (n->cap < len) bc_num_expand(n, len);
1497 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1498 memset(n->num, 0, sizeof(BcDig) * places);
1505 static void bc_num_clean(BcNum *n)
1507 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1510 else if (n->len < n->rdx)
1514 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1517 bc_num_extend(n, scale - n->rdx);
1519 bc_num_truncate(n, n->rdx - scale);
1522 if (n->len != 0) n->neg = !neg1 != !neg2;
1525 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1529 b->len = n->len - idx;
1531 a->rdx = b->rdx = 0;
1533 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1534 memcpy(a->num, n->num, idx * sizeof(BcDig));
1544 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1546 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1548 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1549 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1550 if (places + n->len > BC_MAX_NUM)
1551 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1554 if (n->rdx >= places)
1557 bc_num_extend(n, places - n->rdx);
1563 RETURN_STATUS(BC_STATUS_SUCCESS);
1565 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1567 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1569 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1570 BcNumBinaryOp op, size_t req)
1573 BcNum num2, *ptr_a, *ptr_b;
1578 memcpy(ptr_a, c, sizeof(BcNum));
1586 memcpy(ptr_b, c, sizeof(BcNum));
1593 bc_num_init(c, req);
1595 bc_num_expand(c, req);
1597 s = BC_STATUS_SUCCESS;
1598 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1600 if (init) bc_num_free(&num2);
1604 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1606 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1607 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1608 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1609 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1610 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1611 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1613 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1615 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1617 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1620 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1622 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1624 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1627 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1629 size_t req = BC_NUM_MREQ(a, b, scale);
1630 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1633 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1635 size_t req = BC_NUM_MREQ(a, b, scale);
1636 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1639 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1641 size_t req = BC_NUM_MREQ(a, b, scale);
1642 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1645 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1647 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1650 static const BcNumBinaryOp zxc_program_ops[] = {
1651 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1653 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1654 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1655 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1656 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1657 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1658 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1660 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1669 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1671 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1673 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1675 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1676 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1679 // Because this function doesn't need to use scale (per the bc spec),
1680 // I am hijacking it to say whether it's doing an add or a subtract.
1684 if (sub && c->len) c->neg = !c->neg;
1685 RETURN_STATUS(BC_STATUS_SUCCESS);
1689 RETURN_STATUS(BC_STATUS_SUCCESS);
1693 c->rdx = BC_MAX(a->rdx, b->rdx);
1694 min_rdx = BC_MIN(a->rdx, b->rdx);
1697 if (a->rdx > b->rdx) {
1698 diff = a->rdx - b->rdx;
1700 ptr_a = a->num + diff;
1703 diff = b->rdx - a->rdx;
1706 ptr_b = b->num + diff;
1710 for (i = 0; i < diff; ++i, ++c->len)
1714 a_int = BC_NUM_INT(a);
1715 b_int = BC_NUM_INT(b);
1717 if (a_int > b_int) {
1728 for (i = 0; i < min_rdx + min_int; ++i) {
1729 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1731 ptr_c[i] = (BcDig)(in % 10);
1733 for (; i < max + min_rdx; ++i) {
1734 unsigned in = (unsigned)ptr[i] + carry;
1736 ptr_c[i] = (BcDig)(in % 10);
1740 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1742 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1745 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1748 BcNum *minuend, *subtrahend;
1750 bool aneg, bneg, neg;
1752 // Because this function doesn't need to use scale (per the bc spec),
1753 // I am hijacking it to say whether it's doing an add or a subtract.
1757 if (sub && c->len) c->neg = !c->neg;
1758 RETURN_STATUS(BC_STATUS_SUCCESS);
1762 RETURN_STATUS(BC_STATUS_SUCCESS);
1767 a->neg = b->neg = false;
1769 cmp = bc_num_cmp(a, b);
1775 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1776 RETURN_STATUS(BC_STATUS_SUCCESS);
1784 if (sub) neg = !neg;
1789 bc_num_copy(c, minuend);
1792 if (c->rdx < subtrahend->rdx) {
1793 bc_num_extend(c, subtrahend->rdx - c->rdx);
1796 start = c->rdx - subtrahend->rdx;
1798 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1802 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1805 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1807 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1810 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1811 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1814 if (a->len == 0 || b->len == 0) {
1816 RETURN_STATUS(BC_STATUS_SUCCESS);
1818 aone = BC_NUM_ONE(a);
1819 if (aone || BC_NUM_ONE(b)) {
1820 bc_num_copy(c, aone ? b : a);
1821 RETURN_STATUS(BC_STATUS_SUCCESS);
1824 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1825 || a->len < BC_NUM_KARATSUBA_LEN
1826 || b->len < BC_NUM_KARATSUBA_LEN
1830 bc_num_expand(c, a->len + b->len + 1);
1832 memset(c->num, 0, sizeof(BcDig) * c->cap);
1835 for (i = 0; i < b->len; ++i) {
1837 for (j = 0; j < a->len; ++j) {
1838 unsigned in = c->num[i + j];
1839 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1840 // note: compilers prefer _unsigned_ div/const
1842 c->num[i + j] = (BcDig)(in % 10);
1845 c->num[i + j] += (BcDig) carry;
1846 len = BC_MAX(len, i + j + !!carry);
1848 #if ENABLE_FEATURE_BC_INTERACTIVE
1850 // a*a <- without check below, this will not be interruptible
1851 if (G_interrupt) return BC_STATUS_FAILURE;
1857 RETURN_STATUS(BC_STATUS_SUCCESS);
1860 bc_num_init(&l1, max);
1861 bc_num_init(&h1, max);
1862 bc_num_init(&l2, max);
1863 bc_num_init(&h2, max);
1864 bc_num_init(&m1, max);
1865 bc_num_init(&m2, max);
1866 bc_num_init(&z0, max);
1867 bc_num_init(&z1, max);
1868 bc_num_init(&z2, max);
1869 bc_num_init(&temp, max + max);
1871 bc_num_split(a, max2, &l1, &h1);
1872 bc_num_split(b, max2, &l2, &h2);
1874 s = zbc_num_add(&h1, &l1, &m1, 0);
1876 s = zbc_num_add(&h2, &l2, &m2, 0);
1879 s = zbc_num_k(&h1, &h2, &z0);
1881 s = zbc_num_k(&m1, &m2, &z1);
1883 s = zbc_num_k(&l1, &l2, &z2);
1886 s = zbc_num_sub(&z1, &z0, &temp, 0);
1888 s = zbc_num_sub(&temp, &z2, &z1, 0);
1891 s = zbc_num_shift(&z0, max2 * 2);
1893 s = zbc_num_shift(&z1, max2);
1895 s = zbc_num_add(&z0, &z1, &temp, 0);
1897 s = zbc_num_add(&temp, &z2, c, 0);
1912 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1916 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1918 scale = BC_MAX(scale, a->rdx);
1919 scale = BC_MAX(scale, b->rdx);
1920 scale = BC_MIN(a->rdx + b->rdx, scale);
1921 maxrdx = BC_MAX(maxrdx, scale);
1923 bc_num_init(&cpa, a->len);
1924 bc_num_init(&cpb, b->len);
1926 bc_num_copy(&cpa, a);
1927 bc_num_copy(&cpb, b);
1928 cpa.neg = cpb.neg = false;
1930 s = zbc_num_shift(&cpa, maxrdx);
1932 s = zbc_num_shift(&cpb, maxrdx);
1934 s = zbc_num_k(&cpa, &cpb, c);
1938 bc_num_expand(c, c->len + maxrdx);
1940 if (c->len < maxrdx) {
1941 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1946 bc_num_retireMul(c, scale, a->neg, b->neg);
1952 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1954 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1961 RETURN_STATUS(bc_error("divide by zero"));
1963 bc_num_setToZero(c, scale);
1964 RETURN_STATUS(BC_STATUS_SUCCESS);
1966 if (BC_NUM_ONE(b)) {
1968 bc_num_retireMul(c, scale, a->neg, b->neg);
1969 RETURN_STATUS(BC_STATUS_SUCCESS);
1972 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1973 bc_num_copy(&cp, a);
1977 bc_num_expand(&cp, len + 2);
1978 bc_num_extend(&cp, len - cp.len);
1981 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1983 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1985 if (b->rdx == b->len) {
1987 if (len == 0) break;
1989 if (b->num[len] != 0)
1995 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1997 // We want an extra zero in front to make things simpler.
1998 cp.num[cp.len++] = 0;
2001 bc_num_expand(c, cp.len);
2004 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2008 s = BC_STATUS_SUCCESS;
2009 for (i = end - 1; i < end; --i) {
2012 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2013 bc_num_subArrays(n, b->num, len);
2015 #if ENABLE_FEATURE_BC_INTERACTIVE
2018 // 1/a <- without check below, this will not be interruptible
2020 s = BC_STATUS_FAILURE;
2026 bc_num_retireMul(c, scale, a->neg, b->neg);
2031 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2033 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2034 BcNum *restrict d, size_t scale, size_t ts)
2041 RETURN_STATUS(bc_error("divide by zero"));
2044 bc_num_setToZero(d, ts);
2045 RETURN_STATUS(BC_STATUS_SUCCESS);
2048 bc_num_init(&temp, d->cap);
2049 s = zbc_num_d(a, b, c, scale);
2052 if (scale != 0) scale = ts;
2054 s = zbc_num_m(c, b, &temp, scale);
2056 s = zbc_num_sub(a, &temp, d, scale);
2059 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2062 bc_num_retireMul(d, ts, a->neg, b->neg);
2068 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2070 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2074 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2076 bc_num_init(&c1, len);
2077 s = zbc_num_r(a, b, &c1, c, scale, ts);
2082 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2084 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2086 BcStatus s = BC_STATUS_SUCCESS;
2089 size_t i, powrdx, resrdx;
2092 // GNU bc does not allow 2^2.0 - we do
2093 for (i = 0; i < b->rdx; i++)
2095 RETURN_STATUS(bc_error("not an integer"));
2099 RETURN_STATUS(BC_STATUS_SUCCESS);
2102 bc_num_setToZero(c, scale);
2103 RETURN_STATUS(BC_STATUS_SUCCESS);
2105 if (BC_NUM_ONE(b)) {
2109 s = zbc_num_inv(a, c, scale);
2114 s = zbc_num_ulong_abs(b, &pow);
2115 if (s) RETURN_STATUS(s);
2116 // b is not used beyond this point
2118 bc_num_init(©, a->len);
2119 bc_num_copy(©, a);
2124 if (a->rdx * pow < scale)
2125 scale = a->rdx * pow;
2129 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2131 s = zbc_num_mul(©, ©, ©, powrdx);
2133 // Not needed: zbc_num_mul() has a check for ^C:
2134 //if (G_interrupt) {
2135 // s = BC_STATUS_FAILURE;
2140 bc_num_copy(c, ©);
2142 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2144 s = zbc_num_mul(©, ©, ©, powrdx);
2149 s = zbc_num_mul(c, ©, c, resrdx);
2152 // Not needed: zbc_num_mul() has a check for ^C:
2153 //if (G_interrupt) {
2154 // s = BC_STATUS_FAILURE;
2160 s = zbc_num_inv(c, c, scale);
2164 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2166 // We can't use bc_num_clean() here.
2167 for (i = 0; i < c->len; ++i)
2170 bc_num_setToZero(c, scale);
2177 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2179 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2182 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2184 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2185 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2187 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2188 bc_num_expand(b, req);
2191 bc_num_setToZero(b, scale);
2192 RETURN_STATUS(BC_STATUS_SUCCESS);
2195 RETURN_STATUS(bc_error("negative number"));
2197 if (BC_NUM_ONE(a)) {
2199 bc_num_extend(b, scale);
2200 RETURN_STATUS(BC_STATUS_SUCCESS);
2203 scale = BC_MAX(scale, a->rdx) + 1;
2204 len = a->len + scale;
2206 bc_num_init(&num1, len);
2207 bc_num_init(&num2, len);
2209 half.cap = ARRAY_SIZE(half_digs);
2210 half.num = half_digs;
2215 bc_num_init(&f, len);
2216 bc_num_init(&fprime, len);
2222 pow = BC_NUM_INT(a);
2230 pow -= 2 - (pow & 1);
2232 bc_num_extend(x0, pow);
2234 // Make sure to move the radix back.
2238 x0->rdx = digs = digs1 = 0;
2240 len = BC_NUM_INT(x0) + resrdx - 1;
2242 while (cmp != 0 || digs < len) {
2243 s = zbc_num_div(a, x0, &f, resrdx);
2245 s = zbc_num_add(x0, &f, &fprime, resrdx);
2247 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2250 cmp = bc_num_cmp(x1, x0);
2251 digs = x1->len - (unsigned long long) llabs(cmp);
2253 if (cmp == cmp2 && digs == digs1)
2258 resrdx += times > 4;
2271 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2273 bc_num_free(&fprime);
2279 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2281 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2287 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2290 memcpy(&num2, c, sizeof(BcNum));
2292 bc_num_init(c, len);
2296 bc_num_expand(c, len);
2299 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2301 if (init) bc_num_free(&num2);
2305 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2308 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2311 BcNum base, exp, two, temp;
2315 RETURN_STATUS(bc_error("divide by zero"));
2316 if (a->rdx || b->rdx || c->rdx)
2317 RETURN_STATUS(bc_error("not an integer"));
2319 RETURN_STATUS(bc_error("negative number"));
2321 bc_num_expand(d, c->len);
2322 bc_num_init(&base, c->len);
2323 bc_num_init(&exp, b->len);
2324 bc_num_init(&temp, b->len);
2326 two.cap = ARRAY_SIZE(two_digs);
2333 s = zbc_num_rem(a, c, &base, 0);
2335 bc_num_copy(&exp, b);
2337 while (exp.len != 0) {
2338 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2341 if (BC_NUM_ONE(&temp)) {
2342 s = zbc_num_mul(d, &base, &temp, 0);
2344 s = zbc_num_rem(&temp, c, d, 0);
2348 s = zbc_num_mul(&base, &base, &temp, 0);
2350 s = zbc_num_rem(&temp, c, &base, 0);
2359 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2362 static FAST_FUNC void bc_string_free(void *string)
2364 free(*(char**)string);
2367 static void bc_func_init(BcFunc *f)
2369 bc_char_vec_init(&f->code);
2370 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2371 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2372 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2373 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2374 IF_BC(f->nparams = 0;)
2377 static FAST_FUNC void bc_func_free(void *func)
2379 BcFunc *f = (BcFunc *) func;
2380 bc_vec_free(&f->code);
2381 IF_BC(bc_vec_free(&f->labels);)
2382 IF_BC(bc_vec_free(&f->autos);)
2383 IF_BC(bc_vec_free(&f->strs);)
2384 IF_BC(bc_vec_free(&f->consts);)
2387 static void bc_array_expand(BcVec *a, size_t len);
2389 static void bc_array_init(BcVec *a, bool nums)
2392 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2394 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2395 bc_array_expand(a, 1);
2398 static void bc_array_expand(BcVec *a, size_t len)
2400 if (a->dtor == bc_num_free
2401 // && a->size == sizeof(BcNum) - always true
2404 while (len > a->len) {
2405 bc_num_init_DEF_SIZE(&n);
2410 while (len > a->len) {
2411 bc_array_init(&v, true);
2417 static void bc_array_copy(BcVec *d, const BcVec *s)
2423 bc_vec_expand(d, s->cap);
2428 for (i = 0; i < s->len; i++, dnum++, snum++) {
2429 bc_num_init(dnum, snum->len);
2430 bc_num_copy(dnum, snum);
2435 static void dc_result_copy(BcResult *d, BcResult *src)
2440 case XC_RESULT_TEMP:
2441 case XC_RESULT_IBASE:
2442 case XC_RESULT_SCALE:
2443 case XC_RESULT_OBASE:
2444 bc_num_init(&d->d.n, src->d.n.len);
2445 bc_num_copy(&d->d.n, &src->d.n);
2448 case XC_RESULT_ARRAY:
2449 case XC_RESULT_ARRAY_ELEM:
2450 d->d.id.name = xstrdup(src->d.id.name);
2452 case XC_RESULT_CONSTANT:
2453 IF_BC(case BC_RESULT_LAST:)
2454 IF_BC(case BC_RESULT_ONE:)
2456 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2462 static FAST_FUNC void bc_result_free(void *result)
2464 BcResult *r = (BcResult *) result;
2467 case XC_RESULT_TEMP:
2468 case XC_RESULT_IBASE:
2469 case XC_RESULT_SCALE:
2470 case XC_RESULT_OBASE:
2471 bc_num_free(&r->d.n);
2474 case XC_RESULT_ARRAY:
2475 case XC_RESULT_ARRAY_ELEM:
2484 static int bad_input_byte(char c)
2486 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2489 bc_error_fmt("illegal character 0x%02x", c);
2495 static void xc_read_line(BcVec *vec, FILE *fp)
2498 bc_vec_pop_all(vec);
2501 #if ENABLE_FEATURE_BC_INTERACTIVE
2502 if (G_interrupt) { // ^C was pressed
2505 // ^C while running a script (bc SCRIPT): die.
2506 // We do not return to interactive prompt:
2507 // user might be running us from a shell,
2508 // and SCRIPT might be intended to terminate
2509 // (e.g. contain a "halt" stmt).
2510 // ^C dropping user into a bc prompt instead of
2511 // the shell would be unexpected.
2514 // ^C while interactive input
2516 // GNU bc says "interrupted execution."
2517 // GNU dc says "Interrupt!"
2518 fputs("\ninterrupted execution\n", stderr);
2521 # if ENABLE_FEATURE_EDITING
2522 if (G_ttyin && fp == stdin) {
2524 # define line_buf bb_common_bufsiz1
2525 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2526 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2529 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2534 char c = line_buf[i++];
2535 if (c == '\0') break;
2536 if (bad_input_byte(c)) goto again;
2538 bc_vec_string(vec, n, line_buf);
2549 #if ENABLE_FEATURE_BC_INTERACTIVE
2551 // ^C was pressed: ignore entire line, get another one
2560 bb_perror_msg_and_die("input error");
2561 // Note: EOF does not append '\n'
2564 bad_chars |= bad_input_byte(c);
2565 bc_vec_pushByte(vec, (char)c);
2566 } while (c != '\n');
2569 // Bad chars on this line
2570 if (!G.prs.lex_filename) { // stdin
2571 // ignore entire line, get another one
2574 bb_perror_msg_and_die("file '%s' is not text", G.prs.lex_filename);
2576 bc_vec_pushZeroByte(vec);
2584 // "Input numbers may contain the characters 0-9 and A-Z.
2585 // (Note: They must be capitals. Lower case letters are variable names.)
2586 // Single digit numbers always have the value of the digit regardless of
2587 // the value of ibase. (i.e. A = 10.) For multi-digit numbers, bc changes
2588 // all input digits greater or equal to ibase to the value of ibase-1.
2589 // This makes the number ZZZ always be the largest 3 digit number of the
2591 static bool xc_num_strValid(const char *val)
2599 if (radix) return false;
2603 if ((c < '0' || c > '9') && (c < 'A' || c > 'Z'))
2609 // Note: n is already "bc_num_zero()"ed,
2610 // leading zeroes in "val" are removed
2611 static void bc_num_parseDecimal(BcNum *n, const char *val)
2620 bc_num_expand(n, len + 1); // +1 for e.g. "A" converting into 10
2622 ptr = strchr(val, '.');
2626 n->rdx = (size_t)((val + len) - (ptr + 1));
2628 for (i = 0; val[i]; ++i) {
2629 if (val[i] != '0' && val[i] != '.') {
2630 // Not entirely zero value - convert it, and exit
2632 unsigned c = val[0] - '0';
2634 if (c > 9) { // A-Z => 10-36
2636 c -= ('A' - '9' - 1);
2645 char c = val[i] - '0';
2646 if (c > 9) // A-Z => 9
2652 if (val[--i] == '.') goto skip_dot;
2657 // if for() exits without hitting if(), the value is entirely zero
2660 // Note: n is already "bc_num_zero()"ed,
2661 // leading zeroes in "val" are removed
2662 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2668 BcDig temp_digs[ULONG_NUM_BUFSIZE];
2669 BcDig base_digs[ULONG_NUM_BUFSIZE];
2672 bc_num_init_DEF_SIZE(&mult);
2674 temp.cap = ARRAY_SIZE(temp_digs);
2675 temp.num = temp_digs;
2677 base.cap = ARRAY_SIZE(base_digs);
2678 base.num = base_digs;
2679 bc_num_ulong2num(&base, base_t);
2687 if (c == '\0') goto int_err;
2688 if (c == '.') break;
2690 v = (unsigned)(c <= '9' ? c - '0' : c - 'A' + 10);
2691 if (v > base_t) v = base_t;
2693 s = zbc_num_mul(n, &base, &mult, 0);
2694 if (s) goto int_err;
2695 bc_num_ulong2num(&temp, v);
2696 s = zbc_num_add(&mult, &temp, n, 0);
2697 if (s) goto int_err;
2700 bc_num_init(&result, base.len);
2701 //bc_num_zero(&result); - already is
2710 if (c == '\0') break;
2713 v = (unsigned)(c <= '9' ? c - '0' : c - 'A' + 10);
2714 if (v > base_t) v = base_t;
2716 s = zbc_num_mul(&result, &base, &result, 0);
2718 bc_num_ulong2num(&temp, v);
2719 s = zbc_num_add(&result, &temp, &result, 0);
2721 s = zbc_num_mul(&mult, &base, &mult, 0);
2725 s = zbc_num_div(&result, &mult, &result, digits);
2727 s = zbc_num_add(n, &result, n, digits);
2731 if (n->rdx < digits)
2732 bc_num_extend(n, digits - n->rdx);
2736 bc_num_free(&result);
2741 static BC_STATUS zxc_num_parse(BcNum *n, const char *val, unsigned base_t)
2745 if (!xc_num_strValid(val))
2746 RETURN_STATUS(bc_error("bad number string"));
2751 for (i = 0; ; ++i) {
2753 RETURN_STATUS(BC_STATUS_SUCCESS);
2754 if (val[i] != '.' && val[i] != '0')
2758 if (base_t == 10 || val[1] == '\0')
2759 // Decimal, or single-digit number
2760 bc_num_parseDecimal(n, val);
2762 bc_num_parseBase(n, val, base_t);
2764 RETURN_STATUS(BC_STATUS_SUCCESS);
2766 #define zxc_num_parse(...) (zxc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2768 // p->lex_inbuf points to the current string to be parsed.
2769 // if p->lex_inbuf points to '\0', it's either EOF or it points after
2770 // last processed line's terminating '\n' (and more reading needs to be done
2771 // to get next character).
2773 // If you are in a situation where that is a possibility, call peek_inbuf().
2774 // If necessary, it performs more reading and changes p->lex_inbuf,
2775 // then it returns *p->lex_inbuf (which will be '\0' only if it's EOF).
2776 // After it, just referencing *p->lex_inbuf is valid, and if it wasn't '\0',
2777 // it's ok to do p->lex_inbuf++ once without end-of-buffer checking.
2779 // eat_inbuf() is equvalent to "peek_inbuf(); if (c) p->lex_inbuf++":
2780 // it returns current char and advances the pointer (if not EOF).
2781 // After eat_inbuf(), referencing p->lex_inbuf[-1] and *p->lex_inbuf is valid.
2783 // In many cases, you can use fast *p->lex_inbuf instead of peek_inbuf():
2784 // unless prev char might have been '\n', *p->lex_inbuf is '\0' ONLY
2785 // on real EOF, not end-of-buffer.
2787 // bc cases to test interactively:
2788 // 1 #comment\ - prints "1<newline>" at once (comment is not continued)
2789 // 1 #comment/* - prints "1<newline>" at once
2790 // 1 #comment" - prints "1<newline>" at once
2791 // 1\#comment - error at once (\ is not a line continuation)
2792 // 1 + /*"*/2 - prints "3<newline>" at once
2793 // 1 + /*#*/2 - prints "3<newline>" at once
2794 // "str\" - prints "str\" at once
2795 // "str#" - prints "str#" at once
2796 // "str/*" - prints "str/*" at once
2797 // "str#\ - waits for second line
2798 // end" - ...prints "str#\<newline>end"
2799 static char peek_inbuf(void)
2801 if (*G.prs.lex_inbuf == '\0'
2802 && G.prs.lex_input_fp
2804 xc_read_line(&G.input_buffer, G.prs.lex_input_fp);
2805 G.prs.lex_inbuf = G.input_buffer.v;
2806 if (G.input_buffer.len <= 1) // on EOF, len is 1 (NUL byte)
2807 G.prs.lex_input_fp = NULL;
2809 return *G.prs.lex_inbuf;
2811 static char eat_inbuf(void)
2813 char c = peek_inbuf();
2814 if (c) G.prs.lex_inbuf++;
2818 static void xc_lex_lineComment(void)
2820 BcParse *p = &G.prs;
2823 // Try: echo -n '#foo' | bc
2824 p->lex = XC_LEX_WHITESPACE;
2826 // Not peek_inbuf(): we depend on input being done in whole lines:
2827 // '\0' which isn't the EOF can only be seen after '\n'.
2828 while ((c = *p->lex_inbuf) != '\n' && c != '\0')
2832 static void xc_lex_whitespace(void)
2834 BcParse *p = &G.prs;
2836 p->lex = XC_LEX_WHITESPACE;
2838 // We depend here on input being done in whole lines:
2839 // '\0' which isn't the EOF can only be seen after '\n'.
2840 char c = *p->lex_inbuf;
2841 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2849 static BC_STATUS zxc_lex_number(char last)
2851 BcParse *p = &G.prs;
2855 bc_vec_pop_all(&p->lex_strnumbuf);
2856 bc_vec_pushByte(&p->lex_strnumbuf, last);
2858 // bc: "Input numbers may contain the characters 0-9 and A-Z.
2859 // (Note: They must be capitals. Lower case letters are variable names.)
2860 // Single digit numbers always have the value of the digit regardless of
2861 // the value of ibase. (i.e. A = 10.) For multi-digit numbers, bc changes
2862 // all input digits greater or equal to ibase to the value of ibase-1.
2863 // This makes the number ZZZ always be the largest 3 digit number of the
2865 // dc only allows A-F, the rules about single-char and multi-char are the same.
2866 last_valid_ch = (IS_BC ? 'Z' : 'F');
2868 p->lex = XC_LEX_NUMBER;
2870 // We depend here on input being done in whole lines:
2871 // '\0' which isn't the EOF can only be seen after '\n'.
2872 char c = *p->lex_inbuf;
2876 if (c == '\\' && p->lex_inbuf[1] == '\n') {
2879 dbg_lex("++p->lex_line=%zd", p->lex_line);
2880 c = peek_inbuf(); // force next line to be read
2883 if (!isdigit(c) && (c < 'A' || c > last_valid_ch)) {
2884 if (c != '.') break;
2885 // if '.' was already seen, stop on second one:
2889 // c is one of "0-9A-Z."
2891 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
2894 if (last == '.') // remove trailing '.' if any
2895 bc_vec_pop(&p->lex_strnumbuf);
2896 bc_vec_pushZeroByte(&p->lex_strnumbuf);
2898 G.err_line = G.prs.lex_line;
2899 RETURN_STATUS(BC_STATUS_SUCCESS);
2901 #define zxc_lex_number(...) (zxc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2903 static void xc_lex_name(void)
2905 BcParse *p = &G.prs;
2909 p->lex = XC_LEX_NAME;
2911 // Since names can't cross lines with \<newline>,
2912 // we depend on the fact that whole line is in the buffer
2914 buf = p->lex_inbuf - 1;
2917 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2921 #if 0 // We do not protect against people with gigabyte-long names
2922 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2923 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2924 if (i > BC_MAX_STRING)
2925 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2928 bc_vec_string(&p->lex_strnumbuf, i, buf);
2930 // Increment the index. We minus 1 because it has already been incremented.
2931 p->lex_inbuf += i - 1;
2933 //return BC_STATUS_SUCCESS;
2936 IF_BC(static BC_STATUS zbc_lex_token(void);)
2937 IF_DC(static BC_STATUS zdc_lex_token(void);)
2938 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2939 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2941 static BC_STATUS zxc_lex_next(void)
2943 BcParse *p = &G.prs;
2946 G.err_line = p->lex_line;
2947 p->lex_last = p->lex;
2949 // if (p->lex_last == XC_LEX_EOF)
2950 // RETURN_STATUS(bc_error("end of file"));
2952 // Loop until failure or we don't have whitespace. This
2953 // is so the parser doesn't get inundated with whitespace.
2954 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2955 s = BC_STATUS_SUCCESS;
2957 if (*p->lex_inbuf == '\0') {
2958 p->lex = XC_LEX_EOF;
2959 if (peek_inbuf() == '\0')
2960 RETURN_STATUS(BC_STATUS_SUCCESS);
2962 p->lex_next_at = p->lex_inbuf;
2963 dbg_lex("next string to parse:'%.*s'",
2964 (int)(strchrnul(p->lex_next_at, '\n') - p->lex_next_at),
2968 IF_BC(s = zbc_lex_token());
2970 IF_DC(s = zdc_lex_token());
2972 } while (!s && p->lex == XC_LEX_WHITESPACE);
2973 dbg_lex("p->lex from string:%d", p->lex);
2977 #define zxc_lex_next(...) (zxc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
2980 static BC_STATUS zbc_lex_skip_if_at_NLINE(void)
2982 if (G.prs.lex == XC_LEX_NLINE)
2983 RETURN_STATUS(zxc_lex_next());
2984 RETURN_STATUS(BC_STATUS_SUCCESS);
2986 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2988 static BC_STATUS zbc_lex_next_and_skip_NLINE(void)
2992 if (s) RETURN_STATUS(s);
2993 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
2994 s = zbc_lex_skip_if_at_NLINE();
2997 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2999 static BC_STATUS zbc_lex_identifier(void)
3001 BcParse *p = &G.prs;
3004 const char *buf = p->lex_inbuf - 1;
3006 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3007 const char *keyword8 = bc_lex_kws[i].name8;
3009 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3011 if (j == 8) goto match;
3013 if (keyword8[j] != '\0')
3016 // buf starts with keyword bc_lex_kws[i]
3017 if (isalnum(buf[j]) || buf[j]=='_')
3018 continue; // "ifz" does not match "if" keyword, "if." does
3019 p->lex = BC_LEX_KEY_1st_keyword + i;
3020 if (!keyword_is_POSIX(i)) {
3021 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3022 if (s) RETURN_STATUS(s);
3025 // We minus 1 because the index has already been incremented.
3026 p->lex_inbuf += j - 1;
3027 RETURN_STATUS(BC_STATUS_SUCCESS);
3031 s = BC_STATUS_SUCCESS;
3033 if (p->lex_strnumbuf.len > 2) {
3036 // bc: POSIX only allows one character names; this is bad: 'qwe=1
3038 unsigned len = strchrnul(buf, '\n') - buf;
3039 s = zbc_posix_error_fmt("POSIX only allows one character names; this is bad: '%.*s'", len, buf);
3044 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3046 static BC_STATUS zbc_lex_string(void)
3048 BcParse *p = &G.prs;
3050 p->lex = XC_LEX_STR;
3051 bc_vec_pop_all(&p->lex_strnumbuf);
3053 char c = peek_inbuf(); // strings can cross lines
3055 RETURN_STATUS(bc_error("unterminated string"));
3061 dbg_lex("++p->lex_line=%zd", p->lex_line);
3063 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3066 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3069 G.err_line = p->lex_line;
3070 RETURN_STATUS(BC_STATUS_SUCCESS);
3072 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3074 static void parse_lex_by_checking_eq_sign(unsigned with_and_without)
3076 BcParse *p = &G.prs;
3077 if (*p->lex_inbuf == '=') {
3078 // ^^^ not using peek_inbuf() since '==' etc can't be split across lines
3080 with_and_without >>= 8; // store "with" value
3081 } // else store "without" value
3082 p->lex = (with_and_without & 0xff);
3084 #define parse_lex_by_checking_eq_sign(with, without) \
3085 parse_lex_by_checking_eq_sign(((with)<<8)|(without))
3087 static BC_STATUS zbc_lex_comment(void)
3089 BcParse *p = &G.prs;
3091 p->lex = XC_LEX_WHITESPACE;
3092 // here lex_inbuf is at '*' of opening comment delimiter
3101 c = *p->lex_inbuf; // no need to peek_inbuf()
3107 RETURN_STATUS(bc_error("unterminated comment"));
3111 dbg_lex("++p->lex_line=%zd", p->lex_line);
3114 p->lex_inbuf++; // skip trailing '/'
3116 G.err_line = p->lex_line;
3117 RETURN_STATUS(BC_STATUS_SUCCESS);
3119 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3121 #undef zbc_lex_token
3122 static BC_STATUS zbc_lex_token(void)
3124 BcParse *p = &G.prs;
3125 BcStatus s = BC_STATUS_SUCCESS;
3126 char c = eat_inbuf();
3129 // This is the workhorse of the lexer.
3131 // case '\0': // probably never reached
3133 // p->lex = XC_LEX_EOF;
3137 dbg_lex("++p->lex_line=%zd", p->lex_line);
3138 p->lex = XC_LEX_NLINE;
3145 xc_lex_whitespace();
3148 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3149 if (p->lex == BC_LEX_OP_BOOL_NOT) {
3150 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3151 if (s) RETURN_STATUS(s);
3155 s = zbc_lex_string();
3158 s = zbc_POSIX_does_not_allow("'#' script comments");
3159 if (s) RETURN_STATUS(s);
3160 xc_lex_lineComment();
3163 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3168 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3169 if (s) RETURN_STATUS(s);
3171 p->lex = BC_LEX_OP_BOOL_AND;
3173 p->lex = XC_LEX_INVALID;
3174 s = bc_error_bad_character('&');
3179 p->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3182 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3188 p->lex = BC_LEX_OP_INC;
3190 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3193 p->lex = BC_LEX_COMMA;
3199 p->lex = BC_LEX_OP_DEC;
3201 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3204 if (isdigit(*p->lex_inbuf))
3205 s = zxc_lex_number(c);
3207 p->lex = BC_LEX_KEY_LAST;
3208 s = zbc_POSIX_does_not_allow("'.' as 'last'");
3214 s = zbc_lex_comment();
3216 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3254 s = zxc_lex_number(c);
3257 p->lex = BC_LEX_SCOLON;
3260 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3263 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3266 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3270 p->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3273 if (*p->lex_inbuf == '\n') {
3274 p->lex = XC_LEX_WHITESPACE;
3277 s = bc_error_bad_character(c);
3280 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3308 s = zbc_lex_identifier();
3312 p->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3317 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3318 if (s) RETURN_STATUS(s);
3320 p->lex = BC_LEX_OP_BOOL_OR;
3322 p->lex = XC_LEX_INVALID;
3323 s = bc_error_bad_character(c);
3327 p->lex = XC_LEX_INVALID;
3328 s = bc_error_bad_character(c);
3334 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3338 static BC_STATUS zdc_lex_register(void)
3340 BcParse *p = &G.prs;
3341 if (G_exreg && isspace(*p->lex_inbuf)) {
3342 xc_lex_whitespace(); // eats whitespace (but not newline)
3343 p->lex_inbuf++; // xc_lex_name() expects this
3346 bc_vec_pop_all(&p->lex_strnumbuf);
3347 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf++);
3348 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3349 p->lex = XC_LEX_NAME;
3352 RETURN_STATUS(BC_STATUS_SUCCESS);
3354 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3356 static BC_STATUS zdc_lex_string(void)
3358 BcParse *p = &G.prs;
3361 p->lex = XC_LEX_STR;
3362 bc_vec_pop_all(&p->lex_strnumbuf);
3366 char c = peek_inbuf();
3368 RETURN_STATUS(bc_error("unterminated string"));
3370 if (c == '[') depth++;
3376 dbg_lex("++p->lex_line=%zd", p->lex_line);
3378 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3381 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3382 p->lex_inbuf++; // skip trailing ']'
3384 G.err_line = p->lex_line;
3385 RETURN_STATUS(BC_STATUS_SUCCESS);
3387 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3389 #undef zdc_lex_token
3390 static BC_STATUS zdc_lex_token(void)
3392 static const //BcLexType - should be this type, but narrower type saves size:
3394 dc_lex_regs[] ALIGN1 = {
3395 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3396 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3397 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3401 BcParse *p = &G.prs;
3406 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3407 if (p->lex_last == dc_lex_regs[i])
3408 RETURN_STATUS(zdc_lex_register());
3411 s = BC_STATUS_SUCCESS;
3413 if (c >= '%' && c <= '~'
3414 && (p->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3419 // This is the workhorse of the lexer.
3421 // case '\0': // probably never reached
3422 // p->lex = XC_LEX_EOF;
3425 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3426 // (and "case '\n':" is not just empty here)
3427 // only to allow interactive dc have a way to exit
3428 // "parse" stage of "parse,execute" loop
3429 // on <enter>, not on _next_ token (which would mean
3430 // commands are not executed on pressing <enter>).
3431 // IOW: typing "1p<enter>" should print "1" _at once_,
3432 // not after some more input.
3434 dbg_lex("++p->lex_line=%zd", p->lex_line);
3435 p->lex = XC_LEX_NLINE;
3442 xc_lex_whitespace();
3447 p->lex = XC_LEX_OP_REL_NE;
3449 p->lex = XC_LEX_OP_REL_LE;
3451 p->lex = XC_LEX_OP_REL_GE;
3453 RETURN_STATUS(bc_error_bad_character(c));
3457 xc_lex_lineComment();
3460 if (isdigit(*p->lex_inbuf))
3461 s = zxc_lex_number(c);
3463 s = bc_error_bad_character(c);
3481 s = zxc_lex_number(c);
3484 s = zdc_lex_string();
3487 p->lex = XC_LEX_INVALID;
3488 s = bc_error_bad_character(c);
3494 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3497 static void xc_parse_push(char i)
3499 BcVec *code = &G.prs.func->code;
3500 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, code->len, i);
3501 bc_vec_pushByte(code, i);
3504 static void xc_parse_pushName(char *name)
3507 BcVec *code = &G.prs.func->code;
3508 size_t pos = code->len;
3509 size_t len = strlen(name) + 1;
3511 bc_vec_expand(code, pos + len);
3512 strcpy(code->v + pos, name);
3513 code->len = pos + len;
3515 // Smaller code, but way slow:
3517 xc_parse_push(*name);
3522 // Indexes < 0xfc are encoded verbatim, else first byte is
3523 // 0xfc, 0xfd, 0xfe or 0xff, encoding "1..4 bytes",
3524 // followed by that many bytes, lsb first.
3525 // (The above describes 32-bit case).
3526 #define SMALL_INDEX_LIMIT (0x100 - sizeof(size_t))
3528 static void xc_parse_pushIndex(size_t idx)
3533 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3534 if (idx < SMALL_INDEX_LIMIT) {
3538 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3541 if (idx & mask) break;
3545 // amt is at least 1 here - "one byte of length data follows"
3547 xc_parse_push((SMALL_INDEX_LIMIT - 1) + amt);
3551 xc_parse_push((unsigned char)idx);
3557 static void bc_parse_pushJUMP(size_t idx)
3559 xc_parse_push(BC_INST_JUMP);
3560 xc_parse_pushIndex(idx);
3563 static void bc_parse_pushJUMP_ZERO(size_t idx)
3565 xc_parse_push(BC_INST_JUMP_ZERO);
3566 xc_parse_pushIndex(idx);
3569 static BC_STATUS zbc_parse_pushSTR(void)
3571 BcParse *p = &G.prs;
3572 char *str = xstrdup(p->lex_strnumbuf.v);
3574 xc_parse_push(XC_INST_STR);
3575 xc_parse_pushIndex(p->func->strs.len);
3576 bc_vec_push(&p->func->strs, &str);
3578 RETURN_STATUS(zxc_lex_next());
3580 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3583 static void xc_parse_pushNUM(void)
3585 BcParse *p = &G.prs;
3586 char *num = xstrdup(p->lex_strnumbuf.v);
3587 #if ENABLE_BC && ENABLE_DC
3588 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3590 size_t idx = bc_vec_push(&p->func->consts, &num);
3592 size_t idx = bc_vec_push(&G.prog.consts, &num);
3594 xc_parse_push(XC_INST_NUM);
3595 xc_parse_pushIndex(idx);
3598 static BC_STATUS zxc_parse_text_init(const char *text)
3600 G.prs.func = xc_program_func(G.prs.fidx);
3601 G.prs.lex_inbuf = text;
3602 G.prs.lex = G.prs.lex_last = XC_LEX_INVALID;
3603 RETURN_STATUS(zxc_lex_next());
3605 #define zxc_parse_text_init(...) (zxc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3607 // Called when parsing or execution detects a failure,
3608 // resets execution structures.
3609 static void xc_program_reset(void)
3614 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3615 bc_vec_pop_all(&G.prog.results);
3617 f = xc_program_func_BC_PROG_MAIN();
3618 ip = bc_vec_top(&G.prog.exestack);
3619 ip->inst_idx = f->code.len;
3622 // Called when parsing code detects a failure,
3623 // resets parsing structures.
3624 static void xc_parse_reset(void)
3626 BcParse *p = &G.prs;
3627 if (p->fidx != BC_PROG_MAIN) {
3628 bc_func_free(p->func);
3629 bc_func_init(p->func);
3631 p->fidx = BC_PROG_MAIN;
3632 p->func = xc_program_func_BC_PROG_MAIN();
3635 p->lex_inbuf += strlen(p->lex_inbuf);
3636 p->lex = XC_LEX_EOF;
3638 IF_BC(bc_vec_pop_all(&p->exits);)
3639 IF_BC(bc_vec_pop_all(&p->conds);)
3640 IF_BC(bc_vec_pop_all(&p->ops);)
3645 static void xc_parse_free(void)
3647 IF_BC(bc_vec_free(&G.prs.exits);)
3648 IF_BC(bc_vec_free(&G.prs.conds);)
3649 IF_BC(bc_vec_free(&G.prs.ops);)
3650 bc_vec_free(&G.prs.lex_strnumbuf);
3653 static void xc_parse_create(size_t fidx)
3655 BcParse *p = &G.prs;
3656 memset(p, 0, sizeof(BcParse));
3658 bc_char_vec_init(&p->lex_strnumbuf);
3659 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3660 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3661 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3664 p->func = xc_program_func(fidx);
3667 static void xc_program_add_fn(void)
3673 bc_vec_push(&G.prog.fns, &f);
3679 // Note: takes ownership of 'name' (must be malloced)
3680 static size_t bc_program_addFunc(char *name)
3683 BcId entry, *entry_ptr;
3687 entry.idx = G.prog.fns.len;
3689 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3690 if (!inserted) free(name);
3692 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3693 idx = entry_ptr->idx;
3696 // There is already a function with this name.
3697 // It'll be redefined now, clear old definition.
3698 BcFunc *func = xc_program_func(entry_ptr->idx);
3702 xc_program_add_fn();
3708 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3709 // We can calculate the conversion between tokens and exprs by subtracting the
3710 // position of the first operator in the lex enum and adding the position of the
3711 // first in the expr enum. Note: This only works for binary operators.
3712 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3714 static BcStatus bc_parse_expr_empty_ok(uint8_t flags);
3716 static BC_STATUS zbc_parse_expr(uint8_t flags)
3720 s = bc_parse_expr_empty_ok(flags);
3721 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3722 RETURN_STATUS(bc_error("empty expression"));
3725 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3727 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed);
3728 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3730 static BC_STATUS zbc_parse_stmt(void)
3732 RETURN_STATUS(zbc_parse_stmt_possibly_auto(false));
3734 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3736 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(const char *after_X)
3738 BcParse *p = &G.prs;
3739 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3740 // Same for "else", "while()", "for()".
3741 BcStatus s = zbc_lex_next_and_skip_NLINE();
3742 if (s) RETURN_STATUS(s);
3743 if (p->lex == XC_LEX_NLINE)
3744 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3746 RETURN_STATUS(zbc_parse_stmt());
3748 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3750 static void bc_parse_operator(BcLexType type, size_t start, size_t *nexprs)
3752 BcParse *p = &G.prs;
3753 char l, r = bc_operation_PREC(type - XC_LEX_1st_op);
3754 bool left = bc_operation_LEFT(type - XC_LEX_1st_op);
3756 while (p->ops.len > start) {
3757 BcLexType t = BC_PARSE_TOP_OP(p);
3758 if (t == BC_LEX_LPAREN) break;
3760 l = bc_operation_PREC(t - XC_LEX_1st_op);
3761 if (l >= r && (l != r || !left)) break;
3763 xc_parse_push(BC_TOKEN_2_INST(t));
3764 bc_vec_pop(&p->ops);
3765 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3768 bc_vec_push(&p->ops, &type);
3771 static BC_STATUS zbc_parse_rightParen(size_t ops_bgn, size_t *nexs)
3773 BcParse *p = &G.prs;
3776 if (p->ops.len <= ops_bgn)
3777 RETURN_STATUS(bc_error_bad_expression());
3778 top = BC_PARSE_TOP_OP(p);
3780 while (top != BC_LEX_LPAREN) {
3781 xc_parse_push(BC_TOKEN_2_INST(top));
3783 bc_vec_pop(&p->ops);
3784 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3786 if (p->ops.len <= ops_bgn)
3787 RETURN_STATUS(bc_error_bad_expression());
3788 top = BC_PARSE_TOP_OP(p);
3791 bc_vec_pop(&p->ops);
3793 RETURN_STATUS(BC_STATUS_SUCCESS);
3795 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3797 static BC_STATUS zbc_parse_params(uint8_t flags)
3799 BcParse *p = &G.prs;
3803 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
3804 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3807 if (s) RETURN_STATUS(s);
3810 if (p->lex != BC_LEX_RPAREN) {
3812 s = zbc_parse_expr(flags);
3813 if (s) RETURN_STATUS(s);
3815 if (p->lex != BC_LEX_COMMA) {
3816 if (p->lex == BC_LEX_RPAREN)
3818 RETURN_STATUS(bc_error_bad_token());
3821 if (s) RETURN_STATUS(s);
3825 xc_parse_push(BC_INST_CALL);
3826 xc_parse_pushIndex(nparams);
3828 RETURN_STATUS(BC_STATUS_SUCCESS);
3830 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3832 // Note: takes ownership of 'name' (must be malloced)
3833 static BC_STATUS zbc_parse_call(char *name, uint8_t flags)
3835 BcParse *p = &G.prs;
3837 BcId entry, *entry_ptr;
3842 s = zbc_parse_params(flags);
3845 if (p->lex != BC_LEX_RPAREN) {
3846 s = bc_error_bad_token();
3850 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3852 if (idx == BC_VEC_INVALID_IDX) {
3853 // No such function exists, create an empty one
3854 bc_program_addFunc(name);
3855 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3859 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3860 xc_parse_pushIndex(entry_ptr->idx);
3862 RETURN_STATUS(zxc_lex_next());
3867 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3869 static BC_STATUS zbc_parse_name(BcInst *type, uint8_t flags)
3871 BcParse *p = &G.prs;
3875 name = xstrdup(p->lex_strnumbuf.v);
3879 if (p->lex == BC_LEX_LBRACKET) {
3883 if (p->lex == BC_LEX_RBRACKET) {
3884 if (!(flags & BC_PARSE_ARRAY)) {
3885 s = bc_error_bad_expression();
3888 *type = XC_INST_ARRAY;
3890 *type = XC_INST_ARRAY_ELEM;
3891 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3892 s = zbc_parse_expr(flags);
3897 xc_parse_push(*type);
3898 xc_parse_pushName(name);
3900 } else if (p->lex == BC_LEX_LPAREN) {
3901 if (flags & BC_PARSE_NOCALL) {
3902 s = bc_error_bad_token();
3905 *type = BC_INST_CALL;
3906 s = zbc_parse_call(name, flags);
3908 *type = XC_INST_VAR;
3909 xc_parse_push(XC_INST_VAR);
3910 xc_parse_pushName(name);
3919 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3921 static BC_STATUS zbc_parse_read(void)
3923 BcParse *p = &G.prs;
3927 if (s) RETURN_STATUS(s);
3928 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3931 if (s) RETURN_STATUS(s);
3932 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3934 xc_parse_push(XC_INST_READ);
3938 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3940 static BC_STATUS zbc_parse_builtin(BcLexType type, uint8_t flags, BcInst *prev)
3942 BcParse *p = &G.prs;
3946 if (s) RETURN_STATUS(s);
3947 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3949 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3952 if (s) RETURN_STATUS(s);
3954 s = zbc_parse_expr(flags);
3955 if (s) RETURN_STATUS(s);
3957 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3959 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3960 xc_parse_push(*prev);
3964 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3966 static BC_STATUS zbc_parse_scale(BcInst *type, uint8_t flags)
3968 BcParse *p = &G.prs;
3972 if (s) RETURN_STATUS(s);
3974 if (p->lex != BC_LEX_LPAREN) {
3975 *type = XC_INST_SCALE;
3976 xc_parse_push(XC_INST_SCALE);
3977 RETURN_STATUS(BC_STATUS_SUCCESS);
3980 *type = XC_INST_SCALE_FUNC;
3981 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3984 if (s) RETURN_STATUS(s);
3986 s = zbc_parse_expr(flags);
3987 if (s) RETURN_STATUS(s);
3988 if (p->lex != BC_LEX_RPAREN)
3989 RETURN_STATUS(bc_error_bad_token());
3990 xc_parse_push(XC_INST_SCALE_FUNC);
3992 RETURN_STATUS(zxc_lex_next());
3994 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3996 static BC_STATUS zbc_parse_incdec(BcInst *prev, size_t *nexs, uint8_t flags)
3998 BcParse *p = &G.prs;
4002 BcInst etype = *prev;
4004 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
4005 || etype == XC_INST_SCALE || etype == BC_INST_LAST
4006 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
4008 *prev = inst = BC_INST_INC_POST + (p->lex != BC_LEX_OP_INC);
4009 xc_parse_push(inst);
4012 *prev = inst = BC_INST_INC_PRE + (p->lex != BC_LEX_OP_INC);
4015 if (s) RETURN_STATUS(s);
4018 // Because we parse the next part of the expression
4019 // right here, we need to increment this.
4024 s = zbc_parse_name(prev, flags | BC_PARSE_NOCALL);
4026 case BC_LEX_KEY_IBASE:
4027 case BC_LEX_KEY_LAST:
4028 case BC_LEX_KEY_OBASE:
4029 xc_parse_push(type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4032 case BC_LEX_KEY_SCALE:
4034 if (s) RETURN_STATUS(s);
4035 if (p->lex == BC_LEX_LPAREN)
4036 s = bc_error_bad_token();
4038 xc_parse_push(XC_INST_SCALE);
4041 s = bc_error_bad_token();
4045 if (!s) xc_parse_push(inst);
4050 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4052 static int bc_parse_inst_isLeaf(BcInst p)
4054 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
4055 || p == BC_INST_INC_POST
4056 || p == BC_INST_DEC_POST
4059 #define BC_PARSE_LEAF(prev, bin_last, rparen) \
4060 (!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev)))
4062 static BC_STATUS zbc_parse_minus(BcInst *prev, size_t ops_bgn,
4063 bool rparen, bool bin_last, size_t *nexprs)
4065 BcParse *p = &G.prs;
4070 if (s) RETURN_STATUS(s);
4072 type = BC_PARSE_LEAF(*prev, bin_last, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
4073 *prev = BC_TOKEN_2_INST(type);
4075 // We can just push onto the op stack because this is the largest
4076 // precedence operator that gets pushed. Inc/dec does not.
4077 if (type != XC_LEX_OP_MINUS)
4078 bc_vec_push(&p->ops, &type);
4080 bc_parse_operator(type, ops_bgn, nexprs);
4084 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4086 static BC_STATUS zbc_parse_print(void)
4088 BcParse *p = &G.prs;
4094 if (s) RETURN_STATUS(s);
4096 if (type == XC_LEX_STR) {
4097 s = zbc_parse_pushSTR();
4099 s = zbc_parse_expr(0);
4101 if (s) RETURN_STATUS(s);
4102 xc_parse_push(XC_INST_PRINT_POP);
4103 if (p->lex != BC_LEX_COMMA)
4109 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4111 static BC_STATUS zbc_parse_return(void)
4113 BcParse *p = &G.prs;
4117 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4119 if (s) RETURN_STATUS(s);
4122 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON)
4123 xc_parse_push(BC_INST_RET0);
4125 bool paren = (t == BC_LEX_LPAREN);
4126 s = bc_parse_expr_empty_ok(0);
4127 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4128 xc_parse_push(BC_INST_RET0);
4131 if (s) RETURN_STATUS(s);
4133 if (!paren || p->lex_last != BC_LEX_RPAREN) {
4134 s = zbc_POSIX_requires("parentheses around return expressions");
4135 if (s) RETURN_STATUS(s);
4138 xc_parse_push(XC_INST_RET);
4141 dbg_lex_done("%s:%d done", __func__, __LINE__);
4144 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4146 static void rewrite_label_to_current(size_t idx)
4148 BcParse *p = &G.prs;
4149 size_t *label = bc_vec_item(&p->func->labels, idx);
4150 *label = p->func->code.len;
4153 static BC_STATUS zbc_parse_if(void)
4155 BcParse *p = &G.prs;
4159 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4161 if (s) RETURN_STATUS(s);
4162 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4165 if (s) RETURN_STATUS(s);
4166 s = zbc_parse_expr(BC_PARSE_REL);
4167 if (s) RETURN_STATUS(s);
4168 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4170 // Encode "if zero, jump to ..."
4171 // Pushed value (destination of the jump) is uninitialized,
4172 // will be rewritten to be address of "end of if()" or of "else".
4173 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4174 bc_parse_pushJUMP_ZERO(ip_idx);
4176 s = zbc_parse_stmt_allow_NLINE_before(STRING_if);
4177 if (s) RETURN_STATUS(s);
4179 dbg_lex("%s:%d in if after stmt: p->lex:%d", __func__, __LINE__, p->lex);
4180 if (p->lex == BC_LEX_KEY_ELSE) {
4183 // Encode "after then_stmt, jump to end of if()"
4184 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4185 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4186 bc_parse_pushJUMP(ip2_idx);
4188 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4189 rewrite_label_to_current(ip_idx);
4193 s = zbc_parse_stmt_allow_NLINE_before(STRING_else);
4194 if (s) RETURN_STATUS(s);
4197 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4198 rewrite_label_to_current(ip_idx);
4200 dbg_lex_done("%s:%d done", __func__, __LINE__);
4203 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4205 static BC_STATUS zbc_parse_while(void)
4207 BcParse *p = &G.prs;
4213 if (s) RETURN_STATUS(s);
4214 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4216 if (s) RETURN_STATUS(s);
4218 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4219 ip_idx = cond_idx + 1;
4220 bc_vec_push(&p->conds, &cond_idx);
4222 bc_vec_push(&p->exits, &ip_idx);
4223 bc_vec_push(&p->func->labels, &ip_idx);
4225 s = zbc_parse_expr(BC_PARSE_REL);
4226 if (s) RETURN_STATUS(s);
4227 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4229 bc_parse_pushJUMP_ZERO(ip_idx);
4231 s = zbc_parse_stmt_allow_NLINE_before(STRING_while);
4232 if (s) RETURN_STATUS(s);
4234 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4235 bc_parse_pushJUMP(cond_idx);
4237 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4238 rewrite_label_to_current(ip_idx);
4240 bc_vec_pop(&p->exits);
4241 bc_vec_pop(&p->conds);
4245 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4247 static BC_STATUS zbc_parse_for(void)
4249 BcParse *p = &G.prs;
4251 size_t cond_idx, exit_idx, body_idx, update_idx;
4253 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4255 if (s) RETURN_STATUS(s);
4256 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4258 if (s) RETURN_STATUS(s);
4260 if (p->lex != BC_LEX_SCOLON) {
4261 s = zbc_parse_expr(0);
4262 xc_parse_push(XC_INST_POP);
4263 if (s) RETURN_STATUS(s);
4265 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4266 if (s) RETURN_STATUS(s);
4269 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4271 if (s) RETURN_STATUS(s);
4273 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4274 update_idx = cond_idx + 1;
4275 body_idx = update_idx + 1;
4276 exit_idx = body_idx + 1;
4278 if (p->lex != BC_LEX_SCOLON)
4279 s = zbc_parse_expr(BC_PARSE_REL);
4281 // Set this for the next call to xc_parse_pushNUM().
4282 // This is safe to set because the current token is a semicolon,
4283 // which has no string requirement.
4284 bc_vec_string(&p->lex_strnumbuf, 1, "1");
4286 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4288 if (s) RETURN_STATUS(s);
4290 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4293 if (s) RETURN_STATUS(s);
4295 bc_parse_pushJUMP_ZERO(exit_idx);
4296 bc_parse_pushJUMP(body_idx);
4298 bc_vec_push(&p->conds, &update_idx);
4299 bc_vec_push(&p->func->labels, &p->func->code.len);
4301 if (p->lex != BC_LEX_RPAREN) {
4302 s = zbc_parse_expr(0);
4303 if (s) RETURN_STATUS(s);
4304 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4305 xc_parse_push(XC_INST_POP);
4307 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4308 if (s) RETURN_STATUS(s);
4311 bc_parse_pushJUMP(cond_idx);
4312 bc_vec_push(&p->func->labels, &p->func->code.len);
4314 bc_vec_push(&p->exits, &exit_idx);
4315 bc_vec_push(&p->func->labels, &exit_idx);
4317 s = zbc_parse_stmt_allow_NLINE_before(STRING_for);
4318 if (s) RETURN_STATUS(s);
4320 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4321 bc_parse_pushJUMP(update_idx);
4323 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4324 rewrite_label_to_current(exit_idx);
4326 bc_vec_pop(&p->exits);
4327 bc_vec_pop(&p->conds);
4329 RETURN_STATUS(BC_STATUS_SUCCESS);
4331 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4333 static BC_STATUS zbc_parse_break_or_continue(BcLexType type)
4335 BcParse *p = &G.prs;
4338 if (type == BC_LEX_KEY_BREAK) {
4339 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4340 RETURN_STATUS(bc_error_bad_token());
4341 i = *(size_t*)bc_vec_top(&p->exits);
4343 i = *(size_t*)bc_vec_top(&p->conds);
4345 bc_parse_pushJUMP(i);
4347 RETURN_STATUS(zxc_lex_next());
4349 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4351 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4357 autoid = (void*)f->autos.v;
4358 for (i = 0; i < f->autos.len; i++, autoid++) {
4359 if (strcmp(name, autoid->name) == 0
4360 && var == autoid->idx
4362 RETURN_STATUS(bc_error("duplicate function parameter or auto name"));
4369 bc_vec_push(&f->autos, &a);
4371 RETURN_STATUS(BC_STATUS_SUCCESS);
4373 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4375 static BC_STATUS zbc_parse_funcdef(void)
4377 BcParse *p = &G.prs;
4379 bool var, comma = false;
4382 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4384 if (s) RETURN_STATUS(s);
4385 if (p->lex != XC_LEX_NAME)
4386 RETURN_STATUS(bc_error_bad_function_definition());
4388 name = xstrdup(p->lex_strnumbuf.v);
4389 p->fidx = bc_program_addFunc(name);
4390 p->func = xc_program_func(p->fidx);
4393 if (s) RETURN_STATUS(s);
4394 if (p->lex != BC_LEX_LPAREN)
4395 RETURN_STATUS(bc_error_bad_function_definition());
4397 if (s) RETURN_STATUS(s);
4399 while (p->lex != BC_LEX_RPAREN) {
4400 if (p->lex != XC_LEX_NAME)
4401 RETURN_STATUS(bc_error_bad_function_definition());
4405 name = xstrdup(p->lex_strnumbuf.v);
4409 var = p->lex != BC_LEX_LBRACKET;
4415 if (p->lex != BC_LEX_RBRACKET) {
4416 s = bc_error_bad_function_definition();
4424 comma = p->lex == BC_LEX_COMMA;
4430 s = zbc_func_insert(p->func, name, var);
4434 if (comma) RETURN_STATUS(bc_error_bad_function_definition());
4437 if (s) RETURN_STATUS(s);
4439 if (p->lex != BC_LEX_LBRACE) {
4440 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4441 if (s) RETURN_STATUS(s);
4444 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4445 s = zbc_lex_skip_if_at_NLINE();
4446 if (s) RETURN_STATUS(s);
4447 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4448 if (p->lex != BC_LEX_LBRACE)
4449 RETURN_STATUS(bc_error("function { body } expected"));
4451 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4452 s = zbc_parse_stmt_possibly_auto(true);
4454 if (s) RETURN_STATUS(s);
4456 xc_parse_push(BC_INST_RET0);
4458 // Subsequent code generation is into main program
4459 p->fidx = BC_PROG_MAIN;
4460 p->func = xc_program_func_BC_PROG_MAIN();
4462 dbg_lex_done("%s:%d done", __func__, __LINE__);
4465 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4469 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4471 static BC_STATUS zbc_parse_auto(void)
4473 BcParse *p = &G.prs;
4477 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4479 if (s) RETURN_STATUS(s);
4484 if (p->lex != XC_LEX_NAME)
4485 RETURN_STATUS(bc_error_at("bad 'auto' syntax"));
4487 name = xstrdup(p->lex_strnumbuf.v);
4491 var = (p->lex != BC_LEX_LBRACKET);
4496 if (p->lex != BC_LEX_RBRACKET) {
4497 s = bc_error_at("bad 'auto' syntax");
4504 s = zbc_func_insert(p->func, name, var);
4507 if (p->lex == XC_LEX_NLINE
4508 || p->lex == BC_LEX_SCOLON
4509 //|| p->lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4513 if (p->lex != BC_LEX_COMMA)
4514 RETURN_STATUS(bc_error_at("bad 'auto' syntax"));
4515 s = zxc_lex_next(); // skip comma
4516 if (s) RETURN_STATUS(s);
4519 dbg_lex_done("%s:%d done", __func__, __LINE__);
4520 RETURN_STATUS(BC_STATUS_SUCCESS);
4523 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4526 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4528 #undef zbc_parse_stmt_possibly_auto
4529 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed)
4531 BcParse *p = &G.prs;
4532 BcStatus s = BC_STATUS_SUCCESS;
4534 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
4536 if (p->lex == XC_LEX_NLINE) {
4537 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4538 RETURN_STATUS(zxc_lex_next());
4540 if (p->lex == BC_LEX_SCOLON) {
4541 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4542 RETURN_STATUS(zxc_lex_next());
4545 if (p->lex == BC_LEX_LBRACE) {
4546 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4549 if (s) RETURN_STATUS(s);
4550 } while (p->lex == XC_LEX_NLINE);
4551 if (auto_allowed && p->lex == BC_LEX_KEY_AUTO) {
4552 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4553 s = zbc_parse_auto();
4554 if (s) RETURN_STATUS(s);
4556 while (p->lex != BC_LEX_RBRACE) {
4557 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4558 s = zbc_parse_stmt();
4559 if (s) RETURN_STATUS(s);
4562 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4566 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4568 case XC_LEX_OP_MINUS:
4571 case BC_LEX_OP_BOOL_NOT:
4575 case BC_LEX_KEY_IBASE:
4576 case BC_LEX_KEY_LAST:
4577 case BC_LEX_KEY_LENGTH:
4578 case BC_LEX_KEY_OBASE:
4579 case BC_LEX_KEY_READ:
4580 case BC_LEX_KEY_SCALE:
4581 case BC_LEX_KEY_SQRT:
4582 s = zbc_parse_expr(BC_PARSE_PRINT);
4585 s = zbc_parse_pushSTR();
4586 xc_parse_push(XC_INST_PRINT_STR);
4588 case BC_LEX_KEY_BREAK:
4589 case BC_LEX_KEY_CONTINUE:
4590 s = zbc_parse_break_or_continue(p->lex);
4592 case BC_LEX_KEY_FOR:
4593 s = zbc_parse_for();
4595 case BC_LEX_KEY_HALT:
4596 xc_parse_push(BC_INST_HALT);
4602 case BC_LEX_KEY_LIMITS:
4603 // "limits" is a compile-time command,
4604 // the output is produced at _parse time_.
4606 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4607 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4608 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4609 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4610 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4611 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4612 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4613 "Number of vars = "BC_MAX_VARS_STR "\n"
4617 case BC_LEX_KEY_PRINT:
4618 s = zbc_parse_print();
4620 case BC_LEX_KEY_QUIT:
4621 // "quit" is a compile-time command. For example,
4622 // "if (0 == 1) quit" terminates when parsing the statement,
4623 // not when it is executed
4624 QUIT_OR_RETURN_TO_MAIN;
4625 case BC_LEX_KEY_RETURN:
4627 RETURN_STATUS(bc_error("'return' not in a function"));
4628 s = zbc_parse_return();
4630 case BC_LEX_KEY_WHILE:
4631 s = zbc_parse_while();
4634 s = bc_error_bad_token();
4638 dbg_lex_done("%s:%d done", __func__, __LINE__);
4641 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4643 static BC_STATUS zbc_parse_stmt_or_funcdef(void)
4645 BcParse *p = &G.prs;
4648 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4649 if (p->lex == XC_LEX_EOF)
4650 s = bc_error("end of file");
4651 else if (p->lex == BC_LEX_KEY_DEFINE) {
4652 dbg_lex("%s:%d p->lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4653 s = zbc_parse_funcdef();
4655 dbg_lex("%s:%d p->lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->lex);
4656 s = zbc_parse_stmt();
4659 dbg_lex_done("%s:%d done", __func__, __LINE__);
4662 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4664 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4665 static BcStatus bc_parse_expr_empty_ok(uint8_t flags)
4667 BcParse *p = &G.prs;
4668 BcInst prev = XC_INST_PRINT;
4669 size_t nexprs = 0, ops_bgn = p->ops.len;
4670 unsigned nparens, nrelops;
4671 bool paren_first, rprn, assign, bin_last, incdec;
4673 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4674 paren_first = (p->lex == BC_LEX_LPAREN);
4675 nparens = nrelops = 0;
4676 rprn = assign = incdec = false;
4682 BcLexType t = p->lex;
4684 if (!lex_allowed_in_bc_expr(t))
4687 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4689 s = BC_STATUS_SUCCESS;
4693 dbg_lex("%s:%d LEX_OP_INC/DEC", __func__, __LINE__);
4694 if (incdec) return bc_error_bad_assignment();
4695 s = zbc_parse_incdec(&prev, &nexprs, flags);
4697 rprn = bin_last = false;
4698 //get_token = false; - already is
4700 case XC_LEX_OP_MINUS:
4701 dbg_lex("%s:%d LEX_OP_MINUS", __func__, __LINE__);
4702 s = zbc_parse_minus(&prev, ops_bgn, rprn, bin_last, &nexprs);
4704 //get_token = false; - already is
4705 bin_last = (prev == XC_INST_MINUS);
4706 if (bin_last) incdec = false;
4708 case BC_LEX_OP_ASSIGN_POWER:
4709 case BC_LEX_OP_ASSIGN_MULTIPLY:
4710 case BC_LEX_OP_ASSIGN_DIVIDE:
4711 case BC_LEX_OP_ASSIGN_MODULUS:
4712 case BC_LEX_OP_ASSIGN_PLUS:
4713 case BC_LEX_OP_ASSIGN_MINUS:
4714 case BC_LEX_OP_ASSIGN:
4715 dbg_lex("%s:%d LEX_ASSIGNxyz", __func__, __LINE__);
4716 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4717 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4718 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4720 return bc_error_bad_assignment();
4723 case XC_LEX_OP_POWER:
4724 case XC_LEX_OP_MULTIPLY:
4725 case XC_LEX_OP_DIVIDE:
4726 case XC_LEX_OP_MODULUS:
4727 case XC_LEX_OP_PLUS:
4728 case XC_LEX_OP_REL_EQ:
4729 case XC_LEX_OP_REL_LE:
4730 case XC_LEX_OP_REL_GE:
4731 case XC_LEX_OP_REL_NE:
4732 case XC_LEX_OP_REL_LT:
4733 case XC_LEX_OP_REL_GT:
4734 case BC_LEX_OP_BOOL_NOT:
4735 case BC_LEX_OP_BOOL_OR:
4736 case BC_LEX_OP_BOOL_AND:
4737 dbg_lex("%s:%d LEX_OP_xyz", __func__, __LINE__);
4738 if (t == BC_LEX_OP_BOOL_NOT) {
4739 if (!bin_last && p->lex_last != BC_LEX_OP_BOOL_NOT)
4740 return bc_error_bad_expression();
4741 } else if (prev == XC_INST_BOOL_NOT) {
4742 return bc_error_bad_expression();
4745 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4746 prev = BC_TOKEN_2_INST(t);
4747 bc_parse_operator(t, ops_bgn, &nexprs);
4748 rprn = incdec = false;
4750 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4753 dbg_lex("%s:%d LEX_LPAREN", __func__, __LINE__);
4754 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4755 return bc_error_bad_expression();
4756 bc_vec_push(&p->ops, &t);
4759 rprn = incdec = false;
4762 dbg_lex("%s:%d LEX_RPAREN", __func__, __LINE__);
4763 if (p->lex_last == BC_LEX_LPAREN) {
4764 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4765 return BC_STATUS_PARSE_EMPTY_EXP;
4767 if (bin_last || prev == XC_INST_BOOL_NOT)
4768 return bc_error_bad_expression();
4772 s = zbc_parse_rightParen(ops_bgn, &nexprs);
4776 bin_last = incdec = false;
4779 dbg_lex("%s:%d LEX_NAME", __func__, __LINE__);
4780 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4781 return bc_error_bad_expression();
4782 s = zbc_parse_name(&prev, flags & ~BC_PARSE_NOCALL);
4783 rprn = (prev == BC_INST_CALL);
4785 //get_token = false; - already is
4789 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4790 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4791 return bc_error_bad_expression();
4795 rprn = bin_last = false;
4798 case BC_LEX_KEY_IBASE:
4799 case BC_LEX_KEY_LAST:
4800 case BC_LEX_KEY_OBASE:
4801 dbg_lex("%s:%d LEX_IBASE/LAST/OBASE", __func__, __LINE__);
4802 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4803 return bc_error_bad_expression();
4804 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4805 xc_parse_push((char) prev);
4807 rprn = bin_last = false;
4810 case BC_LEX_KEY_LENGTH:
4811 case BC_LEX_KEY_SQRT:
4812 dbg_lex("%s:%d LEX_LEN/SQRT", __func__, __LINE__);
4813 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4814 return bc_error_bad_expression();
4815 s = zbc_parse_builtin(t, flags, &prev);
4817 rprn = bin_last = incdec = false;
4820 case BC_LEX_KEY_READ:
4821 dbg_lex("%s:%d LEX_READ", __func__, __LINE__);
4822 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4823 return bc_error_bad_expression();
4824 s = zbc_parse_read();
4825 prev = XC_INST_READ;
4827 rprn = bin_last = incdec = false;
4830 case BC_LEX_KEY_SCALE:
4831 dbg_lex("%s:%d LEX_SCALE", __func__, __LINE__);
4832 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4833 return bc_error_bad_expression();
4834 s = zbc_parse_scale(&prev, flags);
4835 //get_token = false; - already is
4836 rprn = bin_last = false;
4840 return bc_error_bad_token();
4843 if (s || G_interrupt) // error, or ^C: stop parsing
4844 return BC_STATUS_FAILURE;
4852 while (p->ops.len > ops_bgn) {
4853 BcLexType top = BC_PARSE_TOP_OP(p);
4854 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4856 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4857 return bc_error_bad_expression();
4859 xc_parse_push(BC_TOKEN_2_INST(top));
4861 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4862 bc_vec_pop(&p->ops);
4865 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4866 return bc_error_bad_expression();
4868 if (!(flags & BC_PARSE_REL) && nrelops) {
4870 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4872 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4874 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4878 if (flags & BC_PARSE_PRINT) {
4879 if (paren_first || !assign)
4880 xc_parse_push(XC_INST_PRINT);
4881 xc_parse_push(XC_INST_POP);
4884 dbg_lex_done("%s:%d done", __func__, __LINE__);
4885 return BC_STATUS_SUCCESS;
4892 static BC_STATUS zdc_parse_register(void)
4894 BcParse *p = &G.prs;
4898 if (s) RETURN_STATUS(s);
4899 if (p->lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4901 xc_parse_pushName(p->lex_strnumbuf.v);
4905 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4907 static void dc_parse_string(void)
4909 BcParse *p = &G.prs;
4911 size_t len = G.prog.strs.len;
4913 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4915 str = xstrdup(p->lex_strnumbuf.v);
4916 xc_parse_push(XC_INST_STR);
4917 xc_parse_pushIndex(len);
4918 bc_vec_push(&G.prog.strs, &str);
4920 // Explanation needed here
4921 xc_program_add_fn();
4922 p->func = xc_program_func(p->fidx);
4924 dbg_lex_done("%s:%d done", __func__, __LINE__);
4927 static BC_STATUS zdc_parse_mem(uint8_t inst, bool name, bool store)
4931 xc_parse_push(inst);
4933 s = zdc_parse_register();
4934 if (s) RETURN_STATUS(s);
4938 xc_parse_push(DC_INST_SWAP);
4939 xc_parse_push(XC_INST_ASSIGN);
4940 xc_parse_push(XC_INST_POP);
4943 RETURN_STATUS(BC_STATUS_SUCCESS);
4945 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4947 static BC_STATUS zdc_parse_cond(uint8_t inst)
4949 BcParse *p = &G.prs;
4952 xc_parse_push(inst);
4953 xc_parse_push(DC_INST_EXEC_COND);
4955 s = zdc_parse_register();
4956 if (s) RETURN_STATUS(s);
4959 if (s) RETURN_STATUS(s);
4961 // Note that 'else' part can not be on the next line:
4962 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4963 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4964 if (p->lex == DC_LEX_ELSE) {
4965 s = zdc_parse_register();
4966 if (s) RETURN_STATUS(s);
4969 xc_parse_push('\0');
4974 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4976 static BC_STATUS zdc_parse_token(BcLexType t)
4980 bool assign, get_token;
4982 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4983 s = BC_STATUS_SUCCESS;
4986 case XC_LEX_OP_REL_EQ:
4987 case XC_LEX_OP_REL_LE:
4988 case XC_LEX_OP_REL_GE:
4989 case XC_LEX_OP_REL_NE:
4990 case XC_LEX_OP_REL_LT:
4991 case XC_LEX_OP_REL_GT:
4992 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
4993 s = zdc_parse_cond(t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
4998 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
4999 s = zdc_parse_mem(XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
5002 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
5006 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
5008 if (s) RETURN_STATUS(s);
5009 if (G.prs.lex != XC_LEX_NUMBER)
5010 RETURN_STATUS(bc_error_bad_token());
5012 xc_parse_push(XC_INST_NEG);
5015 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
5019 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
5020 xc_parse_push(XC_INST_READ);
5022 case DC_LEX_OP_ASSIGN:
5023 case DC_LEX_STORE_PUSH:
5024 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
5025 assign = (t == DC_LEX_OP_ASSIGN);
5026 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
5027 s = zdc_parse_mem(inst, true, assign);
5030 case DC_LEX_LOAD_POP:
5031 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
5032 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
5033 s = zdc_parse_mem(inst, true, false);
5035 case DC_LEX_STORE_IBASE:
5036 case DC_LEX_STORE_SCALE:
5037 case DC_LEX_STORE_OBASE:
5038 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
5039 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
5040 s = zdc_parse_mem(inst, false, true);
5043 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
5044 RETURN_STATUS(bc_error_bad_token());
5047 if (!s && get_token) s = zxc_lex_next();
5049 dbg_lex_done("%s:%d done", __func__, __LINE__);
5052 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
5054 static BC_STATUS zdc_parse_expr(void)
5056 BcParse *p = &G.prs;
5059 i = (int)p->lex - (int)XC_LEX_OP_POWER;
5061 BcInst inst = dc_LEX_to_INST[i];
5062 if (inst != DC_INST_INVALID) {
5063 xc_parse_push(inst);
5064 RETURN_STATUS(zxc_lex_next());
5067 RETURN_STATUS(zdc_parse_token(p->lex));
5069 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
5071 static BC_STATUS zdc_parse_exprs_until_eof(void)
5073 BcParse *p = &G.prs;
5074 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
5075 while (p->lex != XC_LEX_EOF) {
5076 BcStatus s = zdc_parse_expr();
5077 if (s) RETURN_STATUS(s);
5080 dbg_lex_done("%s:%d done", __func__, __LINE__);
5081 RETURN_STATUS(BC_STATUS_SUCCESS);
5083 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5091 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
5092 #define BC_PROG_NUM(r, n) \
5093 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
5095 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5096 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5098 static BcVec* xc_program_search(char *id, bool var)
5105 v = var ? &G.prog.vars : &G.prog.arrs;
5106 map = var ? &G.prog.var_map : &G.prog.arr_map;
5110 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5114 bc_array_init(&v2, var);
5115 bc_vec_push(v, &v2);
5118 ptr = bc_vec_item(map, i);
5119 if (new) ptr->name = xstrdup(e.name);
5120 return bc_vec_item(v, ptr->idx);
5123 // 'num' need not be initialized on entry
5124 static BC_STATUS zxc_program_num(BcResult *r, BcNum **num)
5128 case XC_RESULT_TEMP:
5129 case XC_RESULT_IBASE:
5130 case XC_RESULT_SCALE:
5131 case XC_RESULT_OBASE:
5134 case XC_RESULT_CONSTANT: {
5139 str = *xc_program_const(r->d.id.idx);
5142 bc_num_init(&r->d.n, len);
5144 s = zxc_num_parse(&r->d.n, str, G.prog.ib_t);
5146 bc_num_free(&r->d.n);
5150 r->t = XC_RESULT_TEMP;
5154 case XC_RESULT_ARRAY:
5155 case XC_RESULT_ARRAY_ELEM: {
5158 v = xc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5159 // dc variables are all stacks, so here we have this:
5161 // TODO: eliminate these stacks for bc-only config?
5162 if (r->t == XC_RESULT_ARRAY_ELEM) {
5164 if (v->len <= r->d.id.idx)
5165 bc_array_expand(v, r->d.id.idx + 1);
5166 *num = bc_vec_item(v, r->d.id.idx);
5173 case BC_RESULT_LAST:
5174 *num = &G.prog.last;
5182 // Testing the theory that dc does not reach LAST/ONE
5183 bb_error_msg_and_die("BUG:%d", r->t);
5187 RETURN_STATUS(BC_STATUS_SUCCESS);
5189 #define zxc_program_num(...) (zxc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5191 static BC_STATUS zxc_program_binOpPrep(BcResult **l, BcNum **ln,
5192 BcResult **r, BcNum **rn, bool assign)
5195 BcResultType lt, rt;
5197 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5198 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5200 *r = bc_vec_item_rev(&G.prog.results, 0);
5201 *l = bc_vec_item_rev(&G.prog.results, 1);
5203 s = zxc_program_num(*l, ln);
5204 if (s) RETURN_STATUS(s);
5205 s = zxc_program_num(*r, rn);
5206 if (s) RETURN_STATUS(s);
5211 // We run this again under these conditions in case any vector has been
5212 // reallocated out from under the BcNums or arrays we had.
5213 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5214 s = zxc_program_num(*l, ln);
5215 if (s) RETURN_STATUS(s);
5218 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5219 RETURN_STATUS(bc_error_variable_is_wrong_type());
5220 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5221 RETURN_STATUS(bc_error_variable_is_wrong_type());
5225 #define zxc_program_binOpPrep(...) (zxc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5227 static void xc_program_binOpRetire(BcResult *r)
5229 r->t = XC_RESULT_TEMP;
5230 bc_vec_pop(&G.prog.results);
5231 bc_result_pop_and_push(r);
5234 // Note: *r and *n need not be initialized by caller
5235 static BC_STATUS zxc_program_prep(BcResult **r, BcNum **n)
5239 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5240 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5241 *r = bc_vec_top(&G.prog.results);
5243 s = zxc_program_num(*r, n);
5244 if (s) RETURN_STATUS(s);
5246 if (!BC_PROG_NUM((*r), (*n)))
5247 RETURN_STATUS(bc_error_variable_is_wrong_type());
5251 #define zxc_program_prep(...) (zxc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5253 static void xc_program_retire(BcResult *r, BcResultType t)
5256 bc_result_pop_and_push(r);
5259 static BC_STATUS zxc_program_op(char inst)
5262 BcResult *opd1, *opd2, res;
5265 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5266 if (s) RETURN_STATUS(s);
5267 bc_num_init_DEF_SIZE(&res.d.n);
5269 s = BC_STATUS_SUCCESS;
5270 IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5272 xc_program_binOpRetire(&res);
5276 bc_num_free(&res.d.n);
5279 #define zxc_program_op(...) (zxc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5281 static BC_STATUS zxc_program_read(void)
5289 bc_char_vec_init(&buf);
5290 xc_read_line(&buf, stdin);
5292 f = xc_program_func(BC_PROG_READ);
5293 bc_vec_pop_all(&f->code);
5295 sv_parse = G.prs; // struct copy
5296 xc_parse_create(BC_PROG_READ);
5297 //G.err_line = G.prs.lex_line = 1; - not needed, error line info is not printed for read()
5299 s = zxc_parse_text_init(buf.v);
5300 if (s) goto exec_err;
5302 IF_BC(s = zbc_parse_expr(0));
5304 IF_DC(s = zdc_parse_exprs_until_eof());
5306 if (s) goto exec_err;
5307 if (G.prs.lex != XC_LEX_NLINE && G.prs.lex != XC_LEX_EOF) {
5308 s = bc_error_at("bad read() expression");
5311 xc_parse_push(XC_INST_RET);
5313 ip.func = BC_PROG_READ;
5315 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5316 bc_vec_push(&G.prog.exestack, &ip);
5320 G.prs = sv_parse; // struct copy
5324 #define zxc_program_read(...) (zxc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5326 static size_t xc_program_index(char *code, size_t *bgn)
5328 unsigned char *bytes = (void*)(code + *bgn);
5334 if (amt < SMALL_INDEX_LIMIT) {
5338 amt -= (SMALL_INDEX_LIMIT - 1); // amt is 1 or more here
5344 res |= (size_t)(*bytes++) << i;
5346 } while (--amt != 0);
5351 static char *xc_program_name(char *code, size_t *bgn)
5354 *bgn += strlen(code) + 1;
5356 return xstrdup(code);
5359 static void xc_program_printString(const char *str)
5362 if (!str[0] && IS_DC) {
5363 // Example: echo '[]ap' | dc
5364 // should print two bytes: 0x00, 0x0A
5372 static const char esc[] ALIGN1 = "nabfrt""e\\";
5376 n = strchr(esc, c); // note: c can be NUL
5378 // Just print the backslash and following character
5382 if (n - esc == 0) // "\n" ?
5383 G.prog.nchars = SIZE_MAX;
5384 c = "\n\a\b\f\r\t""\\\\""\\"[n - esc];
5385 // n a b f r t e \ \<end of line>
5393 static void bc_num_printNewline(void)
5395 if (G.prog.nchars == G.prog.len - 1) {
5403 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5406 bb_putchar((char) num);
5407 G.prog.nchars += width;
5411 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5415 bc_num_printNewline();
5416 bb_putchar(radix ? '.' : ' ');
5419 bc_num_printNewline();
5420 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5423 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5425 bc_num_printNewline();
5428 bb_putchar(((char) dig) + '0');
5432 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5435 bc_num_printNewline();
5440 bc_num_printNewline();
5441 bb_putchar(bb_hexdigits_upcase[num]);
5442 G.prog.nchars += width;
5445 static void bc_num_printDecimal(BcNum *n)
5447 size_t i, rdx = n->rdx - 1;
5454 for (i = n->len - 1; i < n->len; --i)
5455 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5458 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5460 static BC_STATUS zxc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5465 BcDig base_digs[ULONG_NUM_BUFSIZE];
5466 BcNum intp, fracp, digit, frac_len;
5467 unsigned long dig, *ptr;
5472 print(0, width, false);
5473 RETURN_STATUS(BC_STATUS_SUCCESS);
5476 bc_vec_init(&stack, sizeof(long), NULL);
5477 bc_num_init(&intp, n->len);
5478 bc_num_init(&fracp, n->rdx);
5479 bc_num_init(&digit, width);
5480 bc_num_init(&frac_len, BC_NUM_INT(n));
5481 bc_num_copy(&intp, n);
5482 bc_num_one(&frac_len);
5483 base.cap = ARRAY_SIZE(base_digs);
5484 base.num = base_digs;
5485 bc_num_ulong2num(&base, base_t);
5487 bc_num_truncate(&intp, intp.rdx);
5488 s = zbc_num_sub(n, &intp, &fracp, 0);
5491 while (intp.len != 0) {
5492 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5494 s = zbc_num_ulong(&digit, &dig);
5496 bc_vec_push(&stack, &dig);
5499 for (i = 0; i < stack.len; ++i) {
5500 ptr = bc_vec_item_rev(&stack, i);
5501 print(*ptr, width, false);
5504 if (!n->rdx) goto err;
5506 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5507 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5509 s = zbc_num_ulong(&fracp, &dig);
5511 bc_num_ulong2num(&intp, dig);
5512 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5514 print(dig, width, radix);
5515 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5519 bc_num_free(&frac_len);
5520 bc_num_free(&digit);
5521 bc_num_free(&fracp);
5523 bc_vec_free(&stack);
5526 #define zxc_num_printNum(...) (zxc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5528 static BC_STATUS zxc_num_printBase(BcNum *n)
5542 if (G.prog.ob_t <= 16) {
5544 print = bc_num_printHex;
5546 unsigned i = G.prog.ob_t - 1;
5554 print = bc_num_printDigits;
5557 s = zxc_num_printNum(n, G.prog.ob_t, width, print);
5562 #define zxc_num_printBase(...) (zxc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5564 static BC_STATUS zxc_num_print(BcNum *n, bool newline)
5566 BcStatus s = BC_STATUS_SUCCESS;
5568 bc_num_printNewline();
5573 } else if (G.prog.ob_t == 10)
5574 bc_num_printDecimal(n);
5576 s = zxc_num_printBase(n);
5585 #define zxc_num_print(...) (zxc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5587 static BC_STATUS zxc_program_print(char inst, size_t idx)
5592 bool pop = (inst != XC_INST_PRINT);
5594 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5595 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5597 r = bc_vec_item_rev(&G.prog.results, idx);
5598 s = zxc_program_num(r, &num);
5599 if (s) RETURN_STATUS(s);
5601 if (BC_PROG_NUM(r, num)) {
5602 s = zxc_num_print(num, !pop);
5604 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5609 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5610 str = *xc_program_str(idx);
5612 if (inst == XC_INST_PRINT_STR) {
5614 G.prog.nchars += printf("%s", str);
5615 nl = strrchr(str, '\n');
5617 G.prog.nchars = strlen(nl + 1);
5619 xc_program_printString(str);
5620 if (inst == XC_INST_PRINT)
5625 if (!s && pop) bc_vec_pop(&G.prog.results);
5629 #define zxc_program_print(...) (zxc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5631 static BC_STATUS zxc_program_negate(void)
5637 s = zxc_program_prep(&ptr, &num);
5638 if (s) RETURN_STATUS(s);
5640 bc_num_init(&res.d.n, num->len);
5641 bc_num_copy(&res.d.n, num);
5642 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5644 xc_program_retire(&res, XC_RESULT_TEMP);
5648 #define zxc_program_negate(...) (zxc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5650 static BC_STATUS zxc_program_logical(char inst)
5653 BcResult *opd1, *opd2, res;
5657 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5658 if (s) RETURN_STATUS(s);
5660 bc_num_init_DEF_SIZE(&res.d.n);
5662 if (inst == XC_INST_BOOL_AND)
5663 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5664 else if (inst == XC_INST_BOOL_OR)
5665 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5667 cond = bc_num_cmp(n1, n2);
5669 case XC_INST_REL_EQ:
5672 case XC_INST_REL_LE:
5675 case XC_INST_REL_GE:
5678 case XC_INST_REL_LT:
5681 case XC_INST_REL_GT:
5684 default: // = case XC_INST_REL_NE:
5685 //cond = (cond != 0); - not needed
5690 if (cond) bc_num_one(&res.d.n);
5691 //else bc_num_zero(&res.d.n); - already is
5693 xc_program_binOpRetire(&res);
5697 #define zxc_program_logical(...) (zxc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5700 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5705 memset(&n2, 0, sizeof(BcNum));
5706 n2.rdx = res.d.id.idx = r->d.id.idx;
5707 res.t = XC_RESULT_STR;
5710 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5711 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5713 bc_vec_pop(&G.prog.results);
5716 bc_result_pop_and_push(&res);
5717 bc_vec_push(v, &n2);
5719 RETURN_STATUS(BC_STATUS_SUCCESS);
5721 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5724 static BC_STATUS zxc_program_copyToVar(char *name, bool var)
5731 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5732 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5734 ptr = bc_vec_top(&G.prog.results);
5735 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5736 RETURN_STATUS(bc_error_variable_is_wrong_type());
5737 v = xc_program_search(name, var);
5740 if (ptr->t == XC_RESULT_STR && !var)
5741 RETURN_STATUS(bc_error_variable_is_wrong_type());
5742 if (ptr->t == XC_RESULT_STR)
5743 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5746 s = zxc_program_num(ptr, &n);
5747 if (s) RETURN_STATUS(s);
5749 // Do this once more to make sure that pointers were not invalidated.
5750 v = xc_program_search(name, var);
5753 bc_num_init_DEF_SIZE(&r.d.n);
5754 bc_num_copy(&r.d.n, n);
5756 bc_array_init(&r.d.v, true);
5757 bc_array_copy(&r.d.v, (BcVec *) n);
5760 bc_vec_push(v, &r.d);
5761 bc_vec_pop(&G.prog.results);
5765 #define zxc_program_copyToVar(...) (zxc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5767 static BC_STATUS zxc_program_assign(char inst)
5770 BcResult *left, *right, res;
5772 bool assign = (inst == XC_INST_ASSIGN);
5775 s = zxc_program_binOpPrep(&left, &l, &right, &r, assign);
5776 if (s) RETURN_STATUS(s);
5778 ib = left->t == XC_RESULT_IBASE;
5779 sc = left->t == XC_RESULT_SCALE;
5782 if (right->t == XC_RESULT_STR) {
5785 if (left->t != XC_RESULT_VAR)
5786 RETURN_STATUS(bc_error_variable_is_wrong_type());
5787 v = xc_program_search(left->d.id.name, true);
5789 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5793 if (left->t == XC_RESULT_CONSTANT || left->t == XC_RESULT_TEMP)
5794 RETURN_STATUS(bc_error_bad_assignment());
5797 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5798 RETURN_STATUS(bc_error("divide by zero"));
5803 s = BC_STATUS_SUCCESS;
5804 IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5806 if (s) RETURN_STATUS(s);
5811 if (ib || sc || left->t == XC_RESULT_OBASE) {
5812 static const char *const msg[] = {
5813 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5814 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5815 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5821 s = zbc_num_ulong(l, &val);
5822 if (s) RETURN_STATUS(s);
5823 s = left->t - XC_RESULT_IBASE;
5826 ptr = &G.prog.scale;
5829 RETURN_STATUS(bc_error(msg[s]));
5830 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5831 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5835 RETURN_STATUS(bc_error(msg[s]));
5837 *ptr = (size_t) val;
5838 s = BC_STATUS_SUCCESS;
5841 bc_num_init(&res.d.n, l->len);
5842 bc_num_copy(&res.d.n, l);
5843 xc_program_binOpRetire(&res);
5847 #define zxc_program_assign(...) (zxc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5850 #define xc_program_pushVar(code, bgn, pop, copy) \
5851 xc_program_pushVar(code, bgn)
5852 // for bc, 'pop' and 'copy' are always false
5854 static BC_STATUS xc_program_pushVar(char *code, size_t *bgn,
5855 bool pop, bool copy)
5858 char *name = xc_program_name(code, bgn);
5860 r.t = XC_RESULT_VAR;
5865 BcVec *v = xc_program_search(name, true);
5866 BcNum *num = bc_vec_top(v);
5869 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5870 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5873 if (!BC_PROG_STR(num)) {
5874 r.t = XC_RESULT_TEMP;
5875 bc_num_init_DEF_SIZE(&r.d.n);
5876 bc_num_copy(&r.d.n, num);
5878 r.t = XC_RESULT_STR;
5879 r.d.id.idx = num->rdx;
5882 if (!copy) bc_vec_pop(v);
5886 bc_vec_push(&G.prog.results, &r);
5888 RETURN_STATUS(BC_STATUS_SUCCESS);
5890 #define zxc_program_pushVar(...) (xc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5892 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5894 BcStatus s = BC_STATUS_SUCCESS;
5898 r.d.id.name = xc_program_name(code, bgn);
5900 if (inst == XC_INST_ARRAY) {
5901 r.t = XC_RESULT_ARRAY;
5902 bc_vec_push(&G.prog.results, &r);
5907 s = zxc_program_prep(&operand, &num);
5909 s = zbc_num_ulong(num, &temp);
5912 if (temp > BC_MAX_DIM) {
5913 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5917 r.d.id.idx = (size_t) temp;
5918 xc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5921 if (s) free(r.d.id.name);
5924 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5927 static BC_STATUS zbc_program_incdec(char inst)
5930 BcResult *ptr, res, copy;
5934 s = zxc_program_prep(&ptr, &num);
5935 if (s) RETURN_STATUS(s);
5937 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5938 copy.t = XC_RESULT_TEMP;
5939 bc_num_init(©.d.n, num->len);
5940 bc_num_copy(©.d.n, num);
5943 res.t = BC_RESULT_ONE;
5944 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
5945 ? BC_INST_ASSIGN_PLUS
5946 : BC_INST_ASSIGN_MINUS;
5948 bc_vec_push(&G.prog.results, &res);
5949 s = zxc_program_assign(inst);
5950 if (s) RETURN_STATUS(s);
5952 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5953 bc_result_pop_and_push(©);
5958 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5960 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5968 nparams = xc_program_index(code, idx);
5970 ip.func = xc_program_index(code, idx);
5971 func = xc_program_func(ip.func);
5973 if (func->code.len == 0) {
5974 RETURN_STATUS(bc_error("undefined function"));
5976 if (nparams != func->nparams) {
5977 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5979 ip.results_len_before_call = G.prog.results.len - nparams;
5981 for (i = 0; i < nparams; ++i) {
5984 a = bc_vec_item(&func->autos, nparams - 1 - i);
5985 arg = bc_vec_top(&G.prog.results);
5987 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) || arg->t == XC_RESULT_STR)
5988 RETURN_STATUS(bc_error_variable_is_wrong_type());
5990 s = zxc_program_copyToVar(a->name, a->idx);
5991 if (s) RETURN_STATUS(s);
5994 a = bc_vec_item(&func->autos, i);
5995 for (; i < func->autos.len; i++, a++) {
5998 v = xc_program_search(a->name, a->idx);
6001 bc_num_init_DEF_SIZE(&n2);
6002 bc_vec_push(v, &n2);
6005 bc_array_init(&v2, true);
6006 bc_vec_push(v, &v2);
6010 bc_vec_push(&G.prog.exestack, &ip);
6012 RETURN_STATUS(BC_STATUS_SUCCESS);
6014 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
6016 static BC_STATUS zbc_program_return(char inst)
6022 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6024 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == XC_INST_RET)))
6025 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6027 f = xc_program_func(ip->func);
6028 res.t = XC_RESULT_TEMP;
6030 if (inst == XC_INST_RET) {
6033 BcResult *operand = bc_vec_top(&G.prog.results);
6035 s = zxc_program_num(operand, &num);
6036 if (s) RETURN_STATUS(s);
6037 bc_num_init(&res.d.n, num->len);
6038 bc_num_copy(&res.d.n, num);
6040 bc_num_init_DEF_SIZE(&res.d.n);
6041 //bc_num_zero(&res.d.n); - already is
6044 // We need to pop arguments as well, so this takes that into account.
6045 a = (void*)f->autos.v;
6046 for (i = 0; i < f->autos.len; i++, a++) {
6048 v = xc_program_search(a->name, a->idx);
6052 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
6053 bc_vec_push(&G.prog.results, &res);
6054 bc_vec_pop(&G.prog.exestack);
6056 RETURN_STATUS(BC_STATUS_SUCCESS);
6058 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6061 static unsigned long xc_program_scale(BcNum *n)
6063 return (unsigned long) n->rdx;
6066 static unsigned long xc_program_len(BcNum *n)
6068 size_t len = n->len;
6070 if (n->rdx != len) return len;
6072 if (len == 0) break;
6074 if (n->num[len] != 0) break;
6079 static BC_STATUS zxc_program_builtin(char inst)
6085 bool len = (inst == XC_INST_LENGTH);
6087 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6088 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6089 opnd = bc_vec_top(&G.prog.results);
6091 s = zxc_program_num(opnd, &num);
6092 if (s) RETURN_STATUS(s);
6095 if (!BC_PROG_NUM(opnd, num) && !len)
6096 RETURN_STATUS(bc_error_variable_is_wrong_type());
6099 bc_num_init_DEF_SIZE(&res.d.n);
6101 if (inst == XC_INST_SQRT)
6102 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6104 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6105 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6109 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6111 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6113 str = xc_program_str(idx);
6114 bc_num_ulong2num(&res.d.n, strlen(*str));
6118 bc_num_ulong2num(&res.d.n, len ? xc_program_len(num) : xc_program_scale(num));
6121 xc_program_retire(&res, XC_RESULT_TEMP);
6125 #define zxc_program_builtin(...) (zxc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6128 static BC_STATUS zdc_program_divmod(void)
6131 BcResult *opd1, *opd2, res, res2;
6134 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6135 if (s) RETURN_STATUS(s);
6137 bc_num_init_DEF_SIZE(&res.d.n);
6138 bc_num_init(&res2.d.n, n2->len);
6140 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6143 xc_program_binOpRetire(&res2);
6144 res.t = XC_RESULT_TEMP;
6145 bc_vec_push(&G.prog.results, &res);
6149 bc_num_free(&res2.d.n);
6150 bc_num_free(&res.d.n);
6153 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6155 static BC_STATUS zdc_program_modexp(void)
6158 BcResult *r1, *r2, *r3, res;
6159 BcNum *n1, *n2, *n3;
6161 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6162 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6163 s = zxc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6164 if (s) RETURN_STATUS(s);
6166 r1 = bc_vec_item_rev(&G.prog.results, 2);
6167 s = zxc_program_num(r1, &n1);
6168 if (s) RETURN_STATUS(s);
6169 if (!BC_PROG_NUM(r1, n1))
6170 RETURN_STATUS(bc_error_variable_is_wrong_type());
6172 // Make sure that the values have their pointers updated, if necessary.
6173 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6174 if (r1->t == r2->t) {
6175 s = zxc_program_num(r2, &n2);
6176 if (s) RETURN_STATUS(s);
6178 if (r1->t == r3->t) {
6179 s = zxc_program_num(r3, &n3);
6180 if (s) RETURN_STATUS(s);
6184 bc_num_init(&res.d.n, n3->len);
6185 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6188 bc_vec_pop(&G.prog.results);
6189 xc_program_binOpRetire(&res);
6193 bc_num_free(&res.d.n);
6196 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6198 static void dc_program_stackLen(void)
6201 size_t len = G.prog.results.len;
6203 res.t = XC_RESULT_TEMP;
6205 bc_num_init_DEF_SIZE(&res.d.n);
6206 bc_num_ulong2num(&res.d.n, len);
6207 bc_vec_push(&G.prog.results, &res);
6210 static BC_STATUS zdc_program_asciify(void)
6220 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6221 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6223 r = bc_vec_top(&G.prog.results);
6224 s = zxc_program_num(r, &num);
6225 if (s) RETURN_STATUS(s);
6227 if (BC_PROG_NUM(r, num)) {
6230 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6232 bc_num_init_DEF_SIZE(&n);
6233 bc_num_copy(&n, num);
6234 bc_num_truncate(&n, n.rdx);
6236 strmb.cap = ARRAY_SIZE(strmb_digs);
6237 strmb.num = strmb_digs;
6238 bc_num_ulong2num(&strmb, 0x100);
6240 s = zbc_num_mod(&n, &strmb, &n, 0);
6241 if (s) goto num_err;
6242 s = zbc_num_ulong(&n, &val);
6243 if (s) goto num_err;
6250 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6251 sp = *xc_program_str(idx);
6255 strs = (void*)G.prog.strs.v;
6256 for (idx = 0; idx < G.prog.strs.len; idx++) {
6257 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6263 //str[1] = '\0'; - already is
6264 bc_vec_push(&G.prog.strs, &str);
6266 res.t = XC_RESULT_STR;
6268 bc_result_pop_and_push(&res);
6270 RETURN_STATUS(BC_STATUS_SUCCESS);
6275 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6277 static BC_STATUS zdc_program_printStream(void)
6284 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6285 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6286 r = bc_vec_top(&G.prog.results);
6288 s = zxc_program_num(r, &n);
6289 if (s) RETURN_STATUS(s);
6291 if (BC_PROG_NUM(r, n)) {
6292 s = zxc_num_printNum(n, 0x100, 1, dc_num_printChar);
6295 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6296 str = *xc_program_str(idx);
6302 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6304 static BC_STATUS zdc_program_nquit(void)
6311 s = zxc_program_prep(&opnd, &num);
6312 if (s) RETURN_STATUS(s);
6313 s = zbc_num_ulong(num, &val);
6314 if (s) RETURN_STATUS(s);
6316 bc_vec_pop(&G.prog.results);
6318 if (G.prog.exestack.len < val)
6319 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6320 if (G.prog.exestack.len == val) {
6321 QUIT_OR_RETURN_TO_MAIN;
6324 bc_vec_npop(&G.prog.exestack, val);
6328 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6330 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6332 BcStatus s = BC_STATUS_SUCCESS;
6338 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6339 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6341 r = bc_vec_top(&G.prog.results);
6344 BcNum *n = n; // for compiler
6347 char *then_name = xc_program_name(code, bgn);
6348 char *else_name = NULL;
6350 if (code[*bgn] == '\0')
6353 else_name = xc_program_name(code, bgn);
6355 exec = r->d.n.len != 0;
6357 if (!exec && else_name != NULL) {
6364 v = xc_program_search(name, true);
6371 if (!exec) goto exit;
6372 if (!BC_PROG_STR(n)) {
6373 s = bc_error_variable_is_wrong_type();
6379 if (r->t == XC_RESULT_STR) {
6381 } else if (r->t == XC_RESULT_VAR) {
6383 s = zxc_program_num(r, &n);
6384 if (s || !BC_PROG_STR(n)) goto exit;
6390 fidx = sidx + BC_PROG_REQ_FUNCS;
6392 f = xc_program_func(fidx);
6394 if (f->code.len == 0) {
6398 sv_parse = G.prs; // struct copy
6399 xc_parse_create(fidx);
6400 str = *xc_program_str(sidx);
6401 s = zxc_parse_text_init(str);
6404 s = zdc_parse_exprs_until_eof();
6406 xc_parse_push(DC_INST_POP_EXEC);
6407 if (G.prs.lex != XC_LEX_EOF)
6408 s = bc_error_bad_expression();
6410 G.prs = sv_parse; // struct copy
6413 bc_vec_pop_all(&f->code);
6421 bc_vec_pop(&G.prog.results);
6422 bc_vec_push(&G.prog.exestack, &ip);
6424 RETURN_STATUS(BC_STATUS_SUCCESS);
6426 bc_vec_pop(&G.prog.results);
6429 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6432 static void xc_program_pushGlobal(char inst)
6437 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6438 if (inst == XC_INST_IBASE)
6439 val = (unsigned long) G.prog.ib_t;
6440 else if (inst == XC_INST_SCALE)
6441 val = (unsigned long) G.prog.scale;
6443 val = (unsigned long) G.prog.ob_t;
6445 bc_num_init_DEF_SIZE(&res.d.n);
6446 bc_num_ulong2num(&res.d.n, val);
6447 bc_vec_push(&G.prog.results, &res);
6450 static BC_STATUS zxc_program_exec(void)
6453 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6454 BcFunc *func = xc_program_func(ip->func);
6455 char *code = func->code.v;
6457 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6458 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6459 while (ip->inst_idx < func->code.len) {
6460 BcStatus s = BC_STATUS_SUCCESS;
6461 char inst = code[ip->inst_idx++];
6463 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6466 case BC_INST_JUMP_ZERO: {
6469 dbg_exec("BC_INST_JUMP_ZERO:");
6470 s = zxc_program_prep(&ptr, &num);
6471 if (s) RETURN_STATUS(s);
6472 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6473 bc_vec_pop(&G.prog.results);
6475 xc_program_index(code, &ip->inst_idx);
6478 // else: fall through
6480 case BC_INST_JUMP: {
6481 size_t idx = xc_program_index(code, &ip->inst_idx);
6482 size_t *addr = bc_vec_item(&func->labels, idx);
6483 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6484 ip->inst_idx = *addr;
6488 dbg_exec("BC_INST_CALL:");
6489 s = zbc_program_call(code, &ip->inst_idx);
6490 goto read_updated_ip;
6491 case BC_INST_INC_PRE:
6492 case BC_INST_DEC_PRE:
6493 case BC_INST_INC_POST:
6494 case BC_INST_DEC_POST:
6495 dbg_exec("BC_INST_INCDEC:");
6496 s = zbc_program_incdec(inst);
6499 dbg_exec("BC_INST_HALT:");
6500 QUIT_OR_RETURN_TO_MAIN;
6504 dbg_exec("BC_INST_RET[0]:");
6505 s = zbc_program_return(inst);
6506 goto read_updated_ip;
6507 case XC_INST_BOOL_OR:
6508 case XC_INST_BOOL_AND:
6510 case XC_INST_REL_EQ:
6511 case XC_INST_REL_LE:
6512 case XC_INST_REL_GE:
6513 case XC_INST_REL_NE:
6514 case XC_INST_REL_LT:
6515 case XC_INST_REL_GT:
6516 dbg_exec("BC_INST_BOOL:");
6517 s = zxc_program_logical(inst);
6520 dbg_exec("XC_INST_READ:");
6521 s = zxc_program_read();
6522 goto read_updated_ip;
6524 dbg_exec("XC_INST_VAR:");
6525 s = zxc_program_pushVar(code, &ip->inst_idx, false, false);
6527 case XC_INST_ARRAY_ELEM:
6529 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6530 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6534 dbg_exec("BC_INST_LAST:");
6535 r.t = BC_RESULT_LAST;
6536 bc_vec_push(&G.prog.results, &r);
6542 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6543 xc_program_pushGlobal(inst);
6545 case XC_INST_SCALE_FUNC:
6546 case XC_INST_LENGTH:
6548 dbg_exec("BC_INST_builtin:");
6549 s = zxc_program_builtin(inst);
6552 dbg_exec("XC_INST_NUM:");
6553 r.t = XC_RESULT_CONSTANT;
6554 r.d.id.idx = xc_program_index(code, &ip->inst_idx);
6555 bc_vec_push(&G.prog.results, &r);
6558 dbg_exec("XC_INST_POP:");
6559 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6560 s = bc_error_stack_has_too_few_elements();
6562 bc_vec_pop(&G.prog.results);
6565 case XC_INST_PRINT_POP:
6566 case XC_INST_PRINT_STR:
6567 dbg_exec("XC_INST_PRINTxyz:");
6568 s = zxc_program_print(inst, 0);
6571 dbg_exec("XC_INST_STR:");
6572 r.t = XC_RESULT_STR;
6573 r.d.id.idx = xc_program_index(code, &ip->inst_idx);
6574 bc_vec_push(&G.prog.results, &r);
6577 case XC_INST_MULTIPLY:
6578 case XC_INST_DIVIDE:
6579 case XC_INST_MODULUS:
6582 dbg_exec("BC_INST_binaryop:");
6583 s = zxc_program_op(inst);
6585 case XC_INST_BOOL_NOT: {
6587 dbg_exec("XC_INST_BOOL_NOT:");
6588 s = zxc_program_prep(&ptr, &num);
6589 if (s) RETURN_STATUS(s);
6590 bc_num_init_DEF_SIZE(&r.d.n);
6591 if (bc_num_cmp(num, &G.prog.zero) == 0)
6593 //else bc_num_zero(&r.d.n); - already is
6594 xc_program_retire(&r, XC_RESULT_TEMP);
6598 dbg_exec("XC_INST_NEG:");
6599 s = zxc_program_negate();
6602 case BC_INST_ASSIGN_POWER:
6603 case BC_INST_ASSIGN_MULTIPLY:
6604 case BC_INST_ASSIGN_DIVIDE:
6605 case BC_INST_ASSIGN_MODULUS:
6606 case BC_INST_ASSIGN_PLUS:
6607 case BC_INST_ASSIGN_MINUS:
6609 case XC_INST_ASSIGN:
6610 dbg_exec("BC_INST_ASSIGNxyz:");
6611 s = zxc_program_assign(inst);
6614 case DC_INST_POP_EXEC:
6615 dbg_exec("DC_INST_POP_EXEC:");
6616 bc_vec_pop(&G.prog.exestack);
6617 goto read_updated_ip;
6618 case DC_INST_MODEXP:
6619 dbg_exec("DC_INST_MODEXP:");
6620 s = zdc_program_modexp();
6622 case DC_INST_DIVMOD:
6623 dbg_exec("DC_INST_DIVMOD:");
6624 s = zdc_program_divmod();
6626 case DC_INST_EXECUTE:
6627 case DC_INST_EXEC_COND:
6628 dbg_exec("DC_INST_EXEC[_COND]:");
6629 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6630 goto read_updated_ip;
6631 case DC_INST_PRINT_STACK: {
6633 dbg_exec("DC_INST_PRINT_STACK:");
6634 for (idx = 0; idx < G.prog.results.len; ++idx) {
6635 s = zxc_program_print(XC_INST_PRINT, idx);
6640 case DC_INST_CLEAR_STACK:
6641 dbg_exec("DC_INST_CLEAR_STACK:");
6642 bc_vec_pop_all(&G.prog.results);
6644 case DC_INST_STACK_LEN:
6645 dbg_exec("DC_INST_STACK_LEN:");
6646 dc_program_stackLen();
6648 case DC_INST_DUPLICATE:
6649 dbg_exec("DC_INST_DUPLICATE:");
6650 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6651 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6652 ptr = bc_vec_top(&G.prog.results);
6653 dc_result_copy(&r, ptr);
6654 bc_vec_push(&G.prog.results, &r);
6656 case DC_INST_SWAP: {
6658 dbg_exec("DC_INST_SWAP:");
6659 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6660 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6661 ptr = bc_vec_item_rev(&G.prog.results, 0);
6662 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6663 memcpy(&r, ptr, sizeof(BcResult));
6664 memcpy(ptr, ptr2, sizeof(BcResult));
6665 memcpy(ptr2, &r, sizeof(BcResult));
6668 case DC_INST_ASCIIFY:
6669 dbg_exec("DC_INST_ASCIIFY:");
6670 s = zdc_program_asciify();
6672 case DC_INST_PRINT_STREAM:
6673 dbg_exec("DC_INST_PRINT_STREAM:");
6674 s = zdc_program_printStream();
6677 case DC_INST_PUSH_VAR: {
6678 bool copy = inst == DC_INST_LOAD;
6679 s = zxc_program_pushVar(code, &ip->inst_idx, true, copy);
6682 case DC_INST_PUSH_TO_VAR: {
6683 char *name = xc_program_name(code, &ip->inst_idx);
6684 s = zxc_program_copyToVar(name, true);
6689 dbg_exec("DC_INST_QUIT:");
6690 if (G.prog.exestack.len <= 2)
6691 QUIT_OR_RETURN_TO_MAIN;
6692 bc_vec_npop(&G.prog.exestack, 2);
6693 goto read_updated_ip;
6695 dbg_exec("DC_INST_NQUIT:");
6696 s = zdc_program_nquit();
6697 //goto read_updated_ip; - just fall through to it
6700 // Instruction stack has changed, read new pointers
6701 ip = bc_vec_top(&G.prog.exestack);
6702 func = xc_program_func(ip->func);
6703 code = func->code.v;
6704 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6707 if (s || G_interrupt) {
6715 RETURN_STATUS(BC_STATUS_SUCCESS);
6717 #define zxc_program_exec(...) (zxc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6719 static unsigned xc_vm_envLen(const char *var)
6725 len = BC_NUM_PRINT_WIDTH;
6726 if (!lenv) return len;
6728 len = bb_strtou(lenv, NULL, 10) - 1;
6729 if (errno || len < 2 || len >= INT_MAX)
6730 len = BC_NUM_PRINT_WIDTH;
6735 static BC_STATUS zxc_vm_process(const char *text)
6739 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6740 s = zxc_parse_text_init(text); // does the first zxc_lex_next()
6741 if (s) RETURN_STATUS(s);
6744 while (G.prs.lex != XC_LEX_EOF) {
6748 dbg_lex("%s:%d G.prs.lex:%d, parsing...", __func__, __LINE__, G.prs.lex);
6751 if (G.prs.lex == BC_LEX_SCOLON
6752 || G.prs.lex == XC_LEX_NLINE
6759 s = zbc_parse_stmt_or_funcdef();
6762 // Check that next token is a correct stmt delimiter -
6763 // disallows "print 1 print 2" and such.
6764 if (G.prs.lex != BC_LEX_SCOLON
6765 && G.prs.lex != XC_LEX_NLINE
6766 && G.prs.lex != XC_LEX_EOF
6768 bc_error_at("bad statement terminator");
6771 // The above logic is fragile. Check these examples:
6772 // - interactive read() still works
6776 // Most of dc parsing assumes all whitespace,
6777 // including '\n', is eaten.
6778 while (G.prs.lex == XC_LEX_NLINE) {
6781 if (G.prs.lex == XC_LEX_EOF)
6784 s = zdc_parse_expr();
6787 if (s || G_interrupt) {
6789 xc_parse_reset(); // includes xc_program_reset()
6790 RETURN_STATUS(BC_STATUS_FAILURE);
6793 dbg_lex("%s:%d executing...", __func__, __LINE__);
6794 s = zxc_program_exec();
6800 ip = (void*)G.prog.exestack.v;
6802 if (G.prog.exestack.len != 1) // should have only main's IP
6803 bb_error_msg_and_die("BUG:call stack");
6804 if (ip->func != BC_PROG_MAIN)
6805 bb_error_msg_and_die("BUG:not MAIN");
6807 f = xc_program_func_BC_PROG_MAIN();
6808 // bc discards strings, constants and code after each
6809 // top-level statement in the "main program".
6810 // This prevents "yes 1 | bc" from growing its memory
6811 // without bound. This can be done because data stack
6812 // is empty and thus can't hold any references to
6813 // strings or constants, there is no generated code
6814 // which can hold references (after we discard one
6815 // we just executed). Code of functions can have references,
6816 // but bc stores function strings/constants in per-function
6820 if (G.prog.results.len != 0) // should be empty
6821 bb_error_msg_and_die("BUG:data stack");
6823 IF_BC(bc_vec_pop_all(&f->strs);)
6824 IF_BC(bc_vec_pop_all(&f->consts);)
6826 if (G.prog.results.len == 0
6827 && G.prog.vars.len == 0
6829 // If stack is empty and no registers exist (TODO: or they are all empty),
6830 // we can get rid of accumulated strings and constants.
6831 // In this example dc process should not grow
6832 // its memory consumption with time:
6834 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6835 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6837 // The code is discarded always (below), thus this example
6838 // should also not grow its memory consumption with time,
6839 // even though its data stack is not empty:
6840 // { echo 1; yes dk; } | dc
6842 // We drop generated and executed code for both bc and dc:
6843 bc_vec_pop_all(&f->code);
6847 dbg_lex_done("%s:%d done", __func__, __LINE__);
6850 #define zxc_vm_process(...) (zxc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6852 static BC_STATUS zxc_vm_execute_FILE(FILE *fp, const char *filename)
6854 // So far bc/dc have no way to include a file from another file,
6855 // therefore we know G.prs.lex_filename == NULL on entry
6856 //const char *sv_file;
6859 G.prs.lex_filename = filename;
6860 G.prs.lex_input_fp = fp;
6861 G.err_line = G.prs.lex_line = 1;
6862 dbg_lex("p->lex_line reset to 1");
6865 s = zxc_vm_process("");
6866 // We do not stop looping on errors here if reading stdin.
6867 // Example: start interactive bc and enter "return".
6868 // It should say "'return' not in a function"
6869 // but should not exit.
6870 } while (G.prs.lex_input_fp == stdin);
6871 G.prs.lex_filename = NULL;
6874 #define zxc_vm_execute_FILE(...) (zxc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6876 static BC_STATUS zxc_vm_file(const char *file)
6881 fp = xfopen_for_read(file);
6882 s = zxc_vm_execute_FILE(fp, file);
6887 #define zxc_vm_file(...) (zxc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6890 static void bc_vm_info(void)
6892 printf("%s "BB_VER"\n"
6893 "Adapted from https://github.com/gavinhoward/bc\n"
6894 "Original code (c) 2018 Gavin D. Howard and contributors\n"
6898 static void bc_args(char **argv)
6904 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6905 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6906 "warn\0" No_argument "w"
6907 "version\0" No_argument "v"
6908 "standard\0" No_argument "s"
6909 "quiet\0" No_argument "q"
6910 "mathlib\0" No_argument "l"
6911 "interactive\0" No_argument "i"
6914 opts = option_mask32 |= getopt32(argv, "wvsqli");
6916 if (getenv("POSIXLY_CORRECT"))
6917 option_mask32 |= BC_FLAG_S;
6919 if (opts & BC_FLAG_V) {
6924 for (i = optind; argv[i]; ++i)
6925 bc_vec_push(&G.files, argv + i);
6928 static void bc_vm_envArgs(void)
6932 char *env_args = getenv("BC_ENV_ARGS");
6934 if (!env_args) return;
6936 G.env_args = xstrdup(env_args);
6939 bc_vec_init(&v, sizeof(char *), NULL);
6941 while (*(buf = skip_whitespace(buf)) != '\0') {
6942 bc_vec_push(&v, &buf);
6943 buf = skip_non_whitespace(buf);
6949 // NULL terminate, and pass argv[] so that first arg is argv[1]
6950 if (sizeof(int) == sizeof(char*)) {
6951 bc_vec_push(&v, &const_int_0);
6953 static char *const nullptr = NULL;
6954 bc_vec_push(&v, &nullptr);
6956 bc_args(((char **)v.v) - 1);
6961 static const char bc_lib[] ALIGN1 = {
6964 "\n" "auto b,s,n,r,d,i,p,f,v"
6965 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6966 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6967 //e(-.998896): GNU:.36828580434569428695
6968 // above code:.36828580434569428696
6969 // actual value:.3682858043456942869594...
6970 // but for now let's be "GNU compatible"
6979 "\n" "scale=scale(x)+1"
6989 "\n" "for(i=2;v;++i){"
6995 "\n" "while(d--)r*=r"
6998 "\n" "if(n)return(1/r)"
7002 "\n" "auto b,s,r,p,a,q,i,v"
7006 "\n" "r=(1-10^scale)/1"
7017 "\n" "while(x<=.5){"
7021 "\n" "r=a=(x-1)/(x+1)"
7024 "\n" "for(i=3;v;i+=2){"
7035 "\n" "auto b,s,r,a,q,i"
7036 "\n" "if(x<0)return(-s(-x))"
7040 "\n" "scale=1.1*s+2"
7049 "\n" "for(i=3;a;i+=2){"
7050 "\n" "a*=q/(i*(i-1))"
7063 "\n" "x=s(2*a(1)+x)"
7069 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7077 "\n" "if(scale<65){"
7078 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7079 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7089 "\n" "x=(x-.2)/(1+.2*x)"
7094 "\n" "for(i=3;t;i+=2){"
7101 "\n" "return((m*a+r)/n)"
7103 "\n" "define j(n,x){"
7104 "\n" "auto b,s,o,a,i,v,f"
7115 "\n" "for(i=2;i<=n;++i)a*=i"
7117 "\n" "a=(x^n)/2^n/a"
7120 "\n" "scale+=length(a)-scale(a)"
7121 "\n" "for(i=1;v;++i){"
7122 "\n" "v=v*f/i/(n+i)"
7128 "\n" "return(a*r/1)"
7133 static BC_STATUS zxc_vm_exec(void)
7140 if (option_mask32 & BC_FLAG_L) {
7141 // We know that internal library is not buggy,
7142 // thus error checking is normally disabled.
7143 # define DEBUG_LIB 0
7144 s = zxc_vm_process(bc_lib);
7145 if (DEBUG_LIB && s) RETURN_STATUS(s);
7149 s = BC_STATUS_SUCCESS;
7150 fname = (void*)G.files.v;
7151 for (i = 0; i < G.files.len; i++) {
7152 s = zxc_vm_file(*fname++);
7153 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7154 // Debug config, non-interactive mode:
7155 // return all the way back to main.
7156 // Non-debug builds do not come here
7157 // in non-interactive mode, they exit.
7162 if (IS_BC || (option_mask32 & BC_FLAG_I))
7163 s = zxc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7167 #define zxc_vm_exec(...) (zxc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7169 #if ENABLE_FEATURE_CLEAN_UP
7170 static void xc_program_free(void)
7172 bc_vec_free(&G.prog.fns);
7173 IF_BC(bc_vec_free(&G.prog.fn_map);)
7174 bc_vec_free(&G.prog.vars);
7175 bc_vec_free(&G.prog.var_map);
7176 bc_vec_free(&G.prog.arrs);
7177 bc_vec_free(&G.prog.arr_map);
7178 IF_DC(bc_vec_free(&G.prog.strs);)
7179 IF_DC(bc_vec_free(&G.prog.consts);)
7180 bc_vec_free(&G.prog.results);
7181 bc_vec_free(&G.prog.exestack);
7182 IF_BC(bc_num_free(&G.prog.last);)
7183 //IF_BC(bc_num_free(&G.prog.zero);)
7184 IF_BC(bc_num_free(&G.prog.one);)
7185 bc_vec_free(&G.input_buffer);
7189 static void xc_program_init(void)
7193 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7194 memset(&ip, 0, sizeof(BcInstPtr));
7196 // G.prog.nchars = G.prog.scale = 0; - already is
7200 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7201 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7203 //bc_num_init_DEF_SIZE(&G.prog.zero); - not needed
7204 //bc_num_zero(&G.prog.zero); - already is
7206 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7207 IF_BC(bc_num_one(&G.prog.one);)
7209 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7210 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7213 // Names are chosen simply to be distinct and never match
7214 // a valid function name (and be short)
7215 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7216 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7218 // in dc, functions have no names
7219 xc_program_add_fn();
7220 xc_program_add_fn();
7223 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7224 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7226 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7227 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7229 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7230 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7231 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7232 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7233 bc_vec_push(&G.prog.exestack, &ip);
7235 bc_char_vec_init(&G.input_buffer);
7238 static int xc_vm_init(const char *env_len)
7240 G.prog.len = xc_vm_envLen(env_len);
7241 #if ENABLE_FEATURE_EDITING
7242 G.line_input_state = new_line_input_t(DO_HISTORY);
7244 bc_vec_init(&G.files, sizeof(char *), NULL);
7247 IF_BC(if (IS_BC) bc_vm_envArgs();)
7248 xc_parse_create(BC_PROG_MAIN);
7250 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7251 //-i option unconditionally enables this regardless of isatty():
7253 #if ENABLE_FEATURE_BC_INTERACTIVE
7255 // With SA_RESTART, most system calls will restart
7256 // (IOW: they won't fail with EINTR).
7257 // In particular, this means ^C won't cause
7258 // stdout to get into "error state" if SIGINT hits
7259 // within write() syscall.
7261 // The downside is that ^C while tty input is taken
7262 // will only be handled after [Enter] since read()
7263 // from stdin is not interrupted by ^C either,
7264 // it restarts, thus fgetc() does not return on ^C.
7265 // (This problem manifests only if line editing is disabled)
7266 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7268 // Without SA_RESTART, this exhibits a bug:
7269 // "while (1) print 1" and try ^C-ing it.
7270 // Intermittently, instead of returning to input line,
7271 // you'll get "output error: Interrupted system call"
7273 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7277 return 0; // "not a tty"
7280 static BcStatus xc_vm_run(void)
7282 BcStatus st = zxc_vm_exec();
7283 #if ENABLE_FEATURE_CLEAN_UP
7284 if (G_exiting) // it was actually "halt" or "quit"
7287 bc_vec_free(&G.files);
7291 # if ENABLE_FEATURE_EDITING
7292 free_line_input_t(G.line_input_state);
7296 dbg_exec("exiting with exitcode %d", st);
7301 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7302 int bc_main(int argc UNUSED_PARAM, char **argv)
7308 is_tty = xc_vm_init("BC_LINE_LENGTH");
7312 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7320 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7321 int dc_main(int argc UNUSED_PARAM, char **argv)
7327 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7328 // 1 char wider than bc from the same package.
7329 // Both default width, and xC_LINE_LENGTH=N are wider:
7330 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7333 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7336 // Do the same, or it's a bug?
7337 xc_vm_init("DC_LINE_LENGTH");
7339 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7340 noscript = BC_FLAG_I;
7342 int n = getopt(argc, argv, "e:f:x");
7348 n = zxc_vm_process(optarg);
7353 n = zxc_vm_file(optarg);
7357 option_mask32 |= DC_FLAG_X;
7367 bc_vec_push(&G.files, argv++);
7370 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin