1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Adapted from https://github.com/gavinhoward/bc
5 * Original code copyright (c) 2018 Gavin D. Howard and contributors.
7 //TODO: GNU extensions:
8 // support "define f(*param[])" - "pass array by reference" syntax
11 #define DEBUG_COMPILE 0
13 // This can be left enabled for production as well:
14 #define SANITY_CHECKS 1
17 //config: bool "bc (45 kb)"
19 //config: select FEATURE_DC_BIG
21 //config: bc is a command-line, arbitrary-precision calculator with a
22 //config: Turing-complete language. See the GNU bc manual
23 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
24 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
26 //config: This bc has five differences to the GNU bc:
27 //config: 1) The period (.) is a shortcut for "last", as in the BSD bc.
28 //config: 2) Arrays are copied before being passed as arguments to
29 //config: functions. This behavior is required by the bc spec.
30 //config: 3) Arrays can be passed to the builtin "length" function to get
31 //config: the number of elements in the array. This prints "1":
32 //config: a[0] = 0; length(a[])
33 //config: 4) The precedence of the boolean "not" operator (!) is equal to
34 //config: that of the unary minus (-) negation operator. This still
35 //config: allows POSIX-compliant scripts to work while somewhat
36 //config: preserving expected behavior (versus C) and making parsing
38 //config: 5) "read()" accepts expressions, not only numeric literals.
41 //config: bool "dc (36 kb)"
44 //config: dc is a reverse-polish notation command-line calculator which
45 //config: supports unlimited precision arithmetic. See the FreeBSD man page
46 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
47 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
49 //config: This dc has a few differences from the two above:
50 //config: 1) When printing a byte stream (command "P"), this dc follows what
51 //config: the FreeBSD dc does.
52 //config: 2) Implements the GNU extensions for divmod ("~") and
53 //config: modular exponentiation ("|").
54 //config: 3) Implements all FreeBSD extensions, except for "J" and "M".
55 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
56 //config: However, they are implemented differently. When it encounters
57 //config: whitespace where a register should be, it skips the whitespace.
58 //config: If the character following is not a lowercase letter, an error
59 //config: is issued. Otherwise, the register name is parsed by the
60 //config: following regex: [a-z][a-z0-9_]*
61 //config: This generally means that register names will be surrounded by
62 //config: whitespace. Examples:
63 //config: l idx s temp L index S temp2 < do_thing
64 //config: Also note that, like the FreeBSD dc, extended registers are not
65 //config: allowed unless the "-x" option is given.
67 //config:if BC || DC # for menuconfig indenting
69 //config:config FEATURE_DC_BIG
70 //config: bool "Use bc code base for dc (larger, more features)"
73 //config:config FEATURE_DC_LIBM
74 //config: bool "Enable power and exp functions (requires libm)"
76 //config: depends on DC && !BC && !FEATURE_DC_BIG
78 //config: Enable power and exp functions.
79 //config: NOTE: This will require libm to be present for linking.
81 //config:config FEATURE_BC_INTERACTIVE
82 //config: bool "Interactive mode (+4kb)"
84 //config: depends on BC || (DC && FEATURE_DC_BIG)
86 //config: Enable interactive mode: when started on a tty,
87 //config: ^C interrupts execution and returns to command line,
88 //config: errors also return to command line instead of exiting,
89 //config: line editing with history is available.
91 //config: With this option off, input can still be taken from tty,
92 //config: but all errors are fatal, ^C is fatal,
93 //config: tty is treated exactly the same as any other
94 //config: standard input (IOW: no line editing).
96 //config:config FEATURE_BC_LONG_OPTIONS
97 //config: bool "Enable bc/dc long options"
99 //config: depends on BC || (DC && FEATURE_DC_BIG)
103 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
104 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
106 //kbuild:lib-$(CONFIG_BC) += bc.o
107 //kbuild:lib-$(CONFIG_DC) += bc.o
109 //See www.gnu.org/software/bc/manual/bc.html
110 //usage:#define bc_trivial_usage
111 //usage: "[-sqlw] FILE..."
113 //usage:#define bc_full_usage "\n"
114 //usage: "\nArbitrary precision calculator"
116 ///////: "\n -i Interactive" - has no effect for now
117 //usage: "\n -q Quiet"
118 //usage: "\n -l Load standard math library"
119 //usage: "\n -s Be POSIX compatible"
120 //usage: "\n -w Warn if extensions are used"
121 ///////: "\n -v Version"
123 //usage: "\n$BC_LINE_LENGTH changes output width"
125 //usage:#define bc_example_usage
126 //usage: "3 + 4.129\n"
127 //usage: "1903 - 2893\n"
128 //usage: "-129 * 213.28935\n"
129 //usage: "12 / -1932\n"
131 //usage: "34 ^ 189\n"
132 //usage: "scale = 13\n"
133 //usage: "ibase = 2\n"
134 //usage: "obase = A\n"
136 //usage:#define dc_trivial_usage
137 //usage: IF_FEATURE_DC_BIG("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
139 //usage:#define dc_full_usage "\n"
140 //usage: "\nTiny RPN calculator. Operations:"
141 //usage: "\n+, -, *, /, %, ~, ^," IF_FEATURE_DC_BIG(" |,")
142 //usage: "\np - print top of the stack without popping"
143 //usage: "\nf - print entire stack"
144 //usage: "\nk - pop the value and set the precision"
145 //usage: "\ni - pop the value and set input radix"
146 //usage: "\no - pop the value and set output radix"
147 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
149 //usage:#define dc_example_usage
150 //usage: "$ dc -e'2 2 + p'\n"
152 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
154 //usage: "$ dc -e'0 1 & p'\n"
156 //usage: "$ dc -e'0 1 | p'\n"
158 //usage: "$ echo '72 9 / 8 * p' | dc\n"
162 #include "common_bufsiz.h"
164 #if !ENABLE_BC && !ENABLE_FEATURE_DC_BIG
169 static uint8_t lex_indent;
170 #define dbg_lex(...) \
172 fprintf(stderr, "%*s", lex_indent, ""); \
173 bb_error_msg(__VA_ARGS__); \
175 #define dbg_lex_enter(...) \
177 dbg_lex(__VA_ARGS__); \
180 #define dbg_lex_done(...) \
183 dbg_lex(__VA_ARGS__); \
186 # define dbg_lex(...) ((void)0)
187 # define dbg_lex_enter(...) ((void)0)
188 # define dbg_lex_done(...) ((void)0)
192 # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
194 # define dbg_compile(...) ((void)0)
198 # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
200 # define dbg_exec(...) ((void)0)
203 typedef enum BcStatus {
204 BC_STATUS_SUCCESS = 0,
205 BC_STATUS_FAILURE = 1,
206 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr_empty_ok() uses this
209 #define BC_VEC_INVALID_IDX ((size_t) -1)
210 #define BC_VEC_START_CAP (1 << 5)
212 typedef void (*BcVecFree)(void *) FAST_FUNC;
214 typedef struct BcVec {
222 typedef signed char BcDig;
224 typedef struct BcNum {
232 #define BC_NUM_MAX_IBASE 36
233 // larger value might speed up BIGNUM calculations a bit:
234 #define BC_NUM_DEF_SIZE 16
235 #define BC_NUM_PRINT_WIDTH 69
237 #define BC_NUM_KARATSUBA_LEN 32
239 typedef enum BcInst {
246 XC_INST_NEG, // order
248 XC_INST_REL_EQ, // should
249 XC_INST_REL_LE, // match
250 XC_INST_REL_GE, // LEX
251 XC_INST_REL_NE, // constants
252 XC_INST_REL_LT, // for
253 XC_INST_REL_GT, // these
255 XC_INST_POWER, // operations
256 XC_INST_MULTIPLY, // |
258 XC_INST_MODULUS, // |
262 XC_INST_BOOL_NOT, // |
263 XC_INST_BOOL_OR, // |
264 XC_INST_BOOL_AND, // |
266 BC_INST_ASSIGN_POWER, // |
267 BC_INST_ASSIGN_MULTIPLY,// |
268 BC_INST_ASSIGN_DIVIDE, // |
269 BC_INST_ASSIGN_MODULUS, // |
270 BC_INST_ASSIGN_PLUS, // |
271 BC_INST_ASSIGN_MINUS, // |
281 XC_INST_IBASE, // order of these constans should match other enums
282 XC_INST_OBASE, // order of these constans should match other enums
283 XC_INST_SCALE, // order of these constans should match other enums
284 IF_BC(BC_INST_LAST,) // order of these constans should match other enums
315 DC_INST_PRINT_STREAM,
330 DC_INST_INVALID = -1,
334 typedef struct BcId {
339 typedef struct BcFunc {
345 IF_BC(size_t nparams;)
346 IF_BC(bool voidfunc;)
349 typedef enum BcResultType {
351 IF_BC(BC_RESULT_VOID,) // same as TEMP, but INST_PRINT will ignore it
354 XC_RESULT_ARRAY_ELEM,
359 //code uses "inst - XC_INST_IBASE + XC_RESULT_IBASE" construct,
360 XC_RESULT_IBASE, // relative order should match for: XC_INST_IBASE
361 XC_RESULT_OBASE, // relative order should match for: XC_INST_OBASE
362 XC_RESULT_SCALE, // relative order should match for: XC_INST_SCALE
363 IF_BC(BC_RESULT_LAST,) // relative order should match for: BC_INST_LAST
365 IF_BC(BC_RESULT_ONE,)
368 typedef union BcResultData {
374 typedef struct BcResult {
379 typedef struct BcInstPtr {
384 typedef enum BcLexType {
395 XC_LEX_NEG = XC_LEX_1st_op, // order
397 XC_LEX_OP_REL_EQ, // should
398 XC_LEX_OP_REL_LE, // match
399 XC_LEX_OP_REL_GE, // INST
400 XC_LEX_OP_REL_NE, // constants
401 XC_LEX_OP_REL_LT, // for
402 XC_LEX_OP_REL_GT, // these
404 XC_LEX_OP_POWER, // operations
405 XC_LEX_OP_MULTIPLY, // |
406 XC_LEX_OP_DIVIDE, // |
407 XC_LEX_OP_MODULUS, // |
409 XC_LEX_OP_MINUS, // |
410 XC_LEX_OP_last = XC_LEX_OP_MINUS,
412 BC_LEX_OP_BOOL_NOT, // |
413 BC_LEX_OP_BOOL_OR, // |
414 BC_LEX_OP_BOOL_AND, // |
416 BC_LEX_OP_ASSIGN_POWER, // |
417 BC_LEX_OP_ASSIGN_MULTIPLY, // |
418 BC_LEX_OP_ASSIGN_DIVIDE, // |
419 BC_LEX_OP_ASSIGN_MODULUS, // |
420 BC_LEX_OP_ASSIGN_PLUS, // |
421 BC_LEX_OP_ASSIGN_MINUS, // |
423 BC_LEX_OP_ASSIGN, // V
428 BC_LEX_LPAREN, // () are 0x28 and 0x29
429 BC_LEX_RPAREN, // must be LPAREN+1: code uses (c - '(' + BC_LEX_LPAREN)
431 BC_LEX_LBRACKET, // [] are 0x5B and 0x5D
433 BC_LEX_RBRACKET, // must be LBRACKET+2: code uses (c - '[' + BC_LEX_LBRACKET)
435 BC_LEX_LBRACE, // {} are 0x7B and 0x7D
437 BC_LEX_RBRACE, // must be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
439 BC_LEX_KEY_1st_keyword,
440 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
447 // code uses "type - BC_LEX_KEY_IBASE + XC_INST_IBASE" construct,
448 BC_LEX_KEY_IBASE, // relative order should match for: XC_INST_IBASE
449 BC_LEX_KEY_OBASE, // relative order should match for: XC_INST_OBASE
451 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
464 DC_LEX_OP_BOOL_NOT = XC_LEX_OP_last + 1,
496 // code uses "t - DC_LEX_STORE_IBASE + XC_INST_IBASE" construct,
497 DC_LEX_STORE_IBASE, // relative order should match for: XC_INST_IBASE
498 DC_LEX_STORE_OBASE, // relative order should match for: XC_INST_OBASE
499 DC_LEX_STORE_SCALE, // relative order should match for: XC_INST_SCALE
508 // must match order of BC_LEX_KEY_foo etc above
510 struct BcLexKeyword {
513 #define LEX_KW_ENTRY(a, b) \
514 { .name8 = a /*, .posix = b */ }
515 static const struct BcLexKeyword bc_lex_kws[20] = {
516 LEX_KW_ENTRY("auto" , 1), // 0
517 LEX_KW_ENTRY("break" , 1), // 1
518 LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
519 LEX_KW_ENTRY("define" , 1), // 3
520 LEX_KW_ENTRY("else" , 0), // 4
521 LEX_KW_ENTRY("for" , 1), // 5
522 LEX_KW_ENTRY("halt" , 0), // 6
523 LEX_KW_ENTRY("ibase" , 1), // 7
524 LEX_KW_ENTRY("obase" , 1), // 8
525 LEX_KW_ENTRY("if" , 1), // 9
526 LEX_KW_ENTRY("last" , 0), // 10
527 LEX_KW_ENTRY("length" , 1), // 11
528 LEX_KW_ENTRY("limits" , 0), // 12
529 LEX_KW_ENTRY("print" , 0), // 13
530 LEX_KW_ENTRY("quit" , 1), // 14
531 LEX_KW_ENTRY("read" , 0), // 15
532 LEX_KW_ENTRY("return" , 1), // 16
533 LEX_KW_ENTRY("scale" , 1), // 17
534 LEX_KW_ENTRY("sqrt" , 1), // 18
535 LEX_KW_ENTRY("while" , 1), // 19
538 #define STRING_else (bc_lex_kws[4].name8)
539 #define STRING_for (bc_lex_kws[5].name8)
540 #define STRING_if (bc_lex_kws[9].name8)
541 #define STRING_while (bc_lex_kws[19].name8)
565 #define keyword_is_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
567 // This is a bit array that corresponds to token types. An entry is
568 // true if the token is valid in an expression, false otherwise.
569 // Used to figure out when expr parsing should stop *without error message*
570 // - 0 element indicates this condition. 1 means "this token is to be eaten
571 // as part of the expression", it can then still be determined to be invalid
572 // by later processing.
574 #define EXBITS(a,b,c,d,e,f,g,h) \
575 ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
576 BC_PARSE_EXPRS_BITS = 0 // corresponding BC_LEX_xyz:
577 + (EXBITS(0,0,0,0,0,1,1,1) << (0*8)) // 0: EOF INVAL NL WS STR NAME NUM -
578 + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: == <= >= != < > ^ *
579 + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: / % + - ! || && ^=
580 + (EXBITS(1,1,1,1,1,1,1,1) << (3*8)) // 24: *= /= %= += -= = ++ --
581 + (EXBITS(1,1,0,0,0,0,0,0) << (4*8)) // 32: ( ) [ , ] { ; }
582 + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
583 + (EXBITS(1,0,1,1,0,0,0,1) << (6*8)) // 48: obase if last length limits print quit read
584 + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
587 static ALWAYS_INLINE long lex_allowed_in_bc_expr(unsigned i)
589 #if ULONG_MAX > 0xffffffff
590 // 64-bit version (will not work correctly for 32-bit longs!)
591 return BC_PARSE_EXPRS_BITS & (1UL << i);
594 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
596 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
599 return m & (1UL << i);
603 // This is an array of data for operators that correspond to
604 // [XC_LEX_1st_op...] token types.
605 static const uint8_t bc_ops_prec_and_assoc[] ALIGN1 = {
606 #define OP(p,l) ((int)(l) * 0x10 + (p))
608 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
610 OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
611 OP(4, true ), OP( 4, true ), // + -
613 OP(7, true ), OP( 7, true ), // or and
614 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
615 OP(5, false), OP( 5, false ), // -= =
616 OP(0, false), OP( 0, false ), // inc dec
619 #define bc_operation_PREC(i) (bc_ops_prec_and_assoc[i] & 0x0f)
620 #define bc_operation_LEFT(i) (bc_ops_prec_and_assoc[i] & 0x10)
624 static const //BcLexType - should be this type
626 dc_char_to_LEX[] ALIGN1 = {
628 XC_LEX_OP_MODULUS, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_LPAREN,
630 XC_LEX_INVALID, XC_LEX_OP_MULTIPLY, XC_LEX_OP_PLUS, XC_LEX_INVALID,
632 XC_LEX_OP_MINUS, XC_LEX_INVALID, XC_LEX_OP_DIVIDE,
634 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
635 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
636 XC_LEX_INVALID, XC_LEX_INVALID,
638 DC_LEX_COLON, DC_LEX_SCOLON, XC_LEX_OP_REL_GT, XC_LEX_OP_REL_EQ,
639 XC_LEX_OP_REL_LT, DC_LEX_READ, XC_LEX_INVALID,
641 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
642 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_EQ_NO_REG, XC_LEX_INVALID,
644 DC_LEX_IBASE, XC_LEX_INVALID, DC_LEX_SCALE, DC_LEX_LOAD_POP,
645 XC_LEX_INVALID, DC_LEX_OP_BOOL_NOT, DC_LEX_OBASE, DC_LEX_PRINT_STREAM,
647 DC_LEX_NQUIT, DC_LEX_POP, DC_LEX_STORE_PUSH, XC_LEX_INVALID,
648 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_SCALE_FACTOR,
650 XC_LEX_INVALID, DC_LEX_LENGTH,
652 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
654 XC_LEX_OP_POWER, XC_LEX_NEG, XC_LEX_INVALID,
656 DC_LEX_ASCIIFY, XC_LEX_INVALID, DC_LEX_CLEAR_STACK, DC_LEX_DUPLICATE,
657 DC_LEX_ELSE, DC_LEX_PRINT_STACK, XC_LEX_INVALID, XC_LEX_INVALID,
659 DC_LEX_STORE_IBASE, XC_LEX_INVALID, DC_LEX_STORE_SCALE, DC_LEX_LOAD,
660 XC_LEX_INVALID, DC_LEX_PRINT_POP, DC_LEX_STORE_OBASE, DC_LEX_PRINT,
662 DC_LEX_QUIT, DC_LEX_SWAP, DC_LEX_OP_ASSIGN, XC_LEX_INVALID,
663 XC_LEX_INVALID, DC_LEX_SQRT, XC_LEX_INVALID, DC_LEX_EXECUTE,
665 XC_LEX_INVALID, DC_LEX_STACK_LEVEL,
667 DC_LEX_LBRACE, DC_LEX_OP_MODEXP, XC_LEX_INVALID, DC_LEX_OP_DIVMOD,
669 static const //BcInst - should be this type. Using signed narrow type since DC_INST_INVALID is -1
671 dc_LEX_to_INST[] ALIGN1 = { //starts at XC_LEX_OP_POWER // corresponding XC/DC_LEX_xyz:
672 XC_INST_POWER, XC_INST_MULTIPLY, // XC_LEX_OP_POWER XC_LEX_OP_MULTIPLY
673 XC_INST_DIVIDE, XC_INST_MODULUS, // XC_LEX_OP_DIVIDE XC_LEX_OP_MODULUS
674 XC_INST_PLUS, XC_INST_MINUS, // XC_LEX_OP_PLUS XC_LEX_OP_MINUS
675 XC_INST_BOOL_NOT, // DC_LEX_OP_BOOL_NOT
676 DC_INST_INVALID, // DC_LEX_OP_ASSIGN
677 XC_INST_REL_GT, // DC_LEX_LPAREN
678 DC_INST_INVALID, // DC_LEX_SCOLON
679 DC_INST_INVALID, // DC_LEX_READ
680 XC_INST_IBASE, // DC_LEX_IBASE
681 XC_INST_SCALE, // DC_LEX_SCALE
682 XC_INST_OBASE, // DC_LEX_OBASE
683 XC_INST_LENGTH, // DC_LEX_LENGTH
684 XC_INST_PRINT, // DC_LEX_PRINT
685 DC_INST_QUIT, // DC_LEX_QUIT
686 XC_INST_SQRT, // DC_LEX_SQRT
687 XC_INST_REL_GE, // DC_LEX_LBRACE
688 XC_INST_REL_EQ, // DC_LEX_EQ_NO_REG
689 DC_INST_MODEXP, DC_INST_DIVMOD, // DC_LEX_OP_MODEXP DC_LEX_OP_DIVMOD
690 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_COLON DC_LEX_ELSE
691 DC_INST_EXECUTE, // DC_LEX_EXECUTE
692 DC_INST_PRINT_STACK, DC_INST_CLEAR_STACK, // DC_LEX_PRINT_STACK DC_LEX_CLEAR_STACK
693 DC_INST_STACK_LEN, DC_INST_DUPLICATE, // DC_LEX_STACK_LEVEL DC_LEX_DUPLICATE
694 DC_INST_SWAP, XC_INST_POP, // DC_LEX_SWAP DC_LEX_POP
695 DC_INST_ASCIIFY, DC_INST_PRINT_STREAM, // DC_LEX_ASCIIFY DC_LEX_PRINT_STREAM
696 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_IBASE DC_LEX_STORE_OBASE
697 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_SCALE DC_LEX_LOAD
698 DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_LOAD_POP DC_LEX_STORE_PUSH
699 XC_INST_PRINT, DC_INST_NQUIT, // DC_LEX_PRINT_POP DC_LEX_NQUIT
700 XC_INST_SCALE_FUNC, // DC_LEX_SCALE_FACTOR
701 // DC_INST_INVALID in this table either means that corresponding LEX
702 // is not possible for dc, or that it does not compile one-to-one
707 typedef struct BcParse {
708 smallint lex; // was BcLexType // first member is most used
709 smallint lex_last; // was BcLexType
711 const char *lex_inbuf;
712 const char *lex_next_at; // last lex_next() was called at this string
713 const char *lex_filename;
719 IF_BC(size_t in_funcdef;)
725 typedef struct BcProgram {
754 BcParse prs; // first member is most used
756 // For error messages. Can be set to current parsed line,
757 // or [TODO] to current executing line (can be before last parsed one)
762 IF_FEATURE_BC_INTERACTIVE(smallint ttyin;)
763 IF_FEATURE_CLEAN_UP(smallint exiting;)
771 #if ENABLE_FEATURE_EDITING
772 line_input_t *line_input_state;
775 #define G (*ptr_to_globals)
776 #define INIT_G() do { \
777 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
779 #define FREE_G() do { \
780 FREE_PTR_TO_GLOBALS(); \
782 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
783 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
784 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
785 #if ENABLE_FEATURE_BC_INTERACTIVE
786 # define G_interrupt bb_got_signal
787 # define G_ttyin G.ttyin
789 # define G_interrupt 0
792 #if ENABLE_FEATURE_CLEAN_UP
793 # define G_exiting G.exiting
797 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
798 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
801 # define BC_PARSE_REL (1 << 0)
802 # define BC_PARSE_PRINT (1 << 1)
803 # define BC_PARSE_ARRAY (1 << 2)
804 # define BC_PARSE_NOCALL (1 << 3)
807 #define BC_PROG_MAIN 0
808 #define BC_PROG_READ 1
810 #define BC_PROG_REQ_FUNCS 2
813 #define BC_FLAG_W (1 << 0)
814 #define BC_FLAG_V (1 << 1)
815 #define BC_FLAG_S (1 << 2)
816 #define BC_FLAG_Q (1 << 3)
817 #define BC_FLAG_L (1 << 4)
818 #define BC_FLAG_I ((1 << 5) * ENABLE_DC)
819 #define DC_FLAG_X ((1 << 6) * ENABLE_DC)
821 #define BC_MAX_OBASE ((unsigned) 999)
822 #define BC_MAX_DIM ((unsigned) INT_MAX)
823 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
824 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
825 #define BC_MAX_NUM BC_MAX_STRING
826 // Unused apart from "limits" message. Just show a "biggish number" there.
827 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
828 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
829 #define BC_MAX_EXP_STR "999999999"
830 #define BC_MAX_VARS_STR "999999999"
832 #define BC_MAX_OBASE_STR "999"
834 #if INT_MAX == 2147483647
835 # define BC_MAX_DIM_STR "2147483647"
836 #elif INT_MAX == 9223372036854775807
837 # define BC_MAX_DIM_STR "9223372036854775807"
839 # error Strange INT_MAX
842 #if UINT_MAX == 4294967295
843 # define BC_MAX_SCALE_STR "4294967295"
844 # define BC_MAX_STRING_STR "4294967294"
845 #elif UINT_MAX == 18446744073709551615
846 # define BC_MAX_SCALE_STR "18446744073709551615"
847 # define BC_MAX_STRING_STR "18446744073709551614"
849 # error Strange UINT_MAX
851 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
853 // In configurations where errors abort instead of propagating error
854 // return code up the call chain, functions returning BC_STATUS
855 // actually don't return anything, they always succeed and return "void".
856 // A macro wrapper is provided, which makes this statement work:
858 // and makes it visible to the compiler that s is always zero,
859 // allowing compiler to optimize dead code after the statement.
861 // To make code more readable, each such function has a "z"
862 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
864 #if ENABLE_FEATURE_BC_INTERACTIVE || ENABLE_FEATURE_CLEAN_UP
865 # define ERRORS_ARE_FATAL 0
866 # define ERRORFUNC /*nothing*/
867 # define IF_ERROR_RETURN_POSSIBLE(a) a
868 # define BC_STATUS BcStatus
869 # define RETURN_STATUS(v) return (v)
870 # define COMMA_SUCCESS /*nothing*/
872 # define ERRORS_ARE_FATAL 1
873 # define ERRORFUNC NORETURN
874 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
875 # define BC_STATUS void
876 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
877 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
884 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
885 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
887 static void fflush_and_check(void)
890 if (ferror(stdout) || ferror(stderr))
891 bb_perror_msg_and_die("output error");
894 #if ENABLE_FEATURE_CLEAN_UP
895 #define QUIT_OR_RETURN_TO_MAIN \
897 IF_FEATURE_BC_INTERACTIVE(G_ttyin = 0;) /* do not loop in main loop anymore */ \
899 return BC_STATUS_FAILURE; \
902 static void quit(void) NORETURN;
903 static void quit(void)
906 bb_perror_msg_and_die("input error");
908 dbg_exec("quit(): exiting with exitcode SUCCESS");
911 #define QUIT_OR_RETURN_TO_MAIN quit()
914 static void bc_verror_msg(const char *fmt, va_list p)
916 const char *sv = sv; // for compiler
917 if (G.prs.lex_filename) {
919 applet_name = xasprintf("%s: %s:%lu", applet_name,
920 G.prs.lex_filename, (unsigned long)G.err_line
923 bb_verror_msg(fmt, p, NULL);
924 if (G.prs.lex_filename) {
925 free((char*)applet_name);
930 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
935 bc_verror_msg(fmt, p);
938 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
939 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
944 static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
948 // Are non-POSIX constructs totally ok?
949 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
950 RETURN_STATUS(BC_STATUS_SUCCESS); // yes
953 bc_verror_msg(fmt, p);
956 // Do we treat non-POSIX constructs as errors?
957 if (!(option_mask32 & BC_FLAG_S))
958 RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
960 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
961 RETURN_STATUS(BC_STATUS_FAILURE);
964 #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
967 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
968 // This idiom begs for tail-call optimization, but for it to work,
969 // function must not have caller-cleaned parameters on stack.
970 // Unfortunately, vararg function API does exactly that on most arches.
971 // Thus, use these shims for the cases when we have no vararg PARAMS:
972 static ERRORFUNC int bc_error(const char *msg)
974 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
976 static ERRORFUNC int bc_error_at(const char *msg)
978 const char *err_at = G.prs.lex_next_at;
980 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt(
983 (int)(strchrnul(err_at, '\n') - err_at),
987 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
989 static ERRORFUNC int bc_error_bad_character(char c)
992 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
993 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
995 static ERRORFUNC int bc_error_bad_function_definition(void)
997 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad function definition");
999 static ERRORFUNC int bc_error_bad_expression(void)
1001 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad expression");
1003 static ERRORFUNC int bc_error_bad_assignment(void)
1005 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at(
1006 "bad assignment: left side must be variable or array element"
1009 static ERRORFUNC int bc_error_bad_token(void)
1011 IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad token");
1013 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1015 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1017 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1019 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1022 static BC_STATUS zbc_POSIX_requires(const char *msg)
1024 RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
1026 #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
1027 static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
1029 RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
1031 #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
1032 static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1034 RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; this is bad:", msg));
1036 #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)
1037 static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1039 RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in 'for()'", "POSIX does not allow ", msg));
1041 #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)
1044 static void bc_vec_grow(BcVec *v, size_t n)
1046 size_t cap = v->cap * 2;
1047 while (cap < v->len + n) cap *= 2;
1048 v->v = xrealloc(v->v, v->size * cap);
1052 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1055 v->cap = BC_VEC_START_CAP;
1058 v->v = xmalloc(esize * BC_VEC_START_CAP);
1061 static void bc_char_vec_init(BcVec *v)
1063 bc_vec_init(v, sizeof(char), NULL);
1066 static void bc_vec_expand(BcVec *v, size_t req)
1069 v->v = xrealloc(v->v, v->size * req);
1074 static void bc_vec_pop(BcVec *v)
1078 v->dtor(v->v + (v->size * v->len));
1081 static void bc_vec_npop(BcVec *v, size_t n)
1086 size_t len = v->len - n;
1087 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1091 static void bc_vec_pop_all(BcVec *v)
1093 bc_vec_npop(v, v->len);
1096 static size_t bc_vec_push(BcVec *v, const void *data)
1098 size_t len = v->len;
1099 if (len >= v->cap) bc_vec_grow(v, 1);
1100 memmove(v->v + (v->size * len), data, v->size);
1105 // G.prog.results often needs "pop old operand, push result" idiom.
1106 // Can do this without a few extra ops
1107 static size_t bc_result_pop_and_push(const void *data)
1109 BcVec *v = &G.prog.results;
1111 size_t len = v->len - 1;
1113 last = v->v + (v->size * len);
1116 memmove(last, data, v->size);
1120 static size_t bc_vec_pushByte(BcVec *v, char data)
1122 return bc_vec_push(v, &data);
1125 static size_t bc_vec_pushZeroByte(BcVec *v)
1127 //return bc_vec_pushByte(v, '\0');
1129 return bc_vec_push(v, &const_int_0);
1132 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1135 bc_vec_push(v, data);
1139 if (v->len == v->cap) bc_vec_grow(v, 1);
1141 ptr = v->v + v->size * idx;
1143 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1144 memmove(ptr, data, v->size);
1148 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1151 bc_vec_expand(v, len + 1);
1152 memcpy(v->v, str, len);
1155 bc_vec_pushZeroByte(v);
1158 static void *bc_vec_item(const BcVec *v, size_t idx)
1160 return v->v + v->size * idx;
1163 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1165 return v->v + v->size * (v->len - idx - 1);
1168 static void *bc_vec_top(const BcVec *v)
1170 return v->v + v->size * (v->len - 1);
1173 static FAST_FUNC void bc_vec_free(void *vec)
1175 BcVec *v = (BcVec *) vec;
1180 static BcFunc* xc_program_func(size_t idx)
1182 return bc_vec_item(&G.prog.fns, idx);
1184 // BC_PROG_MAIN is zeroth element, so:
1185 #define xc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1188 static BcFunc* bc_program_current_func(void)
1190 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1191 BcFunc *func = xc_program_func(ip->func);
1196 static char** xc_program_str(size_t idx)
1200 BcFunc *func = bc_program_current_func();
1201 return bc_vec_item(&func->strs, idx);
1204 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1207 static char** xc_program_const(size_t idx)
1211 BcFunc *func = bc_program_current_func();
1212 return bc_vec_item(&func->consts, idx);
1215 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1218 static int bc_id_cmp(const void *e1, const void *e2)
1220 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1223 static FAST_FUNC void bc_id_free(void *id)
1225 free(((BcId *) id)->name);
1228 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1230 size_t low = 0, high = v->len;
1232 while (low < high) {
1233 size_t mid = (low + high) / 2;
1234 BcId *id = bc_vec_item(v, mid);
1235 int result = bc_id_cmp(ptr, id);
1248 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1250 size_t n = *i = bc_map_find_ge(v, ptr);
1253 bc_vec_push(v, ptr);
1254 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1255 return 0; // "was not inserted"
1257 bc_vec_pushAt(v, ptr, n);
1258 return 1; // "was inserted"
1262 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1264 size_t i = bc_map_find_ge(v, ptr);
1265 if (i >= v->len) return BC_VEC_INVALID_IDX;
1266 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1270 static void bc_num_setToZero(BcNum *n, size_t scale)
1277 static void bc_num_zero(BcNum *n)
1279 bc_num_setToZero(n, 0);
1282 static void bc_num_one(BcNum *n)
1284 bc_num_setToZero(n, 0);
1289 // Note: this also sets BcNum to zero
1290 static void bc_num_init(BcNum *n, size_t req)
1292 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1293 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1294 n->num = xmalloc(req);
1301 static void bc_num_init_DEF_SIZE(BcNum *n)
1303 bc_num_init(n, BC_NUM_DEF_SIZE);
1306 static void bc_num_expand(BcNum *n, size_t req)
1308 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1310 n->num = xrealloc(n->num, req);
1315 static FAST_FUNC void bc_num_free(void *num)
1317 free(((BcNum *) num)->num);
1320 static void bc_num_copy(BcNum *d, BcNum *s)
1323 bc_num_expand(d, s->cap);
1327 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1331 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1334 unsigned long result;
1338 while (i > n->rdx) {
1339 unsigned long prev = result;
1340 result = result * 10 + n->num[--i];
1341 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1342 // 0x1ff00000 * 10 is 0x13f600000,
1343 // or 0x3f600000 truncated to 32 bits. Which is larger.
1344 // However, (N*10)/8 < N check is always correct.
1345 if ((result / 8) < prev)
1346 RETURN_STATUS(bc_error("overflow"));
1350 RETURN_STATUS(BC_STATUS_SUCCESS);
1352 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1354 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1356 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1358 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1360 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1362 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1363 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1364 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1365 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1367 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1368 // would not hit realloc() code path - not good if num[] is not malloced
1370 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1376 if (val == 0) return;
1378 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1385 if (val == 0) break;
1389 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1392 for (i = 0; i < len; ++i) {
1394 for (j = i; a[j] < 0;) {
1401 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1419 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1420 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1421 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1422 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1423 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1425 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1427 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1428 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1430 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1433 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1435 size_t i, min, a_int, b_int, diff;
1436 BcDig *max_num, *min_num;
1440 if (a == b) return 0;
1441 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1442 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1444 if (a->neg != b->neg) // signs of a and b differ
1445 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1446 return (int)b->neg - (int)a->neg;
1447 neg = a->neg; // 1 if both negative, 0 if both positive
1449 a_int = BC_NUM_INT(a);
1450 b_int = BC_NUM_INT(b);
1453 if (a_int != 0) return (ssize_t) a_int;
1455 a_max = (a->rdx > b->rdx);
1458 diff = a->rdx - b->rdx;
1459 max_num = a->num + diff;
1461 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1464 diff = b->rdx - a->rdx;
1465 max_num = b->num + diff;
1467 neg = !neg; // same as "neg = (a_max == neg)"
1470 cmp = bc_num_compare(max_num, min_num, b_int + min);
1471 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1473 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1474 if (max_num[i]) return BC_NUM_NEG(1, neg);
1480 static void bc_num_truncate(BcNum *n, size_t places)
1482 if (places == 0) return;
1488 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1492 static void bc_num_extend(BcNum *n, size_t places)
1494 size_t len = n->len + places;
1497 if (n->cap < len) bc_num_expand(n, len);
1499 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1500 memset(n->num, 0, sizeof(BcDig) * places);
1507 static void bc_num_clean(BcNum *n)
1509 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1512 else if (n->len < n->rdx)
1516 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1519 bc_num_extend(n, scale - n->rdx);
1521 bc_num_truncate(n, n->rdx - scale);
1524 if (n->len != 0) n->neg = !neg1 != !neg2;
1527 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1531 b->len = n->len - idx;
1533 a->rdx = b->rdx = 0;
1535 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1536 memcpy(a->num, n->num, idx * sizeof(BcDig));
1546 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1548 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1550 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1551 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1552 if (places + n->len > BC_MAX_NUM)
1553 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1556 if (n->rdx >= places)
1559 bc_num_extend(n, places - n->rdx);
1565 RETURN_STATUS(BC_STATUS_SUCCESS);
1567 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1569 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1571 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1572 BcNumBinaryOp op, size_t req)
1575 BcNum num2, *ptr_a, *ptr_b;
1580 memcpy(ptr_a, c, sizeof(BcNum));
1588 memcpy(ptr_b, c, sizeof(BcNum));
1595 bc_num_init(c, req);
1597 bc_num_expand(c, req);
1599 s = BC_STATUS_SUCCESS;
1600 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1602 if (init) bc_num_free(&num2);
1606 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1608 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1609 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1610 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1611 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1612 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1613 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1615 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1617 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1619 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1622 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1624 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1626 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1629 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1631 size_t req = BC_NUM_MREQ(a, b, scale);
1632 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1635 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1637 size_t req = BC_NUM_MREQ(a, b, scale);
1638 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1641 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1643 size_t req = BC_NUM_MREQ(a, b, scale);
1644 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1647 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1649 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1652 static const BcNumBinaryOp zxc_program_ops[] = {
1653 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1655 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1656 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1657 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1658 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1659 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1660 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1662 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1671 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1673 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1675 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1677 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1678 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1681 // Because this function doesn't need to use scale (per the bc spec),
1682 // I am hijacking it to say whether it's doing an add or a subtract.
1686 if (sub && c->len) c->neg = !c->neg;
1687 RETURN_STATUS(BC_STATUS_SUCCESS);
1691 RETURN_STATUS(BC_STATUS_SUCCESS);
1695 c->rdx = BC_MAX(a->rdx, b->rdx);
1696 min_rdx = BC_MIN(a->rdx, b->rdx);
1699 if (a->rdx > b->rdx) {
1700 diff = a->rdx - b->rdx;
1702 ptr_a = a->num + diff;
1705 diff = b->rdx - a->rdx;
1708 ptr_b = b->num + diff;
1712 for (i = 0; i < diff; ++i, ++c->len)
1716 a_int = BC_NUM_INT(a);
1717 b_int = BC_NUM_INT(b);
1719 if (a_int > b_int) {
1730 for (i = 0; i < min_rdx + min_int; ++i) {
1731 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1733 ptr_c[i] = (BcDig)(in % 10);
1735 for (; i < max + min_rdx; ++i) {
1736 unsigned in = (unsigned)ptr[i] + carry;
1738 ptr_c[i] = (BcDig)(in % 10);
1742 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1744 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1747 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1750 BcNum *minuend, *subtrahend;
1752 bool aneg, bneg, neg;
1754 // Because this function doesn't need to use scale (per the bc spec),
1755 // I am hijacking it to say whether it's doing an add or a subtract.
1759 if (sub && c->len) c->neg = !c->neg;
1760 RETURN_STATUS(BC_STATUS_SUCCESS);
1764 RETURN_STATUS(BC_STATUS_SUCCESS);
1769 a->neg = b->neg = false;
1771 cmp = bc_num_cmp(a, b);
1777 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1778 RETURN_STATUS(BC_STATUS_SUCCESS);
1786 if (sub) neg = !neg;
1791 bc_num_copy(c, minuend);
1794 if (c->rdx < subtrahend->rdx) {
1795 bc_num_extend(c, subtrahend->rdx - c->rdx);
1798 start = c->rdx - subtrahend->rdx;
1800 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1804 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1807 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1809 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1812 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1813 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1816 if (a->len == 0 || b->len == 0) {
1818 RETURN_STATUS(BC_STATUS_SUCCESS);
1820 aone = BC_NUM_ONE(a);
1821 if (aone || BC_NUM_ONE(b)) {
1822 bc_num_copy(c, aone ? b : a);
1823 RETURN_STATUS(BC_STATUS_SUCCESS);
1826 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1827 || a->len < BC_NUM_KARATSUBA_LEN
1828 || b->len < BC_NUM_KARATSUBA_LEN
1832 bc_num_expand(c, a->len + b->len + 1);
1834 memset(c->num, 0, sizeof(BcDig) * c->cap);
1837 for (i = 0; i < b->len; ++i) {
1839 for (j = 0; j < a->len; ++j) {
1840 unsigned in = c->num[i + j];
1841 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1842 // note: compilers prefer _unsigned_ div/const
1844 c->num[i + j] = (BcDig)(in % 10);
1847 c->num[i + j] += (BcDig) carry;
1848 len = BC_MAX(len, i + j + !!carry);
1850 #if ENABLE_FEATURE_BC_INTERACTIVE
1852 // a*a <- without check below, this will not be interruptible
1853 if (G_interrupt) return BC_STATUS_FAILURE;
1859 RETURN_STATUS(BC_STATUS_SUCCESS);
1862 bc_num_init(&l1, max);
1863 bc_num_init(&h1, max);
1864 bc_num_init(&l2, max);
1865 bc_num_init(&h2, max);
1866 bc_num_init(&m1, max);
1867 bc_num_init(&m2, max);
1868 bc_num_init(&z0, max);
1869 bc_num_init(&z1, max);
1870 bc_num_init(&z2, max);
1871 bc_num_init(&temp, max + max);
1873 bc_num_split(a, max2, &l1, &h1);
1874 bc_num_split(b, max2, &l2, &h2);
1876 s = zbc_num_add(&h1, &l1, &m1, 0);
1878 s = zbc_num_add(&h2, &l2, &m2, 0);
1881 s = zbc_num_k(&h1, &h2, &z0);
1883 s = zbc_num_k(&m1, &m2, &z1);
1885 s = zbc_num_k(&l1, &l2, &z2);
1888 s = zbc_num_sub(&z1, &z0, &temp, 0);
1890 s = zbc_num_sub(&temp, &z2, &z1, 0);
1893 s = zbc_num_shift(&z0, max2 * 2);
1895 s = zbc_num_shift(&z1, max2);
1897 s = zbc_num_add(&z0, &z1, &temp, 0);
1899 s = zbc_num_add(&temp, &z2, c, 0);
1914 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1918 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1920 scale = BC_MAX(scale, a->rdx);
1921 scale = BC_MAX(scale, b->rdx);
1922 scale = BC_MIN(a->rdx + b->rdx, scale);
1923 maxrdx = BC_MAX(maxrdx, scale);
1925 bc_num_init(&cpa, a->len);
1926 bc_num_init(&cpb, b->len);
1928 bc_num_copy(&cpa, a);
1929 bc_num_copy(&cpb, b);
1930 cpa.neg = cpb.neg = false;
1932 s = zbc_num_shift(&cpa, maxrdx);
1934 s = zbc_num_shift(&cpb, maxrdx);
1936 s = zbc_num_k(&cpa, &cpb, c);
1940 bc_num_expand(c, c->len + maxrdx);
1942 if (c->len < maxrdx) {
1943 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1948 bc_num_retireMul(c, scale, a->neg, b->neg);
1954 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1956 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1963 RETURN_STATUS(bc_error("divide by zero"));
1965 bc_num_setToZero(c, scale);
1966 RETURN_STATUS(BC_STATUS_SUCCESS);
1968 if (BC_NUM_ONE(b)) {
1970 bc_num_retireMul(c, scale, a->neg, b->neg);
1971 RETURN_STATUS(BC_STATUS_SUCCESS);
1974 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1975 bc_num_copy(&cp, a);
1979 bc_num_expand(&cp, len + 2);
1980 bc_num_extend(&cp, len - cp.len);
1983 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1985 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1987 if (b->rdx == b->len) {
1989 if (len == 0) break;
1991 if (b->num[len] != 0)
1997 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1999 // We want an extra zero in front to make things simpler.
2000 cp.num[cp.len++] = 0;
2003 bc_num_expand(c, cp.len);
2006 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2010 s = BC_STATUS_SUCCESS;
2011 for (i = end - 1; i < end; --i) {
2014 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2015 bc_num_subArrays(n, b->num, len);
2017 #if ENABLE_FEATURE_BC_INTERACTIVE
2020 // 1/a <- without check below, this will not be interruptible
2022 s = BC_STATUS_FAILURE;
2028 bc_num_retireMul(c, scale, a->neg, b->neg);
2033 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2035 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2036 BcNum *restrict d, size_t scale, size_t ts)
2043 RETURN_STATUS(bc_error("divide by zero"));
2046 bc_num_setToZero(d, ts);
2047 RETURN_STATUS(BC_STATUS_SUCCESS);
2050 bc_num_init(&temp, d->cap);
2051 s = zbc_num_d(a, b, c, scale);
2054 if (scale != 0) scale = ts;
2056 s = zbc_num_m(c, b, &temp, scale);
2058 s = zbc_num_sub(a, &temp, d, scale);
2061 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2064 bc_num_retireMul(d, ts, a->neg, b->neg);
2070 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2072 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2076 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2078 bc_num_init(&c1, len);
2079 s = zbc_num_r(a, b, &c1, c, scale, ts);
2084 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2086 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2088 BcStatus s = BC_STATUS_SUCCESS;
2091 size_t i, powrdx, resrdx;
2094 // GNU bc does not allow 2^2.0 - we do
2095 for (i = 0; i < b->rdx; i++)
2097 RETURN_STATUS(bc_error("not an integer"));
2101 RETURN_STATUS(BC_STATUS_SUCCESS);
2104 bc_num_setToZero(c, scale);
2105 RETURN_STATUS(BC_STATUS_SUCCESS);
2107 if (BC_NUM_ONE(b)) {
2111 s = zbc_num_inv(a, c, scale);
2116 s = zbc_num_ulong_abs(b, &pow);
2117 if (s) RETURN_STATUS(s);
2118 // b is not used beyond this point
2120 bc_num_init(©, a->len);
2121 bc_num_copy(©, a);
2126 if (a->rdx * pow < scale)
2127 scale = a->rdx * pow;
2131 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2133 s = zbc_num_mul(©, ©, ©, powrdx);
2135 // Not needed: zbc_num_mul() has a check for ^C:
2136 //if (G_interrupt) {
2137 // s = BC_STATUS_FAILURE;
2142 bc_num_copy(c, ©);
2144 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2146 s = zbc_num_mul(©, ©, ©, powrdx);
2151 s = zbc_num_mul(c, ©, c, resrdx);
2154 // Not needed: zbc_num_mul() has a check for ^C:
2155 //if (G_interrupt) {
2156 // s = BC_STATUS_FAILURE;
2162 s = zbc_num_inv(c, c, scale);
2166 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2168 // We can't use bc_num_clean() here.
2169 for (i = 0; i < c->len; ++i)
2172 bc_num_setToZero(c, scale);
2179 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2181 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2184 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2186 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2187 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2189 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2190 bc_num_expand(b, req);
2193 bc_num_setToZero(b, scale);
2194 RETURN_STATUS(BC_STATUS_SUCCESS);
2197 RETURN_STATUS(bc_error("negative number"));
2199 if (BC_NUM_ONE(a)) {
2201 bc_num_extend(b, scale);
2202 RETURN_STATUS(BC_STATUS_SUCCESS);
2205 scale = BC_MAX(scale, a->rdx) + 1;
2206 len = a->len + scale;
2208 bc_num_init(&num1, len);
2209 bc_num_init(&num2, len);
2211 half.cap = ARRAY_SIZE(half_digs);
2212 half.num = half_digs;
2217 bc_num_init(&f, len);
2218 bc_num_init(&fprime, len);
2224 pow = BC_NUM_INT(a);
2232 pow -= 2 - (pow & 1);
2234 bc_num_extend(x0, pow);
2236 // Make sure to move the radix back.
2240 x0->rdx = digs = digs1 = 0;
2242 len = BC_NUM_INT(x0) + resrdx - 1;
2244 while (cmp != 0 || digs < len) {
2245 s = zbc_num_div(a, x0, &f, resrdx);
2247 s = zbc_num_add(x0, &f, &fprime, resrdx);
2249 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2252 cmp = bc_num_cmp(x1, x0);
2253 digs = x1->len - (unsigned long long) llabs(cmp);
2255 if (cmp == cmp2 && digs == digs1)
2260 resrdx += times > 4;
2273 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2275 bc_num_free(&fprime);
2281 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2283 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2289 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2292 memcpy(&num2, c, sizeof(BcNum));
2294 bc_num_init(c, len);
2298 bc_num_expand(c, len);
2301 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2303 if (init) bc_num_free(&num2);
2307 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2310 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2313 BcNum base, exp, two, temp;
2317 RETURN_STATUS(bc_error("divide by zero"));
2318 if (a->rdx || b->rdx || c->rdx)
2319 RETURN_STATUS(bc_error("not an integer"));
2321 RETURN_STATUS(bc_error("negative number"));
2323 bc_num_expand(d, c->len);
2324 bc_num_init(&base, c->len);
2325 bc_num_init(&exp, b->len);
2326 bc_num_init(&temp, b->len);
2328 two.cap = ARRAY_SIZE(two_digs);
2335 s = zbc_num_rem(a, c, &base, 0);
2337 bc_num_copy(&exp, b);
2339 while (exp.len != 0) {
2340 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2343 if (BC_NUM_ONE(&temp)) {
2344 s = zbc_num_mul(d, &base, &temp, 0);
2346 s = zbc_num_rem(&temp, c, d, 0);
2350 s = zbc_num_mul(&base, &base, &temp, 0);
2352 s = zbc_num_rem(&temp, c, &base, 0);
2361 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2364 static FAST_FUNC void bc_string_free(void *string)
2366 free(*(char**)string);
2369 static void bc_func_init(BcFunc *f)
2371 bc_char_vec_init(&f->code);
2372 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2373 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2374 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2375 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2376 IF_BC(f->nparams = 0;)
2379 static FAST_FUNC void bc_func_free(void *func)
2381 BcFunc *f = (BcFunc *) func;
2382 bc_vec_free(&f->code);
2383 IF_BC(bc_vec_free(&f->labels);)
2384 IF_BC(bc_vec_free(&f->autos);)
2385 IF_BC(bc_vec_free(&f->strs);)
2386 IF_BC(bc_vec_free(&f->consts);)
2389 static void bc_array_expand(BcVec *a, size_t len);
2391 static void bc_array_init(BcVec *a, bool nums)
2394 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2396 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2397 bc_array_expand(a, 1);
2400 static void bc_array_expand(BcVec *a, size_t len)
2402 if (a->dtor == bc_num_free
2403 // && a->size == sizeof(BcNum) - always true
2406 while (len > a->len) {
2407 bc_num_init_DEF_SIZE(&n);
2412 while (len > a->len) {
2413 bc_array_init(&v, true);
2419 static void bc_array_copy(BcVec *d, const BcVec *s)
2425 bc_vec_expand(d, s->cap);
2430 for (i = 0; i < s->len; i++, dnum++, snum++) {
2431 bc_num_init(dnum, snum->len);
2432 bc_num_copy(dnum, snum);
2437 static void dc_result_copy(BcResult *d, BcResult *src)
2442 case XC_RESULT_TEMP:
2443 case XC_RESULT_IBASE:
2444 case XC_RESULT_SCALE:
2445 case XC_RESULT_OBASE:
2446 bc_num_init(&d->d.n, src->d.n.len);
2447 bc_num_copy(&d->d.n, &src->d.n);
2450 case XC_RESULT_ARRAY:
2451 case XC_RESULT_ARRAY_ELEM:
2452 d->d.id.name = xstrdup(src->d.id.name);
2454 case XC_RESULT_CONSTANT:
2456 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2458 default: // placate compiler
2459 // BC_RESULT_VOID, BC_RESULT_LAST, BC_RESULT_ONE - do not happen
2465 static FAST_FUNC void bc_result_free(void *result)
2467 BcResult *r = (BcResult *) result;
2470 case XC_RESULT_TEMP:
2471 IF_BC(case BC_RESULT_VOID:)
2472 case XC_RESULT_IBASE:
2473 case XC_RESULT_SCALE:
2474 case XC_RESULT_OBASE:
2475 bc_num_free(&r->d.n);
2478 case XC_RESULT_ARRAY:
2479 case XC_RESULT_ARRAY_ELEM:
2488 static int bad_input_byte(char c)
2490 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2493 bc_error_fmt("illegal character 0x%02x", c);
2499 static void xc_read_line(BcVec *vec, FILE *fp)
2502 bc_vec_pop_all(vec);
2505 #if ENABLE_FEATURE_BC_INTERACTIVE
2506 if (G_interrupt) { // ^C was pressed
2509 // ^C while running a script (bc SCRIPT): die.
2510 // We do not return to interactive prompt:
2511 // user might be running us from a shell,
2512 // and SCRIPT might be intended to terminate
2513 // (e.g. contain a "halt" stmt).
2514 // ^C dropping user into a bc prompt instead of
2515 // the shell would be unexpected.
2518 // ^C while interactive input
2520 // GNU bc says "interrupted execution."
2521 // GNU dc says "Interrupt!"
2522 fputs("\ninterrupted execution\n", stderr);
2525 # if ENABLE_FEATURE_EDITING
2526 if (G_ttyin && fp == stdin) {
2528 # define line_buf bb_common_bufsiz1
2529 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2530 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2533 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2538 char c = line_buf[i++];
2539 if (c == '\0') break;
2540 if (bad_input_byte(c)) goto again;
2542 bc_vec_string(vec, n, line_buf);
2553 #if ENABLE_FEATURE_BC_INTERACTIVE
2555 // ^C was pressed: ignore entire line, get another one
2564 bb_perror_msg_and_die("input error");
2565 // Note: EOF does not append '\n'
2568 bad_chars |= bad_input_byte(c);
2569 bc_vec_pushByte(vec, (char)c);
2570 } while (c != '\n');
2573 // Bad chars on this line
2574 if (!G.prs.lex_filename) { // stdin
2575 // ignore entire line, get another one
2578 bb_perror_msg_and_die("file '%s' is not text", G.prs.lex_filename);
2580 bc_vec_pushZeroByte(vec);
2588 // "Input numbers may contain the characters 0-9 and A-Z.
2589 // (Note: They must be capitals. Lower case letters are variable names.)
2590 // Single digit numbers always have the value of the digit regardless of
2591 // the value of ibase. (i.e. A = 10.) For multi-digit numbers, bc changes
2592 // all input digits greater or equal to ibase to the value of ibase-1.
2593 // This makes the number ZZZ always be the largest 3 digit number of the
2595 static bool xc_num_strValid(const char *val)
2603 if (radix) return false;
2607 if ((c < '0' || c > '9') && (c < 'A' || c > 'Z'))
2613 // Note: n is already "bc_num_zero()"ed,
2614 // leading zeroes in "val" are removed
2615 static void bc_num_parseDecimal(BcNum *n, const char *val)
2624 bc_num_expand(n, len + 1); // +1 for e.g. "A" converting into 10
2626 ptr = strchr(val, '.');
2630 n->rdx = (size_t)((val + len) - (ptr + 1));
2632 for (i = 0; val[i]; ++i) {
2633 if (val[i] != '0' && val[i] != '.') {
2634 // Not entirely zero value - convert it, and exit
2636 unsigned c = val[0] - '0';
2638 if (c > 9) { // A-Z => 10-36
2640 c -= ('A' - '9' - 1);
2649 char c = val[i] - '0';
2650 if (c > 9) // A-Z => 9
2656 if (val[--i] == '.') goto skip_dot;
2661 // if for() exits without hitting if(), the value is entirely zero
2664 // Note: n is already "bc_num_zero()"ed,
2665 // leading zeroes in "val" are removed
2666 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2672 BcDig temp_digs[ULONG_NUM_BUFSIZE];
2673 BcDig base_digs[ULONG_NUM_BUFSIZE];
2676 bc_num_init_DEF_SIZE(&mult);
2678 temp.cap = ARRAY_SIZE(temp_digs);
2679 temp.num = temp_digs;
2681 base.cap = ARRAY_SIZE(base_digs);
2682 base.num = base_digs;
2683 bc_num_ulong2num(&base, base_t);
2691 if (c == '\0') goto int_err;
2692 if (c == '.') break;
2694 v = (unsigned)(c <= '9' ? c - '0' : c - 'A' + 10);
2695 if (v > base_t) v = base_t;
2697 s = zbc_num_mul(n, &base, &mult, 0);
2698 if (s) goto int_err;
2699 bc_num_ulong2num(&temp, v);
2700 s = zbc_num_add(&mult, &temp, n, 0);
2701 if (s) goto int_err;
2704 bc_num_init(&result, base.len);
2705 //bc_num_zero(&result); - already is
2714 if (c == '\0') break;
2717 v = (unsigned)(c <= '9' ? c - '0' : c - 'A' + 10);
2718 if (v > base_t) v = base_t;
2720 s = zbc_num_mul(&result, &base, &result, 0);
2722 bc_num_ulong2num(&temp, v);
2723 s = zbc_num_add(&result, &temp, &result, 0);
2725 s = zbc_num_mul(&mult, &base, &mult, 0);
2729 s = zbc_num_div(&result, &mult, &result, digits);
2731 s = zbc_num_add(n, &result, n, digits);
2735 if (n->rdx < digits)
2736 bc_num_extend(n, digits - n->rdx);
2740 bc_num_free(&result);
2745 static BC_STATUS zxc_num_parse(BcNum *n, const char *val, unsigned base_t)
2749 if (!xc_num_strValid(val))
2750 RETURN_STATUS(bc_error("bad number string"));
2755 for (i = 0; ; ++i) {
2757 RETURN_STATUS(BC_STATUS_SUCCESS);
2758 if (val[i] != '.' && val[i] != '0')
2762 if (base_t == 10 || val[1] == '\0')
2763 // Decimal, or single-digit number
2764 bc_num_parseDecimal(n, val);
2766 bc_num_parseBase(n, val, base_t);
2768 RETURN_STATUS(BC_STATUS_SUCCESS);
2770 #define zxc_num_parse(...) (zxc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2772 // p->lex_inbuf points to the current string to be parsed.
2773 // if p->lex_inbuf points to '\0', it's either EOF or it points after
2774 // last processed line's terminating '\n' (and more reading needs to be done
2775 // to get next character).
2777 // If you are in a situation where that is a possibility, call peek_inbuf().
2778 // If necessary, it performs more reading and changes p->lex_inbuf,
2779 // then it returns *p->lex_inbuf (which will be '\0' only if it's EOF).
2780 // After it, just referencing *p->lex_inbuf is valid, and if it wasn't '\0',
2781 // it's ok to do p->lex_inbuf++ once without end-of-buffer checking.
2783 // eat_inbuf() is equvalent to "peek_inbuf(); if (c) p->lex_inbuf++":
2784 // it returns current char and advances the pointer (if not EOF).
2785 // After eat_inbuf(), referencing p->lex_inbuf[-1] and *p->lex_inbuf is valid.
2787 // In many cases, you can use fast *p->lex_inbuf instead of peek_inbuf():
2788 // unless prev char might have been '\n', *p->lex_inbuf is '\0' ONLY
2789 // on real EOF, not end-of-buffer.
2791 // bc cases to test interactively:
2792 // 1 #comment\ - prints "1<newline>" at once (comment is not continued)
2793 // 1 #comment/* - prints "1<newline>" at once
2794 // 1 #comment" - prints "1<newline>" at once
2795 // 1\#comment - error at once (\ is not a line continuation)
2796 // 1 + /*"*/2 - prints "3<newline>" at once
2797 // 1 + /*#*/2 - prints "3<newline>" at once
2798 // "str\" - prints "str\" at once
2799 // "str#" - prints "str#" at once
2800 // "str/*" - prints "str/*" at once
2801 // "str#\ - waits for second line
2802 // end" - ...prints "str#\<newline>end"
2803 static char peek_inbuf(void)
2805 if (*G.prs.lex_inbuf == '\0'
2806 && G.prs.lex_input_fp
2808 xc_read_line(&G.input_buffer, G.prs.lex_input_fp);
2809 G.prs.lex_inbuf = G.input_buffer.v;
2810 if (G.input_buffer.len <= 1) // on EOF, len is 1 (NUL byte)
2811 G.prs.lex_input_fp = NULL;
2813 return *G.prs.lex_inbuf;
2815 static char eat_inbuf(void)
2817 char c = peek_inbuf();
2818 if (c) G.prs.lex_inbuf++;
2822 static void xc_lex_lineComment(void)
2824 BcParse *p = &G.prs;
2827 // Try: echo -n '#foo' | bc
2828 p->lex = XC_LEX_WHITESPACE;
2830 // Not peek_inbuf(): we depend on input being done in whole lines:
2831 // '\0' which isn't the EOF can only be seen after '\n'.
2832 while ((c = *p->lex_inbuf) != '\n' && c != '\0')
2836 static void xc_lex_whitespace(void)
2838 BcParse *p = &G.prs;
2840 p->lex = XC_LEX_WHITESPACE;
2842 // We depend here on input being done in whole lines:
2843 // '\0' which isn't the EOF can only be seen after '\n'.
2844 char c = *p->lex_inbuf;
2845 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2853 static BC_STATUS zxc_lex_number(char last)
2855 BcParse *p = &G.prs;
2859 bc_vec_pop_all(&p->lex_strnumbuf);
2860 bc_vec_pushByte(&p->lex_strnumbuf, last);
2862 // bc: "Input numbers may contain the characters 0-9 and A-Z.
2863 // (Note: They must be capitals. Lower case letters are variable names.)
2864 // Single digit numbers always have the value of the digit regardless of
2865 // the value of ibase. (i.e. A = 10.) For multi-digit numbers, bc changes
2866 // all input digits greater or equal to ibase to the value of ibase-1.
2867 // This makes the number ZZZ always be the largest 3 digit number of the
2869 // dc only allows A-F, the rules about single-char and multi-char are the same.
2870 last_valid_ch = (IS_BC ? 'Z' : 'F');
2872 p->lex = XC_LEX_NUMBER;
2874 // We depend here on input being done in whole lines:
2875 // '\0' which isn't the EOF can only be seen after '\n'.
2876 char c = *p->lex_inbuf;
2880 if (c == '\\' && p->lex_inbuf[1] == '\n') {
2883 dbg_lex("++p->lex_line=%zd", p->lex_line);
2884 c = peek_inbuf(); // force next line to be read
2887 if (!isdigit(c) && (c < 'A' || c > last_valid_ch)) {
2888 if (c != '.') break;
2889 // if '.' was already seen, stop on second one:
2893 // c is one of "0-9A-Z."
2895 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
2898 if (last == '.') // remove trailing '.' if any
2899 bc_vec_pop(&p->lex_strnumbuf);
2900 bc_vec_pushZeroByte(&p->lex_strnumbuf);
2902 G.err_line = G.prs.lex_line;
2903 RETURN_STATUS(BC_STATUS_SUCCESS);
2905 #define zxc_lex_number(...) (zxc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2907 static void xc_lex_name(void)
2909 BcParse *p = &G.prs;
2913 p->lex = XC_LEX_NAME;
2915 // Since names can't cross lines with \<newline>,
2916 // we depend on the fact that whole line is in the buffer
2918 buf = p->lex_inbuf - 1;
2921 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2925 #if 0 // We do not protect against people with gigabyte-long names
2926 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2927 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2928 if (i > BC_MAX_STRING)
2929 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2932 bc_vec_string(&p->lex_strnumbuf, i, buf);
2934 // Increment the index. We minus 1 because it has already been incremented.
2935 p->lex_inbuf += i - 1;
2937 //return BC_STATUS_SUCCESS;
2940 IF_BC(static BC_STATUS zbc_lex_token(void);)
2941 IF_DC(static BC_STATUS zdc_lex_token(void);)
2942 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2943 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2945 static BC_STATUS zxc_lex_next(void)
2947 BcParse *p = &G.prs;
2950 G.err_line = p->lex_line;
2951 p->lex_last = p->lex;
2953 // if (p->lex_last == XC_LEX_EOF)
2954 // RETURN_STATUS(bc_error("end of file"));
2956 // Loop until failure or we don't have whitespace. This
2957 // is so the parser doesn't get inundated with whitespace.
2958 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2959 s = BC_STATUS_SUCCESS;
2961 if (*p->lex_inbuf == '\0') {
2962 p->lex = XC_LEX_EOF;
2963 if (peek_inbuf() == '\0')
2964 RETURN_STATUS(BC_STATUS_SUCCESS);
2966 p->lex_next_at = p->lex_inbuf;
2967 dbg_lex("next string to parse:'%.*s'",
2968 (int)(strchrnul(p->lex_next_at, '\n') - p->lex_next_at),
2972 IF_BC(s = zbc_lex_token());
2974 IF_DC(s = zdc_lex_token());
2976 } while (!s && p->lex == XC_LEX_WHITESPACE);
2977 dbg_lex("p->lex from string:%d", p->lex);
2981 #define zxc_lex_next(...) (zxc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
2984 static BC_STATUS zbc_lex_skip_if_at_NLINE(void)
2986 if (G.prs.lex == XC_LEX_NLINE)
2987 RETURN_STATUS(zxc_lex_next());
2988 RETURN_STATUS(BC_STATUS_SUCCESS);
2990 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2992 static BC_STATUS zbc_lex_next_and_skip_NLINE(void)
2996 if (s) RETURN_STATUS(s);
2997 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
2998 s = zbc_lex_skip_if_at_NLINE();
3001 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3003 static BC_STATUS zbc_lex_identifier(void)
3005 BcParse *p = &G.prs;
3008 const char *buf = p->lex_inbuf - 1;
3010 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3011 const char *keyword8 = bc_lex_kws[i].name8;
3013 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3015 if (j == 8) goto match;
3017 if (keyword8[j] != '\0')
3020 // buf starts with keyword bc_lex_kws[i]
3021 if (isalnum(buf[j]) || buf[j]=='_')
3022 continue; // "ifz" does not match "if" keyword, "if." does
3023 p->lex = BC_LEX_KEY_1st_keyword + i;
3024 if (!keyword_is_POSIX(i)) {
3025 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3026 if (s) RETURN_STATUS(s);
3029 // We minus 1 because the index has already been incremented.
3030 p->lex_inbuf += j - 1;
3031 RETURN_STATUS(BC_STATUS_SUCCESS);
3035 s = BC_STATUS_SUCCESS;
3037 if (p->lex_strnumbuf.len > 2) {
3040 // bc: POSIX only allows one character names; this is bad: 'qwe=1
3042 unsigned len = strchrnul(buf, '\n') - buf;
3043 s = zbc_posix_error_fmt("POSIX only allows one character names; this is bad: '%.*s'", len, buf);
3048 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3050 static BC_STATUS zbc_lex_string(void)
3052 BcParse *p = &G.prs;
3054 p->lex = XC_LEX_STR;
3055 bc_vec_pop_all(&p->lex_strnumbuf);
3057 char c = peek_inbuf(); // strings can cross lines
3059 RETURN_STATUS(bc_error("unterminated string"));
3065 dbg_lex("++p->lex_line=%zd", p->lex_line);
3067 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3070 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3073 G.err_line = p->lex_line;
3074 RETURN_STATUS(BC_STATUS_SUCCESS);
3076 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3078 static void parse_lex_by_checking_eq_sign(unsigned with_and_without)
3080 BcParse *p = &G.prs;
3081 if (*p->lex_inbuf == '=') {
3082 // ^^^ not using peek_inbuf() since '==' etc can't be split across lines
3084 with_and_without >>= 8; // store "with" value
3085 } // else store "without" value
3086 p->lex = (with_and_without & 0xff);
3088 #define parse_lex_by_checking_eq_sign(with, without) \
3089 parse_lex_by_checking_eq_sign(((with)<<8)|(without))
3091 static BC_STATUS zbc_lex_comment(void)
3093 BcParse *p = &G.prs;
3095 p->lex = XC_LEX_WHITESPACE;
3096 // here lex_inbuf is at '*' of opening comment delimiter
3105 c = *p->lex_inbuf; // no need to peek_inbuf()
3111 RETURN_STATUS(bc_error("unterminated comment"));
3115 dbg_lex("++p->lex_line=%zd", p->lex_line);
3118 p->lex_inbuf++; // skip trailing '/'
3120 G.err_line = p->lex_line;
3121 RETURN_STATUS(BC_STATUS_SUCCESS);
3123 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3125 #undef zbc_lex_token
3126 static BC_STATUS zbc_lex_token(void)
3128 BcParse *p = &G.prs;
3129 BcStatus s = BC_STATUS_SUCCESS;
3130 char c = eat_inbuf();
3133 // This is the workhorse of the lexer.
3135 // case '\0': // probably never reached
3137 // p->lex = XC_LEX_EOF;
3141 dbg_lex("++p->lex_line=%zd", p->lex_line);
3142 p->lex = XC_LEX_NLINE;
3149 xc_lex_whitespace();
3152 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3153 if (p->lex == BC_LEX_OP_BOOL_NOT) {
3154 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3155 if (s) RETURN_STATUS(s);
3159 s = zbc_lex_string();
3162 s = zbc_POSIX_does_not_allow("'#' script comments");
3163 if (s) RETURN_STATUS(s);
3164 xc_lex_lineComment();
3167 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3172 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3173 if (s) RETURN_STATUS(s);
3175 p->lex = BC_LEX_OP_BOOL_AND;
3177 p->lex = XC_LEX_INVALID;
3178 s = bc_error_bad_character('&');
3183 p->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3186 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3192 p->lex = BC_LEX_OP_INC;
3194 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3197 p->lex = BC_LEX_COMMA;
3203 p->lex = BC_LEX_OP_DEC;
3205 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3208 if (isdigit(*p->lex_inbuf))
3209 s = zxc_lex_number(c);
3211 p->lex = BC_LEX_KEY_LAST;
3212 s = zbc_POSIX_does_not_allow("'.' as 'last'");
3218 s = zbc_lex_comment();
3220 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3258 s = zxc_lex_number(c);
3261 p->lex = BC_LEX_SCOLON;
3264 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3267 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3270 parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3274 p->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3277 if (*p->lex_inbuf == '\n') {
3278 p->lex = XC_LEX_WHITESPACE;
3281 s = bc_error_bad_character(c);
3284 parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3312 s = zbc_lex_identifier();
3316 p->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3321 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3322 if (s) RETURN_STATUS(s);
3324 p->lex = BC_LEX_OP_BOOL_OR;
3326 p->lex = XC_LEX_INVALID;
3327 s = bc_error_bad_character(c);
3331 p->lex = XC_LEX_INVALID;
3332 s = bc_error_bad_character(c);
3338 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3342 static BC_STATUS zdc_lex_register(void)
3344 BcParse *p = &G.prs;
3345 if (G_exreg && isspace(*p->lex_inbuf)) {
3346 xc_lex_whitespace(); // eats whitespace (but not newline)
3347 p->lex_inbuf++; // xc_lex_name() expects this
3350 bc_vec_pop_all(&p->lex_strnumbuf);
3351 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf++);
3352 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3353 p->lex = XC_LEX_NAME;
3356 RETURN_STATUS(BC_STATUS_SUCCESS);
3358 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3360 static BC_STATUS zdc_lex_string(void)
3362 BcParse *p = &G.prs;
3365 p->lex = XC_LEX_STR;
3366 bc_vec_pop_all(&p->lex_strnumbuf);
3370 char c = peek_inbuf();
3372 RETURN_STATUS(bc_error("unterminated string"));
3374 if (c == '[') depth++;
3380 dbg_lex("++p->lex_line=%zd", p->lex_line);
3382 bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
3385 bc_vec_pushZeroByte(&p->lex_strnumbuf);
3386 p->lex_inbuf++; // skip trailing ']'
3388 G.err_line = p->lex_line;
3389 RETURN_STATUS(BC_STATUS_SUCCESS);
3391 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3393 #undef zdc_lex_token
3394 static BC_STATUS zdc_lex_token(void)
3396 static const //BcLexType - should be this type, but narrower type saves size:
3398 dc_lex_regs[] ALIGN1 = {
3399 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3400 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3401 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3405 BcParse *p = &G.prs;
3410 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3411 if (p->lex_last == dc_lex_regs[i])
3412 RETURN_STATUS(zdc_lex_register());
3415 s = BC_STATUS_SUCCESS;
3417 if (c >= '%' && c <= '~'
3418 && (p->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3423 // This is the workhorse of the lexer.
3425 // case '\0': // probably never reached
3426 // p->lex = XC_LEX_EOF;
3429 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3430 // (and "case '\n':" is not just empty here)
3431 // only to allow interactive dc have a way to exit
3432 // "parse" stage of "parse,execute" loop
3433 // on <enter>, not on _next_ token (which would mean
3434 // commands are not executed on pressing <enter>).
3435 // IOW: typing "1p<enter>" should print "1" _at once_,
3436 // not after some more input.
3438 dbg_lex("++p->lex_line=%zd", p->lex_line);
3439 p->lex = XC_LEX_NLINE;
3446 xc_lex_whitespace();
3451 p->lex = XC_LEX_OP_REL_NE;
3453 p->lex = XC_LEX_OP_REL_LE;
3455 p->lex = XC_LEX_OP_REL_GE;
3457 RETURN_STATUS(bc_error_bad_character(c));
3461 xc_lex_lineComment();
3464 if (isdigit(*p->lex_inbuf))
3465 s = zxc_lex_number(c);
3467 s = bc_error_bad_character(c);
3485 s = zxc_lex_number(c);
3488 s = zdc_lex_string();
3491 p->lex = XC_LEX_INVALID;
3492 s = bc_error_bad_character(c);
3498 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3501 static void xc_parse_push(char i)
3503 BcVec *code = &G.prs.func->code;
3504 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, code->len, i);
3505 bc_vec_pushByte(code, i);
3508 static void xc_parse_pushName(char *name)
3511 BcVec *code = &G.prs.func->code;
3512 size_t pos = code->len;
3513 size_t len = strlen(name) + 1;
3515 bc_vec_expand(code, pos + len);
3516 strcpy(code->v + pos, name);
3517 code->len = pos + len;
3519 // Smaller code, but way slow:
3521 xc_parse_push(*name);
3526 // Indexes < 0xfc are encoded verbatim, else first byte is
3527 // 0xfc, 0xfd, 0xfe or 0xff, encoding "1..4 bytes",
3528 // followed by that many bytes, lsb first.
3529 // (The above describes 32-bit case).
3530 #define SMALL_INDEX_LIMIT (0x100 - sizeof(size_t))
3532 static void xc_parse_pushIndex(size_t idx)
3537 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3538 if (idx < SMALL_INDEX_LIMIT) {
3543 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3546 if (idx & mask) break;
3550 // amt is at least 1 here - "one byte of length data follows"
3552 xc_parse_push((SMALL_INDEX_LIMIT - 1) + amt);
3555 xc_parse_push((unsigned char)idx);
3561 static void bc_parse_pushJUMP(size_t idx)
3563 xc_parse_push(BC_INST_JUMP);
3564 xc_parse_pushIndex(idx);
3567 static void bc_parse_pushJUMP_ZERO(size_t idx)
3569 xc_parse_push(BC_INST_JUMP_ZERO);
3570 xc_parse_pushIndex(idx);
3573 static BC_STATUS zbc_parse_pushSTR(void)
3575 BcParse *p = &G.prs;
3576 char *str = xstrdup(p->lex_strnumbuf.v);
3578 xc_parse_push(XC_INST_STR);
3579 xc_parse_pushIndex(p->func->strs.len);
3580 bc_vec_push(&p->func->strs, &str);
3582 RETURN_STATUS(zxc_lex_next());
3584 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3587 static void xc_parse_pushNUM(void)
3589 BcParse *p = &G.prs;
3590 char *num = xstrdup(p->lex_strnumbuf.v);
3591 #if ENABLE_BC && ENABLE_DC
3592 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3594 size_t idx = bc_vec_push(&p->func->consts, &num);
3596 size_t idx = bc_vec_push(&G.prog.consts, &num);
3598 xc_parse_push(XC_INST_NUM);
3599 xc_parse_pushIndex(idx);
3602 static BC_STATUS zxc_parse_text_init(const char *text)
3604 G.prs.func = xc_program_func(G.prs.fidx);
3605 G.prs.lex_inbuf = text;
3606 G.prs.lex = G.prs.lex_last = XC_LEX_INVALID;
3607 RETURN_STATUS(zxc_lex_next());
3609 #define zxc_parse_text_init(...) (zxc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3611 // Called when parsing or execution detects a failure,
3612 // resets execution structures.
3613 static void xc_program_reset(void)
3618 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3619 bc_vec_pop_all(&G.prog.results);
3621 f = xc_program_func_BC_PROG_MAIN();
3622 ip = bc_vec_top(&G.prog.exestack);
3623 ip->inst_idx = f->code.len;
3626 // Called when parsing code detects a failure,
3627 // resets parsing structures.
3628 static void xc_parse_reset(void)
3630 BcParse *p = &G.prs;
3631 if (p->fidx != BC_PROG_MAIN) {
3632 bc_func_free(p->func);
3633 bc_func_init(p->func);
3635 p->fidx = BC_PROG_MAIN;
3636 p->func = xc_program_func_BC_PROG_MAIN();
3639 p->lex_inbuf += strlen(p->lex_inbuf);
3640 p->lex = XC_LEX_EOF;
3642 IF_BC(bc_vec_pop_all(&p->exits);)
3643 IF_BC(bc_vec_pop_all(&p->conds);)
3644 IF_BC(bc_vec_pop_all(&p->ops);)
3649 static void xc_parse_free(void)
3651 IF_BC(bc_vec_free(&G.prs.exits);)
3652 IF_BC(bc_vec_free(&G.prs.conds);)
3653 IF_BC(bc_vec_free(&G.prs.ops);)
3654 bc_vec_free(&G.prs.lex_strnumbuf);
3657 static void xc_parse_create(size_t fidx)
3659 BcParse *p = &G.prs;
3660 memset(p, 0, sizeof(BcParse));
3662 bc_char_vec_init(&p->lex_strnumbuf);
3663 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3664 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3665 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3668 p->func = xc_program_func(fidx);
3671 static void xc_program_add_fn(void)
3677 bc_vec_push(&G.prog.fns, &f);
3683 // Note: takes ownership of 'name' (must be malloced)
3684 static size_t bc_program_addFunc(char *name)
3687 BcId entry, *entry_ptr;
3691 entry.idx = G.prog.fns.len;
3693 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3694 if (!inserted) free(name);
3696 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3697 idx = entry_ptr->idx;
3700 // There is already a function with this name.
3701 // It'll be redefined now, clear old definition.
3702 BcFunc *func = xc_program_func(entry_ptr->idx);
3706 xc_program_add_fn();
3712 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3713 // We can calculate the conversion between tokens and exprs by subtracting the
3714 // position of the first operator in the lex enum and adding the position of the
3715 // first in the expr enum. Note: This only works for binary operators.
3716 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3718 static BcStatus bc_parse_expr_empty_ok(uint8_t flags);
3720 static BC_STATUS zbc_parse_expr(uint8_t flags)
3724 s = bc_parse_expr_empty_ok(flags);
3725 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3726 RETURN_STATUS(bc_error("empty expression"));
3729 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3731 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed);
3732 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3734 static BC_STATUS zbc_parse_stmt(void)
3736 RETURN_STATUS(zbc_parse_stmt_possibly_auto(false));
3738 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3740 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(const char *after_X)
3742 BcParse *p = &G.prs;
3743 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3744 // Same for "else", "while()", "for()".
3745 BcStatus s = zbc_lex_next_and_skip_NLINE();
3746 if (s) RETURN_STATUS(s);
3747 if (p->lex == XC_LEX_NLINE)
3748 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3750 RETURN_STATUS(zbc_parse_stmt());
3752 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3754 static void bc_parse_operator(BcLexType type, size_t start, size_t *nexprs)
3756 BcParse *p = &G.prs;
3757 char l, r = bc_operation_PREC(type - XC_LEX_1st_op);
3758 bool left = bc_operation_LEFT(type - XC_LEX_1st_op);
3760 while (p->ops.len > start) {
3761 BcLexType t = BC_PARSE_TOP_OP(p);
3762 if (t == BC_LEX_LPAREN) break;
3764 l = bc_operation_PREC(t - XC_LEX_1st_op);
3765 if (l >= r && (l != r || !left)) break;
3767 xc_parse_push(BC_TOKEN_2_INST(t));
3768 bc_vec_pop(&p->ops);
3769 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3772 bc_vec_push(&p->ops, &type);
3775 static BC_STATUS zbc_parse_rightParen(size_t ops_bgn, size_t *nexs)
3777 BcParse *p = &G.prs;
3780 if (p->ops.len <= ops_bgn)
3781 RETURN_STATUS(bc_error_bad_expression());
3782 top = BC_PARSE_TOP_OP(p);
3784 while (top != BC_LEX_LPAREN) {
3785 xc_parse_push(BC_TOKEN_2_INST(top));
3787 bc_vec_pop(&p->ops);
3788 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3790 if (p->ops.len <= ops_bgn)
3791 RETURN_STATUS(bc_error_bad_expression());
3792 top = BC_PARSE_TOP_OP(p);
3795 bc_vec_pop(&p->ops);
3797 RETURN_STATUS(BC_STATUS_SUCCESS);
3799 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3801 static BC_STATUS zbc_parse_params(uint8_t flags)
3803 BcParse *p = &G.prs;
3807 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
3808 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3811 if (s) RETURN_STATUS(s);
3814 if (p->lex != BC_LEX_RPAREN) {
3816 s = zbc_parse_expr(flags);
3817 if (s) RETURN_STATUS(s);
3819 if (p->lex != BC_LEX_COMMA) {
3820 if (p->lex == BC_LEX_RPAREN)
3822 RETURN_STATUS(bc_error_bad_token());
3825 if (s) RETURN_STATUS(s);
3829 xc_parse_push(BC_INST_CALL);
3830 xc_parse_pushIndex(nparams);
3832 RETURN_STATUS(BC_STATUS_SUCCESS);
3834 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3836 // Note: takes ownership of 'name' (must be malloced)
3837 static BC_STATUS zbc_parse_call(char *name, uint8_t flags)
3839 BcParse *p = &G.prs;
3841 BcId entry, *entry_ptr;
3846 s = zbc_parse_params(flags);
3849 if (p->lex != BC_LEX_RPAREN) {
3850 s = bc_error_bad_token();
3854 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3856 if (idx == BC_VEC_INVALID_IDX) {
3857 // No such function exists, create an empty one
3858 bc_program_addFunc(name);
3859 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3863 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3864 xc_parse_pushIndex(entry_ptr->idx);
3866 RETURN_STATUS(zxc_lex_next());
3871 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3873 static BC_STATUS zbc_parse_name(BcInst *type, uint8_t flags)
3875 BcParse *p = &G.prs;
3879 name = xstrdup(p->lex_strnumbuf.v);
3883 if (p->lex == BC_LEX_LBRACKET) {
3887 if (p->lex == BC_LEX_RBRACKET) {
3888 if (!(flags & BC_PARSE_ARRAY)) {
3889 s = bc_error_bad_expression();
3892 *type = XC_INST_ARRAY;
3894 *type = XC_INST_ARRAY_ELEM;
3895 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3896 s = zbc_parse_expr(flags);
3901 xc_parse_push(*type);
3902 xc_parse_pushName(name);
3904 } else if (p->lex == BC_LEX_LPAREN) {
3905 if (flags & BC_PARSE_NOCALL) {
3906 s = bc_error_bad_token();
3909 *type = BC_INST_CALL;
3910 s = zbc_parse_call(name, flags);
3912 *type = XC_INST_VAR;
3913 xc_parse_push(XC_INST_VAR);
3914 xc_parse_pushName(name);
3923 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3925 static BC_STATUS zbc_parse_read(void)
3927 BcParse *p = &G.prs;
3931 if (s) RETURN_STATUS(s);
3932 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3935 if (s) RETURN_STATUS(s);
3936 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3938 xc_parse_push(XC_INST_READ);
3942 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3944 static BC_STATUS zbc_parse_builtin(BcLexType type, uint8_t flags, BcInst *prev)
3946 BcParse *p = &G.prs;
3950 if (s) RETURN_STATUS(s);
3951 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3953 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3956 if (s) RETURN_STATUS(s);
3958 s = zbc_parse_expr(flags);
3959 if (s) RETURN_STATUS(s);
3961 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3963 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3964 xc_parse_push(*prev);
3968 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3970 static BC_STATUS zbc_parse_scale(BcInst *type, uint8_t flags)
3972 BcParse *p = &G.prs;
3976 if (s) RETURN_STATUS(s);
3978 if (p->lex != BC_LEX_LPAREN) {
3979 *type = XC_INST_SCALE;
3980 xc_parse_push(XC_INST_SCALE);
3981 RETURN_STATUS(BC_STATUS_SUCCESS);
3984 *type = XC_INST_SCALE_FUNC;
3985 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3988 if (s) RETURN_STATUS(s);
3990 s = zbc_parse_expr(flags);
3991 if (s) RETURN_STATUS(s);
3992 if (p->lex != BC_LEX_RPAREN)
3993 RETURN_STATUS(bc_error_bad_token());
3994 xc_parse_push(XC_INST_SCALE_FUNC);
3996 RETURN_STATUS(zxc_lex_next());
3998 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
4000 static BC_STATUS zbc_parse_incdec(BcInst *prev, size_t *nexs, uint8_t flags)
4002 BcParse *p = &G.prs;
4006 BcInst etype = *prev;
4008 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
4009 || etype == XC_INST_SCALE || etype == BC_INST_LAST
4010 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
4012 *prev = inst = BC_INST_INC_POST + (p->lex != BC_LEX_OP_INC);
4013 xc_parse_push(inst);
4016 *prev = inst = BC_INST_INC_PRE + (p->lex != BC_LEX_OP_INC);
4019 if (s) RETURN_STATUS(s);
4022 // Because we parse the next part of the expression
4023 // right here, we need to increment this.
4028 s = zbc_parse_name(prev, flags | BC_PARSE_NOCALL);
4030 case BC_LEX_KEY_IBASE:
4031 case BC_LEX_KEY_LAST:
4032 case BC_LEX_KEY_OBASE:
4033 xc_parse_push(type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4036 case BC_LEX_KEY_SCALE:
4038 if (s) RETURN_STATUS(s);
4039 if (p->lex == BC_LEX_LPAREN)
4040 s = bc_error_bad_token();
4042 xc_parse_push(XC_INST_SCALE);
4045 s = bc_error_bad_token();
4049 if (!s) xc_parse_push(inst);
4054 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4056 static int bc_parse_inst_isLeaf(BcInst p)
4058 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
4059 || p == BC_INST_INC_POST
4060 || p == BC_INST_DEC_POST
4063 #define BC_PARSE_LEAF(prev, bin_last, rparen) \
4064 (!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev)))
4066 static BC_STATUS zbc_parse_minus(BcInst *prev, size_t ops_bgn,
4067 bool rparen, bool bin_last, size_t *nexprs)
4069 BcParse *p = &G.prs;
4074 if (s) RETURN_STATUS(s);
4076 type = BC_PARSE_LEAF(*prev, bin_last, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
4077 *prev = BC_TOKEN_2_INST(type);
4079 // We can just push onto the op stack because this is the largest
4080 // precedence operator that gets pushed. Inc/dec does not.
4081 if (type != XC_LEX_OP_MINUS)
4082 bc_vec_push(&p->ops, &type);
4084 bc_parse_operator(type, ops_bgn, nexprs);
4088 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4090 static BC_STATUS zbc_parse_print(void)
4092 BcParse *p = &G.prs;
4098 if (s) RETURN_STATUS(s);
4100 if (type == XC_LEX_STR) {
4101 s = zbc_parse_pushSTR();
4103 s = zbc_parse_expr(0);
4105 if (s) RETURN_STATUS(s);
4106 xc_parse_push(XC_INST_PRINT_POP);
4107 if (p->lex != BC_LEX_COMMA)
4113 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4115 static BC_STATUS zbc_parse_return(void)
4117 BcParse *p = &G.prs;
4121 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4123 if (s) RETURN_STATUS(s);
4126 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON || t == BC_LEX_RBRACE)
4127 xc_parse_push(BC_INST_RET0);
4129 //TODO: if (p->func->voidfunc) ERROR
4130 s = zbc_parse_expr(0);
4131 if (s) RETURN_STATUS(s);
4133 if (t != BC_LEX_LPAREN // "return EXPR", no ()
4134 || p->lex_last != BC_LEX_RPAREN // example: "return (a) + b"
4136 s = zbc_POSIX_requires("parentheses around return expressions");
4137 if (s) RETURN_STATUS(s);
4140 xc_parse_push(XC_INST_RET);
4143 dbg_lex_done("%s:%d done", __func__, __LINE__);
4146 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4148 static void rewrite_label_to_current(size_t idx)
4150 BcParse *p = &G.prs;
4151 size_t *label = bc_vec_item(&p->func->labels, idx);
4152 *label = p->func->code.len;
4155 static BC_STATUS zbc_parse_if(void)
4157 BcParse *p = &G.prs;
4161 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4163 if (s) RETURN_STATUS(s);
4164 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4167 if (s) RETURN_STATUS(s);
4168 s = zbc_parse_expr(BC_PARSE_REL);
4169 if (s) RETURN_STATUS(s);
4170 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4172 // Encode "if zero, jump to ..."
4173 // Pushed value (destination of the jump) is uninitialized,
4174 // will be rewritten to be address of "end of if()" or of "else".
4175 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4176 bc_parse_pushJUMP_ZERO(ip_idx);
4178 s = zbc_parse_stmt_allow_NLINE_before(STRING_if);
4179 if (s) RETURN_STATUS(s);
4181 dbg_lex("%s:%d in if after stmt: p->lex:%d", __func__, __LINE__, p->lex);
4182 if (p->lex == BC_LEX_KEY_ELSE) {
4185 // Encode "after then_stmt, jump to end of if()"
4186 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4187 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4188 bc_parse_pushJUMP(ip2_idx);
4190 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4191 rewrite_label_to_current(ip_idx);
4195 s = zbc_parse_stmt_allow_NLINE_before(STRING_else);
4196 if (s) RETURN_STATUS(s);
4199 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4200 rewrite_label_to_current(ip_idx);
4202 dbg_lex_done("%s:%d done", __func__, __LINE__);
4205 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4207 static BC_STATUS zbc_parse_while(void)
4209 BcParse *p = &G.prs;
4215 if (s) RETURN_STATUS(s);
4216 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4218 if (s) RETURN_STATUS(s);
4220 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4221 ip_idx = cond_idx + 1;
4222 bc_vec_push(&p->conds, &cond_idx);
4224 bc_vec_push(&p->exits, &ip_idx);
4225 bc_vec_push(&p->func->labels, &ip_idx);
4227 s = zbc_parse_expr(BC_PARSE_REL);
4228 if (s) RETURN_STATUS(s);
4229 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4231 bc_parse_pushJUMP_ZERO(ip_idx);
4233 s = zbc_parse_stmt_allow_NLINE_before(STRING_while);
4234 if (s) RETURN_STATUS(s);
4236 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4237 bc_parse_pushJUMP(cond_idx);
4239 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4240 rewrite_label_to_current(ip_idx);
4242 bc_vec_pop(&p->exits);
4243 bc_vec_pop(&p->conds);
4247 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4249 static BC_STATUS zbc_parse_for(void)
4251 BcParse *p = &G.prs;
4253 size_t cond_idx, exit_idx, body_idx, update_idx;
4255 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4257 if (s) RETURN_STATUS(s);
4258 if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4260 if (s) RETURN_STATUS(s);
4262 if (p->lex != BC_LEX_SCOLON) {
4263 s = zbc_parse_expr(0);
4264 xc_parse_push(XC_INST_POP);
4265 if (s) RETURN_STATUS(s);
4267 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4268 if (s) RETURN_STATUS(s);
4271 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4273 if (s) RETURN_STATUS(s);
4275 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4276 update_idx = cond_idx + 1;
4277 body_idx = update_idx + 1;
4278 exit_idx = body_idx + 1;
4280 if (p->lex != BC_LEX_SCOLON)
4281 s = zbc_parse_expr(BC_PARSE_REL);
4283 // Set this for the next call to xc_parse_pushNUM().
4284 // This is safe to set because the current token is a semicolon,
4285 // which has no string requirement.
4286 bc_vec_string(&p->lex_strnumbuf, 1, "1");
4288 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4290 if (s) RETURN_STATUS(s);
4292 if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4295 if (s) RETURN_STATUS(s);
4297 bc_parse_pushJUMP_ZERO(exit_idx);
4298 bc_parse_pushJUMP(body_idx);
4300 bc_vec_push(&p->conds, &update_idx);
4301 bc_vec_push(&p->func->labels, &p->func->code.len);
4303 if (p->lex != BC_LEX_RPAREN) {
4304 s = zbc_parse_expr(0);
4305 if (s) RETURN_STATUS(s);
4306 if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4307 xc_parse_push(XC_INST_POP);
4309 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4310 if (s) RETURN_STATUS(s);
4313 bc_parse_pushJUMP(cond_idx);
4314 bc_vec_push(&p->func->labels, &p->func->code.len);
4316 bc_vec_push(&p->exits, &exit_idx);
4317 bc_vec_push(&p->func->labels, &exit_idx);
4319 s = zbc_parse_stmt_allow_NLINE_before(STRING_for);
4320 if (s) RETURN_STATUS(s);
4322 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4323 bc_parse_pushJUMP(update_idx);
4325 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4326 rewrite_label_to_current(exit_idx);
4328 bc_vec_pop(&p->exits);
4329 bc_vec_pop(&p->conds);
4331 RETURN_STATUS(BC_STATUS_SUCCESS);
4333 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4335 static BC_STATUS zbc_parse_break_or_continue(BcLexType type)
4337 BcParse *p = &G.prs;
4340 if (type == BC_LEX_KEY_BREAK) {
4341 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4342 RETURN_STATUS(bc_error_bad_token());
4343 i = *(size_t*)bc_vec_top(&p->exits);
4345 i = *(size_t*)bc_vec_top(&p->conds);
4347 bc_parse_pushJUMP(i);
4349 RETURN_STATUS(zxc_lex_next());
4351 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4353 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4359 autoid = (void*)f->autos.v;
4360 for (i = 0; i < f->autos.len; i++, autoid++) {
4361 if (strcmp(name, autoid->name) == 0
4362 && var == autoid->idx
4364 RETURN_STATUS(bc_error("duplicate function parameter or auto name"));
4371 bc_vec_push(&f->autos, &a);
4373 RETURN_STATUS(BC_STATUS_SUCCESS);
4375 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4377 static BC_STATUS zbc_parse_funcdef(void)
4379 BcParse *p = &G.prs;
4381 bool var, comma, voidfunc;
4384 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4386 if (s) RETURN_STATUS(s);
4387 if (p->lex != XC_LEX_NAME)
4388 RETURN_STATUS(bc_error_bad_function_definition());
4390 // To be maximally both POSIX and GNU-compatible,
4391 // "void" is not treated as a normal keyword:
4392 // you can have variable named "void", and even a function
4393 // named "void": "define void() { return 6; }" is ok.
4394 // _Only_ "define void f() ..." syntax treats "void"
4396 voidfunc = (strcmp(p->lex_strnumbuf.v, "void") == 0);
4399 if (s) RETURN_STATUS(s);
4401 voidfunc = (voidfunc && p->lex == XC_LEX_NAME);
4404 if (s) RETURN_STATUS(s);
4407 if (p->lex != BC_LEX_LPAREN)
4408 RETURN_STATUS(bc_error_bad_function_definition());
4410 p->fidx = bc_program_addFunc(xstrdup(p->lex_strnumbuf.v));
4411 p->func = xc_program_func(p->fidx);
4412 p->func->voidfunc = voidfunc;
4415 if (s) RETURN_STATUS(s);
4418 while (p->lex != BC_LEX_RPAREN) {
4419 if (p->lex != XC_LEX_NAME)
4420 RETURN_STATUS(bc_error_bad_function_definition());
4424 name = xstrdup(p->lex_strnumbuf.v);
4428 var = p->lex != BC_LEX_LBRACKET;
4434 if (p->lex != BC_LEX_RBRACKET) {
4435 s = bc_error_bad_function_definition();
4443 comma = p->lex == BC_LEX_COMMA;
4449 s = zbc_func_insert(p->func, name, var);
4453 if (comma) RETURN_STATUS(bc_error_bad_function_definition());
4456 if (s) RETURN_STATUS(s);
4458 if (p->lex != BC_LEX_LBRACE) {
4459 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4460 if (s) RETURN_STATUS(s);
4463 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4464 s = zbc_lex_skip_if_at_NLINE();
4465 if (s) RETURN_STATUS(s);
4466 // GNU bc requires a {} block even if function body has single stmt, enforce this
4467 if (p->lex != BC_LEX_LBRACE)
4468 RETURN_STATUS(bc_error("function { body } expected"));
4470 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4471 s = zbc_parse_stmt_possibly_auto(true);
4473 if (s) RETURN_STATUS(s);
4475 xc_parse_push(BC_INST_RET0);
4477 // Subsequent code generation is into main program
4478 p->fidx = BC_PROG_MAIN;
4479 p->func = xc_program_func_BC_PROG_MAIN();
4481 dbg_lex_done("%s:%d done", __func__, __LINE__);
4484 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4488 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4490 static BC_STATUS zbc_parse_auto(void)
4492 BcParse *p = &G.prs;
4496 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4498 if (s) RETURN_STATUS(s);
4503 if (p->lex != XC_LEX_NAME)
4504 RETURN_STATUS(bc_error_at("bad 'auto' syntax"));
4506 name = xstrdup(p->lex_strnumbuf.v);
4510 var = (p->lex != BC_LEX_LBRACKET);
4515 if (p->lex != BC_LEX_RBRACKET) {
4516 s = bc_error_at("bad 'auto' syntax");
4523 s = zbc_func_insert(p->func, name, var);
4526 if (p->lex == XC_LEX_NLINE
4527 || p->lex == BC_LEX_SCOLON
4528 //|| p->lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4532 if (p->lex != BC_LEX_COMMA)
4533 RETURN_STATUS(bc_error_at("bad 'auto' syntax"));
4534 s = zxc_lex_next(); // skip comma
4535 if (s) RETURN_STATUS(s);
4538 dbg_lex_done("%s:%d done", __func__, __LINE__);
4539 RETURN_STATUS(BC_STATUS_SUCCESS);
4542 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4545 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4547 #undef zbc_parse_stmt_possibly_auto
4548 static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed)
4550 BcParse *p = &G.prs;
4551 BcStatus s = BC_STATUS_SUCCESS;
4553 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
4555 if (p->lex == XC_LEX_NLINE) {
4556 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4557 RETURN_STATUS(zxc_lex_next());
4559 if (p->lex == BC_LEX_SCOLON) {
4560 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4561 RETURN_STATUS(zxc_lex_next());
4564 if (p->lex == BC_LEX_LBRACE) {
4565 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4568 if (s) RETURN_STATUS(s);
4569 } while (p->lex == XC_LEX_NLINE);
4570 if (auto_allowed && p->lex == BC_LEX_KEY_AUTO) {
4571 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4572 s = zbc_parse_auto();
4573 if (s) RETURN_STATUS(s);
4575 while (p->lex != BC_LEX_RBRACE) {
4576 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4577 //FIXME: prevent wrong syntax such as "{ print 1 print 2 }"
4578 s = zbc_parse_stmt();
4579 if (s) RETURN_STATUS(s);
4582 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4586 dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
4588 case XC_LEX_OP_MINUS:
4591 case BC_LEX_OP_BOOL_NOT:
4595 case BC_LEX_KEY_IBASE:
4596 case BC_LEX_KEY_LAST:
4597 case BC_LEX_KEY_LENGTH:
4598 case BC_LEX_KEY_OBASE:
4599 case BC_LEX_KEY_READ:
4600 case BC_LEX_KEY_SCALE:
4601 case BC_LEX_KEY_SQRT:
4602 s = zbc_parse_expr(BC_PARSE_PRINT);
4605 s = zbc_parse_pushSTR();
4606 xc_parse_push(XC_INST_PRINT_STR);
4608 case BC_LEX_KEY_BREAK:
4609 case BC_LEX_KEY_CONTINUE:
4610 s = zbc_parse_break_or_continue(p->lex);
4612 case BC_LEX_KEY_FOR:
4613 s = zbc_parse_for();
4615 case BC_LEX_KEY_HALT:
4616 xc_parse_push(BC_INST_HALT);
4622 case BC_LEX_KEY_LIMITS:
4623 // "limits" is a compile-time command,
4624 // the output is produced at _parse time_.
4626 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4627 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4628 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4629 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4630 // "BC_NUM_MAX = "BC_MAX_NUM_STR "\n" - GNU bc does not show this
4631 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4632 "Number of vars = "BC_MAX_VARS_STR "\n"
4636 case BC_LEX_KEY_PRINT:
4637 s = zbc_parse_print();
4639 case BC_LEX_KEY_QUIT:
4640 // "quit" is a compile-time command. For example,
4641 // "if (0 == 1) quit" terminates when parsing the statement,
4642 // not when it is executed
4643 QUIT_OR_RETURN_TO_MAIN;
4644 case BC_LEX_KEY_RETURN:
4646 RETURN_STATUS(bc_error("'return' not in a function"));
4647 s = zbc_parse_return();
4649 case BC_LEX_KEY_WHILE:
4650 s = zbc_parse_while();
4653 s = bc_error_bad_token();
4657 dbg_lex_done("%s:%d done", __func__, __LINE__);
4660 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4662 static BC_STATUS zbc_parse_stmt_or_funcdef(void)
4664 BcParse *p = &G.prs;
4667 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4668 if (p->lex == XC_LEX_EOF)
4669 s = bc_error("end of file");
4670 else if (p->lex == BC_LEX_KEY_DEFINE) {
4671 dbg_lex("%s:%d p->lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4672 s = zbc_parse_funcdef();
4674 dbg_lex("%s:%d p->lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->lex);
4675 s = zbc_parse_stmt();
4678 dbg_lex_done("%s:%d done", __func__, __LINE__);
4681 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4683 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4684 static BcStatus bc_parse_expr_empty_ok(uint8_t flags)
4686 BcParse *p = &G.prs;
4687 BcInst prev = XC_INST_PRINT;
4688 size_t nexprs = 0, ops_bgn = p->ops.len;
4689 unsigned nparens, nrelops;
4690 bool paren_first, rprn, assign, bin_last, incdec;
4692 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4693 paren_first = (p->lex == BC_LEX_LPAREN);
4694 nparens = nrelops = 0;
4695 rprn = assign = incdec = false;
4701 BcLexType t = p->lex;
4703 if (!lex_allowed_in_bc_expr(t))
4706 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4708 s = BC_STATUS_SUCCESS;
4712 dbg_lex("%s:%d LEX_OP_INC/DEC", __func__, __LINE__);
4713 if (incdec) return bc_error_bad_assignment();
4714 s = zbc_parse_incdec(&prev, &nexprs, flags);
4716 rprn = bin_last = false;
4717 //get_token = false; - already is
4719 case XC_LEX_OP_MINUS:
4720 dbg_lex("%s:%d LEX_OP_MINUS", __func__, __LINE__);
4721 s = zbc_parse_minus(&prev, ops_bgn, rprn, bin_last, &nexprs);
4723 //get_token = false; - already is
4724 bin_last = (prev == XC_INST_MINUS);
4725 if (bin_last) incdec = false;
4727 case BC_LEX_OP_ASSIGN_POWER:
4728 case BC_LEX_OP_ASSIGN_MULTIPLY:
4729 case BC_LEX_OP_ASSIGN_DIVIDE:
4730 case BC_LEX_OP_ASSIGN_MODULUS:
4731 case BC_LEX_OP_ASSIGN_PLUS:
4732 case BC_LEX_OP_ASSIGN_MINUS:
4733 case BC_LEX_OP_ASSIGN:
4734 dbg_lex("%s:%d LEX_ASSIGNxyz", __func__, __LINE__);
4735 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4736 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4737 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4739 return bc_error_bad_assignment();
4742 case XC_LEX_OP_POWER:
4743 case XC_LEX_OP_MULTIPLY:
4744 case XC_LEX_OP_DIVIDE:
4745 case XC_LEX_OP_MODULUS:
4746 case XC_LEX_OP_PLUS:
4747 case XC_LEX_OP_REL_EQ:
4748 case XC_LEX_OP_REL_LE:
4749 case XC_LEX_OP_REL_GE:
4750 case XC_LEX_OP_REL_NE:
4751 case XC_LEX_OP_REL_LT:
4752 case XC_LEX_OP_REL_GT:
4753 case BC_LEX_OP_BOOL_NOT:
4754 case BC_LEX_OP_BOOL_OR:
4755 case BC_LEX_OP_BOOL_AND:
4756 dbg_lex("%s:%d LEX_OP_xyz", __func__, __LINE__);
4757 if (t == BC_LEX_OP_BOOL_NOT) {
4758 if (!bin_last && p->lex_last != BC_LEX_OP_BOOL_NOT)
4759 return bc_error_bad_expression();
4760 } else if (prev == XC_INST_BOOL_NOT) {
4761 return bc_error_bad_expression();
4764 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4765 prev = BC_TOKEN_2_INST(t);
4766 bc_parse_operator(t, ops_bgn, &nexprs);
4767 rprn = incdec = false;
4769 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4772 dbg_lex("%s:%d LEX_LPAREN", __func__, __LINE__);
4773 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4774 return bc_error_bad_expression();
4775 bc_vec_push(&p->ops, &t);
4778 rprn = incdec = false;
4781 dbg_lex("%s:%d LEX_RPAREN", __func__, __LINE__);
4782 if (p->lex_last == BC_LEX_LPAREN) {
4783 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4784 return BC_STATUS_PARSE_EMPTY_EXP;
4786 if (bin_last || prev == XC_INST_BOOL_NOT)
4787 return bc_error_bad_expression();
4791 s = zbc_parse_rightParen(ops_bgn, &nexprs);
4795 bin_last = incdec = false;
4798 dbg_lex("%s:%d LEX_NAME", __func__, __LINE__);
4799 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4800 return bc_error_bad_expression();
4801 s = zbc_parse_name(&prev, flags & ~BC_PARSE_NOCALL);
4802 rprn = (prev == BC_INST_CALL);
4804 //get_token = false; - already is
4808 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4809 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4810 return bc_error_bad_expression();
4814 rprn = bin_last = false;
4817 case BC_LEX_KEY_IBASE:
4818 case BC_LEX_KEY_LAST:
4819 case BC_LEX_KEY_OBASE:
4820 dbg_lex("%s:%d LEX_IBASE/LAST/OBASE", __func__, __LINE__);
4821 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4822 return bc_error_bad_expression();
4823 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4824 xc_parse_push((char) prev);
4826 rprn = bin_last = false;
4829 case BC_LEX_KEY_LENGTH:
4830 case BC_LEX_KEY_SQRT:
4831 dbg_lex("%s:%d LEX_LEN/SQRT", __func__, __LINE__);
4832 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4833 return bc_error_bad_expression();
4834 s = zbc_parse_builtin(t, flags, &prev);
4836 rprn = bin_last = incdec = false;
4839 case BC_LEX_KEY_READ:
4840 dbg_lex("%s:%d LEX_READ", __func__, __LINE__);
4841 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4842 return bc_error_bad_expression();
4843 s = zbc_parse_read();
4844 prev = XC_INST_READ;
4846 rprn = bin_last = incdec = false;
4849 case BC_LEX_KEY_SCALE:
4850 dbg_lex("%s:%d LEX_SCALE", __func__, __LINE__);
4851 if (BC_PARSE_LEAF(prev, bin_last, rprn))
4852 return bc_error_bad_expression();
4853 s = zbc_parse_scale(&prev, flags);
4854 //get_token = false; - already is
4855 rprn = bin_last = false;
4859 return bc_error_bad_token();
4862 if (s || G_interrupt) // error, or ^C: stop parsing
4863 return BC_STATUS_FAILURE;
4871 while (p->ops.len > ops_bgn) {
4872 BcLexType top = BC_PARSE_TOP_OP(p);
4873 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4875 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4876 return bc_error_bad_expression();
4878 xc_parse_push(BC_TOKEN_2_INST(top));
4880 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4881 bc_vec_pop(&p->ops);
4884 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4885 return bc_error_bad_expression();
4887 if (!(flags & BC_PARSE_REL) && nrelops) {
4889 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4891 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4893 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4897 if (flags & BC_PARSE_PRINT) {
4898 if (paren_first || !assign)
4899 xc_parse_push(XC_INST_PRINT);
4900 xc_parse_push(XC_INST_POP);
4903 dbg_lex_done("%s:%d done", __func__, __LINE__);
4904 return BC_STATUS_SUCCESS;
4911 static BC_STATUS zdc_parse_register(void)
4913 BcParse *p = &G.prs;
4917 if (s) RETURN_STATUS(s);
4918 if (p->lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4920 xc_parse_pushName(p->lex_strnumbuf.v);
4924 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4926 static void dc_parse_string(void)
4928 BcParse *p = &G.prs;
4930 size_t len = G.prog.strs.len;
4932 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4934 str = xstrdup(p->lex_strnumbuf.v);
4935 xc_parse_push(XC_INST_STR);
4936 xc_parse_pushIndex(len);
4937 bc_vec_push(&G.prog.strs, &str);
4939 // Explanation needed here
4940 xc_program_add_fn();
4941 p->func = xc_program_func(p->fidx);
4943 dbg_lex_done("%s:%d done", __func__, __LINE__);
4946 static BC_STATUS zdc_parse_mem(uint8_t inst, bool name, bool store)
4950 xc_parse_push(inst);
4952 s = zdc_parse_register();
4953 if (s) RETURN_STATUS(s);
4957 xc_parse_push(DC_INST_SWAP);
4958 xc_parse_push(XC_INST_ASSIGN);
4959 xc_parse_push(XC_INST_POP);
4962 RETURN_STATUS(BC_STATUS_SUCCESS);
4964 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4966 static BC_STATUS zdc_parse_cond(uint8_t inst)
4968 BcParse *p = &G.prs;
4971 xc_parse_push(inst);
4972 xc_parse_push(DC_INST_EXEC_COND);
4974 s = zdc_parse_register();
4975 if (s) RETURN_STATUS(s);
4978 if (s) RETURN_STATUS(s);
4980 // Note that 'else' part can not be on the next line:
4981 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4982 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4983 if (p->lex == DC_LEX_ELSE) {
4984 s = zdc_parse_register();
4985 if (s) RETURN_STATUS(s);
4988 xc_parse_push('\0');
4993 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4995 static BC_STATUS zdc_parse_token(BcLexType t)
4999 bool assign, get_token;
5001 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
5002 s = BC_STATUS_SUCCESS;
5005 case XC_LEX_OP_REL_EQ:
5006 case XC_LEX_OP_REL_LE:
5007 case XC_LEX_OP_REL_GE:
5008 case XC_LEX_OP_REL_NE:
5009 case XC_LEX_OP_REL_LT:
5010 case XC_LEX_OP_REL_GT:
5011 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
5012 s = zdc_parse_cond(t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
5017 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
5018 s = zdc_parse_mem(XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
5021 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
5025 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
5027 if (s) RETURN_STATUS(s);
5028 if (G.prs.lex != XC_LEX_NUMBER)
5029 RETURN_STATUS(bc_error_bad_token());
5031 xc_parse_push(XC_INST_NEG);
5034 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
5038 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
5039 xc_parse_push(XC_INST_READ);
5041 case DC_LEX_OP_ASSIGN:
5042 case DC_LEX_STORE_PUSH:
5043 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
5044 assign = (t == DC_LEX_OP_ASSIGN);
5045 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
5046 s = zdc_parse_mem(inst, true, assign);
5049 case DC_LEX_LOAD_POP:
5050 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
5051 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
5052 s = zdc_parse_mem(inst, true, false);
5054 case DC_LEX_STORE_IBASE:
5055 case DC_LEX_STORE_SCALE:
5056 case DC_LEX_STORE_OBASE:
5057 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
5058 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
5059 s = zdc_parse_mem(inst, false, true);
5062 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
5063 RETURN_STATUS(bc_error_bad_token());
5066 if (!s && get_token) s = zxc_lex_next();
5068 dbg_lex_done("%s:%d done", __func__, __LINE__);
5071 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
5073 static BC_STATUS zdc_parse_expr(void)
5075 BcParse *p = &G.prs;
5078 if (p->lex == XC_LEX_NLINE)
5079 RETURN_STATUS(zxc_lex_next());
5081 i = (int)p->lex - (int)XC_LEX_OP_POWER;
5083 BcInst inst = dc_LEX_to_INST[i];
5084 if (inst != DC_INST_INVALID) {
5085 xc_parse_push(inst);
5086 RETURN_STATUS(zxc_lex_next());
5089 RETURN_STATUS(zdc_parse_token(p->lex));
5091 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
5093 static BC_STATUS zdc_parse_exprs_until_eof(void)
5095 BcParse *p = &G.prs;
5096 dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
5097 while (p->lex != XC_LEX_EOF) {
5098 BcStatus s = zdc_parse_expr();
5099 if (s) RETURN_STATUS(s);
5102 dbg_lex_done("%s:%d done", __func__, __LINE__);
5103 RETURN_STATUS(BC_STATUS_SUCCESS);
5105 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5113 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
5114 #define BC_PROG_NUM(r, n) \
5115 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
5117 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5118 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5120 static BcVec* xc_program_search(char *id, bool var)
5127 v = var ? &G.prog.vars : &G.prog.arrs;
5128 map = var ? &G.prog.var_map : &G.prog.arr_map;
5132 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5136 bc_array_init(&v2, var);
5137 bc_vec_push(v, &v2);
5140 ptr = bc_vec_item(map, i);
5141 if (new) ptr->name = xstrdup(e.name);
5142 return bc_vec_item(v, ptr->idx);
5145 // 'num' need not be initialized on entry
5146 static BC_STATUS zxc_program_num(BcResult *r, BcNum **num)
5150 case XC_RESULT_TEMP:
5151 IF_BC(case BC_RESULT_VOID:)
5152 case XC_RESULT_IBASE:
5153 case XC_RESULT_SCALE:
5154 case XC_RESULT_OBASE:
5157 case XC_RESULT_CONSTANT: {
5162 str = *xc_program_const(r->d.id.idx);
5165 bc_num_init(&r->d.n, len);
5167 s = zxc_num_parse(&r->d.n, str, G.prog.ib_t);
5169 bc_num_free(&r->d.n);
5173 r->t = XC_RESULT_TEMP;
5177 case XC_RESULT_ARRAY:
5178 case XC_RESULT_ARRAY_ELEM: {
5181 v = xc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5182 // dc variables are all stacks, so here we have this:
5184 // TODO: eliminate these stacks for bc-only config?
5185 if (r->t == XC_RESULT_ARRAY_ELEM) {
5187 if (v->len <= r->d.id.idx)
5188 bc_array_expand(v, r->d.id.idx + 1);
5189 *num = bc_vec_item(v, r->d.id.idx);
5196 case BC_RESULT_LAST:
5197 *num = &G.prog.last;
5205 // Testing the theory that dc does not reach LAST/ONE
5206 bb_error_msg_and_die("BUG:%d", r->t);
5210 RETURN_STATUS(BC_STATUS_SUCCESS);
5212 #define zxc_program_num(...) (zxc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5214 static BC_STATUS zxc_program_binOpPrep(BcResult **l, BcNum **ln,
5215 BcResult **r, BcNum **rn, bool assign)
5218 BcResultType lt, rt;
5220 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5221 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5223 *r = bc_vec_item_rev(&G.prog.results, 0);
5224 *l = bc_vec_item_rev(&G.prog.results, 1);
5226 s = zxc_program_num(*l, ln);
5227 if (s) RETURN_STATUS(s);
5228 s = zxc_program_num(*r, rn);
5229 if (s) RETURN_STATUS(s);
5234 // We run this again under these conditions in case any vector has been
5235 // reallocated out from under the BcNums or arrays we had.
5236 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5237 s = zxc_program_num(*l, ln);
5238 if (s) RETURN_STATUS(s);
5241 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5242 RETURN_STATUS(bc_error_variable_is_wrong_type());
5243 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5244 RETURN_STATUS(bc_error_variable_is_wrong_type());
5248 #define zxc_program_binOpPrep(...) (zxc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5250 static void xc_program_binOpRetire(BcResult *r)
5252 r->t = XC_RESULT_TEMP;
5253 bc_vec_pop(&G.prog.results);
5254 bc_result_pop_and_push(r);
5257 // Note: *r and *n need not be initialized by caller
5258 static BC_STATUS zxc_program_prep(BcResult **r, BcNum **n)
5262 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5263 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5264 *r = bc_vec_top(&G.prog.results);
5266 s = zxc_program_num(*r, n);
5267 if (s) RETURN_STATUS(s);
5269 if (!BC_PROG_NUM((*r), (*n)))
5270 RETURN_STATUS(bc_error_variable_is_wrong_type());
5274 #define zxc_program_prep(...) (zxc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5276 static void xc_program_retire(BcResult *r, BcResultType t)
5279 bc_result_pop_and_push(r);
5282 static BC_STATUS zxc_program_op(char inst)
5285 BcResult *opd1, *opd2, res;
5288 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5289 if (s) RETURN_STATUS(s);
5290 bc_num_init_DEF_SIZE(&res.d.n);
5292 s = BC_STATUS_SUCCESS;
5293 IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5295 xc_program_binOpRetire(&res);
5299 bc_num_free(&res.d.n);
5302 #define zxc_program_op(...) (zxc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5304 static BC_STATUS zxc_program_read(void)
5312 bc_char_vec_init(&buf);
5313 xc_read_line(&buf, stdin);
5315 f = xc_program_func(BC_PROG_READ);
5316 bc_vec_pop_all(&f->code);
5318 sv_parse = G.prs; // struct copy
5319 xc_parse_create(BC_PROG_READ);
5320 //G.err_line = G.prs.lex_line = 1; - not needed, error line info is not printed for read()
5322 s = zxc_parse_text_init(buf.v);
5323 if (s) goto exec_err;
5325 IF_BC(s = zbc_parse_expr(0));
5327 IF_DC(s = zdc_parse_exprs_until_eof());
5329 if (s) goto exec_err;
5330 if (G.prs.lex != XC_LEX_NLINE && G.prs.lex != XC_LEX_EOF) {
5331 s = bc_error_at("bad read() expression");
5334 xc_parse_push(XC_INST_RET);
5336 ip.func = BC_PROG_READ;
5338 bc_vec_push(&G.prog.exestack, &ip);
5342 G.prs = sv_parse; // struct copy
5346 #define zxc_program_read(...) (zxc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5348 static size_t xc_program_index(char *code, size_t *bgn)
5350 unsigned char *bytes = (void*)(code + *bgn);
5356 if (amt < SMALL_INDEX_LIMIT) {
5360 amt -= (SMALL_INDEX_LIMIT - 1); // amt is 1 or more here
5366 res |= (size_t)(*bytes++) << i;
5368 } while (--amt != 0);
5373 static char *xc_program_name(char *code, size_t *bgn)
5376 *bgn += strlen(code) + 1;
5378 return xstrdup(code);
5381 static void xc_program_printString(const char *str)
5384 if (!str[0] && IS_DC) {
5385 // Example: echo '[]ap' | dc
5386 // should print two bytes: 0x00, 0x0A
5394 static const char esc[] ALIGN1 = "nabfrt""e\\";
5398 n = strchr(esc, c); // note: c can be NUL
5400 // Just print the backslash and following character
5404 if (n - esc == 0) // "\n" ?
5405 G.prog.nchars = SIZE_MAX;
5406 c = "\n\a\b\f\r\t""\\\\""\\"[n - esc];
5407 // n a b f r t e \ \<end of line>
5415 static void bc_num_printNewline(void)
5417 if (G.prog.nchars == G.prog.len - 1) {
5425 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5428 bb_putchar((char) num);
5429 G.prog.nchars += width;
5433 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5437 bc_num_printNewline();
5438 bb_putchar(radix ? '.' : ' ');
5441 bc_num_printNewline();
5442 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5445 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5447 bc_num_printNewline();
5450 bb_putchar(((char) dig) + '0');
5454 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5457 bc_num_printNewline();
5462 bc_num_printNewline();
5463 bb_putchar(bb_hexdigits_upcase[num]);
5464 G.prog.nchars += width;
5467 static void bc_num_printDecimal(BcNum *n)
5469 size_t i, rdx = n->rdx - 1;
5476 for (i = n->len - 1; i < n->len; --i)
5477 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5480 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5482 static BC_STATUS zxc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5487 BcDig base_digs[ULONG_NUM_BUFSIZE];
5488 BcNum intp, fracp, digit, frac_len;
5489 unsigned long dig, *ptr;
5494 print(0, width, false);
5495 RETURN_STATUS(BC_STATUS_SUCCESS);
5498 bc_vec_init(&stack, sizeof(long), NULL);
5499 bc_num_init(&intp, n->len);
5500 bc_num_init(&fracp, n->rdx);
5501 bc_num_init(&digit, width);
5502 bc_num_init(&frac_len, BC_NUM_INT(n));
5503 bc_num_copy(&intp, n);
5504 bc_num_one(&frac_len);
5505 base.cap = ARRAY_SIZE(base_digs);
5506 base.num = base_digs;
5507 bc_num_ulong2num(&base, base_t);
5509 bc_num_truncate(&intp, intp.rdx);
5510 s = zbc_num_sub(n, &intp, &fracp, 0);
5513 while (intp.len != 0) {
5514 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5516 s = zbc_num_ulong(&digit, &dig);
5518 bc_vec_push(&stack, &dig);
5521 for (i = 0; i < stack.len; ++i) {
5522 ptr = bc_vec_item_rev(&stack, i);
5523 print(*ptr, width, false);
5526 if (!n->rdx) goto err;
5528 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5529 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5531 s = zbc_num_ulong(&fracp, &dig);
5533 bc_num_ulong2num(&intp, dig);
5534 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5536 print(dig, width, radix);
5537 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5541 bc_num_free(&frac_len);
5542 bc_num_free(&digit);
5543 bc_num_free(&fracp);
5545 bc_vec_free(&stack);
5548 #define zxc_num_printNum(...) (zxc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5550 static BC_STATUS zxc_num_printBase(BcNum *n)
5564 if (G.prog.ob_t <= 16) {
5566 print = bc_num_printHex;
5568 unsigned i = G.prog.ob_t - 1;
5576 print = bc_num_printDigits;
5579 s = zxc_num_printNum(n, G.prog.ob_t, width, print);
5584 #define zxc_num_printBase(...) (zxc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5586 static BC_STATUS zxc_num_print(BcNum *n, bool newline)
5588 BcStatus s = BC_STATUS_SUCCESS;
5590 bc_num_printNewline();
5595 } else if (G.prog.ob_t == 10)
5596 bc_num_printDecimal(n);
5598 s = zxc_num_printBase(n);
5607 #define zxc_num_print(...) (zxc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5610 // for bc, idx is always 0
5611 #define xc_program_print(inst, idx) \
5612 xc_program_print(inst)
5614 static BC_STATUS xc_program_print(char inst, size_t idx)
5619 IF_NOT_DC(size_t idx = 0);
5621 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5622 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5624 r = bc_vec_item_rev(&G.prog.results, idx);
5626 if (inst == XC_INST_PRINT && r->t == BC_RESULT_VOID)
5627 // void function's result on stack, ignore
5628 RETURN_STATUS(BC_STATUS_SUCCESS);
5630 s = zxc_program_num(r, &num);
5631 if (s) RETURN_STATUS(s);
5633 if (BC_PROG_NUM(r, num)) {
5634 s = zxc_num_print(num, /*newline:*/ inst == XC_INST_PRINT);
5636 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5641 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5642 str = *xc_program_str(idx);
5644 if (inst == XC_INST_PRINT_STR) {
5646 G.prog.nchars += printf("%s", str);
5647 nl = strrchr(str, '\n');
5649 G.prog.nchars = strlen(nl + 1);
5651 xc_program_printString(str);
5652 if (inst == XC_INST_PRINT)
5657 if (!s && inst != XC_INST_PRINT) bc_vec_pop(&G.prog.results);
5661 #define zxc_program_print(...) (xc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5663 static BC_STATUS zxc_program_negate(void)
5669 s = zxc_program_prep(&ptr, &num);
5670 if (s) RETURN_STATUS(s);
5672 bc_num_init(&res.d.n, num->len);
5673 bc_num_copy(&res.d.n, num);
5674 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5676 xc_program_retire(&res, XC_RESULT_TEMP);
5680 #define zxc_program_negate(...) (zxc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5682 static BC_STATUS zxc_program_logical(char inst)
5685 BcResult *opd1, *opd2, res;
5689 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5690 if (s) RETURN_STATUS(s);
5692 bc_num_init_DEF_SIZE(&res.d.n);
5694 if (inst == XC_INST_BOOL_AND)
5695 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5696 else if (inst == XC_INST_BOOL_OR)
5697 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5699 cond = bc_num_cmp(n1, n2);
5701 case XC_INST_REL_EQ:
5704 case XC_INST_REL_LE:
5707 case XC_INST_REL_GE:
5710 case XC_INST_REL_LT:
5713 case XC_INST_REL_GT:
5716 default: // = case XC_INST_REL_NE:
5717 //cond = (cond != 0); - not needed
5722 if (cond) bc_num_one(&res.d.n);
5723 //else bc_num_zero(&res.d.n); - already is
5725 xc_program_binOpRetire(&res);
5729 #define zxc_program_logical(...) (zxc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5732 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5737 memset(&n2, 0, sizeof(BcNum));
5738 n2.rdx = res.d.id.idx = r->d.id.idx;
5739 res.t = XC_RESULT_STR;
5742 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5743 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5745 bc_vec_pop(&G.prog.results);
5748 bc_result_pop_and_push(&res);
5749 bc_vec_push(v, &n2);
5751 RETURN_STATUS(BC_STATUS_SUCCESS);
5753 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5756 static BC_STATUS zxc_program_popResultAndCopyToVar(char *name, bool var)
5763 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5764 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5766 ptr = bc_vec_top(&G.prog.results);
5767 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5768 RETURN_STATUS(bc_error_variable_is_wrong_type());
5769 v = xc_program_search(name, var);
5772 if (ptr->t == XC_RESULT_STR && !var)
5773 RETURN_STATUS(bc_error_variable_is_wrong_type());
5774 if (ptr->t == XC_RESULT_STR)
5775 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5778 s = zxc_program_num(ptr, &n);
5779 if (s) RETURN_STATUS(s);
5781 // Do this once more to make sure that pointers were not invalidated.
5782 v = xc_program_search(name, var);
5785 bc_num_init_DEF_SIZE(&r.d.n);
5786 bc_num_copy(&r.d.n, n);
5788 bc_array_init(&r.d.v, true);
5789 bc_array_copy(&r.d.v, (BcVec *) n);
5792 bc_vec_push(v, &r.d);
5793 bc_vec_pop(&G.prog.results);
5797 #define zxc_program_popResultAndCopyToVar(...) (zxc_program_popResultAndCopyToVar(__VA_ARGS__) COMMA_SUCCESS)
5799 static BC_STATUS zxc_program_assign(char inst)
5802 BcResult *left, *right, res;
5804 bool assign = (inst == XC_INST_ASSIGN);
5807 s = zxc_program_binOpPrep(&left, &l, &right, &r, assign);
5808 if (s) RETURN_STATUS(s);
5810 ib = left->t == XC_RESULT_IBASE;
5811 sc = left->t == XC_RESULT_SCALE;
5814 if (right->t == XC_RESULT_STR) {
5817 if (left->t != XC_RESULT_VAR)
5818 RETURN_STATUS(bc_error_variable_is_wrong_type());
5819 v = xc_program_search(left->d.id.name, true);
5821 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5825 if (left->t == XC_RESULT_CONSTANT
5826 || left->t == XC_RESULT_TEMP
5827 IF_BC(|| left->t == BC_RESULT_VOID)
5829 RETURN_STATUS(bc_error_bad_assignment());
5836 s = BC_STATUS_SUCCESS;
5837 IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5839 if (s) RETURN_STATUS(s);
5844 if (ib || sc || left->t == XC_RESULT_OBASE) {
5845 static const char *const msg[] = {
5846 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5847 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5848 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5854 s = zbc_num_ulong(l, &val);
5855 if (s) RETURN_STATUS(s);
5856 s = left->t - XC_RESULT_IBASE;
5859 ptr = &G.prog.scale;
5862 RETURN_STATUS(bc_error(msg[s]));
5863 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5864 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5868 RETURN_STATUS(bc_error(msg[s]));
5870 *ptr = (size_t) val;
5871 s = BC_STATUS_SUCCESS;
5874 bc_num_init(&res.d.n, l->len);
5875 bc_num_copy(&res.d.n, l);
5876 xc_program_binOpRetire(&res);
5880 #define zxc_program_assign(...) (zxc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5883 #define xc_program_pushVar(code, bgn, pop, copy) \
5884 xc_program_pushVar(code, bgn)
5885 // for bc, 'pop' and 'copy' are always false
5887 static BC_STATUS xc_program_pushVar(char *code, size_t *bgn,
5888 bool pop, bool copy)
5891 char *name = xc_program_name(code, bgn);
5893 r.t = XC_RESULT_VAR;
5898 BcVec *v = xc_program_search(name, true);
5899 BcNum *num = bc_vec_top(v);
5902 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5903 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5906 if (!BC_PROG_STR(num)) {
5907 r.t = XC_RESULT_TEMP;
5908 bc_num_init_DEF_SIZE(&r.d.n);
5909 bc_num_copy(&r.d.n, num);
5911 r.t = XC_RESULT_STR;
5912 r.d.id.idx = num->rdx;
5915 if (!copy) bc_vec_pop(v);
5919 bc_vec_push(&G.prog.results, &r);
5921 RETURN_STATUS(BC_STATUS_SUCCESS);
5923 #define zxc_program_pushVar(...) (xc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5925 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5927 BcStatus s = BC_STATUS_SUCCESS;
5931 r.d.id.name = xc_program_name(code, bgn);
5933 if (inst == XC_INST_ARRAY) {
5934 r.t = XC_RESULT_ARRAY;
5935 bc_vec_push(&G.prog.results, &r);
5940 s = zxc_program_prep(&operand, &num);
5942 s = zbc_num_ulong(num, &temp);
5945 if (temp > BC_MAX_DIM) {
5946 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5950 r.d.id.idx = (size_t) temp;
5951 xc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5954 if (s) free(r.d.id.name);
5957 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5960 static BC_STATUS zbc_program_incdec(char inst)
5963 BcResult *ptr, res, copy;
5967 s = zxc_program_prep(&ptr, &num);
5968 if (s) RETURN_STATUS(s);
5970 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5971 copy.t = XC_RESULT_TEMP;
5972 bc_num_init(©.d.n, num->len);
5973 bc_num_copy(©.d.n, num);
5976 res.t = BC_RESULT_ONE;
5977 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
5978 ? BC_INST_ASSIGN_PLUS
5979 : BC_INST_ASSIGN_MINUS;
5981 bc_vec_push(&G.prog.results, &res);
5982 s = zxc_program_assign(inst);
5983 if (s) RETURN_STATUS(s);
5985 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5986 bc_result_pop_and_push(©);
5991 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5993 static BC_STATUS zbc_program_call(char *code, size_t *idx)
6000 nparams = xc_program_index(code, idx);
6001 ip.func = xc_program_index(code, idx);
6002 func = xc_program_func(ip.func);
6004 if (func->code.len == 0) {
6005 RETURN_STATUS(bc_error("undefined function"));
6007 if (nparams != func->nparams) {
6008 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
6012 for (i = 0; i < nparams; ++i) {
6016 a = bc_vec_item(&func->autos, nparams - 1 - i);
6017 arg = bc_vec_top(&G.prog.results);
6019 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) // array/variable mismatch
6020 // || arg->t == XC_RESULT_STR - impossible, f("str") is not a legal syntax (strings are not bc expressions)
6022 RETURN_STATUS(bc_error_variable_is_wrong_type());
6024 s = zxc_program_popResultAndCopyToVar(a->name, a->idx);
6025 if (s) RETURN_STATUS(s);
6028 a = bc_vec_item(&func->autos, i);
6029 for (; i < func->autos.len; i++, a++) {
6032 v = xc_program_search(a->name, a->idx);
6035 bc_num_init_DEF_SIZE(&n2);
6036 bc_vec_push(v, &n2);
6039 bc_array_init(&v2, true);
6040 bc_vec_push(v, &v2);
6044 bc_vec_push(&G.prog.exestack, &ip);
6046 RETURN_STATUS(BC_STATUS_SUCCESS);
6048 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
6050 static BC_STATUS zbc_program_return(char inst)
6056 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6058 f = xc_program_func(ip->func);
6060 res.t = XC_RESULT_TEMP;
6061 if (inst == XC_INST_RET) {
6062 // bc needs this for e.g. RESULT_CONSTANT ("return 5")
6063 // because bc constants are per-function.
6064 // TODO: maybe avoid if value is already RESULT_TEMP?
6067 BcResult *operand = bc_vec_top(&G.prog.results);
6069 s = zxc_program_num(operand, &num);
6070 if (s) RETURN_STATUS(s);
6071 bc_num_init(&res.d.n, num->len);
6072 bc_num_copy(&res.d.n, num);
6073 bc_vec_pop(&G.prog.results);
6076 res.t = BC_RESULT_VOID;
6077 bc_num_init_DEF_SIZE(&res.d.n);
6078 //bc_num_zero(&res.d.n); - already is
6080 bc_vec_push(&G.prog.results, &res);
6082 bc_vec_pop(&G.prog.exestack);
6084 // We need to pop arguments as well, so this takes that into account.
6085 a = (void*)f->autos.v;
6086 for (i = 0; i < f->autos.len; i++, a++) {
6088 v = xc_program_search(a->name, a->idx);
6092 RETURN_STATUS(BC_STATUS_SUCCESS);
6094 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6097 static unsigned long xc_program_scale(BcNum *n)
6099 return (unsigned long) n->rdx;
6102 static unsigned long xc_program_len(BcNum *n)
6104 size_t len = n->len;
6106 if (n->rdx != len) return len;
6108 if (len == 0) break;
6110 if (n->num[len] != 0) break;
6115 static BC_STATUS zxc_program_builtin(char inst)
6121 bool len = (inst == XC_INST_LENGTH);
6123 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6124 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6125 opnd = bc_vec_top(&G.prog.results);
6127 s = zxc_program_num(opnd, &num);
6128 if (s) RETURN_STATUS(s);
6131 if (!BC_PROG_NUM(opnd, num) && !len)
6132 RETURN_STATUS(bc_error_variable_is_wrong_type());
6135 bc_num_init_DEF_SIZE(&res.d.n);
6137 if (inst == XC_INST_SQRT)
6138 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6140 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6141 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6145 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6147 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6149 str = xc_program_str(idx);
6150 bc_num_ulong2num(&res.d.n, strlen(*str));
6154 bc_num_ulong2num(&res.d.n, len ? xc_program_len(num) : xc_program_scale(num));
6157 xc_program_retire(&res, XC_RESULT_TEMP);
6161 #define zxc_program_builtin(...) (zxc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6164 static BC_STATUS zdc_program_divmod(void)
6167 BcResult *opd1, *opd2, res, res2;
6170 s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6171 if (s) RETURN_STATUS(s);
6173 bc_num_init_DEF_SIZE(&res.d.n);
6174 bc_num_init(&res2.d.n, n2->len);
6176 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6179 xc_program_binOpRetire(&res2);
6180 res.t = XC_RESULT_TEMP;
6181 bc_vec_push(&G.prog.results, &res);
6185 bc_num_free(&res2.d.n);
6186 bc_num_free(&res.d.n);
6189 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6191 static BC_STATUS zdc_program_modexp(void)
6194 BcResult *r1, *r2, *r3, res;
6195 BcNum *n1, *n2, *n3;
6197 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6198 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6199 s = zxc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6200 if (s) RETURN_STATUS(s);
6202 r1 = bc_vec_item_rev(&G.prog.results, 2);
6203 s = zxc_program_num(r1, &n1);
6204 if (s) RETURN_STATUS(s);
6205 if (!BC_PROG_NUM(r1, n1))
6206 RETURN_STATUS(bc_error_variable_is_wrong_type());
6208 // Make sure that the values have their pointers updated, if necessary.
6209 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6210 if (r1->t == r2->t) {
6211 s = zxc_program_num(r2, &n2);
6212 if (s) RETURN_STATUS(s);
6214 if (r1->t == r3->t) {
6215 s = zxc_program_num(r3, &n3);
6216 if (s) RETURN_STATUS(s);
6220 bc_num_init(&res.d.n, n3->len);
6221 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6224 bc_vec_pop(&G.prog.results);
6225 xc_program_binOpRetire(&res);
6229 bc_num_free(&res.d.n);
6232 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6234 static void dc_program_stackLen(void)
6237 size_t len = G.prog.results.len;
6239 res.t = XC_RESULT_TEMP;
6241 bc_num_init_DEF_SIZE(&res.d.n);
6242 bc_num_ulong2num(&res.d.n, len);
6243 bc_vec_push(&G.prog.results, &res);
6246 static BC_STATUS zdc_program_asciify(void)
6256 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6257 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6259 r = bc_vec_top(&G.prog.results);
6260 s = zxc_program_num(r, &num);
6261 if (s) RETURN_STATUS(s);
6263 if (BC_PROG_NUM(r, num)) {
6266 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6268 bc_num_init_DEF_SIZE(&n);
6269 bc_num_copy(&n, num);
6270 bc_num_truncate(&n, n.rdx);
6272 strmb.cap = ARRAY_SIZE(strmb_digs);
6273 strmb.num = strmb_digs;
6274 bc_num_ulong2num(&strmb, 0x100);
6276 s = zbc_num_mod(&n, &strmb, &n, 0);
6277 if (s) goto num_err;
6278 s = zbc_num_ulong(&n, &val);
6279 if (s) goto num_err;
6286 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6287 sp = *xc_program_str(idx);
6291 strs = (void*)G.prog.strs.v;
6292 for (idx = 0; idx < G.prog.strs.len; idx++) {
6293 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6299 //str[1] = '\0'; - already is
6300 bc_vec_push(&G.prog.strs, &str);
6302 res.t = XC_RESULT_STR;
6304 bc_result_pop_and_push(&res);
6306 RETURN_STATUS(BC_STATUS_SUCCESS);
6311 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6313 static BC_STATUS zdc_program_printStream(void)
6320 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6321 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6322 r = bc_vec_top(&G.prog.results);
6324 s = zxc_program_num(r, &n);
6325 if (s) RETURN_STATUS(s);
6327 if (BC_PROG_NUM(r, n)) {
6328 s = zxc_num_printNum(n, 0x100, 1, dc_num_printChar);
6331 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6332 str = *xc_program_str(idx);
6338 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6340 static BC_STATUS zdc_program_nquit(void)
6347 s = zxc_program_prep(&opnd, &num);
6348 if (s) RETURN_STATUS(s);
6349 s = zbc_num_ulong(num, &val);
6350 if (s) RETURN_STATUS(s);
6352 bc_vec_pop(&G.prog.results);
6354 if (G.prog.exestack.len < val)
6355 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6356 if (G.prog.exestack.len == val) {
6357 QUIT_OR_RETURN_TO_MAIN;
6360 bc_vec_npop(&G.prog.exestack, val);
6364 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6366 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6368 BcStatus s = BC_STATUS_SUCCESS;
6374 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6375 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6377 r = bc_vec_top(&G.prog.results);
6380 BcNum *n = n; // for compiler
6383 char *then_name = xc_program_name(code, bgn);
6384 char *else_name = NULL;
6386 if (code[*bgn] == '\0')
6389 else_name = xc_program_name(code, bgn);
6391 exec = r->d.n.len != 0;
6393 if (!exec && else_name != NULL) {
6400 v = xc_program_search(name, true);
6407 if (!exec) goto exit;
6408 if (!BC_PROG_STR(n)) {
6409 s = bc_error_variable_is_wrong_type();
6415 if (r->t == XC_RESULT_STR) {
6417 } else if (r->t == XC_RESULT_VAR) {
6419 s = zxc_program_num(r, &n);
6420 if (s || !BC_PROG_STR(n)) goto exit;
6426 fidx = sidx + BC_PROG_REQ_FUNCS;
6428 f = xc_program_func(fidx);
6430 if (f->code.len == 0) {
6434 sv_parse = G.prs; // struct copy
6435 xc_parse_create(fidx);
6436 str = *xc_program_str(sidx);
6437 s = zxc_parse_text_init(str);
6440 s = zdc_parse_exprs_until_eof();
6442 xc_parse_push(DC_INST_POP_EXEC);
6443 if (G.prs.lex != XC_LEX_EOF)
6444 s = bc_error_bad_expression();
6446 G.prs = sv_parse; // struct copy
6449 bc_vec_pop_all(&f->code);
6457 bc_vec_pop(&G.prog.results);
6458 bc_vec_push(&G.prog.exestack, &ip);
6460 RETURN_STATUS(BC_STATUS_SUCCESS);
6462 bc_vec_pop(&G.prog.results);
6465 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6468 static void xc_program_pushGlobal(char inst)
6473 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6474 if (inst == XC_INST_IBASE)
6475 val = (unsigned long) G.prog.ib_t;
6476 else if (inst == XC_INST_SCALE)
6477 val = (unsigned long) G.prog.scale;
6479 val = (unsigned long) G.prog.ob_t;
6481 bc_num_init_DEF_SIZE(&res.d.n);
6482 bc_num_ulong2num(&res.d.n, val);
6483 bc_vec_push(&G.prog.results, &res);
6486 static BC_STATUS zxc_program_exec(void)
6489 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6490 BcFunc *func = xc_program_func(ip->func);
6491 char *code = func->code.v;
6493 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6494 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6495 while (ip->inst_idx < func->code.len) {
6496 BcStatus s = BC_STATUS_SUCCESS;
6497 char inst = code[ip->inst_idx++];
6499 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6502 if (IS_DC) { // end of '?' reached
6503 bc_vec_pop(&G.prog.exestack);
6504 goto read_updated_ip;
6509 dbg_exec("BC_INST_RET[0]:");
6510 s = zbc_program_return(inst);
6511 goto read_updated_ip;
6512 case BC_INST_JUMP_ZERO: {
6515 dbg_exec("BC_INST_JUMP_ZERO:");
6516 s = zxc_program_prep(&ptr, &num);
6517 if (s) RETURN_STATUS(s);
6518 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6519 bc_vec_pop(&G.prog.results);
6521 xc_program_index(code, &ip->inst_idx);
6524 // else: fall through
6526 case BC_INST_JUMP: {
6527 size_t idx = xc_program_index(code, &ip->inst_idx);
6528 size_t *addr = bc_vec_item(&func->labels, idx);
6529 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6530 ip->inst_idx = *addr;
6534 dbg_exec("BC_INST_CALL:");
6535 s = zbc_program_call(code, &ip->inst_idx);
6536 goto read_updated_ip;
6537 case BC_INST_INC_PRE:
6538 case BC_INST_DEC_PRE:
6539 case BC_INST_INC_POST:
6540 case BC_INST_DEC_POST:
6541 dbg_exec("BC_INST_INCDEC:");
6542 s = zbc_program_incdec(inst);
6545 dbg_exec("BC_INST_HALT:");
6546 QUIT_OR_RETURN_TO_MAIN;
6548 case XC_INST_BOOL_OR:
6549 case XC_INST_BOOL_AND:
6551 case XC_INST_REL_EQ:
6552 case XC_INST_REL_LE:
6553 case XC_INST_REL_GE:
6554 case XC_INST_REL_NE:
6555 case XC_INST_REL_LT:
6556 case XC_INST_REL_GT:
6557 dbg_exec("BC_INST_BOOL:");
6558 s = zxc_program_logical(inst);
6561 dbg_exec("XC_INST_READ:");
6562 s = zxc_program_read();
6563 goto read_updated_ip;
6565 dbg_exec("XC_INST_VAR:");
6566 s = zxc_program_pushVar(code, &ip->inst_idx, false, false);
6568 case XC_INST_ARRAY_ELEM:
6570 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6571 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6575 dbg_exec("BC_INST_LAST:");
6576 r.t = BC_RESULT_LAST;
6577 bc_vec_push(&G.prog.results, &r);
6583 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6584 xc_program_pushGlobal(inst);
6586 case XC_INST_SCALE_FUNC:
6587 case XC_INST_LENGTH:
6589 dbg_exec("BC_INST_builtin:");
6590 s = zxc_program_builtin(inst);
6593 dbg_exec("XC_INST_NUM:");
6594 r.t = XC_RESULT_CONSTANT;
6595 r.d.id.idx = xc_program_index(code, &ip->inst_idx);
6596 bc_vec_push(&G.prog.results, &r);
6599 dbg_exec("XC_INST_POP:");
6600 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6601 s = bc_error_stack_has_too_few_elements();
6603 bc_vec_pop(&G.prog.results);
6606 case XC_INST_PRINT_POP:
6607 case XC_INST_PRINT_STR:
6608 dbg_exec("XC_INST_PRINTxyz(%d):", inst - XC_INST_PRINT);
6609 s = zxc_program_print(inst, 0);
6612 dbg_exec("XC_INST_STR:");
6613 r.t = XC_RESULT_STR;
6614 r.d.id.idx = xc_program_index(code, &ip->inst_idx);
6615 bc_vec_push(&G.prog.results, &r);
6618 case XC_INST_MULTIPLY:
6619 case XC_INST_DIVIDE:
6620 case XC_INST_MODULUS:
6623 dbg_exec("BC_INST_binaryop:");
6624 s = zxc_program_op(inst);
6626 case XC_INST_BOOL_NOT: {
6628 dbg_exec("XC_INST_BOOL_NOT:");
6629 s = zxc_program_prep(&ptr, &num);
6630 if (s) RETURN_STATUS(s);
6631 bc_num_init_DEF_SIZE(&r.d.n);
6632 if (bc_num_cmp(num, &G.prog.zero) == 0)
6634 //else bc_num_zero(&r.d.n); - already is
6635 xc_program_retire(&r, XC_RESULT_TEMP);
6639 dbg_exec("XC_INST_NEG:");
6640 s = zxc_program_negate();
6643 case BC_INST_ASSIGN_POWER:
6644 case BC_INST_ASSIGN_MULTIPLY:
6645 case BC_INST_ASSIGN_DIVIDE:
6646 case BC_INST_ASSIGN_MODULUS:
6647 case BC_INST_ASSIGN_PLUS:
6648 case BC_INST_ASSIGN_MINUS:
6650 case XC_INST_ASSIGN:
6651 dbg_exec("BC_INST_ASSIGNxyz:");
6652 s = zxc_program_assign(inst);
6655 case DC_INST_POP_EXEC:
6656 dbg_exec("DC_INST_POP_EXEC:");
6657 bc_vec_pop(&G.prog.exestack);
6658 goto read_updated_ip;
6659 case DC_INST_MODEXP:
6660 dbg_exec("DC_INST_MODEXP:");
6661 s = zdc_program_modexp();
6663 case DC_INST_DIVMOD:
6664 dbg_exec("DC_INST_DIVMOD:");
6665 s = zdc_program_divmod();
6667 case DC_INST_EXECUTE:
6668 case DC_INST_EXEC_COND:
6669 dbg_exec("DC_INST_EXEC[_COND]:");
6670 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6671 goto read_updated_ip;
6672 case DC_INST_PRINT_STACK: {
6674 dbg_exec("DC_INST_PRINT_STACK:");
6675 for (idx = 0; idx < G.prog.results.len; ++idx) {
6676 s = zxc_program_print(XC_INST_PRINT, idx);
6681 case DC_INST_CLEAR_STACK:
6682 dbg_exec("DC_INST_CLEAR_STACK:");
6683 bc_vec_pop_all(&G.prog.results);
6685 case DC_INST_STACK_LEN:
6686 dbg_exec("DC_INST_STACK_LEN:");
6687 dc_program_stackLen();
6689 case DC_INST_DUPLICATE:
6690 dbg_exec("DC_INST_DUPLICATE:");
6691 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6692 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6693 ptr = bc_vec_top(&G.prog.results);
6694 dc_result_copy(&r, ptr);
6695 bc_vec_push(&G.prog.results, &r);
6697 case DC_INST_SWAP: {
6699 dbg_exec("DC_INST_SWAP:");
6700 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6701 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6702 ptr = bc_vec_item_rev(&G.prog.results, 0);
6703 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6704 memcpy(&r, ptr, sizeof(BcResult));
6705 memcpy(ptr, ptr2, sizeof(BcResult));
6706 memcpy(ptr2, &r, sizeof(BcResult));
6709 case DC_INST_ASCIIFY:
6710 dbg_exec("DC_INST_ASCIIFY:");
6711 s = zdc_program_asciify();
6713 case DC_INST_PRINT_STREAM:
6714 dbg_exec("DC_INST_PRINT_STREAM:");
6715 s = zdc_program_printStream();
6718 case DC_INST_PUSH_VAR: {
6719 bool copy = inst == DC_INST_LOAD;
6720 s = zxc_program_pushVar(code, &ip->inst_idx, true, copy);
6723 case DC_INST_PUSH_TO_VAR: {
6724 char *name = xc_program_name(code, &ip->inst_idx);
6725 s = zxc_program_popResultAndCopyToVar(name, true);
6730 dbg_exec("DC_INST_QUIT:");
6731 if (G.prog.exestack.len <= 2)
6732 QUIT_OR_RETURN_TO_MAIN;
6733 bc_vec_npop(&G.prog.exestack, 2);
6734 goto read_updated_ip;
6736 dbg_exec("DC_INST_NQUIT:");
6737 s = zdc_program_nquit();
6738 //goto read_updated_ip; - just fall through to it
6741 // Instruction stack has changed, read new pointers
6742 ip = bc_vec_top(&G.prog.exestack);
6743 func = xc_program_func(ip->func);
6744 code = func->code.v;
6745 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6748 if (s || G_interrupt) {
6756 RETURN_STATUS(BC_STATUS_SUCCESS);
6758 #define zxc_program_exec(...) (zxc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6760 static unsigned xc_vm_envLen(const char *var)
6766 len = BC_NUM_PRINT_WIDTH;
6767 if (!lenv) return len;
6769 len = bb_strtou(lenv, NULL, 10) - 1;
6770 if (errno || len < 2 || len >= INT_MAX)
6771 len = BC_NUM_PRINT_WIDTH;
6776 static BC_STATUS zxc_vm_process(const char *text)
6780 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6781 s = zxc_parse_text_init(text); // does the first zxc_lex_next()
6782 if (s) RETURN_STATUS(s);
6785 while (G.prs.lex != XC_LEX_EOF) {
6789 dbg_lex("%s:%d G.prs.lex:%d, parsing...", __func__, __LINE__, G.prs.lex);
6792 if (G.prs.lex == BC_LEX_SCOLON
6793 || G.prs.lex == XC_LEX_NLINE
6800 s = zbc_parse_stmt_or_funcdef();
6803 // Check that next token is a correct stmt delimiter -
6804 // disallows "print 1 print 2" and such.
6805 if (G.prs.lex != BC_LEX_SCOLON
6806 && G.prs.lex != XC_LEX_NLINE
6807 && G.prs.lex != XC_LEX_EOF
6809 bc_error_at("bad statement terminator");
6812 // The above logic is fragile. Check these examples:
6813 // - interactive read() still works
6817 s = zdc_parse_expr();
6820 if (s || G_interrupt) {
6822 xc_parse_reset(); // includes xc_program_reset()
6823 RETURN_STATUS(BC_STATUS_FAILURE);
6826 dbg_lex("%s:%d executing...", __func__, __LINE__);
6827 s = zxc_program_exec();
6833 ip = (void*)G.prog.exestack.v;
6835 if (G.prog.exestack.len != 1) // should have only main's IP
6836 bb_error_msg_and_die("BUG:call stack");
6837 if (ip->func != BC_PROG_MAIN)
6838 bb_error_msg_and_die("BUG:not MAIN");
6840 f = xc_program_func_BC_PROG_MAIN();
6841 // bc discards strings, constants and code after each
6842 // top-level statement in the "main program".
6843 // This prevents "yes 1 | bc" from growing its memory
6844 // without bound. This can be done because data stack
6845 // is empty and thus can't hold any references to
6846 // strings or constants, there is no generated code
6847 // which can hold references (after we discard one
6848 // we just executed). Code of functions can have references,
6849 // but bc stores function strings/constants in per-function
6853 if (G.prog.results.len != 0) // should be empty
6854 bb_error_msg_and_die("BUG:data stack");
6856 IF_BC(bc_vec_pop_all(&f->strs);)
6857 IF_BC(bc_vec_pop_all(&f->consts);)
6859 if (G.prog.results.len == 0
6860 && G.prog.vars.len == 0
6862 // If stack is empty and no registers exist (TODO: or they are all empty),
6863 // we can get rid of accumulated strings and constants.
6864 // In this example dc process should not grow
6865 // its memory consumption with time:
6867 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6868 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6870 // The code is discarded always (below), thus this example
6871 // should also not grow its memory consumption with time,
6872 // even though its data stack is not empty:
6873 // { echo 1; yes dk; } | dc
6875 // We drop generated and executed code for both bc and dc:
6876 bc_vec_pop_all(&f->code);
6880 dbg_lex_done("%s:%d done", __func__, __LINE__);
6883 #define zxc_vm_process(...) (zxc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6885 static BC_STATUS zxc_vm_execute_FILE(FILE *fp, const char *filename)
6887 // So far bc/dc have no way to include a file from another file,
6888 // therefore we know G.prs.lex_filename == NULL on entry
6889 //const char *sv_file;
6892 G.prs.lex_filename = filename;
6893 G.prs.lex_input_fp = fp;
6894 G.err_line = G.prs.lex_line = 1;
6895 dbg_lex("p->lex_line reset to 1");
6898 s = zxc_vm_process("");
6899 // We do not stop looping on errors here if reading stdin.
6900 // Example: start interactive bc and enter "return".
6901 // It should say "'return' not in a function"
6902 // but should not exit.
6903 } while (G.prs.lex_input_fp == stdin);
6904 G.prs.lex_filename = NULL;
6907 #define zxc_vm_execute_FILE(...) (zxc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6909 static BC_STATUS zxc_vm_file(const char *file)
6914 fp = xfopen_for_read(file);
6915 s = zxc_vm_execute_FILE(fp, file);
6920 #define zxc_vm_file(...) (zxc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6923 static void bc_vm_info(void)
6925 printf("%s "BB_VER"\n"
6926 "Adapted from https://github.com/gavinhoward/bc\n"
6927 "Original code (c) 2018 Gavin D. Howard and contributors\n"
6931 static void bc_args(char **argv)
6937 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6938 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6939 "warn\0" No_argument "w"
6940 "version\0" No_argument "v"
6941 "standard\0" No_argument "s"
6942 "quiet\0" No_argument "q"
6943 "mathlib\0" No_argument "l"
6944 "interactive\0" No_argument "i"
6947 opts = option_mask32 |= getopt32(argv, "wvsqli");
6949 if (getenv("POSIXLY_CORRECT"))
6950 option_mask32 |= BC_FLAG_S;
6952 if (opts & BC_FLAG_V) {
6957 for (i = optind; argv[i]; ++i)
6958 bc_vec_push(&G.files, argv + i);
6961 static void bc_vm_envArgs(void)
6965 char *env_args = getenv("BC_ENV_ARGS");
6967 if (!env_args) return;
6969 G.env_args = xstrdup(env_args);
6972 bc_vec_init(&v, sizeof(char *), NULL);
6974 while (*(buf = skip_whitespace(buf)) != '\0') {
6975 bc_vec_push(&v, &buf);
6976 buf = skip_non_whitespace(buf);
6982 // NULL terminate, and pass argv[] so that first arg is argv[1]
6983 if (sizeof(int) == sizeof(char*)) {
6984 bc_vec_push(&v, &const_int_0);
6986 static char *const nullptr = NULL;
6987 bc_vec_push(&v, &nullptr);
6989 bc_args(((char **)v.v) - 1);
6994 static const char bc_lib[] ALIGN1 = {
6997 "\n" "auto b,s,n,r,d,i,p,f,v"
6998 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6999 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
7000 //e(-.998896): GNU:.36828580434569428695
7001 // above code:.36828580434569428696
7002 // actual value:.3682858043456942869594...
7003 // but for now let's be "GNU compatible"
7012 "\n" "scale=scale(x)+1"
7022 "\n" "for(i=2;v;++i){"
7028 "\n" "while(d--)r*=r"
7031 "\n" "if(n)return(1/r)"
7035 "\n" "auto b,s,r,p,a,q,i,v"
7039 "\n" "r=(1-10^scale)/1"
7050 "\n" "while(x<=.5){"
7054 "\n" "r=a=(x-1)/(x+1)"
7057 "\n" "for(i=3;v;i+=2){"
7068 "\n" "auto b,s,r,a,q,i"
7069 "\n" "if(x<0)return(-s(-x))"
7073 "\n" "scale=1.1*s+2"
7082 "\n" "for(i=3;a;i+=2){"
7083 "\n" "a*=q/(i*(i-1))"
7096 "\n" "x=s(2*a(1)+x)"
7102 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7110 "\n" "if(scale<65){"
7111 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7112 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7122 "\n" "x=(x-.2)/(1+.2*x)"
7127 "\n" "for(i=3;t;i+=2){"
7134 "\n" "return((m*a+r)/n)"
7136 "\n" "define j(n,x){"
7137 "\n" "auto b,s,o,a,i,v,f"
7148 "\n" "for(i=2;i<=n;++i)a*=i"
7150 "\n" "a=(x^n)/2^n/a"
7153 "\n" "scale+=length(a)-scale(a)"
7154 "\n" "for(i=1;v;++i){"
7155 "\n" "v=v*f/i/(n+i)"
7161 "\n" "return(a*r/1)"
7166 static BC_STATUS zxc_vm_exec(void)
7173 if (option_mask32 & BC_FLAG_L) {
7174 // We know that internal library is not buggy,
7175 // thus error checking is normally disabled.
7176 # define DEBUG_LIB 0
7177 s = zxc_vm_process(bc_lib);
7178 if (DEBUG_LIB && s) RETURN_STATUS(s);
7182 s = BC_STATUS_SUCCESS;
7183 fname = (void*)G.files.v;
7184 for (i = 0; i < G.files.len; i++) {
7185 s = zxc_vm_file(*fname++);
7186 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7187 // Debug config, non-interactive mode:
7188 // return all the way back to main.
7189 // Non-debug builds do not come here
7190 // in non-interactive mode, they exit.
7195 if (IS_BC || (option_mask32 & BC_FLAG_I))
7196 s = zxc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7200 #define zxc_vm_exec(...) (zxc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7202 #if ENABLE_FEATURE_CLEAN_UP
7203 static void xc_program_free(void)
7205 bc_vec_free(&G.prog.fns);
7206 IF_BC(bc_vec_free(&G.prog.fn_map);)
7207 bc_vec_free(&G.prog.vars);
7208 bc_vec_free(&G.prog.var_map);
7209 bc_vec_free(&G.prog.arrs);
7210 bc_vec_free(&G.prog.arr_map);
7211 IF_DC(bc_vec_free(&G.prog.strs);)
7212 IF_DC(bc_vec_free(&G.prog.consts);)
7213 bc_vec_free(&G.prog.results);
7214 bc_vec_free(&G.prog.exestack);
7215 IF_BC(bc_num_free(&G.prog.last);)
7216 //IF_BC(bc_num_free(&G.prog.zero);)
7217 IF_BC(bc_num_free(&G.prog.one);)
7218 bc_vec_free(&G.input_buffer);
7222 static void xc_program_init(void)
7226 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7227 memset(&ip, 0, sizeof(BcInstPtr));
7229 // G.prog.nchars = G.prog.scale = 0; - already is
7233 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7234 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7236 //bc_num_init_DEF_SIZE(&G.prog.zero); - not needed
7237 //bc_num_zero(&G.prog.zero); - already is
7239 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7240 IF_BC(bc_num_one(&G.prog.one);)
7242 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7243 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7246 // Names are chosen simply to be distinct and never match
7247 // a valid function name (and be short)
7248 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7249 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7251 // in dc, functions have no names
7252 xc_program_add_fn();
7253 xc_program_add_fn();
7256 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7257 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7259 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7260 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7262 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7263 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7264 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7265 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7266 bc_vec_push(&G.prog.exestack, &ip);
7268 bc_char_vec_init(&G.input_buffer);
7271 static int xc_vm_init(const char *env_len)
7273 G.prog.len = xc_vm_envLen(env_len);
7274 #if ENABLE_FEATURE_EDITING
7275 G.line_input_state = new_line_input_t(DO_HISTORY);
7277 bc_vec_init(&G.files, sizeof(char *), NULL);
7280 IF_BC(if (IS_BC) bc_vm_envArgs();)
7281 xc_parse_create(BC_PROG_MAIN);
7283 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7284 //-i option unconditionally enables this regardless of isatty():
7286 #if ENABLE_FEATURE_BC_INTERACTIVE
7288 // With SA_RESTART, most system calls will restart
7289 // (IOW: they won't fail with EINTR).
7290 // In particular, this means ^C won't cause
7291 // stdout to get into "error state" if SIGINT hits
7292 // within write() syscall.
7294 // The downside is that ^C while tty input is taken
7295 // will only be handled after [Enter] since read()
7296 // from stdin is not interrupted by ^C either,
7297 // it restarts, thus fgetc() does not return on ^C.
7298 // (This problem manifests only if line editing is disabled)
7299 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7301 // Without SA_RESTART, this exhibits a bug:
7302 // "while (1) print 1" and try ^C-ing it.
7303 // Intermittently, instead of returning to input line,
7304 // you'll get "output error: Interrupted system call"
7306 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7310 return 0; // "not a tty"
7313 static BcStatus xc_vm_run(void)
7315 BcStatus st = zxc_vm_exec();
7316 #if ENABLE_FEATURE_CLEAN_UP
7317 if (G_exiting) // it was actually "halt" or "quit"
7320 bc_vec_free(&G.files);
7324 # if ENABLE_FEATURE_EDITING
7325 free_line_input_t(G.line_input_state);
7329 dbg_exec("exiting with exitcode %d", st);
7334 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7335 int bc_main(int argc UNUSED_PARAM, char **argv)
7341 is_tty = xc_vm_init("BC_LINE_LENGTH");
7345 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7353 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7354 int dc_main(int argc UNUSED_PARAM, char **argv)
7360 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7361 // 1 char wider than bc from the same package.
7362 // Both default width, and xC_LINE_LENGTH=N are wider:
7363 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7366 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7369 // Do the same, or it's a bug?
7370 xc_vm_init("DC_LINE_LENGTH");
7372 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7373 noscript = BC_FLAG_I;
7375 int n = getopt(argc, argv, "e:f:x");
7381 n = zxc_vm_process(optarg);
7386 n = zxc_vm_file(optarg);
7390 option_mask32 |= DC_FLAG_X;
7400 bc_vec_push(&G.files, argv++);
7403 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin