1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Adapted from https://github.com/gavinhoward/bc
5 * Original code copyright (c) 2018 Gavin D. Howard and contributors.
8 //config: bool "bc (45 kb)"
10 //config: select FEATURE_DC_BIG
12 //config: bc is a command-line, arbitrary-precision calculator with a
13 //config: Turing-complete language. See the GNU bc manual
14 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
15 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
17 //config: This bc has five differences to the GNU bc:
18 //config: 1) The period (.) is a shortcut for "last", as in the BSD bc.
19 //config: 2) Arrays are copied before being passed as arguments to
20 //config: functions. This behavior is required by the bc spec.
21 //config: 3) Arrays can be passed to the builtin "length" function to get
22 //config: the number of elements in the array. This prints "1":
23 //config: a[0] = 0; length(a[])
24 //config: 4) The precedence of the boolean "not" operator (!) is equal to
25 //config: that of the unary minus (-) negation operator. This still
26 //config: allows POSIX-compliant scripts to work while somewhat
27 //config: preserving expected behavior (versus C) and making parsing
29 //config: 5) "read()" accepts expressions, not only numeric literals.
32 //config: bool "dc (36 kb)"
35 //config: dc is a reverse-polish notation command-line calculator which
36 //config: supports unlimited precision arithmetic. See the FreeBSD man page
37 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
38 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
40 //config: This dc has a few differences from the two above:
41 //config: 1) When printing a byte stream (command "P"), this dc follows what
42 //config: the FreeBSD dc does.
43 //config: 2) Implements the GNU extensions for divmod ("~") and
44 //config: modular exponentiation ("|").
45 //config: 3) Implements all FreeBSD extensions, except for "J" and "M".
46 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
47 //config: However, they are implemented differently. When it encounters
48 //config: whitespace where a register should be, it skips the whitespace.
49 //config: If the character following is not a lowercase letter, an error
50 //config: is issued. Otherwise, the register name is parsed by the
51 //config: following regex: [a-z][a-z0-9_]*
52 //config: This generally means that register names will be surrounded by
53 //config: whitespace. Examples:
54 //config: l idx s temp L index S temp2 < do_thing
55 //config: Also note that, like the FreeBSD dc, extended registers are not
56 //config: allowed unless the "-x" option is given.
58 //config:if BC || DC # for menuconfig indenting
60 //config:config FEATURE_DC_BIG
61 //config: bool "Use bc code base for dc (larger, more features)"
64 //config:config FEATURE_DC_LIBM
65 //config: bool "Enable power and exp functions (requires libm)"
67 //config: depends on DC && !BC && !FEATURE_DC_BIG
69 //config: Enable power and exp functions.
70 //config: NOTE: This will require libm to be present for linking.
72 //config:config FEATURE_BC_INTERACTIVE
73 //config: bool "Interactive mode (+4kb)"
75 //config: depends on BC || (DC && FEATURE_DC_BIG)
77 //config: Enable interactive mode: when started on a tty,
78 //config: ^C interrupts execution and returns to command line,
79 //config: errors also return to command line instead of exiting,
80 //config: line editing with history is available.
82 //config: With this option off, input can still be taken from tty,
83 //config: but all errors are fatal, ^C is fatal,
84 //config: tty is treated exactly the same as any other
85 //config: standard input (IOW: no line editing).
87 //config:config FEATURE_BC_LONG_OPTIONS
88 //config: bool "Enable bc/dc long options"
90 //config: depends on BC || (DC && FEATURE_DC_BIG)
94 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
95 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
97 //kbuild:lib-$(CONFIG_BC) += bc.o
98 //kbuild:lib-$(CONFIG_DC) += bc.o
100 //See www.gnu.org/software/bc/manual/bc.html
101 //usage:#define bc_trivial_usage
102 //usage: "[-sqlw] FILE..."
104 //usage:#define bc_full_usage "\n"
105 //usage: "\nArbitrary precision calculator"
107 ///////: "\n -i Interactive" - has no effect for now
108 //usage: "\n -q Quiet"
109 //usage: "\n -l Load standard math library"
110 //usage: "\n -s Be POSIX compatible"
111 //usage: "\n -w Warn if extensions are used"
112 ///////: "\n -v Version"
114 //usage: "\n$BC_LINE_LENGTH changes output width"
116 //usage:#define bc_example_usage
117 //usage: "3 + 4.129\n"
118 //usage: "1903 - 2893\n"
119 //usage: "-129 * 213.28935\n"
120 //usage: "12 / -1932\n"
122 //usage: "34 ^ 189\n"
123 //usage: "scale = 13\n"
124 //usage: "ibase = 2\n"
125 //usage: "obase = A\n"
127 //usage:#define dc_trivial_usage
128 //usage: IF_FEATURE_DC_BIG("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
130 //usage:#define dc_full_usage "\n"
131 //usage: "\nTiny RPN calculator. Operations:"
132 //usage: "\n+, -, *, /, %, ~, ^," IF_FEATURE_DC_BIG(" |,")
133 //usage: "\np - print top of the stack without popping"
134 //usage: "\nf - print entire stack"
135 //usage: "\nk - pop the value and set the precision"
136 //usage: "\ni - pop the value and set input radix"
137 //usage: "\no - pop the value and set output radix"
138 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
140 //usage:#define dc_example_usage
141 //usage: "$ dc -e'2 2 + p'\n"
143 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
145 //usage: "$ dc -e'0 1 & p'\n"
147 //usage: "$ dc -e'0 1 | p'\n"
149 //usage: "$ echo '72 9 / 8 * p' | dc\n"
153 #include "common_bufsiz.h"
155 #if !ENABLE_BC && !ENABLE_FEATURE_DC_BIG
159 #define DEBUG_LEXER 0
160 #define DEBUG_COMPILE 0
162 // This can be left enabled for production as well:
163 #define SANITY_CHECKS 1
166 static uint8_t lex_indent;
167 #define dbg_lex(...) \
169 fprintf(stderr, "%*s", lex_indent, ""); \
170 bb_error_msg(__VA_ARGS__); \
172 #define dbg_lex_enter(...) \
174 dbg_lex(__VA_ARGS__); \
177 #define dbg_lex_done(...) \
180 dbg_lex(__VA_ARGS__); \
183 # define dbg_lex(...) ((void)0)
184 # define dbg_lex_enter(...) ((void)0)
185 # define dbg_lex_done(...) ((void)0)
189 # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
191 # define dbg_compile(...) ((void)0)
195 # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
197 # define dbg_exec(...) ((void)0)
200 typedef enum BcStatus {
201 BC_STATUS_SUCCESS = 0,
202 BC_STATUS_FAILURE = 1,
203 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr_empty_ok() uses this
206 #define BC_VEC_INVALID_IDX ((size_t) -1)
207 #define BC_VEC_START_CAP (1 << 5)
209 typedef void (*BcVecFree)(void *) FAST_FUNC;
211 typedef struct BcVec {
219 typedef signed char BcDig;
221 typedef struct BcNum {
229 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
230 // larger value might speed up BIGNUM calculations a bit:
231 #define BC_NUM_DEF_SIZE (16)
232 #define BC_NUM_PRINT_WIDTH (69)
234 #define BC_NUM_KARATSUBA_LEN (32)
236 typedef enum BcInst {
243 XC_INST_NEG, // order
245 XC_INST_REL_EQ, // should
246 XC_INST_REL_LE, // match
247 XC_INST_REL_GE, // LEX
248 XC_INST_REL_NE, // constants
249 XC_INST_REL_LT, // for
250 XC_INST_REL_GT, // these
252 XC_INST_POWER, // operations
253 XC_INST_MULTIPLY, // |
255 XC_INST_MODULUS, // |
259 XC_INST_BOOL_NOT, // |
260 XC_INST_BOOL_OR, // |
261 XC_INST_BOOL_AND, // |
263 BC_INST_ASSIGN_POWER, // |
264 BC_INST_ASSIGN_MULTIPLY,// |
265 BC_INST_ASSIGN_DIVIDE, // |
266 BC_INST_ASSIGN_MODULUS, // |
267 BC_INST_ASSIGN_PLUS, // |
268 BC_INST_ASSIGN_MINUS, // |
278 XC_INST_IBASE, // order of these constans should match other enums
279 XC_INST_OBASE, // order of these constans should match other enums
280 XC_INST_SCALE, // order of these constans should match other enums
281 IF_BC(BC_INST_LAST,) // order of these constans should match other enums
312 DC_INST_PRINT_STREAM,
327 DC_INST_INVALID = -1,
331 typedef struct BcId {
336 typedef struct BcFunc {
342 IF_BC(size_t nparams;)
345 typedef enum BcResultType {
349 XC_RESULT_ARRAY_ELEM,
354 //code uses "inst - XC_INST_IBASE + XC_RESULT_IBASE" construct,
355 XC_RESULT_IBASE, // relative order should match for: XC_INST_IBASE
356 XC_RESULT_OBASE, // relative order should match for: XC_INST_OBASE
357 XC_RESULT_SCALE, // relative order should match for: XC_INST_SCALE
358 IF_BC(BC_RESULT_LAST,) // relative order should match for: BC_INST_LAST
360 IF_BC(BC_RESULT_ONE,)
363 typedef union BcResultData {
369 typedef struct BcResult {
374 typedef struct BcInstPtr {
377 IF_BC(size_t results_len_before_call;)
380 typedef enum BcLexType {
391 XC_LEX_NEG = XC_LEX_1st_op, // order
393 XC_LEX_OP_REL_EQ, // should
394 XC_LEX_OP_REL_LE, // match
395 XC_LEX_OP_REL_GE, // INST
396 XC_LEX_OP_REL_NE, // constants
397 XC_LEX_OP_REL_LT, // for
398 XC_LEX_OP_REL_GT, // these
400 XC_LEX_OP_POWER, // operations
401 XC_LEX_OP_MULTIPLY, // |
402 XC_LEX_OP_DIVIDE, // |
403 XC_LEX_OP_MODULUS, // |
405 XC_LEX_OP_MINUS, // |
406 XC_LEX_OP_last = XC_LEX_OP_MINUS,
408 BC_LEX_OP_BOOL_NOT, // |
409 BC_LEX_OP_BOOL_OR, // |
410 BC_LEX_OP_BOOL_AND, // |
412 BC_LEX_OP_ASSIGN_POWER, // |
413 BC_LEX_OP_ASSIGN_MULTIPLY, // |
414 BC_LEX_OP_ASSIGN_DIVIDE, // |
415 BC_LEX_OP_ASSIGN_MODULUS, // |
416 BC_LEX_OP_ASSIGN_PLUS, // |
417 BC_LEX_OP_ASSIGN_MINUS, // |
419 BC_LEX_OP_ASSIGN, // V
424 BC_LEX_LPAREN, // () are 0x28 and 0x29
425 BC_LEX_RPAREN, // must be LPAREN+1: code uses (c - '(' + BC_LEX_LPAREN)
427 BC_LEX_LBRACKET, // [] are 0x5B and 0x5D
429 BC_LEX_RBRACKET, // must be LBRACKET+2: code uses (c - '[' + BC_LEX_LBRACKET)
431 BC_LEX_LBRACE, // {} are 0x7B and 0x7D
433 BC_LEX_RBRACE, // must be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
435 BC_LEX_KEY_1st_keyword,
436 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
443 // code uses "type - BC_LEX_KEY_IBASE + XC_INST_IBASE" construct,
444 BC_LEX_KEY_IBASE, // relative order should match for: XC_INST_IBASE
445 BC_LEX_KEY_OBASE, // relative order should match for: XC_INST_OBASE
447 IF_BC(BC_LEX_KEY_LAST,) // relative order should match for: BC_INST_LAST
460 DC_LEX_OP_BOOL_NOT = XC_LEX_OP_last + 1,
492 // code uses "t - DC_LEX_STORE_IBASE + XC_INST_IBASE" construct,
493 DC_LEX_STORE_IBASE, // relative order should match for: XC_INST_IBASE
494 DC_LEX_STORE_OBASE, // relative order should match for: XC_INST_OBASE
495 DC_LEX_STORE_SCALE, // relative order should match for: XC_INST_SCALE
504 // must match order of BC_LEX_KEY_foo etc above
506 struct BcLexKeyword {
509 #define LEX_KW_ENTRY(a, b) \
510 { .name8 = a /*, .posix = b */ }
511 static const struct BcLexKeyword bc_lex_kws[20] = {
512 LEX_KW_ENTRY("auto" , 1), // 0
513 LEX_KW_ENTRY("break" , 1), // 1
514 LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
515 LEX_KW_ENTRY("define" , 1), // 3
516 LEX_KW_ENTRY("else" , 0), // 4
517 LEX_KW_ENTRY("for" , 1), // 5
518 LEX_KW_ENTRY("halt" , 0), // 6
519 LEX_KW_ENTRY("ibase" , 1), // 7
520 LEX_KW_ENTRY("obase" , 1), // 8
521 LEX_KW_ENTRY("if" , 1), // 9
522 LEX_KW_ENTRY("last" , 0), // 10
523 LEX_KW_ENTRY("length" , 1), // 11
524 LEX_KW_ENTRY("limits" , 0), // 12
525 LEX_KW_ENTRY("print" , 0), // 13
526 LEX_KW_ENTRY("quit" , 1), // 14
527 LEX_KW_ENTRY("read" , 0), // 15
528 LEX_KW_ENTRY("return" , 1), // 16
529 LEX_KW_ENTRY("scale" , 1), // 17
530 LEX_KW_ENTRY("sqrt" , 1), // 18
531 LEX_KW_ENTRY("while" , 1), // 19
534 #define STRING_else (bc_lex_kws[4].name8)
535 #define STRING_for (bc_lex_kws[5].name8)
536 #define STRING_if (bc_lex_kws[9].name8)
537 #define STRING_while (bc_lex_kws[19].name8)
561 #define keyword_is_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
563 // This is a bit array that corresponds to token types. An entry is
564 // true if the token is valid in an expression, false otherwise.
565 // Used to figure out when expr parsing should stop *without error message*
566 // - 0 element indicates this condition. 1 means "this token is to be eaten
567 // as part of the expression", it can then still be determined to be invalid
568 // by later processing.
570 #define EXBITS(a,b,c,d,e,f,g,h) \
571 ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
572 BC_PARSE_EXPRS_BITS = 0 // corresponding BC_LEX_xyz:
573 + (EXBITS(0,0,0,0,0,1,1,1) << (0*8)) // 0: EOF INVAL NL WS STR NAME NUM -
574 + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: == <= >= != < > ^ *
575 + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: / % + - ! || && ^=
576 + (EXBITS(1,1,1,1,1,1,1,1) << (3*8)) // 24: *= /= %= += -= = ++ --
577 + (EXBITS(1,1,0,0,0,0,0,0) << (4*8)) // 32: ( ) [ , ] { ; }
578 + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
579 + (EXBITS(1,0,1,1,0,0,0,1) << (6*8)) // 48: obase if last length limits print quit read
580 + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
583 static ALWAYS_INLINE long lex_allowed_in_bc_expr(unsigned i)
585 #if ULONG_MAX > 0xffffffff
586 // 64-bit version (will not work correctly for 32-bit longs!)
587 return BC_PARSE_EXPRS_BITS & (1UL << i);
590 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
592 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
595 return m & (1UL << i);
599 // This is an array of data for operators that correspond to
600 // [XC_LEX_1st_op...] token types.
601 static const uint8_t bc_parse_ops[] ALIGN1 = {
602 #define OP(p,l) ((int)(l) * 0x10 + (p))
604 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
606 OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
607 OP(4, true ), OP( 4, true ), // + -
609 OP(7, true ), OP( 7, true ), // or and
610 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
611 OP(5, false), OP( 5, false ), // -= =
612 OP(0, false), OP( 0, false ), // inc dec
615 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
616 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
620 static const //BcLexType - should be this type
622 dc_char_to_LEX[] ALIGN1 = {
624 XC_LEX_OP_MODULUS, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_LPAREN,
626 XC_LEX_INVALID, XC_LEX_OP_MULTIPLY, XC_LEX_OP_PLUS, XC_LEX_INVALID,
628 XC_LEX_OP_MINUS, XC_LEX_INVALID, XC_LEX_OP_DIVIDE,
630 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
631 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
632 XC_LEX_INVALID, XC_LEX_INVALID,
634 DC_LEX_COLON, DC_LEX_SCOLON, XC_LEX_OP_REL_GT, XC_LEX_OP_REL_EQ,
635 XC_LEX_OP_REL_LT, DC_LEX_READ, XC_LEX_INVALID,
637 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
638 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_EQ_NO_REG, XC_LEX_INVALID,
640 DC_LEX_IBASE, XC_LEX_INVALID, DC_LEX_SCALE, DC_LEX_LOAD_POP,
641 XC_LEX_INVALID, DC_LEX_OP_BOOL_NOT, DC_LEX_OBASE, DC_LEX_PRINT_STREAM,
643 DC_LEX_NQUIT, DC_LEX_POP, DC_LEX_STORE_PUSH, XC_LEX_INVALID, XC_LEX_INVALID,
644 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_SCALE_FACTOR, XC_LEX_INVALID,
646 DC_LEX_LENGTH, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
648 XC_LEX_OP_POWER, XC_LEX_NEG, XC_LEX_INVALID,
650 DC_LEX_ASCIIFY, XC_LEX_INVALID, DC_LEX_CLEAR_STACK, DC_LEX_DUPLICATE,
651 DC_LEX_ELSE, DC_LEX_PRINT_STACK, XC_LEX_INVALID, XC_LEX_INVALID,
653 DC_LEX_STORE_IBASE, XC_LEX_INVALID, DC_LEX_STORE_SCALE, DC_LEX_LOAD,
654 XC_LEX_INVALID, DC_LEX_PRINT_POP, DC_LEX_STORE_OBASE, DC_LEX_PRINT,
656 DC_LEX_QUIT, DC_LEX_SWAP, DC_LEX_OP_ASSIGN, XC_LEX_INVALID,
657 XC_LEX_INVALID, DC_LEX_SQRT, XC_LEX_INVALID, DC_LEX_EXECUTE,
659 XC_LEX_INVALID, DC_LEX_STACK_LEVEL,
661 DC_LEX_LBRACE, DC_LEX_OP_MODEXP, XC_LEX_INVALID, DC_LEX_OP_DIVMOD,
663 static const //BcInst - should be this type. Using signed narrow type since DC_INST_INVALID is -1
665 dc_LEX_to_INST[] ALIGN1 = { //starts at XC_LEX_OP_POWER // corresponding XC/DC_LEX_xyz:
666 XC_INST_POWER, XC_INST_MULTIPLY, // XC_LEX_OP_POWER XC_LEX_OP_MULTIPLY
667 XC_INST_DIVIDE, XC_INST_MODULUS, // XC_LEX_OP_DIVIDE XC_LEX_OP_MODULUS
668 XC_INST_PLUS, XC_INST_MINUS, // XC_LEX_OP_PLUS XC_LEX_OP_MINUS
669 XC_INST_BOOL_NOT, // DC_LEX_OP_BOOL_NOT
670 DC_INST_INVALID, // DC_LEX_OP_ASSIGN
671 XC_INST_REL_GT, // DC_LEX_LPAREN
672 DC_INST_INVALID, // DC_LEX_SCOLON
673 DC_INST_INVALID, // DC_LEX_READ
674 XC_INST_IBASE, // DC_LEX_IBASE
675 XC_INST_SCALE, // DC_LEX_SCALE
676 XC_INST_OBASE, // DC_LEX_OBASE
677 XC_INST_LENGTH, // DC_LEX_LENGTH
678 XC_INST_PRINT, // DC_LEX_PRINT
679 DC_INST_QUIT, // DC_LEX_QUIT
680 XC_INST_SQRT, // DC_LEX_SQRT
681 XC_INST_REL_GE, // DC_LEX_LBRACE
682 XC_INST_REL_EQ, // DC_LEX_EQ_NO_REG
683 DC_INST_MODEXP, DC_INST_DIVMOD, // DC_LEX_OP_MODEXP DC_LEX_OP_DIVMOD
684 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_COLON DC_LEX_ELSE
685 DC_INST_EXECUTE, // DC_LEX_EXECUTE
686 DC_INST_PRINT_STACK, DC_INST_CLEAR_STACK, // DC_LEX_PRINT_STACK DC_LEX_CLEAR_STACK
687 DC_INST_STACK_LEN, DC_INST_DUPLICATE, // DC_LEX_STACK_LEVEL DC_LEX_DUPLICATE
688 DC_INST_SWAP, XC_INST_POP, // DC_LEX_SWAP DC_LEX_POP
689 DC_INST_ASCIIFY, DC_INST_PRINT_STREAM, // DC_LEX_ASCIIFY DC_LEX_PRINT_STREAM
690 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_IBASE DC_LEX_STORE_OBASE
691 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_SCALE DC_LEX_LOAD
692 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_LOAD_POP DC_LEX_STORE_PUSH
693 XC_INST_PRINT, DC_INST_NQUIT, // DC_LEX_PRINT_POP DC_LEX_NQUIT
694 XC_INST_SCALE_FUNC, // DC_LEX_SCALE_FACTOR
695 // DC_INST_INVALID in this table either means that corresponding LEX
696 // is not possible for dc, or that it does not compile one-to-one
701 typedef struct BcParse {
702 smallint lex; // was BcLexType // first member is most used
703 smallint lex_last; // was BcLexType
705 const char *lex_inbuf;
706 const char *lex_next_at; // last lex_next() was called at this string
707 const char *lex_filename;
713 IF_BC(size_t in_funcdef;)
719 typedef struct BcProgram {
748 BcParse prs; // first member is most used
750 // For error messages. Can be set to current parsed line,
751 // or [TODO] to current executing line (can be before last parsed one)
756 IF_FEATURE_BC_INTERACTIVE(smallint ttyin;)
757 IF_FEATURE_CLEAN_UP(smallint exiting;)
765 #if ENABLE_FEATURE_EDITING
766 line_input_t *line_input_state;
769 #define G (*ptr_to_globals)
770 #define INIT_G() do { \
771 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
773 #define FREE_G() do { \
774 FREE_PTR_TO_GLOBALS(); \
776 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
777 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
778 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
779 #if ENABLE_FEATURE_BC_INTERACTIVE
780 # define G_interrupt bb_got_signal
781 # define G_ttyin G.ttyin
783 # define G_interrupt 0
786 #if ENABLE_FEATURE_CLEAN_UP
787 # define G_exiting G.exiting
791 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
792 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
795 # define BC_PARSE_REL (1 << 0)
796 # define BC_PARSE_PRINT (1 << 1)
797 # define BC_PARSE_ARRAY (1 << 2)
798 # define BC_PARSE_NOCALL (1 << 3)
801 #define BC_PROG_MAIN (0)
802 #define BC_PROG_READ (1)
804 #define BC_PROG_REQ_FUNCS (2)
807 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
808 #define BC_PROG_NUM(r, n) \
809 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
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(a, b) ((a) > (b) ? (a) : (b))
820 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
822 #define BC_MAX_OBASE ((unsigned) 999)
823 #define BC_MAX_DIM ((unsigned) INT_MAX)
824 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
825 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
826 #define BC_MAX_NUM BC_MAX_STRING
827 // Unused apart from "limits" message. Just show a "biggish number" there.
828 //#define BC_MAX_NAME BC_MAX_STRING
829 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
830 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
831 #define BC_MAX_NAME_STR "999999999"
832 #define BC_MAX_EXP_STR "999999999"
833 #define BC_MAX_VARS_STR "999999999"
835 #define BC_MAX_OBASE_STR "999"
837 #if INT_MAX == 2147483647
838 # define BC_MAX_DIM_STR "2147483647"
839 #elif INT_MAX == 9223372036854775807
840 # define BC_MAX_DIM_STR "9223372036854775807"
842 # error Strange INT_MAX
845 #if UINT_MAX == 4294967295
846 # define BC_MAX_SCALE_STR "4294967295"
847 # define BC_MAX_STRING_STR "4294967294"
848 #elif UINT_MAX == 18446744073709551615
849 # define BC_MAX_SCALE_STR "18446744073709551615"
850 # define BC_MAX_STRING_STR "18446744073709551614"
852 # error Strange UINT_MAX
854 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
856 // In configurations where errors abort instead of propagating error
857 // return code up the call chain, functions returning BC_STATUS
858 // actually don't return anything, they always succeed and return "void".
859 // A macro wrapper is provided, which makes this statement work:
861 // and makes it visible to the compiler that s is always zero,
862 // allowing compiler to optimize dead code after the statement.
864 // To make code more readable, each such function has a "z"
865 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
867 #if ENABLE_FEATURE_BC_INTERACTIVE || ENABLE_FEATURE_CLEAN_UP
868 # define ERRORS_ARE_FATAL 0
869 # define ERRORFUNC /*nothing*/
870 # define IF_ERROR_RETURN_POSSIBLE(a) a
871 # define BC_STATUS BcStatus
872 # define RETURN_STATUS(v) return (v)
873 # define COMMA_SUCCESS /*nothing*/
875 # define ERRORS_ARE_FATAL 1
876 # define ERRORFUNC NORETURN
877 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
878 # define BC_STATUS void
879 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
880 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
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_bad_character(char c)
977 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
978 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
980 static ERRORFUNC int bc_error_bad_expression(void)
982 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
984 static ERRORFUNC int bc_error_bad_token(void)
986 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
988 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
990 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
992 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
994 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
997 static BC_STATUS zbc_POSIX_requires(const char *msg)
999 RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
1001 #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
1002 static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
1004 RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
1006 #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
1007 static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1009 RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; this is bad:", msg));
1011 #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)
1012 static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1014 RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in 'for()'", "POSIX does not allow ", msg));
1016 #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)
1019 static void bc_vec_grow(BcVec *v, size_t n)
1021 size_t cap = v->cap * 2;
1022 while (cap < v->len + n) cap *= 2;
1023 v->v = xrealloc(v->v, v->size * cap);
1027 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1030 v->cap = BC_VEC_START_CAP;
1033 v->v = xmalloc(esize * BC_VEC_START_CAP);
1036 static void bc_char_vec_init(BcVec *v)
1038 bc_vec_init(v, sizeof(char), NULL);
1041 static void bc_vec_expand(BcVec *v, size_t req)
1044 v->v = xrealloc(v->v, v->size * req);
1049 static void bc_vec_pop(BcVec *v)
1053 v->dtor(v->v + (v->size * v->len));
1056 static void bc_vec_npop(BcVec *v, size_t n)
1061 size_t len = v->len - n;
1062 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1066 static void bc_vec_pop_all(BcVec *v)
1068 bc_vec_npop(v, v->len);
1071 static size_t bc_vec_push(BcVec *v, const void *data)
1073 size_t len = v->len;
1074 if (len >= v->cap) bc_vec_grow(v, 1);
1075 memmove(v->v + (v->size * len), data, v->size);
1080 // G.prog.results often needs "pop old operand, push result" idiom.
1081 // Can do this without a few extra ops
1082 static size_t bc_result_pop_and_push(const void *data)
1084 BcVec *v = &G.prog.results;
1086 size_t len = v->len - 1;
1088 last = v->v + (v->size * len);
1091 memmove(last, data, v->size);
1095 static size_t bc_vec_pushByte(BcVec *v, char data)
1097 return bc_vec_push(v, &data);
1100 static size_t bc_vec_pushZeroByte(BcVec *v)
1102 //return bc_vec_pushByte(v, '\0');
1104 return bc_vec_push(v, &const_int_0);
1107 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1110 bc_vec_push(v, data);
1114 if (v->len == v->cap) bc_vec_grow(v, 1);
1116 ptr = v->v + v->size * idx;
1118 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1119 memmove(ptr, data, v->size);
1123 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1126 bc_vec_expand(v, len + 1);
1127 memcpy(v->v, str, len);
1130 bc_vec_pushZeroByte(v);
1133 static void *bc_vec_item(const BcVec *v, size_t idx)
1135 return v->v + v->size * idx;
1138 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1140 return v->v + v->size * (v->len - idx - 1);
1143 static void *bc_vec_top(const BcVec *v)
1145 return v->v + v->size * (v->len - 1);
1148 static FAST_FUNC void bc_vec_free(void *vec)
1150 BcVec *v = (BcVec *) vec;
1155 static BcFunc* xc_program_func(size_t idx)
1157 return bc_vec_item(&G.prog.fns, idx);
1159 // BC_PROG_MAIN is zeroth element, so:
1160 #define xc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1163 static BcFunc* bc_program_current_func(void)
1165 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1166 BcFunc *func = xc_program_func(ip->func);
1171 static char** xc_program_str(size_t idx)
1175 BcFunc *func = bc_program_current_func();
1176 return bc_vec_item(&func->strs, idx);
1179 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1182 static char** xc_program_const(size_t idx)
1186 BcFunc *func = bc_program_current_func();
1187 return bc_vec_item(&func->consts, idx);
1190 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1193 static int bc_id_cmp(const void *e1, const void *e2)
1195 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1198 static FAST_FUNC void bc_id_free(void *id)
1200 free(((BcId *) id)->name);
1203 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1205 size_t low = 0, high = v->len;
1207 while (low < high) {
1208 size_t mid = (low + high) / 2;
1209 BcId *id = bc_vec_item(v, mid);
1210 int result = bc_id_cmp(ptr, id);
1223 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1225 size_t n = *i = bc_map_find_ge(v, ptr);
1228 bc_vec_push(v, ptr);
1229 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1230 return 0; // "was not inserted"
1232 bc_vec_pushAt(v, ptr, n);
1233 return 1; // "was inserted"
1237 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1239 size_t i = bc_map_find_ge(v, ptr);
1240 if (i >= v->len) return BC_VEC_INVALID_IDX;
1241 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1245 static void bc_num_setToZero(BcNum *n, size_t scale)
1252 static void bc_num_zero(BcNum *n)
1254 bc_num_setToZero(n, 0);
1257 static void bc_num_one(BcNum *n)
1259 bc_num_setToZero(n, 0);
1264 // Note: this also sets BcNum to zero
1265 static void bc_num_init(BcNum *n, size_t req)
1267 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1268 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1269 n->num = xmalloc(req);
1276 static void bc_num_init_DEF_SIZE(BcNum *n)
1278 bc_num_init(n, BC_NUM_DEF_SIZE);
1281 static void bc_num_expand(BcNum *n, size_t req)
1283 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1285 n->num = xrealloc(n->num, req);
1290 static FAST_FUNC void bc_num_free(void *num)
1292 free(((BcNum *) num)->num);
1295 static void bc_num_copy(BcNum *d, BcNum *s)
1298 bc_num_expand(d, s->cap);
1302 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1306 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1309 unsigned long result;
1313 while (i > n->rdx) {
1314 unsigned long prev = result;
1315 result = result * 10 + n->num[--i];
1316 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1317 // 0x1ff00000 * 10 is 0x13f600000,
1318 // or 0x3f600000 truncated to 32 bits. Which is larger.
1319 // However, (N*10)/8 < N check is always correct.
1320 if ((result / 8) < prev)
1321 RETURN_STATUS(bc_error("overflow"));
1325 RETURN_STATUS(BC_STATUS_SUCCESS);
1327 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1329 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1331 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1333 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1335 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1337 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1338 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1339 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1340 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1342 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1343 // would not hit realloc() code path - not good if num[] is not malloced
1345 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1351 if (val == 0) return;
1353 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1360 if (val == 0) break;
1364 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1367 for (i = 0; i < len; ++i) {
1369 for (j = i; a[j] < 0;) {
1376 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1394 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1395 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1396 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1397 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1398 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1400 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1402 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1403 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1405 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1408 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1410 size_t i, min, a_int, b_int, diff;
1411 BcDig *max_num, *min_num;
1415 if (a == b) return 0;
1416 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1417 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1419 if (a->neg != b->neg) // signs of a and b differ
1420 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1421 return (int)b->neg - (int)a->neg;
1422 neg = a->neg; // 1 if both negative, 0 if both positive
1424 a_int = BC_NUM_INT(a);
1425 b_int = BC_NUM_INT(b);
1428 if (a_int != 0) return (ssize_t) a_int;
1430 a_max = (a->rdx > b->rdx);
1433 diff = a->rdx - b->rdx;
1434 max_num = a->num + diff;
1436 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1439 diff = b->rdx - a->rdx;
1440 max_num = b->num + diff;
1442 neg = !neg; // same as "neg = (a_max == neg)"
1445 cmp = bc_num_compare(max_num, min_num, b_int + min);
1446 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1448 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1449 if (max_num[i]) return BC_NUM_NEG(1, neg);
1455 static void bc_num_truncate(BcNum *n, size_t places)
1457 if (places == 0) return;
1463 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1467 static void bc_num_extend(BcNum *n, size_t places)
1469 size_t len = n->len + places;
1472 if (n->cap < len) bc_num_expand(n, len);
1474 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1475 memset(n->num, 0, sizeof(BcDig) * places);
1482 static void bc_num_clean(BcNum *n)
1484 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1487 else if (n->len < n->rdx)
1491 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1494 bc_num_extend(n, scale - n->rdx);
1496 bc_num_truncate(n, n->rdx - scale);
1499 if (n->len != 0) n->neg = !neg1 != !neg2;
1502 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1506 b->len = n->len - idx;
1508 a->rdx = b->rdx = 0;
1510 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1511 memcpy(a->num, n->num, idx * sizeof(BcDig));
1521 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1523 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1525 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1526 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1527 if (places + n->len > BC_MAX_NUM)
1528 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1531 if (n->rdx >= places)
1534 bc_num_extend(n, places - n->rdx);
1540 RETURN_STATUS(BC_STATUS_SUCCESS);
1542 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1544 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1546 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1547 BcNumBinaryOp op, size_t req)
1550 BcNum num2, *ptr_a, *ptr_b;
1555 memcpy(ptr_a, c, sizeof(BcNum));
1563 memcpy(ptr_b, c, sizeof(BcNum));
1570 bc_num_init(c, req);
1572 bc_num_expand(c, req);
1574 s = BC_STATUS_SUCCESS;
1575 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1577 if (init) bc_num_free(&num2);
1581 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1583 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1584 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1585 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1586 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1587 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1588 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1590 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1592 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1594 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1597 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1599 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1601 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1604 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1606 size_t req = BC_NUM_MREQ(a, b, scale);
1607 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1610 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1612 size_t req = BC_NUM_MREQ(a, b, scale);
1613 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1616 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1618 size_t req = BC_NUM_MREQ(a, b, scale);
1619 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1622 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1624 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1627 static const BcNumBinaryOp zxc_program_ops[] = {
1628 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1630 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1631 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1632 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1633 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1634 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1635 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1637 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1646 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1648 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1650 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1652 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1653 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1656 // Because this function doesn't need to use scale (per the bc spec),
1657 // I am hijacking it to say whether it's doing an add or a subtract.
1661 if (sub && c->len) c->neg = !c->neg;
1662 RETURN_STATUS(BC_STATUS_SUCCESS);
1666 RETURN_STATUS(BC_STATUS_SUCCESS);
1670 c->rdx = BC_MAX(a->rdx, b->rdx);
1671 min_rdx = BC_MIN(a->rdx, b->rdx);
1674 if (a->rdx > b->rdx) {
1675 diff = a->rdx - b->rdx;
1677 ptr_a = a->num + diff;
1680 diff = b->rdx - a->rdx;
1683 ptr_b = b->num + diff;
1687 for (i = 0; i < diff; ++i, ++c->len)
1691 a_int = BC_NUM_INT(a);
1692 b_int = BC_NUM_INT(b);
1694 if (a_int > b_int) {
1705 for (i = 0; i < min_rdx + min_int; ++i) {
1706 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1708 ptr_c[i] = (BcDig)(in % 10);
1710 for (; i < max + min_rdx; ++i) {
1711 unsigned in = (unsigned)ptr[i] + carry;
1713 ptr_c[i] = (BcDig)(in % 10);
1717 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1719 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1722 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1725 BcNum *minuend, *subtrahend;
1727 bool aneg, bneg, neg;
1729 // Because this function doesn't need to use scale (per the bc spec),
1730 // I am hijacking it to say whether it's doing an add or a subtract.
1734 if (sub && c->len) c->neg = !c->neg;
1735 RETURN_STATUS(BC_STATUS_SUCCESS);
1739 RETURN_STATUS(BC_STATUS_SUCCESS);
1744 a->neg = b->neg = false;
1746 cmp = bc_num_cmp(a, b);
1752 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1753 RETURN_STATUS(BC_STATUS_SUCCESS);
1761 if (sub) neg = !neg;
1766 bc_num_copy(c, minuend);
1769 if (c->rdx < subtrahend->rdx) {
1770 bc_num_extend(c, subtrahend->rdx - c->rdx);
1773 start = c->rdx - subtrahend->rdx;
1775 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1779 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1782 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1784 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1787 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1788 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1791 if (a->len == 0 || b->len == 0) {
1793 RETURN_STATUS(BC_STATUS_SUCCESS);
1795 aone = BC_NUM_ONE(a);
1796 if (aone || BC_NUM_ONE(b)) {
1797 bc_num_copy(c, aone ? b : a);
1798 RETURN_STATUS(BC_STATUS_SUCCESS);
1801 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1802 || a->len < BC_NUM_KARATSUBA_LEN
1803 || b->len < BC_NUM_KARATSUBA_LEN
1807 bc_num_expand(c, a->len + b->len + 1);
1809 memset(c->num, 0, sizeof(BcDig) * c->cap);
1812 for (i = 0; i < b->len; ++i) {
1814 for (j = 0; j < a->len; ++j) {
1815 unsigned in = c->num[i + j];
1816 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1817 // note: compilers prefer _unsigned_ div/const
1819 c->num[i + j] = (BcDig)(in % 10);
1822 c->num[i + j] += (BcDig) carry;
1823 len = BC_MAX(len, i + j + !!carry);
1825 #if ENABLE_FEATURE_BC_INTERACTIVE
1827 // a*a <- without check below, this will not be interruptible
1828 if (G_interrupt) return BC_STATUS_FAILURE;
1834 RETURN_STATUS(BC_STATUS_SUCCESS);
1837 bc_num_init(&l1, max);
1838 bc_num_init(&h1, max);
1839 bc_num_init(&l2, max);
1840 bc_num_init(&h2, max);
1841 bc_num_init(&m1, max);
1842 bc_num_init(&m2, max);
1843 bc_num_init(&z0, max);
1844 bc_num_init(&z1, max);
1845 bc_num_init(&z2, max);
1846 bc_num_init(&temp, max + max);
1848 bc_num_split(a, max2, &l1, &h1);
1849 bc_num_split(b, max2, &l2, &h2);
1851 s = zbc_num_add(&h1, &l1, &m1, 0);
1853 s = zbc_num_add(&h2, &l2, &m2, 0);
1856 s = zbc_num_k(&h1, &h2, &z0);
1858 s = zbc_num_k(&m1, &m2, &z1);
1860 s = zbc_num_k(&l1, &l2, &z2);
1863 s = zbc_num_sub(&z1, &z0, &temp, 0);
1865 s = zbc_num_sub(&temp, &z2, &z1, 0);
1868 s = zbc_num_shift(&z0, max2 * 2);
1870 s = zbc_num_shift(&z1, max2);
1872 s = zbc_num_add(&z0, &z1, &temp, 0);
1874 s = zbc_num_add(&temp, &z2, c, 0);
1889 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1893 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1895 scale = BC_MAX(scale, a->rdx);
1896 scale = BC_MAX(scale, b->rdx);
1897 scale = BC_MIN(a->rdx + b->rdx, scale);
1898 maxrdx = BC_MAX(maxrdx, scale);
1900 bc_num_init(&cpa, a->len);
1901 bc_num_init(&cpb, b->len);
1903 bc_num_copy(&cpa, a);
1904 bc_num_copy(&cpb, b);
1905 cpa.neg = cpb.neg = false;
1907 s = zbc_num_shift(&cpa, maxrdx);
1909 s = zbc_num_shift(&cpb, maxrdx);
1911 s = zbc_num_k(&cpa, &cpb, c);
1915 bc_num_expand(c, c->len + maxrdx);
1917 if (c->len < maxrdx) {
1918 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1923 bc_num_retireMul(c, scale, a->neg, b->neg);
1929 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1931 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1938 RETURN_STATUS(bc_error("divide by zero"));
1940 bc_num_setToZero(c, scale);
1941 RETURN_STATUS(BC_STATUS_SUCCESS);
1943 if (BC_NUM_ONE(b)) {
1945 bc_num_retireMul(c, scale, a->neg, b->neg);
1946 RETURN_STATUS(BC_STATUS_SUCCESS);
1949 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1950 bc_num_copy(&cp, a);
1954 bc_num_expand(&cp, len + 2);
1955 bc_num_extend(&cp, len - cp.len);
1958 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1960 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1962 if (b->rdx == b->len) {
1964 if (len == 0) break;
1966 if (b->num[len] != 0)
1972 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1974 // We want an extra zero in front to make things simpler.
1975 cp.num[cp.len++] = 0;
1978 bc_num_expand(c, cp.len);
1981 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1985 s = BC_STATUS_SUCCESS;
1986 for (i = end - 1; i < end; --i) {
1989 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
1990 bc_num_subArrays(n, b->num, len);
1992 #if ENABLE_FEATURE_BC_INTERACTIVE
1995 // 1/a <- without check below, this will not be interruptible
1997 s = BC_STATUS_FAILURE;
2003 bc_num_retireMul(c, scale, a->neg, b->neg);
2008 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2010 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2011 BcNum *restrict d, size_t scale, size_t ts)
2018 RETURN_STATUS(bc_error("divide by zero"));
2021 bc_num_setToZero(d, ts);
2022 RETURN_STATUS(BC_STATUS_SUCCESS);
2025 bc_num_init(&temp, d->cap);
2026 s = zbc_num_d(a, b, c, scale);
2029 if (scale != 0) scale = ts;
2031 s = zbc_num_m(c, b, &temp, scale);
2033 s = zbc_num_sub(a, &temp, d, scale);
2036 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2039 bc_num_retireMul(d, ts, a->neg, b->neg);
2045 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2047 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2051 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2053 bc_num_init(&c1, len);
2054 s = zbc_num_r(a, b, &c1, c, scale, ts);
2059 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2061 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2063 BcStatus s = BC_STATUS_SUCCESS;
2066 size_t i, powrdx, resrdx;
2069 // GNU bc does not allow 2^2.0 - we do
2070 for (i = 0; i < b->rdx; i++)
2072 RETURN_STATUS(bc_error("not an integer"));
2076 RETURN_STATUS(BC_STATUS_SUCCESS);
2079 bc_num_setToZero(c, scale);
2080 RETURN_STATUS(BC_STATUS_SUCCESS);
2082 if (BC_NUM_ONE(b)) {
2086 s = zbc_num_inv(a, c, scale);
2091 s = zbc_num_ulong_abs(b, &pow);
2092 if (s) RETURN_STATUS(s);
2093 // b is not used beyond this point
2095 bc_num_init(©, a->len);
2096 bc_num_copy(©, a);
2101 if (a->rdx * pow < scale)
2102 scale = a->rdx * pow;
2106 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2108 s = zbc_num_mul(©, ©, ©, powrdx);
2110 // Not needed: zbc_num_mul() has a check for ^C:
2111 //if (G_interrupt) {
2112 // s = BC_STATUS_FAILURE;
2117 bc_num_copy(c, ©);
2119 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2121 s = zbc_num_mul(©, ©, ©, powrdx);
2126 s = zbc_num_mul(c, ©, c, resrdx);
2129 // Not needed: zbc_num_mul() has a check for ^C:
2130 //if (G_interrupt) {
2131 // s = BC_STATUS_FAILURE;
2137 s = zbc_num_inv(c, c, scale);
2141 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2143 // We can't use bc_num_clean() here.
2144 for (i = 0; i < c->len; ++i)
2147 bc_num_setToZero(c, scale);
2154 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2156 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2159 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2160 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2161 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2163 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2164 bc_num_expand(b, req);
2167 bc_num_setToZero(b, scale);
2168 RETURN_STATUS(BC_STATUS_SUCCESS);
2171 RETURN_STATUS(bc_error("negative number"));
2173 if (BC_NUM_ONE(a)) {
2175 bc_num_extend(b, scale);
2176 RETURN_STATUS(BC_STATUS_SUCCESS);
2179 scale = BC_MAX(scale, a->rdx) + 1;
2180 len = a->len + scale;
2182 bc_num_init(&num1, len);
2183 bc_num_init(&num2, len);
2184 bc_num_init_DEF_SIZE(&half);
2190 bc_num_init(&f, len);
2191 bc_num_init(&fprime, len);
2197 pow = BC_NUM_INT(a);
2205 pow -= 2 - (pow & 1);
2207 bc_num_extend(x0, pow);
2209 // Make sure to move the radix back.
2213 x0->rdx = digs = digs1 = 0;
2215 len = BC_NUM_INT(x0) + resrdx - 1;
2217 while (cmp != 0 || digs < len) {
2218 s = zbc_num_div(a, x0, &f, resrdx);
2220 s = zbc_num_add(x0, &f, &fprime, resrdx);
2222 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2225 cmp = bc_num_cmp(x1, x0);
2226 digs = x1->len - (unsigned long long) llabs(cmp);
2228 if (cmp == cmp2 && digs == digs1)
2233 resrdx += times > 4;
2246 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2248 bc_num_free(&fprime);
2255 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2257 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2263 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2266 memcpy(&num2, c, sizeof(BcNum));
2268 bc_num_init(c, len);
2272 bc_num_expand(c, len);
2275 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2277 if (init) bc_num_free(&num2);
2281 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2284 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2287 BcNum base, exp, two, temp;
2291 RETURN_STATUS(bc_error("divide by zero"));
2292 if (a->rdx || b->rdx || c->rdx)
2293 RETURN_STATUS(bc_error("not an integer"));
2295 RETURN_STATUS(bc_error("negative number"));
2297 bc_num_expand(d, c->len);
2298 bc_num_init(&base, c->len);
2299 bc_num_init(&exp, b->len);
2300 bc_num_init(&temp, b->len);
2302 two.cap = ARRAY_SIZE(two_digs);
2309 s = zbc_num_rem(a, c, &base, 0);
2311 bc_num_copy(&exp, b);
2313 while (exp.len != 0) {
2314 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2317 if (BC_NUM_ONE(&temp)) {
2318 s = zbc_num_mul(d, &base, &temp, 0);
2320 s = zbc_num_rem(&temp, c, d, 0);
2324 s = zbc_num_mul(&base, &base, &temp, 0);
2326 s = zbc_num_rem(&temp, c, &base, 0);
2335 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2338 static FAST_FUNC void bc_string_free(void *string)
2340 free(*(char**)string);
2343 static void bc_func_init(BcFunc *f)
2345 bc_char_vec_init(&f->code);
2346 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2347 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2348 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2349 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2350 IF_BC(f->nparams = 0;)
2353 static FAST_FUNC void bc_func_free(void *func)
2355 BcFunc *f = (BcFunc *) func;
2356 bc_vec_free(&f->code);
2357 IF_BC(bc_vec_free(&f->labels);)
2358 IF_BC(bc_vec_free(&f->autos);)
2359 IF_BC(bc_vec_free(&f->strs);)
2360 IF_BC(bc_vec_free(&f->consts);)
2363 static void bc_array_expand(BcVec *a, size_t len);
2365 static void bc_array_init(BcVec *a, bool nums)
2368 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2370 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2371 bc_array_expand(a, 1);
2374 static void bc_array_expand(BcVec *a, size_t len)
2376 if (a->dtor == bc_num_free
2377 // && a->size == sizeof(BcNum) - always true
2380 while (len > a->len) {
2381 bc_num_init_DEF_SIZE(&n);
2386 while (len > a->len) {
2387 bc_array_init(&v, true);
2393 static void bc_array_copy(BcVec *d, const BcVec *s)
2399 bc_vec_expand(d, s->cap);
2404 for (i = 0; i < s->len; i++, dnum++, snum++) {
2405 bc_num_init(dnum, snum->len);
2406 bc_num_copy(dnum, snum);
2411 static void dc_result_copy(BcResult *d, BcResult *src)
2416 case XC_RESULT_TEMP:
2417 case XC_RESULT_IBASE:
2418 case XC_RESULT_SCALE:
2419 case XC_RESULT_OBASE:
2420 bc_num_init(&d->d.n, src->d.n.len);
2421 bc_num_copy(&d->d.n, &src->d.n);
2424 case XC_RESULT_ARRAY:
2425 case XC_RESULT_ARRAY_ELEM:
2426 d->d.id.name = xstrdup(src->d.id.name);
2428 case XC_RESULT_CONSTANT:
2429 IF_BC(case BC_RESULT_LAST:)
2430 IF_BC(case BC_RESULT_ONE:)
2432 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2438 static FAST_FUNC void bc_result_free(void *result)
2440 BcResult *r = (BcResult *) result;
2443 case XC_RESULT_TEMP:
2444 case XC_RESULT_IBASE:
2445 case XC_RESULT_SCALE:
2446 case XC_RESULT_OBASE:
2447 bc_num_free(&r->d.n);
2450 case XC_RESULT_ARRAY:
2451 case XC_RESULT_ARRAY_ELEM:
2460 static int bad_input_byte(char c)
2462 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2465 bc_error_fmt("illegal character 0x%02x", c);
2471 static void xc_read_line(BcVec *vec, FILE *fp)
2474 bc_vec_pop_all(vec);
2477 #if ENABLE_FEATURE_BC_INTERACTIVE
2478 if (G_interrupt) { // ^C was pressed
2481 // ^C while running a script (bc SCRIPT): die.
2482 // We do not return to interactive prompt:
2483 // user might be running us from a shell,
2484 // and SCRIPT might be intended to terminate
2485 // (e.g. contain a "halt" stmt).
2486 // ^C dropping user into a bc prompt instead of
2487 // the shell would be unexpected.
2490 // ^C while interactive input
2492 // GNU bc says "interrupted execution."
2493 // GNU dc says "Interrupt!"
2494 fputs("\ninterrupted execution\n", stderr);
2497 # if ENABLE_FEATURE_EDITING
2498 if (G_ttyin && fp == stdin) {
2500 # define line_buf bb_common_bufsiz1
2501 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2502 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2505 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2510 char c = line_buf[i++];
2512 if (bad_input_byte(c)) goto again;
2514 bc_vec_string(vec, n, line_buf);
2524 #if ENABLE_FEATURE_BC_INTERACTIVE
2526 // ^C was pressed: ignore entire line, get another one
2527 bc_vec_pop_all(vec);
2531 do c = fgetc(fp); while (c == '\0');
2534 bb_perror_msg_and_die("input error");
2535 // Note: EOF does not append '\n'
2538 bad_chars |= bad_input_byte(c);
2539 bc_vec_pushByte(vec, (char)c);
2540 } while (c != '\n');
2543 // Bad chars on this line
2544 if (!G.prs.lex_filename) { // stdin
2545 // ignore entire line, get another one
2548 bb_perror_msg_and_die("file '%s' is not text", G.prs.lex_filename);
2550 bc_vec_pushZeroByte(vec);
2558 static bool xc_num_strValid(const char *val, size_t base)
2563 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2570 if (radix) return false;
2574 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2580 // Note: n is already "bc_num_zero()"ed,
2581 // leading zeroes in "val" are removed
2582 static void bc_num_parseDecimal(BcNum *n, const char *val)
2591 bc_num_expand(n, len);
2593 ptr = strchr(val, '.');
2597 n->rdx = (size_t)((val + len) - (ptr + 1));
2599 for (i = 0; val[i]; ++i) {
2600 if (val[i] != '0' && val[i] != '.') {
2601 // Not entirely zero value - convert it, and exit
2604 n->num[n->len] = val[i] - '0';
2608 if (val[--i] == '.') goto skip_dot;
2613 // if for() exits without hitting if(), the value is entirely zero
2616 // Note: n is already "bc_num_zero()"ed,
2617 // leading zeroes in "val" are removed
2618 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2621 BcNum temp, mult, result;
2623 BcDig base_digs[ULONG_NUM_BUFSIZE];
2628 for (i = 0; ; ++i) {
2631 if (val[i] != '.' && val[i] != '0')
2635 bc_num_init_DEF_SIZE(&temp);
2636 bc_num_init_DEF_SIZE(&mult);
2637 base.cap = ARRAY_SIZE(base_digs);
2638 base.num = base_digs;
2639 bc_num_ulong2num(&base, base_t);
2643 if (c == '\0') goto int_err;
2644 if (c == '.') break;
2646 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2648 s = zbc_num_mul(n, &base, &mult, 0);
2649 if (s) goto int_err;
2650 bc_num_ulong2num(&temp, v);
2651 s = zbc_num_add(&mult, &temp, n, 0);
2652 if (s) goto int_err;
2655 bc_num_init(&result, base.len);
2656 //bc_num_zero(&result); - already is
2662 if (c == '\0') break;
2665 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2667 s = zbc_num_mul(&result, &base, &result, 0);
2669 bc_num_ulong2num(&temp, v);
2670 s = zbc_num_add(&result, &temp, &result, 0);
2672 s = zbc_num_mul(&mult, &base, &mult, 0);
2676 s = zbc_num_div(&result, &mult, &result, digits);
2678 s = zbc_num_add(n, &result, n, digits);
2682 if (n->rdx < digits)
2683 bc_num_extend(n, digits - n->rdx);
2687 bc_num_free(&result);
2693 static BC_STATUS zxc_num_parse(BcNum *n, const char *val, unsigned base_t)
2695 if (!xc_num_strValid(val, base_t))
2696 RETURN_STATUS(bc_error("bad number string"));
2699 while (*val == '0') val++;
2702 bc_num_parseDecimal(n, val);
2704 bc_num_parseBase(n, val, base_t);
2706 RETURN_STATUS(BC_STATUS_SUCCESS);
2708 #define zxc_num_parse(...) (zxc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2710 static bool xc_lex_more_input(void)
2712 BcParse *p = &G.prs;
2714 bc_vec_pop_all(&G.input_buffer);
2716 xc_read_line(&G.input_buffer, G.prs.lex_input_fp);
2718 p->lex_inbuf = G.input_buffer.v;
2719 // bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2721 return G.input_buffer.len > 1;
2724 // p->lex_inbuf points to the current string to be parsed.
2725 // if p->lex_inbuf points to '\0', it's either EOF or it points after
2726 // last processed line's terminating '\n' (and more reading needs to be done
2727 // to get next character).
2729 // If you are in a situation where that is a possibility, call peek_inbuf().
2730 // If necessary, it performs more reading and changes p->lex_inbuf,
2731 // then it returns *p->lex_inbuf (which will be '\0' only if it's EOF).
2732 // After it, just referencing *p->lex_inbuf is valid, and if it wasn't '\0',
2733 // it's ok to do p->lex_inbuf++ once without end-of-buffer checking.
2735 // eat_inbuf() is equvalent to "peek_inbuf(); if (c) p->lex_inbuf++":
2736 // it returns current char and advances the pointer (if not EOF).
2737 // After eat_inbuf(), referencing p->lex_inbuf[-1] and *p->lex_inbuf is valid.
2739 // In many cases, you can use fast *p->lex_inbuf instead of peek_inbuf():
2740 // unless prev char might have been '\n', *p->lex_inbuf is '\0' ONLY
2741 // on real EOF, not end-of-buffer.
2743 // bc cases to test interactively:
2744 // 1 #comment\ - prints "1<newline>" at once (comment is not continued)
2745 // 1 #comment/* - prints "1<newline>" at once
2746 // 1 #comment" - prints "1<newline>" at once
2747 // 1\#comment - error at once (\ is not a line continuation)
2748 // 1 + /*"*/2 - prints "3<newline>" at once
2749 // 1 + /*#*/2 - prints "3<newline>" at once
2750 // "str\" - prints "str\" at once
2751 // "str#" - prints "str#" at once
2752 // "str/*" - prints "str/*" at once
2753 // "str#\ - waits for second line
2754 // end" - ...prints "str#\<newline>end"
2755 static char peek_inbuf(void)
2757 if (*G.prs.lex_inbuf == '\0') {
2758 if (G.prs.lex_input_fp)
2759 if (!xc_lex_more_input())
2760 G.prs.lex_input_fp = NULL;
2762 return *G.prs.lex_inbuf;
2764 static char eat_inbuf(void)
2766 char c = peek_inbuf();
2767 if (c) G.prs.lex_inbuf++;
2771 static void xc_lex_lineComment(void)
2773 BcParse *p = &G.prs;
2776 // Try: echo -n '#foo' | bc
2777 p->lex = XC_LEX_WHITESPACE;
2779 // We depend here on input being done in whole lines:
2780 // '\0' which isn't the EOF can only be seen after '\n'.
2781 while ((c = *p->lex_inbuf) != '\n' && c != '\0')
2785 static void xc_lex_whitespace(void)
2787 BcParse *p = &G.prs;
2789 p->lex = XC_LEX_WHITESPACE;
2791 // We depend here on input being done in whole lines:
2792 // '\0' which isn't the EOF can only be seen after '\n'.
2793 char c = *p->lex_inbuf;
2794 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2802 static BC_STATUS zxc_lex_number(char last)
2804 BcParse *p = &G.prs;
2807 bc_vec_pop_all(&p->lex_strnumbuf);
2808 bc_vec_pushByte(&p->lex_strnumbuf, last);
2811 p->lex = XC_LEX_NUMBER;
2813 // We depend here on input being done in whole lines:
2814 // '\0' which isn't the EOF can only be seen after '\n'.
2815 char c = *p->lex_inbuf;
2819 if (c == '\\' && p->lex_inbuf[1] == '\n') {
2822 c = peek_inbuf(); // force next line to be read
2825 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2826 if (c != '.') break;
2827 // if '.' was already seen, stop on second one:
2831 // c is one of "0-9A-F."
2833 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
2836 if (last == '.') // remove trailing '.' if any
2837 bc_vec_pop(&p->lex_strnumbuf);
2838 bc_vec_pushZeroByte(&p->lex_strnumbuf);
2840 G.err_line = G.prs.lex_line;
2841 RETURN_STATUS(BC_STATUS_SUCCESS);
2843 #define zxc_lex_number(...) (zxc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2845 static void xc_lex_name(void)
2847 BcParse *p = &G.prs;
2851 p->lex = XC_LEX_NAME;
2853 // Since names can't cross lines with \<newline>,
2854 // we depend on the fact that whole line is in the buffer
2856 buf = p->lex_inbuf - 1;
2859 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2863 #if 0 // We do not protect against people with gigabyte-long names
2864 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2865 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2866 if (i > BC_MAX_STRING)
2867 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2870 bc_vec_string(&p->lex_strnumbuf, i, buf);
2872 // Increment the index. We minus 1 because it has already been incremented.
2873 p->lex_inbuf += i - 1;
2875 //return BC_STATUS_SUCCESS;
2878 IF_BC(static BC_STATUS zbc_lex_token(void);)
2879 IF_DC(static BC_STATUS zdc_lex_token(void);)
2880 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2881 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2883 static BC_STATUS zxc_lex_next(void)
2885 BcParse *p = &G.prs;
2888 p->lex_last = p->lex;
2890 // if (p->lex_last == XC_LEX_EOF)
2891 // RETURN_STATUS(bc_error("end of file"));
2893 // Loop until failure or we don't have whitespace. This
2894 // is so the parser doesn't get inundated with whitespace.
2895 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2896 s = BC_STATUS_SUCCESS;
2898 if (*p->lex_inbuf == '\0') {
2899 p->lex = XC_LEX_EOF;
2900 if (peek_inbuf() == '\0')
2901 RETURN_STATUS(BC_STATUS_SUCCESS);
2903 p->lex_next_at = p->lex_inbuf;
2904 dbg_lex("next string to parse:'%.*s'",
2905 (int)(strchrnul(p->lex_next_at, '\n') - p->lex_next_at),
2909 IF_BC(s = zbc_lex_token());
2911 IF_DC(s = zdc_lex_token());
2913 } while (!s && p->lex == XC_LEX_WHITESPACE);
2914 dbg_lex("p->lex from string:%d", p->lex);
2918 #define zxc_lex_next(...) (zxc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
2921 static BC_STATUS zbc_lex_skip_if_at_NLINE(void)
2923 if (G.prs.lex == XC_LEX_NLINE)
2924 RETURN_STATUS(zxc_lex_next());
2925 RETURN_STATUS(BC_STATUS_SUCCESS);
2927 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2929 static BC_STATUS zbc_lex_next_and_skip_NLINE(void)
2933 if (s) RETURN_STATUS(s);
2934 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
2935 s = zbc_lex_skip_if_at_NLINE();
2938 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2940 static BC_STATUS zbc_lex_identifier(void)
2942 BcParse *p = &G.prs;
2945 const char *buf = p->lex_inbuf - 1;
2947 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2948 const char *keyword8 = bc_lex_kws[i].name8;
2950 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2952 if (j == 8) goto match;
2954 if (keyword8[j] != '\0')
2957 // buf starts with keyword bc_lex_kws[i]
2958 if (isalnum(buf[j]) || buf[j]=='_')
2959 continue; // "ifz" does not match "if" keyword, "if." does
2960 p->lex = BC_LEX_KEY_1st_keyword + i;
2961 if (!keyword_is_POSIX(i)) {
2962 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
2963 if (s) RETURN_STATUS(s);
2966 // We minus 1 because the index has already been incremented.
2967 p->lex_inbuf += j - 1;
2968 RETURN_STATUS(BC_STATUS_SUCCESS);
2972 s = BC_STATUS_SUCCESS;
2974 if (p->lex_strnumbuf.len > 2) {
2977 // bc: POSIX only allows one character names; this is bad: 'qwe=1
2979 unsigned len = strchrnul(buf, '\n') - buf;
2980 s = zbc_posix_error_fmt("POSIX only allows one character names; this is bad: '%.*s'", len, buf);
2985 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
2987 static BC_STATUS zbc_lex_string(void)
2989 BcParse *p = &G.prs;
2991 p->lex = XC_LEX_STR;
2992 bc_vec_pop_all(&p->lex_strnumbuf);
2994 char c = peek_inbuf(); // strings can cross lines
2996 RETURN_STATUS(bc_error("unterminated string"));
3002 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3005 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3008 G.err_line = p->lex_line;
3009 RETURN_STATUS(BC_STATUS_SUCCESS);
3011 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3013 static void parse_lex_by_checking_eq_sign(unsigned with_and_without)
3015 BcParse *p = &G.prs;
3016 if (*p->lex_inbuf == '=') {
3017 // ^^^ not using peek_inbuf() since '==' etc can't be split across lines
3019 with_and_without >>= 8; // store "with" value
3020 } // else store "without" value
3021 p->lex = (with_and_without & 0xff);
3023 #define parse_lex_by_checking_eq_sign(with, without) \
3024 parse_lex_by_checking_eq_sign(((with)<<8)|(without))
3026 static BC_STATUS zbc_lex_comment(void)
3028 BcParse *p = &G.prs;
3030 p->lex = XC_LEX_WHITESPACE;
3031 // here lex_inbuf is at '*' of opening comment delimiter
3040 c = *p->lex_inbuf; // no need to peek_inbuf()
3046 RETURN_STATUS(bc_error("unterminated comment"));
3051 p->lex_inbuf++; // skip trailing '/'
3053 G.err_line = p->lex_line;
3054 RETURN_STATUS(BC_STATUS_SUCCESS);
3056 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3058 #undef zbc_lex_token
3059 static BC_STATUS zbc_lex_token(void)
3061 BcParse *p = &G.prs;
3062 BcStatus s = BC_STATUS_SUCCESS;
3063 char c = eat_inbuf();
3066 // This is the workhorse of the lexer.
3068 // case '\0': // probably never reached
3070 // p->lex = XC_LEX_EOF;
3074 p->lex = XC_LEX_NLINE;
3081 xc_lex_whitespace();
3084 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3085 if (p->lex == BC_LEX_OP_BOOL_NOT) {
3086 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3087 if (s) RETURN_STATUS(s);
3091 s = zbc_lex_string();
3094 s = zbc_POSIX_does_not_allow("'#' script comments");
3095 if (s) RETURN_STATUS(s);
3096 xc_lex_lineComment();
3099 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3104 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3105 if (s) RETURN_STATUS(s);
3107 p->lex = BC_LEX_OP_BOOL_AND;
3109 p->lex = XC_LEX_INVALID;
3110 s = bc_error_bad_character('&');
3115 p->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3118 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3124 p->lex = BC_LEX_OP_INC;
3126 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3129 p->lex = BC_LEX_COMMA;
3135 p->lex = BC_LEX_OP_DEC;
3137 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3140 if (isdigit(*p->lex_inbuf))
3141 s = zxc_lex_number(c);
3143 p->lex = BC_LEX_KEY_LAST;
3144 s = zbc_POSIX_does_not_allow("'.' as 'last'");
3150 s = zbc_lex_comment();
3152 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3170 s = zxc_lex_number(c);
3173 p->lex = BC_LEX_SCOLON;
3176 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3179 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3182 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3186 p->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3189 if (*p->lex_inbuf == '\n') {
3190 p->lex = XC_LEX_WHITESPACE;
3193 s = bc_error_bad_character(c);
3196 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3224 s = zbc_lex_identifier();
3228 p->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3233 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3234 if (s) RETURN_STATUS(s);
3236 p->lex = BC_LEX_OP_BOOL_OR;
3238 p->lex = XC_LEX_INVALID;
3239 s = bc_error_bad_character(c);
3243 p->lex = XC_LEX_INVALID;
3244 s = bc_error_bad_character(c);
3250 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3254 static BC_STATUS zdc_lex_register(void)
3256 BcParse *p = &G.prs;
3257 if (G_exreg && isspace(*p->lex_inbuf)) {
3258 xc_lex_whitespace(); // eats whitespace (but not newline)
3259 p->lex_inbuf++; // xc_lex_name() expects this
3262 bc_vec_pop_all(&p->lex_strnumbuf);
3263 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf++);
3264 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3265 p->lex = XC_LEX_NAME;
3268 RETURN_STATUS(BC_STATUS_SUCCESS);
3270 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3272 static BC_STATUS zdc_lex_string(void)
3274 BcParse *p = &G.prs;
3277 p->lex = XC_LEX_STR;
3278 bc_vec_pop_all(&p->lex_strnumbuf);
3282 char c = peek_inbuf();
3284 RETURN_STATUS(bc_error("unterminated string"));
3286 if (c == '[') depth++;
3292 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3295 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3296 p->lex_inbuf++; // skip trailing ']'
3298 G.err_line = p->lex_line;
3299 RETURN_STATUS(BC_STATUS_SUCCESS);
3301 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3303 #undef zdc_lex_token
3304 static BC_STATUS zdc_lex_token(void)
3306 static const //BcLexType - should be this type, but narrower type saves size:
3308 dc_lex_regs[] ALIGN1 = {
3309 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3310 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3311 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3315 BcParse *p = &G.prs;
3320 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3321 if (p->lex_last == dc_lex_regs[i])
3322 RETURN_STATUS(zdc_lex_register());
3325 s = BC_STATUS_SUCCESS;
3327 if (c >= '%' && c <= '~'
3328 && (p->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3333 // This is the workhorse of the lexer.
3335 // case '\0': // probably never reached
3336 // p->lex = XC_LEX_EOF;
3339 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3340 // (and "case '\n':" is not just empty here)
3341 // only to allow interactive dc have a way to exit
3342 // "parse" stage of "parse,execute" loop
3343 // on <enter>, not on _next_ token (which would mean
3344 // commands are not executed on pressing <enter>).
3345 // IOW: typing "1p<enter>" should print "1" _at once_,
3346 // not after some more input.
3348 p->lex = XC_LEX_NLINE;
3355 xc_lex_whitespace();
3360 p->lex = XC_LEX_OP_REL_NE;
3362 p->lex = XC_LEX_OP_REL_LE;
3364 p->lex = XC_LEX_OP_REL_GE;
3366 RETURN_STATUS(bc_error_bad_character(c));
3370 xc_lex_lineComment();
3373 if (isdigit(*p->lex_inbuf))
3374 s = zxc_lex_number(c);
3376 s = bc_error_bad_character(c);
3394 s = zxc_lex_number(c);
3397 s = zdc_lex_string();
3400 p->lex = XC_LEX_INVALID;
3401 s = bc_error_bad_character(c);
3407 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3410 static void xc_parse_push(char i)
3412 BcVec *code = &G.prs.func->code;
3413 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, code->len, i);
3414 bc_vec_pushByte(code, i);
3417 static void xc_parse_pushName(char *name)
3420 BcVec *code = &G.prs.func->code;
3421 size_t pos = code->len;
3422 size_t len = strlen(name) + 1;
3424 bc_vec_expand(code, pos + len);
3425 strcpy(code->v + pos, name);
3426 code->len = pos + len;
3428 // Smaller code, but way slow:
3430 xc_parse_push(*name);
3435 // Indexes < 0xfc are encoded verbatim, else first byte is
3436 // 0xfc, 0xfd, 0xfe or 0xff, encoding "1..4 bytes",
3437 // followed by that many bytes, lsb first.
3438 // (The above describes 32-bit case).
3439 #define SMALL_INDEX_LIMIT (0x100 - sizeof(size_t))
3441 static void xc_parse_pushIndex(size_t idx)
3446 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3447 if (idx < SMALL_INDEX_LIMIT) {
3451 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3454 if (idx & mask) break;
3459 xc_parse_push(SMALL_INDEX_LIMIT + amt);
3463 xc_parse_push((unsigned char)idx);
3469 static void bc_parse_pushJUMP(size_t idx)
3471 xc_parse_push(BC_INST_JUMP);
3472 xc_parse_pushIndex(idx);
3475 static void bc_parse_pushJUMP_ZERO(size_t idx)
3477 xc_parse_push(BC_INST_JUMP_ZERO);
3478 xc_parse_pushIndex(idx);
3481 static BC_STATUS zbc_parse_pushSTR(void)
3483 BcParse *p = &G.prs;
3484 char *str = xstrdup(p->lex_strnumbuf.v);
3486 xc_parse_push(XC_INST_STR);
3487 xc_parse_pushIndex(p->func->strs.len);
3488 bc_vec_push(&p->func->strs, &str);
3490 RETURN_STATUS(zxc_lex_next());
3492 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3495 static void xc_parse_pushNUM(void)
3497 BcParse *p = &G.prs;
3498 char *num = xstrdup(p->lex_strnumbuf.v);
3499 #if ENABLE_BC && ENABLE_DC
3500 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3502 size_t idx = bc_vec_push(&p->func->consts, &num);
3504 size_t idx = bc_vec_push(&G.prog.consts, &num);
3506 xc_parse_push(XC_INST_NUM);
3507 xc_parse_pushIndex(idx);
3510 static BC_STATUS zxc_parse_text_init(const char *text)
3512 G.prs.func = xc_program_func(G.prs.fidx);
3513 G.prs.lex_inbuf = text;
3514 G.prs.lex = G.prs.lex_last = XC_LEX_INVALID;
3515 RETURN_STATUS(zxc_lex_next());
3517 #define zxc_parse_text_init(...) (zxc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3519 // Called when parsing or execution detects a failure,
3520 // resets execution structures.
3521 static void xc_program_reset(void)
3526 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3527 bc_vec_pop_all(&G.prog.results);
3529 f = xc_program_func_BC_PROG_MAIN();
3530 ip = bc_vec_top(&G.prog.exestack);
3531 ip->inst_idx = f->code.len;
3534 // Called when parsing code detects a failure,
3535 // resets parsing structures.
3536 static void xc_parse_reset(void)
3538 BcParse *p = &G.prs;
3539 if (p->fidx != BC_PROG_MAIN) {
3540 bc_func_free(p->func);
3541 bc_func_init(p->func);
3543 p->fidx = BC_PROG_MAIN;
3544 p->func = xc_program_func_BC_PROG_MAIN();
3547 p->lex_inbuf += strlen(p->lex_inbuf);
3548 p->lex = XC_LEX_EOF;
3550 IF_BC(bc_vec_pop_all(&p->exits);)
3551 IF_BC(bc_vec_pop_all(&p->conds);)
3552 IF_BC(bc_vec_pop_all(&p->ops);)
3557 static void xc_parse_free(void)
3559 IF_BC(bc_vec_free(&G.prs.exits);)
3560 IF_BC(bc_vec_free(&G.prs.conds);)
3561 IF_BC(bc_vec_free(&G.prs.ops);)
3562 bc_vec_free(&G.prs.lex_strnumbuf);
3565 static void xc_parse_create(size_t fidx)
3567 BcParse *p = &G.prs;
3568 memset(p, 0, sizeof(BcParse));
3570 bc_char_vec_init(&p->lex_strnumbuf);
3571 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3572 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3573 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3576 p->func = xc_program_func(fidx);
3579 static void xc_program_add_fn(void)
3585 bc_vec_push(&G.prog.fns, &f);
3591 // Note: takes ownership of 'name' (must be malloced)
3592 static size_t bc_program_addFunc(char *name)
3595 BcId entry, *entry_ptr;
3599 entry.idx = G.prog.fns.len;
3601 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3602 if (!inserted) free(name);
3604 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3605 idx = entry_ptr->idx;
3608 // There is already a function with this name.
3609 // It'll be redefined now, clear old definition.
3610 BcFunc *func = xc_program_func(entry_ptr->idx);
3614 xc_program_add_fn();
3620 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3621 // We can calculate the conversion between tokens and exprs by subtracting the
3622 // position of the first operator in the lex enum and adding the position of the
3623 // first in the expr enum. Note: This only works for binary operators.
3624 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3626 static BcStatus bc_parse_expr_empty_ok(uint8_t flags);
3628 static BC_STATUS zbc_parse_expr(uint8_t flags)
3632 s = bc_parse_expr_empty_ok(flags);
3633 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3634 RETURN_STATUS(bc_error("empty expression"));
3637 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3639 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed);
3640 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3642 static BC_STATUS zbc_parse_stmt(void)
3644 RETURN_STATUS(zbc_parse_stmt_possibly_auto(false));
3646 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3648 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(const char *after_X)
3650 BcParse *p = &G.prs;
3651 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3652 // Same for "else", "while()", "for()".
3653 BcStatus s = zbc_lex_next_and_skip_NLINE();
3654 if (s) RETURN_STATUS(s);
3655 if (p->lex == XC_LEX_NLINE)
3656 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3658 RETURN_STATUS(zbc_parse_stmt());
3660 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3662 static void bc_parse_operator(BcLexType type, size_t start, size_t *nexprs)
3664 BcParse *p = &G.prs;
3665 char l, r = bc_parse_op_PREC(type - XC_LEX_1st_op);
3666 bool left = bc_parse_op_LEFT(type - XC_LEX_1st_op);
3668 while (p->ops.len > start) {
3669 BcLexType t = BC_PARSE_TOP_OP(p);
3670 if (t == BC_LEX_LPAREN) break;
3672 l = bc_parse_op_PREC(t - XC_LEX_1st_op);
3673 if (l >= r && (l != r || !left)) break;
3675 xc_parse_push(BC_TOKEN_2_INST(t));
3676 bc_vec_pop(&p->ops);
3677 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3680 bc_vec_push(&p->ops, &type);
3683 static BC_STATUS zbc_parse_rightParen(size_t ops_bgn, size_t *nexs)
3685 BcParse *p = &G.prs;
3688 if (p->ops.len <= ops_bgn)
3689 RETURN_STATUS(bc_error_bad_expression());
3690 top = BC_PARSE_TOP_OP(p);
3692 while (top != BC_LEX_LPAREN) {
3693 xc_parse_push(BC_TOKEN_2_INST(top));
3695 bc_vec_pop(&p->ops);
3696 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3698 if (p->ops.len <= ops_bgn)
3699 RETURN_STATUS(bc_error_bad_expression());
3700 top = BC_PARSE_TOP_OP(p);
3703 bc_vec_pop(&p->ops);
3705 RETURN_STATUS(BC_STATUS_SUCCESS);
3707 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3709 static BC_STATUS zbc_parse_params(uint8_t flags)
3711 BcParse *p = &G.prs;
3715 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
3716 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3719 if (s) RETURN_STATUS(s);
3722 if (p->lex != BC_LEX_RPAREN) {
3724 s = zbc_parse_expr(flags);
3725 if (s) RETURN_STATUS(s);
3727 if (p->lex != BC_LEX_COMMA) {
3728 if (p->lex == BC_LEX_RPAREN)
3730 RETURN_STATUS(bc_error_bad_token());
3733 if (s) RETURN_STATUS(s);
3737 xc_parse_push(BC_INST_CALL);
3738 xc_parse_pushIndex(nparams);
3740 RETURN_STATUS(BC_STATUS_SUCCESS);
3742 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3744 // Note: takes ownership of 'name' (must be malloced)
3745 static BC_STATUS zbc_parse_call(char *name, uint8_t flags)
3747 BcParse *p = &G.prs;
3749 BcId entry, *entry_ptr;
3754 s = zbc_parse_params(flags);
3757 if (p->lex != BC_LEX_RPAREN) {
3758 s = bc_error_bad_token();
3762 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3764 if (idx == BC_VEC_INVALID_IDX) {
3765 // No such function exists, create an empty one
3766 bc_program_addFunc(name);
3767 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3771 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3772 xc_parse_pushIndex(entry_ptr->idx);
3774 RETURN_STATUS(zxc_lex_next());
3779 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3781 static BC_STATUS zbc_parse_name(BcInst *type, uint8_t flags)
3783 BcParse *p = &G.prs;
3787 name = xstrdup(p->lex_strnumbuf.v);
3791 if (p->lex == BC_LEX_LBRACKET) {
3795 if (p->lex == BC_LEX_RBRACKET) {
3796 if (!(flags & BC_PARSE_ARRAY)) {
3797 s = bc_error_bad_expression();
3800 *type = XC_INST_ARRAY;
3802 *type = XC_INST_ARRAY_ELEM;
3803 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3804 s = zbc_parse_expr(flags);
3809 xc_parse_push(*type);
3810 xc_parse_pushName(name);
3812 } else if (p->lex == BC_LEX_LPAREN) {
3813 if (flags & BC_PARSE_NOCALL) {
3814 s = bc_error_bad_token();
3817 *type = BC_INST_CALL;
3818 s = zbc_parse_call(name, flags);
3820 *type = XC_INST_VAR;
3821 xc_parse_push(XC_INST_VAR);
3822 xc_parse_pushName(name);
3831 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3833 static BC_STATUS zbc_parse_read(void)
3835 BcParse *p = &G.prs;
3839 if (s) RETURN_STATUS(s);
3840 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3843 if (s) RETURN_STATUS(s);
3844 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3846 xc_parse_push(XC_INST_READ);
3850 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3852 static BC_STATUS zbc_parse_builtin(BcLexType type, uint8_t flags, BcInst *prev)
3854 BcParse *p = &G.prs;
3858 if (s) RETURN_STATUS(s);
3859 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3861 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3864 if (s) RETURN_STATUS(s);
3866 s = zbc_parse_expr(flags);
3867 if (s) RETURN_STATUS(s);
3869 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3871 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3872 xc_parse_push(*prev);
3876 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3878 static BC_STATUS zbc_parse_scale(BcInst *type, uint8_t flags)
3880 BcParse *p = &G.prs;
3884 if (s) RETURN_STATUS(s);
3886 if (p->lex != BC_LEX_LPAREN) {
3887 *type = XC_INST_SCALE;
3888 xc_parse_push(XC_INST_SCALE);
3889 RETURN_STATUS(BC_STATUS_SUCCESS);
3892 *type = XC_INST_SCALE_FUNC;
3893 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3896 if (s) RETURN_STATUS(s);
3898 s = zbc_parse_expr(flags);
3899 if (s) RETURN_STATUS(s);
3900 if (p->lex != BC_LEX_RPAREN)
3901 RETURN_STATUS(bc_error_bad_token());
3902 xc_parse_push(XC_INST_SCALE_FUNC);
3904 RETURN_STATUS(zxc_lex_next());
3906 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3908 static BC_STATUS zbc_parse_incdec(BcInst *prev, bool *paren_expr,
3909 size_t *nexprs, uint8_t flags)
3911 BcParse *p = &G.prs;
3915 BcInst etype = *prev;
3917 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
3918 || etype == XC_INST_SCALE || etype == BC_INST_LAST
3919 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
3921 *prev = inst = BC_INST_INC_POST + (p->lex != BC_LEX_OP_INC);
3922 xc_parse_push(inst);
3925 *prev = inst = BC_INST_INC_PRE + (p->lex != BC_LEX_OP_INC);
3929 if (s) RETURN_STATUS(s);
3932 // Because we parse the next part of the expression
3933 // right here, we need to increment this.
3934 *nexprs = *nexprs + 1;
3938 s = zbc_parse_name(prev, flags | BC_PARSE_NOCALL);
3940 case BC_LEX_KEY_IBASE:
3941 case BC_LEX_KEY_LAST:
3942 case BC_LEX_KEY_OBASE:
3943 xc_parse_push(type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
3946 case BC_LEX_KEY_SCALE:
3948 if (s) RETURN_STATUS(s);
3949 if (p->lex == BC_LEX_LPAREN)
3950 s = bc_error_bad_token();
3952 xc_parse_push(XC_INST_SCALE);
3955 s = bc_error_bad_token();
3959 if (!s) xc_parse_push(inst);
3964 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
3967 #define BC_PARSE_LEAF(p, rparen) \
3969 || ((p) >= XC_INST_NUM && (p) <= XC_INST_SQRT) \
3970 || (p) == BC_INST_INC_POST \
3971 || (p) == BC_INST_DEC_POST \
3974 static int ok_in_expr(BcInst p)
3976 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
3977 || p == BC_INST_INC_POST
3978 || p == BC_INST_DEC_POST
3981 #define BC_PARSE_LEAF(p, rparen) ((rparen) || ok_in_expr(p))
3984 static BC_STATUS zbc_parse_minus(BcInst *prev, size_t ops_bgn,
3985 bool rparen, size_t *nexprs)
3987 BcParse *p = &G.prs;
3990 BcInst etype = *prev;
3993 if (s) RETURN_STATUS(s);
3995 type = BC_PARSE_LEAF(etype, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
3996 *prev = BC_TOKEN_2_INST(type);
3998 // We can just push onto the op stack because this is the largest
3999 // precedence operator that gets pushed. Inc/dec does not.
4000 if (type != XC_LEX_OP_MINUS)
4001 bc_vec_push(&p->ops, &type);
4003 bc_parse_operator(type, ops_bgn, nexprs);
4007 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4009 static BC_STATUS zbc_parse_print(void)
4011 BcParse *p = &G.prs;
4017 if (s) RETURN_STATUS(s);
4019 if (type == XC_LEX_STR) {
4020 s = zbc_parse_pushSTR();
4022 s = zbc_parse_expr(0);
4024 if (s) RETURN_STATUS(s);
4025 xc_parse_push(XC_INST_PRINT_POP);
4026 if (p->lex != BC_LEX_COMMA)
4032 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4034 static BC_STATUS zbc_parse_return(void)
4036 BcParse *p = &G.prs;
4040 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4042 if (s) RETURN_STATUS(s);
4045 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON)
4046 xc_parse_push(BC_INST_RET0);
4048 bool paren = (t == BC_LEX_LPAREN);
4049 s = bc_parse_expr_empty_ok(0);
4050 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4051 xc_parse_push(BC_INST_RET0);
4054 if (s) RETURN_STATUS(s);
4056 if (!paren || p->lex_last != BC_LEX_RPAREN) {
4057 s = zbc_POSIX_requires("parentheses around return expressions");
4058 if (s) RETURN_STATUS(s);
4061 xc_parse_push(XC_INST_RET);
4064 dbg_lex_done("%s:%d done", __func__, __LINE__);
4067 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4069 static void rewrite_label_to_current(size_t idx)
4071 BcParse *p = &G.prs;
4072 size_t *label = bc_vec_item(&p->func->labels, idx);
4073 *label = p->func->code.len;
4076 static BC_STATUS zbc_parse_if(void)
4078 BcParse *p = &G.prs;
4082 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4084 if (s) RETURN_STATUS(s);
4085 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4088 if (s) RETURN_STATUS(s);
4089 s = zbc_parse_expr(BC_PARSE_REL);
4090 if (s) RETURN_STATUS(s);
4091 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4093 // Encode "if zero, jump to ..."
4094 // Pushed value (destination of the jump) is uninitialized,
4095 // will be rewritten to be address of "end of if()" or of "else".
4096 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4097 bc_parse_pushJUMP_ZERO(ip_idx);
4099 s = zbc_parse_stmt_allow_NLINE_before(STRING_if);
4100 if (s) RETURN_STATUS(s);
4102 dbg_lex("%s:%d in if after stmt: p->lex:%d", __func__, __LINE__, p->lex);
4103 if (p->lex == BC_LEX_KEY_ELSE) {
4106 // Encode "after then_stmt, jump to end of if()"
4107 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4108 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4109 bc_parse_pushJUMP(ip2_idx);
4111 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4112 rewrite_label_to_current(ip_idx);
4116 s = zbc_parse_stmt_allow_NLINE_before(STRING_else);
4117 if (s) RETURN_STATUS(s);
4120 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4121 rewrite_label_to_current(ip_idx);
4123 dbg_lex_done("%s:%d done", __func__, __LINE__);
4126 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4128 static BC_STATUS zbc_parse_while(void)
4130 BcParse *p = &G.prs;
4136 if (s) RETURN_STATUS(s);
4137 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4139 if (s) RETURN_STATUS(s);
4141 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4142 ip_idx = cond_idx + 1;
4143 bc_vec_push(&p->conds, &cond_idx);
4145 bc_vec_push(&p->exits, &ip_idx);
4146 bc_vec_push(&p->func->labels, &ip_idx);
4148 s = zbc_parse_expr(BC_PARSE_REL);
4149 if (s) RETURN_STATUS(s);
4150 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4152 bc_parse_pushJUMP_ZERO(ip_idx);
4154 s = zbc_parse_stmt_allow_NLINE_before(STRING_while);
4155 if (s) RETURN_STATUS(s);
4157 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4158 bc_parse_pushJUMP(cond_idx);
4160 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4161 rewrite_label_to_current(ip_idx);
4163 bc_vec_pop(&p->exits);
4164 bc_vec_pop(&p->conds);
4168 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4170 static BC_STATUS zbc_parse_for(void)
4172 BcParse *p = &G.prs;
4174 size_t cond_idx, exit_idx, body_idx, update_idx;
4176 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4178 if (s) RETURN_STATUS(s);
4179 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4181 if (s) RETURN_STATUS(s);
4183 if (p->lex != BC_LEX_SCOLON) {
4184 s = zbc_parse_expr(0);
4185 xc_parse_push(XC_INST_POP);
4186 if (s) RETURN_STATUS(s);
4188 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4189 if (s) RETURN_STATUS(s);
4192 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4194 if (s) RETURN_STATUS(s);
4196 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4197 update_idx = cond_idx + 1;
4198 body_idx = update_idx + 1;
4199 exit_idx = body_idx + 1;
4201 if (p->lex != BC_LEX_SCOLON)
4202 s = zbc_parse_expr(BC_PARSE_REL);
4204 // Set this for the next call to xc_parse_pushNUM().
4205 // This is safe to set because the current token is a semicolon,
4206 // which has no string requirement.
4207 bc_vec_string(&p->lex_strnumbuf, 1, "1");
4209 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4211 if (s) RETURN_STATUS(s);
4213 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4216 if (s) RETURN_STATUS(s);
4218 bc_parse_pushJUMP_ZERO(exit_idx);
4219 bc_parse_pushJUMP(body_idx);
4221 bc_vec_push(&p->conds, &update_idx);
4222 bc_vec_push(&p->func->labels, &p->func->code.len);
4224 if (p->lex != BC_LEX_RPAREN) {
4225 s = zbc_parse_expr(0);
4226 if (s) RETURN_STATUS(s);
4227 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4228 xc_parse_push(XC_INST_POP);
4230 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4231 if (s) RETURN_STATUS(s);
4234 bc_parse_pushJUMP(cond_idx);
4235 bc_vec_push(&p->func->labels, &p->func->code.len);
4237 bc_vec_push(&p->exits, &exit_idx);
4238 bc_vec_push(&p->func->labels, &exit_idx);
4240 s = zbc_parse_stmt_allow_NLINE_before(STRING_for);
4241 if (s) RETURN_STATUS(s);
4243 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4244 bc_parse_pushJUMP(update_idx);
4246 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4247 rewrite_label_to_current(exit_idx);
4249 bc_vec_pop(&p->exits);
4250 bc_vec_pop(&p->conds);
4252 RETURN_STATUS(BC_STATUS_SUCCESS);
4254 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4256 static BC_STATUS zbc_parse_break_or_continue(BcLexType type)
4258 BcParse *p = &G.prs;
4261 if (type == BC_LEX_KEY_BREAK) {
4262 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4263 RETURN_STATUS(bc_error_bad_token());
4264 i = *(size_t*)bc_vec_top(&p->exits);
4266 i = *(size_t*)bc_vec_top(&p->conds);
4268 bc_parse_pushJUMP(i);
4270 RETURN_STATUS(zxc_lex_next());
4272 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4274 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4280 autoid = (void*)f->autos.v;
4281 for (i = 0; i < f->autos.len; i++, autoid++) {
4282 if (strcmp(name, autoid->name) == 0)
4283 RETURN_STATUS(bc_error("duplicate function parameter or auto name"));
4289 bc_vec_push(&f->autos, &a);
4291 RETURN_STATUS(BC_STATUS_SUCCESS);
4293 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4295 static BC_STATUS zbc_parse_funcdef(void)
4297 BcParse *p = &G.prs;
4299 bool var, comma = false;
4302 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4304 if (s) RETURN_STATUS(s);
4305 if (p->lex != XC_LEX_NAME)
4306 RETURN_STATUS(bc_error("bad function definition"));
4308 name = xstrdup(p->lex_strnumbuf.v);
4309 p->fidx = bc_program_addFunc(name);
4310 p->func = xc_program_func(p->fidx);
4313 if (s) RETURN_STATUS(s);
4314 if (p->lex != BC_LEX_LPAREN)
4315 RETURN_STATUS(bc_error("bad function definition"));
4317 if (s) RETURN_STATUS(s);
4319 while (p->lex != BC_LEX_RPAREN) {
4320 if (p->lex != XC_LEX_NAME)
4321 RETURN_STATUS(bc_error("bad function definition"));
4325 name = xstrdup(p->lex_strnumbuf.v);
4329 var = p->lex != BC_LEX_LBRACKET;
4335 if (p->lex != BC_LEX_RBRACKET) {
4336 s = bc_error("bad function definition");
4344 comma = p->lex == BC_LEX_COMMA;
4350 s = zbc_func_insert(p->func, name, var);
4354 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4357 if (s) RETURN_STATUS(s);
4359 if (p->lex != BC_LEX_LBRACE) {
4360 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4361 if (s) RETURN_STATUS(s);
4364 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4365 s = zbc_lex_skip_if_at_NLINE();
4366 if (s) RETURN_STATUS(s);
4367 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4368 if (p->lex != BC_LEX_LBRACE)
4369 RETURN_STATUS(bc_error("function { body } expected"));
4371 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4372 s = zbc_parse_stmt_possibly_auto(true);
4374 if (s) RETURN_STATUS(s);
4376 xc_parse_push(BC_INST_RET0);
4378 // Subsequent code generation is into main program
4379 p->fidx = BC_PROG_MAIN;
4380 p->func = xc_program_func_BC_PROG_MAIN();
4382 dbg_lex_done("%s:%d done", __func__, __LINE__);
4385 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4389 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4391 static BC_STATUS zbc_parse_auto(void)
4393 BcParse *p = &G.prs;
4397 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4399 if (s) RETURN_STATUS(s);
4404 if (p->lex != XC_LEX_NAME)
4405 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4407 name = xstrdup(p->lex_strnumbuf.v);
4411 var = (p->lex != BC_LEX_LBRACKET);
4416 if (p->lex != BC_LEX_RBRACKET) {
4417 s = bc_error("bad 'auto' syntax");
4424 s = zbc_func_insert(p->func, name, var);
4427 if (p->lex == XC_LEX_NLINE
4428 || p->lex == BC_LEX_SCOLON
4429 //|| p->lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4433 if (p->lex != BC_LEX_COMMA)
4434 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4435 s = zxc_lex_next(); // skip comma
4436 if (s) RETURN_STATUS(s);
4439 dbg_lex_done("%s:%d done", __func__, __LINE__);
4440 RETURN_STATUS(BC_STATUS_SUCCESS);
4443 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4446 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4448 #undef zbc_parse_stmt_possibly_auto
4449 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed)
4451 BcParse *p = &G.prs;
4452 BcStatus s = BC_STATUS_SUCCESS;
4454 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
4456 if (p->lex == XC_LEX_NLINE) {
4457 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4458 RETURN_STATUS(zxc_lex_next());
4460 if (p->lex == BC_LEX_SCOLON) {
4461 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4462 RETURN_STATUS(zxc_lex_next());
4465 if (p->lex == BC_LEX_LBRACE) {
4466 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4469 if (s) RETURN_STATUS(s);
4470 } while (p->lex == XC_LEX_NLINE);
4471 if (auto_allowed && p->lex == BC_LEX_KEY_AUTO) {
4472 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4473 s = zbc_parse_auto();
4474 if (s) RETURN_STATUS(s);
4476 while (p->lex != BC_LEX_RBRACE) {
4477 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4478 s = zbc_parse_stmt();
4479 if (s) RETURN_STATUS(s);
4482 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4486 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4488 case XC_LEX_OP_MINUS:
4491 case BC_LEX_OP_BOOL_NOT:
4495 case BC_LEX_KEY_IBASE:
4496 case BC_LEX_KEY_LAST:
4497 case BC_LEX_KEY_LENGTH:
4498 case BC_LEX_KEY_OBASE:
4499 case BC_LEX_KEY_READ:
4500 case BC_LEX_KEY_SCALE:
4501 case BC_LEX_KEY_SQRT:
4502 s = zbc_parse_expr(BC_PARSE_PRINT);
4505 s = zbc_parse_pushSTR();
4506 xc_parse_push(XC_INST_PRINT_STR);
4508 case BC_LEX_KEY_BREAK:
4509 case BC_LEX_KEY_CONTINUE:
4510 s = zbc_parse_break_or_continue(p->lex);
4512 case BC_LEX_KEY_FOR:
4513 s = zbc_parse_for();
4515 case BC_LEX_KEY_HALT:
4516 xc_parse_push(BC_INST_HALT);
4522 case BC_LEX_KEY_LIMITS:
4523 // "limits" is a compile-time command,
4524 // the output is produced at _parse time_.
4526 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4527 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4528 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4529 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4530 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4531 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4532 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4533 "Number of vars = "BC_MAX_VARS_STR "\n"
4537 case BC_LEX_KEY_PRINT:
4538 s = zbc_parse_print();
4540 case BC_LEX_KEY_QUIT:
4541 // "quit" is a compile-time command. For example,
4542 // "if (0 == 1) quit" terminates when parsing the statement,
4543 // not when it is executed
4544 QUIT_OR_RETURN_TO_MAIN;
4545 case BC_LEX_KEY_RETURN:
4547 RETURN_STATUS(bc_error("'return' not in a function"));
4548 s = zbc_parse_return();
4550 case BC_LEX_KEY_WHILE:
4551 s = zbc_parse_while();
4554 s = bc_error_bad_token();
4558 dbg_lex_done("%s:%d done", __func__, __LINE__);
4561 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4563 static BC_STATUS zbc_parse_stmt_or_funcdef(void)
4565 BcParse *p = &G.prs;
4568 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4569 if (p->lex == XC_LEX_EOF)
4570 s = bc_error("end of file");
4571 else if (p->lex == BC_LEX_KEY_DEFINE) {
4572 dbg_lex("%s:%d p->lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4573 s = zbc_parse_funcdef();
4575 dbg_lex("%s:%d p->lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->lex);
4576 s = zbc_parse_stmt();
4579 dbg_lex_done("%s:%d done", __func__, __LINE__);
4582 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4584 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4585 static BcStatus bc_parse_expr_empty_ok(uint8_t flags)
4587 BcParse *p = &G.prs;
4588 BcInst prev = XC_INST_PRINT;
4589 size_t nexprs = 0, ops_bgn = p->ops.len;
4590 unsigned nparens, nrelops;
4591 bool paren_first, paren_expr, rprn, assign, bin_last;
4593 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4594 paren_first = (p->lex == BC_LEX_LPAREN);
4595 nparens = nrelops = 0;
4596 paren_expr = rprn = assign = false;
4602 BcLexType t = p->lex;
4604 if (!lex_allowed_in_bc_expr(t))
4607 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4609 s = BC_STATUS_SUCCESS;
4613 dbg_lex("%s:%d LEX_OP_INC/DEC", __func__, __LINE__);
4614 s = zbc_parse_incdec(&prev, &paren_expr, &nexprs, flags);
4615 rprn = bin_last = false;
4616 //get_token = false; - already is
4618 case XC_LEX_OP_MINUS:
4619 dbg_lex("%s:%d LEX_OP_MINUS", __func__, __LINE__);
4620 s = zbc_parse_minus(&prev, ops_bgn, rprn, &nexprs);
4622 //get_token = false; - already is
4623 bin_last = (prev == XC_INST_MINUS);
4625 case BC_LEX_OP_ASSIGN_POWER:
4626 case BC_LEX_OP_ASSIGN_MULTIPLY:
4627 case BC_LEX_OP_ASSIGN_DIVIDE:
4628 case BC_LEX_OP_ASSIGN_MODULUS:
4629 case BC_LEX_OP_ASSIGN_PLUS:
4630 case BC_LEX_OP_ASSIGN_MINUS:
4631 case BC_LEX_OP_ASSIGN:
4632 dbg_lex("%s:%d LEX_ASSIGNxyz", __func__, __LINE__);
4633 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4634 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4635 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4637 return bc_error("bad assignment:"
4638 " left side must be variable"
4640 ); // note: shared string
4643 case XC_LEX_OP_POWER:
4644 case XC_LEX_OP_MULTIPLY:
4645 case XC_LEX_OP_DIVIDE:
4646 case XC_LEX_OP_MODULUS:
4647 case XC_LEX_OP_PLUS:
4648 case XC_LEX_OP_REL_EQ:
4649 case XC_LEX_OP_REL_LE:
4650 case XC_LEX_OP_REL_GE:
4651 case XC_LEX_OP_REL_NE:
4652 case XC_LEX_OP_REL_LT:
4653 case XC_LEX_OP_REL_GT:
4654 case BC_LEX_OP_BOOL_NOT:
4655 case BC_LEX_OP_BOOL_OR:
4656 case BC_LEX_OP_BOOL_AND:
4657 dbg_lex("%s:%d LEX_OP_xyz", __func__, __LINE__);
4658 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4659 || (t != BC_LEX_OP_BOOL_NOT && prev == XC_INST_BOOL_NOT)
4661 return bc_error_bad_expression();
4663 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4664 prev = BC_TOKEN_2_INST(t);
4665 bc_parse_operator(t, ops_bgn, &nexprs);
4668 //get_token = false; - already is
4669 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4672 dbg_lex("%s:%d LEX_LPAREN", __func__, __LINE__);
4673 if (BC_PARSE_LEAF(prev, rprn))
4674 return bc_error_bad_expression();
4675 bc_vec_push(&p->ops, &t);
4679 rprn = bin_last = false;
4682 dbg_lex("%s:%d LEX_RPAREN", __func__, __LINE__);
4683 if (bin_last || prev == XC_INST_BOOL_NOT)
4684 return bc_error_bad_expression();
4689 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4690 return BC_STATUS_PARSE_EMPTY_EXP;
4692 s = zbc_parse_rightParen(ops_bgn, &nexprs);
4695 paren_expr = rprn = true;
4699 dbg_lex("%s:%d LEX_NAME", __func__, __LINE__);
4700 if (BC_PARSE_LEAF(prev, rprn))
4701 return bc_error_bad_expression();
4702 s = zbc_parse_name(&prev, flags & ~BC_PARSE_NOCALL);
4704 rprn = bin_last = false;
4705 //get_token = false; - already is
4709 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4710 if (BC_PARSE_LEAF(prev, rprn))
4711 return bc_error_bad_expression();
4716 rprn = bin_last = false;
4719 case BC_LEX_KEY_IBASE:
4720 case BC_LEX_KEY_LAST:
4721 case BC_LEX_KEY_OBASE:
4722 dbg_lex("%s:%d LEX_IBASE/LAST/OBASE", __func__, __LINE__);
4723 if (BC_PARSE_LEAF(prev, rprn))
4724 return bc_error_bad_expression();
4725 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4726 xc_parse_push((char) prev);
4729 rprn = bin_last = false;
4732 case BC_LEX_KEY_LENGTH:
4733 case BC_LEX_KEY_SQRT:
4734 dbg_lex("%s:%d LEX_LEN/SQRT", __func__, __LINE__);
4735 if (BC_PARSE_LEAF(prev, rprn))
4736 return bc_error_bad_expression();
4737 s = zbc_parse_builtin(t, flags, &prev);
4740 rprn = bin_last = false;
4743 case BC_LEX_KEY_READ:
4744 dbg_lex("%s:%d LEX_READ", __func__, __LINE__);
4745 if (BC_PARSE_LEAF(prev, rprn))
4746 return bc_error_bad_expression();
4747 s = zbc_parse_read();
4748 prev = XC_INST_READ;
4751 rprn = bin_last = false;
4754 case BC_LEX_KEY_SCALE:
4755 dbg_lex("%s:%d LEX_SCALE", __func__, __LINE__);
4756 if (BC_PARSE_LEAF(prev, rprn))
4757 return bc_error_bad_expression();
4758 s = zbc_parse_scale(&prev, flags);
4759 prev = XC_INST_SCALE;
4760 //get_token = false; - already is
4762 rprn = bin_last = false;
4766 return bc_error_bad_token();
4769 if (s || G_interrupt) // error, or ^C: stop parsing
4770 return BC_STATUS_FAILURE;
4778 while (p->ops.len > ops_bgn) {
4779 BcLexType top = BC_PARSE_TOP_OP(p);
4780 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4782 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4783 return bc_error_bad_expression();
4785 xc_parse_push(BC_TOKEN_2_INST(top));
4787 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4788 bc_vec_pop(&p->ops);
4791 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4792 return bc_error_bad_expression();
4794 if (!(flags & BC_PARSE_REL) && nrelops) {
4796 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4798 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4800 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4804 if (flags & BC_PARSE_PRINT) {
4805 if (paren_first || !assign)
4806 xc_parse_push(XC_INST_PRINT);
4807 xc_parse_push(XC_INST_POP);
4810 dbg_lex_done("%s:%d done", __func__, __LINE__);
4811 return BC_STATUS_SUCCESS;
4818 static BC_STATUS zdc_parse_register(void)
4820 BcParse *p = &G.prs;
4824 if (s) RETURN_STATUS(s);
4825 if (p->lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4827 xc_parse_pushName(p->lex_strnumbuf.v);
4831 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4833 static void dc_parse_string(void)
4835 BcParse *p = &G.prs;
4837 size_t len = G.prog.strs.len;
4839 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4841 str = xstrdup(p->lex_strnumbuf.v);
4842 xc_parse_push(XC_INST_STR);
4843 xc_parse_pushIndex(len);
4844 bc_vec_push(&G.prog.strs, &str);
4846 // Explanation needed here
4847 xc_program_add_fn();
4848 p->func = xc_program_func(p->fidx);
4850 dbg_lex_done("%s:%d done", __func__, __LINE__);
4853 static BC_STATUS zdc_parse_mem(uint8_t inst, bool name, bool store)
4857 xc_parse_push(inst);
4859 s = zdc_parse_register();
4860 if (s) RETURN_STATUS(s);
4864 xc_parse_push(DC_INST_SWAP);
4865 xc_parse_push(XC_INST_ASSIGN);
4866 xc_parse_push(XC_INST_POP);
4869 RETURN_STATUS(BC_STATUS_SUCCESS);
4871 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4873 static BC_STATUS zdc_parse_cond(uint8_t inst)
4875 BcParse *p = &G.prs;
4878 xc_parse_push(inst);
4879 xc_parse_push(DC_INST_EXEC_COND);
4881 s = zdc_parse_register();
4882 if (s) RETURN_STATUS(s);
4885 if (s) RETURN_STATUS(s);
4887 // Note that 'else' part can not be on the next line:
4888 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4889 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4890 if (p->lex == DC_LEX_ELSE) {
4891 s = zdc_parse_register();
4892 if (s) RETURN_STATUS(s);
4895 xc_parse_push('\0');
4900 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4902 static BC_STATUS zdc_parse_token(BcLexType t)
4906 bool assign, get_token;
4908 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4909 s = BC_STATUS_SUCCESS;
4912 case XC_LEX_OP_REL_EQ:
4913 case XC_LEX_OP_REL_LE:
4914 case XC_LEX_OP_REL_GE:
4915 case XC_LEX_OP_REL_NE:
4916 case XC_LEX_OP_REL_LT:
4917 case XC_LEX_OP_REL_GT:
4918 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
4919 s = zdc_parse_cond(t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
4924 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
4925 s = zdc_parse_mem(XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
4928 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
4932 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
4934 if (s) RETURN_STATUS(s);
4935 if (G.prs.lex != XC_LEX_NUMBER)
4936 RETURN_STATUS(bc_error_bad_token());
4938 xc_parse_push(XC_INST_NEG);
4941 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4945 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
4946 xc_parse_push(XC_INST_READ);
4948 case DC_LEX_OP_ASSIGN:
4949 case DC_LEX_STORE_PUSH:
4950 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
4951 assign = (t == DC_LEX_OP_ASSIGN);
4952 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
4953 s = zdc_parse_mem(inst, true, assign);
4956 case DC_LEX_LOAD_POP:
4957 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
4958 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
4959 s = zdc_parse_mem(inst, true, false);
4961 case DC_LEX_STORE_IBASE:
4962 case DC_LEX_STORE_SCALE:
4963 case DC_LEX_STORE_OBASE:
4964 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
4965 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
4966 s = zdc_parse_mem(inst, false, true);
4969 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
4970 RETURN_STATUS(bc_error_bad_token());
4973 if (!s && get_token) s = zxc_lex_next();
4975 dbg_lex_done("%s:%d done", __func__, __LINE__);
4978 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
4980 static BC_STATUS zdc_parse_expr(void)
4982 BcParse *p = &G.prs;
4985 i = (int)p->lex - (int)XC_LEX_OP_POWER;
4987 BcInst inst = dc_LEX_to_INST[i];
4988 if (inst != DC_INST_INVALID) {
4989 xc_parse_push(inst);
4990 RETURN_STATUS(zxc_lex_next());
4993 RETURN_STATUS(zdc_parse_token(p->lex));
4995 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
4997 static BC_STATUS zdc_parse_exprs_until_eof(void)
4999 BcParse *p = &G.prs;
5000 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
5001 while (p->lex != XC_LEX_EOF) {
5002 BcStatus s = zdc_parse_expr();
5003 if (s) RETURN_STATUS(s);
5006 dbg_lex_done("%s:%d done", __func__, __LINE__);
5007 RETURN_STATUS(BC_STATUS_SUCCESS);
5009 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5017 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5018 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5020 static BcVec* xc_program_search(char *id, bool var)
5027 v = var ? &G.prog.vars : &G.prog.arrs;
5028 map = var ? &G.prog.var_map : &G.prog.arr_map;
5032 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5036 bc_array_init(&v2, var);
5037 bc_vec_push(v, &v2);
5040 ptr = bc_vec_item(map, i);
5041 if (new) ptr->name = xstrdup(e.name);
5042 return bc_vec_item(v, ptr->idx);
5045 // 'num' need not be initialized on entry
5046 static BC_STATUS zxc_program_num(BcResult *r, BcNum **num, bool hex)
5050 case XC_RESULT_TEMP:
5051 case XC_RESULT_IBASE:
5052 case XC_RESULT_SCALE:
5053 case XC_RESULT_OBASE:
5056 case XC_RESULT_CONSTANT: {
5062 str = *xc_program_const(r->d.id.idx);
5065 bc_num_init(&r->d.n, len);
5067 hex = hex && len == 1;
5068 base_t = hex ? 16 : G.prog.ib_t;
5069 s = zxc_num_parse(&r->d.n, str, base_t);
5071 bc_num_free(&r->d.n);
5075 r->t = XC_RESULT_TEMP;
5079 case XC_RESULT_ARRAY:
5080 case XC_RESULT_ARRAY_ELEM: {
5083 v = xc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5085 if (r->t == XC_RESULT_ARRAY_ELEM) {
5087 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5088 *num = bc_vec_item(v, r->d.id.idx);
5090 *num = bc_vec_top(v);
5094 case BC_RESULT_LAST:
5095 *num = &G.prog.last;
5103 // Testing the theory that dc does not reach LAST/ONE
5104 bb_error_msg_and_die("BUG:%d", r->t);
5108 RETURN_STATUS(BC_STATUS_SUCCESS);
5110 #define zxc_program_num(...) (zxc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5112 static BC_STATUS zxc_program_binOpPrep(BcResult **l, BcNum **ln,
5113 BcResult **r, BcNum **rn, bool assign)
5117 BcResultType lt, rt;
5119 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5120 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5122 *r = bc_vec_item_rev(&G.prog.results, 0);
5123 *l = bc_vec_item_rev(&G.prog.results, 1);
5127 hex = assign && (lt == XC_RESULT_IBASE || lt == XC_RESULT_OBASE);
5129 s = zxc_program_num(*l, ln, false);
5130 if (s) RETURN_STATUS(s);
5131 s = zxc_program_num(*r, rn, hex);
5132 if (s) RETURN_STATUS(s);
5134 // We run this again under these conditions in case any vector has been
5135 // reallocated out from under the BcNums or arrays we had.
5136 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5137 s = zxc_program_num(*l, ln, false);
5138 if (s) RETURN_STATUS(s);
5141 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5142 RETURN_STATUS(bc_error_variable_is_wrong_type());
5143 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5144 RETURN_STATUS(bc_error_variable_is_wrong_type());
5148 #define zxc_program_binOpPrep(...) (zxc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5150 static void xc_program_binOpRetire(BcResult *r)
5152 r->t = XC_RESULT_TEMP;
5153 bc_vec_pop(&G.prog.results);
5154 bc_result_pop_and_push(r);
5157 // Note: *r and *n need not be initialized by caller
5158 static BC_STATUS zxc_program_prep(BcResult **r, BcNum **n)
5162 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5163 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5164 *r = bc_vec_top(&G.prog.results);
5166 s = zxc_program_num(*r, n, false);
5167 if (s) RETURN_STATUS(s);
5169 if (!BC_PROG_NUM((*r), (*n)))
5170 RETURN_STATUS(bc_error_variable_is_wrong_type());
5174 #define zxc_program_prep(...) (zxc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5176 static void xc_program_retire(BcResult *r, BcResultType t)
5179 bc_result_pop_and_push(r);
5182 static BC_STATUS zxc_program_op(char inst)
5185 BcResult *opd1, *opd2, res;
5188 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5189 if (s) RETURN_STATUS(s);
5190 bc_num_init_DEF_SIZE(&res.d.n);
5192 s = BC_STATUS_SUCCESS;
5193 IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5195 xc_program_binOpRetire(&res);
5199 bc_num_free(&res.d.n);
5202 #define zxc_program_op(...) (zxc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5204 static BC_STATUS zxc_program_read(void)
5212 bc_char_vec_init(&buf);
5213 xc_read_line(&buf, stdin);
5215 f = xc_program_func(BC_PROG_READ);
5216 bc_vec_pop_all(&f->code);
5218 sv_parse = G.prs; // struct copy
5219 xc_parse_create(BC_PROG_READ);
5220 //G.err_line = G.prs.lex_line = 1; - not needed, error line info is not printed for read()
5222 s = zxc_parse_text_init(buf.v);
5223 if (s) goto exec_err;
5225 IF_BC(s = zbc_parse_expr(0));
5227 IF_DC(s = zdc_parse_exprs_until_eof());
5229 if (s) goto exec_err;
5231 if (G.prs.lex != XC_LEX_NLINE && G.prs.lex != XC_LEX_EOF) {
5232 s = bc_error("bad read() expression");
5236 ip.func = BC_PROG_READ;
5238 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5240 xc_parse_push(XC_INST_RET);
5241 bc_vec_push(&G.prog.exestack, &ip);
5245 G.prs = sv_parse; // struct copy
5249 #define zxc_program_read(...) (zxc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5251 static size_t xc_program_index(char *code, size_t *bgn)
5253 unsigned char *bytes = (void*)(code + *bgn);
5259 if (amt < SMALL_INDEX_LIMIT) {
5263 amt -= SMALL_INDEX_LIMIT;
5268 for (i = 0; i < amt; i += 8)
5269 res |= (size_t)(*bytes++) << i;
5274 static char *xc_program_name(char *code, size_t *bgn)
5277 *bgn += strlen(code) + 1;
5279 return xstrdup(code);
5282 static void xc_program_printString(const char *str)
5286 // Example: echo '[]ap' | dc
5287 // should print two bytes: 0x00, 0x0A
5294 if (c != '\\' || !*str)
5314 G.prog.nchars = SIZE_MAX;
5326 // Just print the backslash and following character.
5337 static void bc_num_printNewline(void)
5339 if (G.prog.nchars == G.prog.len - 1) {
5347 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5350 bb_putchar((char) num);
5351 G.prog.nchars += width;
5355 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5359 bc_num_printNewline();
5360 bb_putchar(radix ? '.' : ' ');
5363 bc_num_printNewline();
5364 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5367 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5369 bc_num_printNewline();
5372 bb_putchar(((char) dig) + '0');
5376 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5379 bc_num_printNewline();
5384 bc_num_printNewline();
5385 bb_putchar(bb_hexdigits_upcase[num]);
5386 G.prog.nchars += width;
5389 static void bc_num_printDecimal(BcNum *n)
5391 size_t i, rdx = n->rdx - 1;
5398 for (i = n->len - 1; i < n->len; --i)
5399 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5402 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5404 static BC_STATUS zxc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5409 BcDig base_digs[ULONG_NUM_BUFSIZE];
5410 BcNum intp, fracp, digit, frac_len;
5411 unsigned long dig, *ptr;
5416 print(0, width, false);
5417 RETURN_STATUS(BC_STATUS_SUCCESS);
5420 bc_vec_init(&stack, sizeof(long), NULL);
5421 bc_num_init(&intp, n->len);
5422 bc_num_init(&fracp, n->rdx);
5423 bc_num_init(&digit, width);
5424 bc_num_init(&frac_len, BC_NUM_INT(n));
5425 bc_num_copy(&intp, n);
5426 bc_num_one(&frac_len);
5427 base.cap = ARRAY_SIZE(base_digs);
5428 base.num = base_digs;
5429 bc_num_ulong2num(&base, base_t);
5431 bc_num_truncate(&intp, intp.rdx);
5432 s = zbc_num_sub(n, &intp, &fracp, 0);
5435 while (intp.len != 0) {
5436 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5438 s = zbc_num_ulong(&digit, &dig);
5440 bc_vec_push(&stack, &dig);
5443 for (i = 0; i < stack.len; ++i) {
5444 ptr = bc_vec_item_rev(&stack, i);
5445 print(*ptr, width, false);
5448 if (!n->rdx) goto err;
5450 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5451 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5453 s = zbc_num_ulong(&fracp, &dig);
5455 bc_num_ulong2num(&intp, dig);
5456 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5458 print(dig, width, radix);
5459 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5463 bc_num_free(&frac_len);
5464 bc_num_free(&digit);
5465 bc_num_free(&fracp);
5467 bc_vec_free(&stack);
5470 #define zxc_num_printNum(...) (zxc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5472 static BC_STATUS zxc_num_printBase(BcNum *n)
5486 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5488 print = bc_num_printHex;
5490 unsigned i = G.prog.ob_t - 1;
5498 print = bc_num_printDigits;
5501 s = zxc_num_printNum(n, G.prog.ob_t, width, print);
5506 #define zxc_num_printBase(...) (zxc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5508 static BC_STATUS zxc_num_print(BcNum *n, bool newline)
5510 BcStatus s = BC_STATUS_SUCCESS;
5512 bc_num_printNewline();
5517 } else if (G.prog.ob_t == 10)
5518 bc_num_printDecimal(n);
5520 s = zxc_num_printBase(n);
5529 #define zxc_num_print(...) (zxc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5531 static BC_STATUS zxc_program_print(char inst, size_t idx)
5536 bool pop = (inst != XC_INST_PRINT);
5538 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5539 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5541 r = bc_vec_item_rev(&G.prog.results, idx);
5542 s = zxc_program_num(r, &num, false);
5543 if (s) RETURN_STATUS(s);
5545 if (BC_PROG_NUM(r, num)) {
5546 s = zxc_num_print(num, !pop);
5548 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5553 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5554 str = *xc_program_str(idx);
5556 if (inst == XC_INST_PRINT_STR) {
5559 if (c == '\0') break;
5562 if (c == '\n') G.prog.nchars = 0;
5565 xc_program_printString(str);
5566 if (inst == XC_INST_PRINT) bb_putchar('\n');
5570 if (!s && pop) bc_vec_pop(&G.prog.results);
5574 #define zxc_program_print(...) (zxc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5576 static BC_STATUS zxc_program_negate(void)
5582 s = zxc_program_prep(&ptr, &num);
5583 if (s) RETURN_STATUS(s);
5585 bc_num_init(&res.d.n, num->len);
5586 bc_num_copy(&res.d.n, num);
5587 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5589 xc_program_retire(&res, XC_RESULT_TEMP);
5593 #define zxc_program_negate(...) (zxc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5595 static BC_STATUS zxc_program_logical(char inst)
5598 BcResult *opd1, *opd2, res;
5602 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5603 if (s) RETURN_STATUS(s);
5605 bc_num_init_DEF_SIZE(&res.d.n);
5607 if (inst == XC_INST_BOOL_AND)
5608 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5609 else if (inst == XC_INST_BOOL_OR)
5610 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5612 cond = bc_num_cmp(n1, n2);
5614 case XC_INST_REL_EQ:
5617 case XC_INST_REL_LE:
5620 case XC_INST_REL_GE:
5623 case XC_INST_REL_LT:
5626 case XC_INST_REL_GT:
5629 default: // = case XC_INST_REL_NE:
5630 //cond = (cond != 0); - not needed
5635 if (cond) bc_num_one(&res.d.n);
5636 //else bc_num_zero(&res.d.n); - already is
5638 xc_program_binOpRetire(&res);
5642 #define zxc_program_logical(...) (zxc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5645 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5650 memset(&n2, 0, sizeof(BcNum));
5651 n2.rdx = res.d.id.idx = r->d.id.idx;
5652 res.t = XC_RESULT_STR;
5655 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5656 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5658 bc_vec_pop(&G.prog.results);
5661 bc_result_pop_and_push(&res);
5662 bc_vec_push(v, &n2);
5664 RETURN_STATUS(BC_STATUS_SUCCESS);
5666 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5669 static BC_STATUS zxc_program_copyToVar(char *name, bool var)
5676 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5677 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5679 ptr = bc_vec_top(&G.prog.results);
5680 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5681 RETURN_STATUS(bc_error_variable_is_wrong_type());
5682 v = xc_program_search(name, var);
5685 if (ptr->t == XC_RESULT_STR && !var)
5686 RETURN_STATUS(bc_error_variable_is_wrong_type());
5687 if (ptr->t == XC_RESULT_STR)
5688 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5691 s = zxc_program_num(ptr, &n, false);
5692 if (s) RETURN_STATUS(s);
5694 // Do this once more to make sure that pointers were not invalidated.
5695 v = xc_program_search(name, var);
5698 bc_num_init_DEF_SIZE(&r.d.n);
5699 bc_num_copy(&r.d.n, n);
5701 bc_array_init(&r.d.v, true);
5702 bc_array_copy(&r.d.v, (BcVec *) n);
5705 bc_vec_push(v, &r.d);
5706 bc_vec_pop(&G.prog.results);
5710 #define zxc_program_copyToVar(...) (zxc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5712 static BC_STATUS zxc_program_assign(char inst)
5715 BcResult *left, *right, res;
5717 bool assign = (inst == XC_INST_ASSIGN);
5720 s = zxc_program_binOpPrep(&left, &l, &right, &r, assign);
5721 if (s) RETURN_STATUS(s);
5723 ib = left->t == XC_RESULT_IBASE;
5724 sc = left->t == XC_RESULT_SCALE;
5727 if (right->t == XC_RESULT_STR) {
5730 if (left->t != XC_RESULT_VAR)
5731 RETURN_STATUS(bc_error_variable_is_wrong_type());
5732 v = xc_program_search(left->d.id.name, true);
5734 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5738 if (left->t == XC_RESULT_CONSTANT || left->t == XC_RESULT_TEMP)
5739 RETURN_STATUS(bc_error("bad assignment:"
5740 " left side must be variable"
5742 )); // note: shared string
5745 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5746 RETURN_STATUS(bc_error("divide by zero"));
5751 s = BC_STATUS_SUCCESS;
5752 IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5754 if (s) RETURN_STATUS(s);
5759 if (ib || sc || left->t == XC_RESULT_OBASE) {
5760 static const char *const msg[] = {
5761 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5762 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5763 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5769 s = zbc_num_ulong(l, &val);
5770 if (s) RETURN_STATUS(s);
5771 s = left->t - XC_RESULT_IBASE;
5774 ptr = &G.prog.scale;
5777 RETURN_STATUS(bc_error(msg[s]));
5778 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5779 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5783 RETURN_STATUS(bc_error(msg[s]));
5785 *ptr = (size_t) val;
5786 s = BC_STATUS_SUCCESS;
5789 bc_num_init(&res.d.n, l->len);
5790 bc_num_copy(&res.d.n, l);
5791 xc_program_binOpRetire(&res);
5795 #define zxc_program_assign(...) (zxc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5798 #define xc_program_pushVar(code, bgn, pop, copy) \
5799 xc_program_pushVar(code, bgn)
5800 // for bc, 'pop' and 'copy' are always false
5802 static BC_STATUS xc_program_pushVar(char *code, size_t *bgn,
5803 bool pop, bool copy)
5806 char *name = xc_program_name(code, bgn);
5808 r.t = XC_RESULT_VAR;
5813 BcVec *v = xc_program_search(name, true);
5814 BcNum *num = bc_vec_top(v);
5817 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5818 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5821 if (!BC_PROG_STR(num)) {
5822 r.t = XC_RESULT_TEMP;
5823 bc_num_init_DEF_SIZE(&r.d.n);
5824 bc_num_copy(&r.d.n, num);
5826 r.t = XC_RESULT_STR;
5827 r.d.id.idx = num->rdx;
5830 if (!copy) bc_vec_pop(v);
5834 bc_vec_push(&G.prog.results, &r);
5836 RETURN_STATUS(BC_STATUS_SUCCESS);
5838 #define zxc_program_pushVar(...) (xc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5840 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5842 BcStatus s = BC_STATUS_SUCCESS;
5846 r.d.id.name = xc_program_name(code, bgn);
5848 if (inst == XC_INST_ARRAY) {
5849 r.t = XC_RESULT_ARRAY;
5850 bc_vec_push(&G.prog.results, &r);
5855 s = zxc_program_prep(&operand, &num);
5857 s = zbc_num_ulong(num, &temp);
5860 if (temp > BC_MAX_DIM) {
5861 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5865 r.d.id.idx = (size_t) temp;
5866 xc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5869 if (s) free(r.d.id.name);
5872 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5875 static BC_STATUS zbc_program_incdec(char inst)
5878 BcResult *ptr, res, copy;
5882 s = zxc_program_prep(&ptr, &num);
5883 if (s) RETURN_STATUS(s);
5885 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5886 copy.t = XC_RESULT_TEMP;
5887 bc_num_init(©.d.n, num->len);
5888 bc_num_copy(©.d.n, num);
5891 res.t = BC_RESULT_ONE;
5892 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
5893 ? BC_INST_ASSIGN_PLUS
5894 : BC_INST_ASSIGN_MINUS;
5896 bc_vec_push(&G.prog.results, &res);
5897 s = zxc_program_assign(inst);
5898 if (s) RETURN_STATUS(s);
5900 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5901 bc_result_pop_and_push(©);
5906 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5908 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5916 nparams = xc_program_index(code, idx);
5918 ip.func = xc_program_index(code, idx);
5919 func = xc_program_func(ip.func);
5921 if (func->code.len == 0) {
5922 RETURN_STATUS(bc_error("undefined function"));
5924 if (nparams != func->nparams) {
5925 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5927 ip.results_len_before_call = G.prog.results.len - nparams;
5929 for (i = 0; i < nparams; ++i) {
5932 a = bc_vec_item(&func->autos, nparams - 1 - i);
5933 arg = bc_vec_top(&G.prog.results);
5935 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) || arg->t == XC_RESULT_STR)
5936 RETURN_STATUS(bc_error_variable_is_wrong_type());
5938 s = zxc_program_copyToVar(a->name, a->idx);
5939 if (s) RETURN_STATUS(s);
5942 a = bc_vec_item(&func->autos, i);
5943 for (; i < func->autos.len; i++, a++) {
5946 v = xc_program_search(a->name, a->idx);
5949 bc_num_init_DEF_SIZE(&n2);
5950 bc_vec_push(v, &n2);
5953 bc_array_init(&v2, true);
5954 bc_vec_push(v, &v2);
5958 bc_vec_push(&G.prog.exestack, &ip);
5960 RETURN_STATUS(BC_STATUS_SUCCESS);
5962 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
5964 static BC_STATUS zbc_program_return(char inst)
5970 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
5972 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == XC_INST_RET)))
5973 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5975 f = xc_program_func(ip->func);
5976 res.t = XC_RESULT_TEMP;
5978 if (inst == XC_INST_RET) {
5981 BcResult *operand = bc_vec_top(&G.prog.results);
5983 s = zxc_program_num(operand, &num, false);
5984 if (s) RETURN_STATUS(s);
5985 bc_num_init(&res.d.n, num->len);
5986 bc_num_copy(&res.d.n, num);
5988 bc_num_init_DEF_SIZE(&res.d.n);
5989 //bc_num_zero(&res.d.n); - already is
5992 // We need to pop arguments as well, so this takes that into account.
5993 a = (void*)f->autos.v;
5994 for (i = 0; i < f->autos.len; i++, a++) {
5996 v = xc_program_search(a->name, a->idx);
6000 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
6001 bc_vec_push(&G.prog.results, &res);
6002 bc_vec_pop(&G.prog.exestack);
6004 RETURN_STATUS(BC_STATUS_SUCCESS);
6006 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6009 static unsigned long xc_program_scale(BcNum *n)
6011 return (unsigned long) n->rdx;
6014 static unsigned long xc_program_len(BcNum *n)
6016 size_t len = n->len;
6018 if (n->rdx != len) return len;
6020 if (len == 0) break;
6022 if (n->num[len] != 0) break;
6027 static BC_STATUS zxc_program_builtin(char inst)
6033 bool len = (inst == XC_INST_LENGTH);
6035 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6036 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6037 opnd = bc_vec_top(&G.prog.results);
6039 s = zxc_program_num(opnd, &num, false);
6040 if (s) RETURN_STATUS(s);
6043 if (!BC_PROG_NUM(opnd, num) && !len)
6044 RETURN_STATUS(bc_error_variable_is_wrong_type());
6047 bc_num_init_DEF_SIZE(&res.d.n);
6049 if (inst == XC_INST_SQRT)
6050 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6052 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6053 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6057 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6059 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6061 str = xc_program_str(idx);
6062 bc_num_ulong2num(&res.d.n, strlen(*str));
6066 bc_num_ulong2num(&res.d.n, len ? xc_program_len(num) : xc_program_scale(num));
6069 xc_program_retire(&res, XC_RESULT_TEMP);
6073 #define zxc_program_builtin(...) (zxc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6076 static BC_STATUS zdc_program_divmod(void)
6079 BcResult *opd1, *opd2, res, res2;
6082 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6083 if (s) RETURN_STATUS(s);
6085 bc_num_init_DEF_SIZE(&res.d.n);
6086 bc_num_init(&res2.d.n, n2->len);
6088 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6091 xc_program_binOpRetire(&res2);
6092 res.t = XC_RESULT_TEMP;
6093 bc_vec_push(&G.prog.results, &res);
6097 bc_num_free(&res2.d.n);
6098 bc_num_free(&res.d.n);
6101 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6103 static BC_STATUS zdc_program_modexp(void)
6106 BcResult *r1, *r2, *r3, res;
6107 BcNum *n1, *n2, *n3;
6109 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6110 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6111 s = zxc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6112 if (s) RETURN_STATUS(s);
6114 r1 = bc_vec_item_rev(&G.prog.results, 2);
6115 s = zxc_program_num(r1, &n1, false);
6116 if (s) RETURN_STATUS(s);
6117 if (!BC_PROG_NUM(r1, n1))
6118 RETURN_STATUS(bc_error_variable_is_wrong_type());
6120 // Make sure that the values have their pointers updated, if necessary.
6121 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6122 if (r1->t == r2->t) {
6123 s = zxc_program_num(r2, &n2, false);
6124 if (s) RETURN_STATUS(s);
6126 if (r1->t == r3->t) {
6127 s = zxc_program_num(r3, &n3, false);
6128 if (s) RETURN_STATUS(s);
6132 bc_num_init(&res.d.n, n3->len);
6133 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6136 bc_vec_pop(&G.prog.results);
6137 xc_program_binOpRetire(&res);
6141 bc_num_free(&res.d.n);
6144 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6146 static void dc_program_stackLen(void)
6149 size_t len = G.prog.results.len;
6151 res.t = XC_RESULT_TEMP;
6153 bc_num_init_DEF_SIZE(&res.d.n);
6154 bc_num_ulong2num(&res.d.n, len);
6155 bc_vec_push(&G.prog.results, &res);
6158 static BC_STATUS zdc_program_asciify(void)
6168 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6169 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6170 r = bc_vec_top(&G.prog.results);
6172 s = zxc_program_num(r, &num, false);
6173 if (s) RETURN_STATUS(s);
6175 if (BC_PROG_NUM(r, num)) {
6178 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6180 bc_num_init_DEF_SIZE(&n);
6181 bc_num_copy(&n, num);
6182 bc_num_truncate(&n, n.rdx);
6184 strmb.cap = ARRAY_SIZE(strmb_digs);
6185 strmb.num = strmb_digs;
6186 bc_num_ulong2num(&strmb, 0x100);
6187 s = zbc_num_mod(&n, &strmb, &n, 0);
6189 if (s) goto num_err;
6190 s = zbc_num_ulong(&n, &val);
6191 if (s) goto num_err;
6198 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6199 sp = *xc_program_str(idx);
6203 strs = (void*)G.prog.strs.v;
6204 for (idx = 0; idx < G.prog.strs.len; idx++) {
6205 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6211 //str[1] = '\0'; - already is
6212 bc_vec_push(&G.prog.strs, &str);
6214 res.t = XC_RESULT_STR;
6216 bc_result_pop_and_push(&res);
6218 RETURN_STATUS(BC_STATUS_SUCCESS);
6223 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6225 static BC_STATUS zdc_program_printStream(void)
6232 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6233 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6234 r = bc_vec_top(&G.prog.results);
6236 s = zxc_program_num(r, &n, false);
6237 if (s) RETURN_STATUS(s);
6239 if (BC_PROG_NUM(r, n)) {
6240 s = zxc_num_printNum(n, 0x100, 1, dc_num_printChar);
6243 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6244 str = *xc_program_str(idx);
6250 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6252 static BC_STATUS zdc_program_nquit(void)
6259 s = zxc_program_prep(&opnd, &num);
6260 if (s) RETURN_STATUS(s);
6261 s = zbc_num_ulong(num, &val);
6262 if (s) RETURN_STATUS(s);
6264 bc_vec_pop(&G.prog.results);
6266 if (G.prog.exestack.len < val)
6267 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6268 if (G.prog.exestack.len == val) {
6269 QUIT_OR_RETURN_TO_MAIN;
6272 bc_vec_npop(&G.prog.exestack, val);
6276 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6278 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6280 BcStatus s = BC_STATUS_SUCCESS;
6286 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6287 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6289 r = bc_vec_top(&G.prog.results);
6292 BcNum *n = n; // for compiler
6295 char *then_name = xc_program_name(code, bgn);
6296 char *else_name = NULL;
6298 if (code[*bgn] == '\0')
6301 else_name = xc_program_name(code, bgn);
6303 exec = r->d.n.len != 0;
6305 if (!exec && else_name != NULL) {
6312 v = xc_program_search(name, true);
6319 if (!exec) goto exit;
6320 if (!BC_PROG_STR(n)) {
6321 s = bc_error_variable_is_wrong_type();
6327 if (r->t == XC_RESULT_STR) {
6329 } else if (r->t == XC_RESULT_VAR) {
6331 s = zxc_program_num(r, &n, false);
6332 if (s || !BC_PROG_STR(n)) goto exit;
6338 fidx = sidx + BC_PROG_REQ_FUNCS;
6340 f = xc_program_func(fidx);
6342 if (f->code.len == 0) {
6346 sv_parse = G.prs; // struct copy
6347 xc_parse_create(fidx);
6348 str = *xc_program_str(sidx);
6349 s = zxc_parse_text_init(str);
6352 s = zdc_parse_exprs_until_eof();
6354 xc_parse_push(DC_INST_POP_EXEC);
6355 if (G.prs.lex != XC_LEX_EOF)
6356 s = bc_error_bad_expression();
6358 G.prs = sv_parse; // struct copy
6361 bc_vec_pop_all(&f->code);
6369 bc_vec_pop(&G.prog.results);
6370 bc_vec_push(&G.prog.exestack, &ip);
6372 RETURN_STATUS(BC_STATUS_SUCCESS);
6374 bc_vec_pop(&G.prog.results);
6377 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6380 static void xc_program_pushGlobal(char inst)
6385 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6386 if (inst == XC_INST_IBASE)
6387 val = (unsigned long) G.prog.ib_t;
6388 else if (inst == XC_INST_SCALE)
6389 val = (unsigned long) G.prog.scale;
6391 val = (unsigned long) G.prog.ob_t;
6393 bc_num_init_DEF_SIZE(&res.d.n);
6394 bc_num_ulong2num(&res.d.n, val);
6395 bc_vec_push(&G.prog.results, &res);
6398 static BC_STATUS zxc_program_exec(void)
6401 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6402 BcFunc *func = xc_program_func(ip->func);
6403 char *code = func->code.v;
6405 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6406 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6407 while (ip->inst_idx < func->code.len) {
6408 BcStatus s = BC_STATUS_SUCCESS;
6409 char inst = code[ip->inst_idx++];
6411 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6414 case BC_INST_JUMP_ZERO: {
6417 dbg_exec("BC_INST_JUMP_ZERO:");
6418 s = zxc_program_prep(&ptr, &num);
6419 if (s) RETURN_STATUS(s);
6420 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6421 bc_vec_pop(&G.prog.results);
6423 xc_program_index(code, &ip->inst_idx);
6426 // else: fall through
6428 case BC_INST_JUMP: {
6429 size_t idx = xc_program_index(code, &ip->inst_idx);
6430 size_t *addr = bc_vec_item(&func->labels, idx);
6431 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6432 ip->inst_idx = *addr;
6436 dbg_exec("BC_INST_CALL:");
6437 s = zbc_program_call(code, &ip->inst_idx);
6438 goto read_updated_ip;
6439 case BC_INST_INC_PRE:
6440 case BC_INST_DEC_PRE:
6441 case BC_INST_INC_POST:
6442 case BC_INST_DEC_POST:
6443 dbg_exec("BC_INST_INCDEC:");
6444 s = zbc_program_incdec(inst);
6447 dbg_exec("BC_INST_HALT:");
6448 QUIT_OR_RETURN_TO_MAIN;
6452 dbg_exec("BC_INST_RET[0]:");
6453 s = zbc_program_return(inst);
6454 goto read_updated_ip;
6455 case XC_INST_BOOL_OR:
6456 case XC_INST_BOOL_AND:
6458 case XC_INST_REL_EQ:
6459 case XC_INST_REL_LE:
6460 case XC_INST_REL_GE:
6461 case XC_INST_REL_NE:
6462 case XC_INST_REL_LT:
6463 case XC_INST_REL_GT:
6464 dbg_exec("BC_INST_BOOL:");
6465 s = zxc_program_logical(inst);
6468 dbg_exec("XC_INST_READ:");
6469 s = zxc_program_read();
6470 goto read_updated_ip;
6472 dbg_exec("XC_INST_VAR:");
6473 s = zxc_program_pushVar(code, &ip->inst_idx, false, false);
6475 case XC_INST_ARRAY_ELEM:
6477 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6478 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6482 dbg_exec("BC_INST_LAST:");
6483 r.t = BC_RESULT_LAST;
6484 bc_vec_push(&G.prog.results, &r);
6490 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6491 xc_program_pushGlobal(inst);
6493 case XC_INST_SCALE_FUNC:
6494 case XC_INST_LENGTH:
6496 dbg_exec("BC_INST_builtin:");
6497 s = zxc_program_builtin(inst);
6500 dbg_exec("XC_INST_NUM:");
6501 r.t = XC_RESULT_CONSTANT;
6502 r.d.id.idx = xc_program_index(code, &ip->inst_idx);
6503 bc_vec_push(&G.prog.results, &r);
6506 dbg_exec("XC_INST_POP:");
6507 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6508 s = bc_error_stack_has_too_few_elements();
6510 bc_vec_pop(&G.prog.results);
6513 case XC_INST_PRINT_POP:
6514 case XC_INST_PRINT_STR:
6515 dbg_exec("XC_INST_PRINTxyz:");
6516 s = zxc_program_print(inst, 0);
6519 dbg_exec("XC_INST_STR:");
6520 r.t = XC_RESULT_STR;
6521 r.d.id.idx = xc_program_index(code, &ip->inst_idx);
6522 bc_vec_push(&G.prog.results, &r);
6525 case XC_INST_MULTIPLY:
6526 case XC_INST_DIVIDE:
6527 case XC_INST_MODULUS:
6530 dbg_exec("BC_INST_binaryop:");
6531 s = zxc_program_op(inst);
6533 case XC_INST_BOOL_NOT: {
6535 dbg_exec("XC_INST_BOOL_NOT:");
6536 s = zxc_program_prep(&ptr, &num);
6537 if (s) RETURN_STATUS(s);
6538 bc_num_init_DEF_SIZE(&r.d.n);
6539 if (bc_num_cmp(num, &G.prog.zero) == 0)
6541 //else bc_num_zero(&r.d.n); - already is
6542 xc_program_retire(&r, XC_RESULT_TEMP);
6546 dbg_exec("XC_INST_NEG:");
6547 s = zxc_program_negate();
6550 case BC_INST_ASSIGN_POWER:
6551 case BC_INST_ASSIGN_MULTIPLY:
6552 case BC_INST_ASSIGN_DIVIDE:
6553 case BC_INST_ASSIGN_MODULUS:
6554 case BC_INST_ASSIGN_PLUS:
6555 case BC_INST_ASSIGN_MINUS:
6557 case XC_INST_ASSIGN:
6558 dbg_exec("BC_INST_ASSIGNxyz:");
6559 s = zxc_program_assign(inst);
6562 case DC_INST_POP_EXEC:
6563 dbg_exec("DC_INST_POP_EXEC:");
6564 bc_vec_pop(&G.prog.exestack);
6565 goto read_updated_ip;
6566 case DC_INST_MODEXP:
6567 dbg_exec("DC_INST_MODEXP:");
6568 s = zdc_program_modexp();
6570 case DC_INST_DIVMOD:
6571 dbg_exec("DC_INST_DIVMOD:");
6572 s = zdc_program_divmod();
6574 case DC_INST_EXECUTE:
6575 case DC_INST_EXEC_COND:
6576 dbg_exec("DC_INST_EXEC[_COND]:");
6577 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6578 goto read_updated_ip;
6579 case DC_INST_PRINT_STACK: {
6581 dbg_exec("DC_INST_PRINT_STACK:");
6582 for (idx = 0; idx < G.prog.results.len; ++idx) {
6583 s = zxc_program_print(XC_INST_PRINT, idx);
6588 case DC_INST_CLEAR_STACK:
6589 dbg_exec("DC_INST_CLEAR_STACK:");
6590 bc_vec_pop_all(&G.prog.results);
6592 case DC_INST_STACK_LEN:
6593 dbg_exec("DC_INST_STACK_LEN:");
6594 dc_program_stackLen();
6596 case DC_INST_DUPLICATE:
6597 dbg_exec("DC_INST_DUPLICATE:");
6598 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6599 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6600 ptr = bc_vec_top(&G.prog.results);
6601 dc_result_copy(&r, ptr);
6602 bc_vec_push(&G.prog.results, &r);
6604 case DC_INST_SWAP: {
6606 dbg_exec("DC_INST_SWAP:");
6607 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6608 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6609 ptr = bc_vec_item_rev(&G.prog.results, 0);
6610 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6611 memcpy(&r, ptr, sizeof(BcResult));
6612 memcpy(ptr, ptr2, sizeof(BcResult));
6613 memcpy(ptr2, &r, sizeof(BcResult));
6616 case DC_INST_ASCIIFY:
6617 dbg_exec("DC_INST_ASCIIFY:");
6618 s = zdc_program_asciify();
6620 case DC_INST_PRINT_STREAM:
6621 dbg_exec("DC_INST_PRINT_STREAM:");
6622 s = zdc_program_printStream();
6625 case DC_INST_PUSH_VAR: {
6626 bool copy = inst == DC_INST_LOAD;
6627 s = zxc_program_pushVar(code, &ip->inst_idx, true, copy);
6630 case DC_INST_PUSH_TO_VAR: {
6631 char *name = xc_program_name(code, &ip->inst_idx);
6632 s = zxc_program_copyToVar(name, true);
6637 dbg_exec("DC_INST_QUIT:");
6638 if (G.prog.exestack.len <= 2)
6639 QUIT_OR_RETURN_TO_MAIN;
6640 bc_vec_npop(&G.prog.exestack, 2);
6641 goto read_updated_ip;
6643 dbg_exec("DC_INST_NQUIT:");
6644 s = zdc_program_nquit();
6645 //goto read_updated_ip; - just fall through to it
6648 // Instruction stack has changed, read new pointers
6649 ip = bc_vec_top(&G.prog.exestack);
6650 func = xc_program_func(ip->func);
6651 code = func->code.v;
6652 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6655 if (s || G_interrupt) {
6663 RETURN_STATUS(BC_STATUS_SUCCESS);
6665 #define zxc_program_exec(...) (zxc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6667 static unsigned xc_vm_envLen(const char *var)
6673 len = BC_NUM_PRINT_WIDTH;
6674 if (!lenv) return len;
6676 len = bb_strtou(lenv, NULL, 10) - 1;
6677 if (errno || len < 2 || len >= INT_MAX)
6678 len = BC_NUM_PRINT_WIDTH;
6683 static BC_STATUS zxc_vm_process(const char *text)
6687 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6688 s = zxc_parse_text_init(text); // does the first zxc_lex_next()
6689 if (s) RETURN_STATUS(s);
6692 while (G.prs.lex != XC_LEX_EOF) {
6696 dbg_lex("%s:%d G.prs.lex:%d, parsing...", __func__, __LINE__, G.prs.lex);
6699 if (G.prs.lex == BC_LEX_SCOLON
6700 || G.prs.lex == XC_LEX_NLINE
6707 s = zbc_parse_stmt_or_funcdef();
6710 // Check that next token is a correct stmt delimiter -
6711 // disallows "print 1 print 2" and such.
6712 if (G.prs.lex != BC_LEX_SCOLON
6713 && G.prs.lex != XC_LEX_NLINE
6714 && G.prs.lex != XC_LEX_EOF
6717 //TODO: commonalize for other parse errors:
6718 err_at = G.prs.lex_next_at ? G.prs.lex_next_at : "UNKNOWN";
6719 bc_error_fmt("bad statement terminator at '%.*s'",
6720 (int)(strchrnul(err_at, '\n') - err_at),
6725 // The above logic is fragile. Check these examples:
6726 // - interactive read() still works
6730 // Most of dc parsing assumes all whitespace,
6731 // including '\n', is eaten.
6732 while (G.prs.lex == XC_LEX_NLINE) {
6735 if (G.prs.lex == XC_LEX_EOF)
6738 s = zdc_parse_expr();
6741 if (s || G_interrupt) {
6743 xc_parse_reset(); // includes xc_program_reset()
6744 RETURN_STATUS(BC_STATUS_FAILURE);
6747 dbg_lex("%s:%d executing...", __func__, __LINE__);
6748 s = zxc_program_exec();
6754 ip = (void*)G.prog.exestack.v;
6756 if (G.prog.exestack.len != 1) // should have only main's IP
6757 bb_error_msg_and_die("BUG:call stack");
6758 if (ip->func != BC_PROG_MAIN)
6759 bb_error_msg_and_die("BUG:not MAIN");
6761 f = xc_program_func_BC_PROG_MAIN();
6762 // bc discards strings, constants and code after each
6763 // top-level statement in the "main program".
6764 // This prevents "yes 1 | bc" from growing its memory
6765 // without bound. This can be done because data stack
6766 // is empty and thus can't hold any references to
6767 // strings or constants, there is no generated code
6768 // which can hold references (after we discard one
6769 // we just executed). Code of functions can have references,
6770 // but bc stores function strings/constants in per-function
6774 if (G.prog.results.len != 0) // should be empty
6775 bb_error_msg_and_die("BUG:data stack");
6777 IF_BC(bc_vec_pop_all(&f->strs);)
6778 IF_BC(bc_vec_pop_all(&f->consts);)
6780 if (G.prog.results.len == 0
6781 && G.prog.vars.len == 0
6783 // If stack is empty and no registers exist (TODO: or they are all empty),
6784 // we can get rid of accumulated strings and constants.
6785 // In this example dc process should not grow
6786 // its memory consumption with time:
6788 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6789 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6791 // The code is discarded always (below), thus this example
6792 // should also not grow its memory consumption with time,
6793 // even though its data stack is not empty:
6794 // { echo 1; yes dk; } | dc
6796 // We drop generated and executed code for both bc and dc:
6797 bc_vec_pop_all(&f->code);
6801 dbg_lex_done("%s:%d done", __func__, __LINE__);
6804 #define zxc_vm_process(...) (zxc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6806 static BC_STATUS zxc_vm_execute_FILE(FILE *fp, const char *filename)
6808 // So far bc/dc have no way to include a file from another file,
6809 // therefore we know G.prs.lex_filename == NULL on entry
6810 //const char *sv_file;
6813 G.prs.lex_filename = filename;
6814 G.prs.lex_input_fp = fp;
6815 G.err_line = G.prs.lex_line = 1;
6818 s = zxc_vm_process("");
6819 // We do not stop looping on errors here if reading stdin.
6820 // Example: start interactive bc and enter "return".
6821 // It should say "'return' not in a function"
6822 // but should not exit.
6823 } while (G.prs.lex_input_fp == stdin);
6824 G.prs.lex_filename = NULL;
6827 #define zxc_vm_execute_FILE(...) (zxc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6829 static BC_STATUS zxc_vm_file(const char *file)
6834 fp = xfopen_for_read(file);
6835 s = zxc_vm_execute_FILE(fp, file);
6840 #define zxc_vm_file(...) (zxc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6843 static void bc_vm_info(void)
6845 printf("%s "BB_VER"\n"
6846 "Adapted from https://github.com/gavinhoward/bc\n"
6847 "Original code (c) 2018 Gavin D. Howard and contributors\n"
6851 static void bc_args(char **argv)
6857 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6858 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6859 "warn\0" No_argument "w"
6860 "version\0" No_argument "v"
6861 "standard\0" No_argument "s"
6862 "quiet\0" No_argument "q"
6863 "mathlib\0" No_argument "l"
6864 "interactive\0" No_argument "i"
6867 opts = option_mask32 |= getopt32(argv, "wvsqli");
6869 if (getenv("POSIXLY_CORRECT"))
6870 option_mask32 |= BC_FLAG_S;
6872 if (opts & BC_FLAG_V) {
6877 for (i = optind; argv[i]; ++i)
6878 bc_vec_push(&G.files, argv + i);
6881 static void bc_vm_envArgs(void)
6885 char *env_args = getenv("BC_ENV_ARGS");
6887 if (!env_args) return;
6889 G.env_args = xstrdup(env_args);
6892 bc_vec_init(&v, sizeof(char *), NULL);
6894 while (*(buf = skip_whitespace(buf)) != '\0') {
6895 bc_vec_push(&v, &buf);
6896 buf = skip_non_whitespace(buf);
6902 // NULL terminate, and pass argv[] so that first arg is argv[1]
6903 if (sizeof(int) == sizeof(char*)) {
6904 bc_vec_push(&v, &const_int_0);
6906 static char *const nullptr = NULL;
6907 bc_vec_push(&v, &nullptr);
6909 bc_args(((char **)v.v) - 1);
6914 static const char bc_lib[] ALIGN1 = {
6917 "\n" "auto b,s,n,r,d,i,p,f,v"
6918 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6919 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6920 //e(-.998896): GNU:.36828580434569428695
6921 // above code:.36828580434569428696
6922 // actual value:.3682858043456942869594...
6923 // but for now let's be "GNU compatible"
6932 "\n" "scale=scale(x)+1"
6942 "\n" "for(i=2;v;++i){"
6948 "\n" "while(d--)r*=r"
6951 "\n" "if(n)return(1/r)"
6955 "\n" "auto b,s,r,p,a,q,i,v"
6959 "\n" "r=(1-10^scale)/1"
6970 "\n" "while(x<=.5){"
6974 "\n" "r=a=(x-1)/(x+1)"
6977 "\n" "for(i=3;v;i+=2){"
6988 "\n" "auto b,s,r,a,q,i"
6989 "\n" "if(x<0)return(-s(-x))"
6993 "\n" "scale=1.1*s+2"
7002 "\n" "for(i=3;a;i+=2){"
7003 "\n" "a*=q/(i*(i-1))"
7016 "\n" "x=s(2*a(1)+x)"
7022 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7030 "\n" "if(scale<65){"
7031 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7032 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7042 "\n" "x=(x-.2)/(1+.2*x)"
7047 "\n" "for(i=3;t;i+=2){"
7054 "\n" "return((m*a+r)/n)"
7056 "\n" "define j(n,x){"
7057 "\n" "auto b,s,o,a,i,v,f"
7068 "\n" "for(i=2;i<=n;++i)a*=i"
7070 "\n" "a=(x^n)/2^n/a"
7073 "\n" "scale+=length(a)-scale(a)"
7074 "\n" "for(i=1;v;++i){"
7075 "\n" "v=v*f/i/(n+i)"
7081 "\n" "return(a*r/1)"
7086 static BC_STATUS zxc_vm_exec(void)
7093 if (option_mask32 & BC_FLAG_L) {
7094 // We know that internal library is not buggy,
7095 // thus error checking is normally disabled.
7096 # define DEBUG_LIB 0
7097 s = zxc_vm_process(bc_lib);
7098 if (DEBUG_LIB && s) RETURN_STATUS(s);
7102 s = BC_STATUS_SUCCESS;
7103 fname = (void*)G.files.v;
7104 for (i = 0; i < G.files.len; i++) {
7105 s = zxc_vm_file(*fname++);
7106 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7107 // Debug config, non-interactive mode:
7108 // return all the way back to main.
7109 // Non-debug builds do not come here
7110 // in non-interactive mode, they exit.
7115 if (IS_BC || (option_mask32 & BC_FLAG_I))
7116 s = zxc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7120 #define zxc_vm_exec(...) (zxc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7122 #if ENABLE_FEATURE_CLEAN_UP
7123 static void xc_program_free(void)
7125 bc_vec_free(&G.prog.fns);
7126 IF_BC(bc_vec_free(&G.prog.fn_map);)
7127 bc_vec_free(&G.prog.vars);
7128 bc_vec_free(&G.prog.var_map);
7129 bc_vec_free(&G.prog.arrs);
7130 bc_vec_free(&G.prog.arr_map);
7131 IF_DC(bc_vec_free(&G.prog.strs);)
7132 IF_DC(bc_vec_free(&G.prog.consts);)
7133 bc_vec_free(&G.prog.results);
7134 bc_vec_free(&G.prog.exestack);
7135 IF_BC(bc_num_free(&G.prog.last);)
7136 //IF_BC(bc_num_free(&G.prog.zero);)
7137 IF_BC(bc_num_free(&G.prog.one);)
7138 bc_vec_free(&G.input_buffer);
7141 static void xc_vm_free(void)
7143 bc_vec_free(&G.files);
7150 static void xc_program_init(void)
7154 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7155 memset(&ip, 0, sizeof(BcInstPtr));
7157 // G.prog.nchars = G.prog.scale = 0; - already is
7161 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7162 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7164 //bc_num_init_DEF_SIZE(&G.prog.zero); - not needed
7165 //bc_num_zero(&G.prog.zero); - already is
7167 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7168 IF_BC(bc_num_one(&G.prog.one);)
7170 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7171 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7174 // Names are chosen simply to be distinct and never match
7175 // a valid function name (and be short)
7176 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7177 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7179 // in dc, functions have no names
7180 xc_program_add_fn();
7181 xc_program_add_fn();
7184 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7185 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7187 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7188 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7190 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7191 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7192 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7193 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7194 bc_vec_push(&G.prog.exestack, &ip);
7196 bc_char_vec_init(&G.input_buffer);
7199 static int xc_vm_init(const char *env_len)
7201 #if ENABLE_FEATURE_EDITING
7202 G.line_input_state = new_line_input_t(DO_HISTORY);
7204 G.prog.len = xc_vm_envLen(env_len);
7206 bc_vec_init(&G.files, sizeof(char *), NULL);
7208 IF_BC(if (IS_BC) bc_vm_envArgs();)
7209 xc_parse_create(BC_PROG_MAIN);
7211 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7212 //-i option unconditionally enables this regardless of isatty():
7214 #if ENABLE_FEATURE_BC_INTERACTIVE
7216 // With SA_RESTART, most system calls will restart
7217 // (IOW: they won't fail with EINTR).
7218 // In particular, this means ^C won't cause
7219 // stdout to get into "error state" if SIGINT hits
7220 // within write() syscall.
7222 // The downside is that ^C while tty input is taken
7223 // will only be handled after [Enter] since read()
7224 // from stdin is not interrupted by ^C either,
7225 // it restarts, thus fgetc() does not return on ^C.
7226 // (This problem manifests only if line editing is disabled)
7227 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7229 // Without SA_RESTART, this exhibits a bug:
7230 // "while (1) print 1" and try ^C-ing it.
7231 // Intermittently, instead of returning to input line,
7232 // you'll get "output error: Interrupted system call"
7234 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7238 return 0; // "not a tty"
7241 static BcStatus xc_vm_run(void)
7243 BcStatus st = zxc_vm_exec();
7244 #if ENABLE_FEATURE_CLEAN_UP
7245 if (G_exiting) // it was actually "halt" or "quit"
7248 # if ENABLE_FEATURE_EDITING
7249 free_line_input_t(G.line_input_state);
7253 dbg_exec("exiting with exitcode %d", st);
7258 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7259 int bc_main(int argc UNUSED_PARAM, char **argv)
7265 is_tty = xc_vm_init("BC_LINE_LENGTH");
7269 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7277 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7278 int dc_main(int argc UNUSED_PARAM, char **argv)
7284 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7285 // 1 char wider than bc from the same package.
7286 // Both default width, and xC_LINE_LENGTH=N are wider:
7287 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7290 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7293 // Do the same, or it's a bug?
7294 xc_vm_init("DC_LINE_LENGTH");
7296 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7297 noscript = BC_FLAG_I;
7299 int n = getopt(argc, argv, "e:f:x");
7305 n = zxc_vm_process(optarg);
7310 n = zxc_vm_file(optarg);
7314 option_mask32 |= DC_FLAG_X;
7324 bc_vec_push(&G.files, argv++);
7327 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin