1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Copyright (c) 2018 Gavin D. Howard and contributors.
7 //config: bool "bc (45 kb; 49 kb when combined with dc)"
10 //config: bc is a command-line, arbitrary-precision calculator with a
11 //config: Turing-complete language. See the GNU bc manual
12 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
13 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
15 //config: This bc has five differences to the GNU bc:
16 //config: 1) The period (.) is a shortcut for "last", as in the BSD bc.
17 //config: 2) Arrays are copied before being passed as arguments to
18 //config: functions. This behavior is required by the bc spec.
19 //config: 3) Arrays can be passed to the builtin "length" function to get
20 //config: the number of elements in the array. This prints "1":
21 //config: a[0] = 0; length(a[])
22 //config: 4) The precedence of the boolean "not" operator (!) is equal to
23 //config: that of the unary minus (-) negation operator. This still
24 //config: allows POSIX-compliant scripts to work while somewhat
25 //config: preserving expected behavior (versus C) and making parsing
27 //config: 5) "read()" accepts expressions, not only numeric literals.
30 //config: -i --interactive force interactive mode
31 //config: -q --quiet don't print version and copyright
32 //config: -s --standard error if any non-POSIX extensions are used
33 //config: -w --warn warn if any non-POSIX extensions are used
34 //config: -l --mathlib use predefined math routines:
35 //config: s(expr) sine in radians
36 //config: c(expr) cosine in radians
37 //config: a(expr) arctangent, returning radians
38 //config: l(expr) natural log
39 //config: e(expr) raises e to the power of expr
40 //config: j(n, x) Bessel function of integer order n of x
43 //config: bool "dc (38 kb; 49 kb when combined with bc)"
46 //config: dc is a reverse-polish notation command-line calculator which
47 //config: supports unlimited precision arithmetic. See the FreeBSD man page
48 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
49 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
51 //config: This dc has a few differences from the two above:
52 //config: 1) When printing a byte stream (command "P"), this dc follows what
53 //config: the FreeBSD dc does.
54 //config: 2) Implements the GNU extensions for divmod ("~") and
55 //config: modular exponentiation ("|").
56 //config: 3) Implements all FreeBSD extensions, except for "J" and "M".
57 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
58 //config: However, they are implemented differently. When it encounters
59 //config: whitespace where a register should be, it skips the whitespace.
60 //config: If the character following is not a lowercase letter, an error
61 //config: is issued. Otherwise, the register name is parsed by the
62 //config: following regex:
63 //config: [a-z][a-z0-9_]*
64 //config: This generally means that register names will be surrounded by
65 //config: whitespace. Examples:
66 //config: l idx s temp L index S temp2 < do_thing
67 //config: Also note that, like the FreeBSD dc, extended registers are not
68 //config: allowed unless the "-x" option is given.
70 //config:config FEATURE_DC_SMALL
71 //config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
72 //config: depends on DC && !BC
75 //config:config FEATURE_DC_LIBM
76 //config: bool "Enable power and exp functions (requires libm)"
78 //config: depends on FEATURE_DC_SMALL
80 //config: Enable power and exp functions.
81 //config: NOTE: This will require libm to be present for linking.
83 //config:config FEATURE_BC_SIGNALS
84 //config: bool "Interactive mode (+4kb)"
86 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
88 //config: Enable interactive mode: when started on a tty,
89 //config: ^C interrupts execution and returns to command line,
90 //config: errors also return to command line instead of exiting,
91 //config: line editing with history is available.
93 //config: With this option off, input can still be taken from tty,
94 //config: but all errors are fatal, ^C is fatal,
95 //config: tty is treated exactly the same as any other
96 //config: standard input (IOW: no line editing).
98 //config:config FEATURE_BC_LONG_OPTIONS
99 //config: bool "Enable bc/dc long options"
101 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
103 //config: Enable long options for bc and dc.
105 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
106 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
108 //kbuild:lib-$(CONFIG_BC) += bc.o
109 //kbuild:lib-$(CONFIG_DC) += bc.o
111 //See www.gnu.org/software/bc/manual/bc.html
112 //usage:#define bc_trivial_usage
113 //usage: "[-sqlw] FILE..."
115 //usage:#define bc_full_usage "\n"
116 //usage: "\nArbitrary precision calculator"
118 ///////: "\n -i Interactive" - has no effect for now
119 //usage: "\n -q Quiet"
120 //usage: "\n -l Load standard math library"
121 //usage: "\n -s Be POSIX compatible"
122 //usage: "\n -w Warn if extensions are used"
123 ///////: "\n -v Version"
125 //usage: "\n$BC_LINE_LENGTH changes output width"
127 //usage:#define bc_example_usage
128 //usage: "3 + 4.129\n"
129 //usage: "1903 - 2893\n"
130 //usage: "-129 * 213.28935\n"
131 //usage: "12 / -1932\n"
133 //usage: "34 ^ 189\n"
134 //usage: "scale = 13\n"
135 //usage: "ibase = 2\n"
136 //usage: "obase = A\n"
138 //usage:#define dc_trivial_usage
139 //usage: IF_NOT_FEATURE_DC_SMALL("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
141 //usage:#define dc_full_usage "\n"
142 //usage: "\nTiny RPN calculator. Operations:"
143 //usage: "\n+, -, *, /, %, ~, ^," IF_NOT_FEATURE_DC_SMALL(" |,")
144 //usage: "\np - print top of the stack without popping"
145 //usage: "\nf - print entire stack"
146 //usage: "\nk - pop the value and set the precision"
147 //usage: "\ni - pop the value and set input radix"
148 //usage: "\no - pop the value and set output radix"
149 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
151 //usage:#define dc_example_usage
152 //usage: "$ dc -e'2 2 + p'\n"
154 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
156 //usage: "$ dc -e'0 1 & p'\n"
158 //usage: "$ dc -e'0 1 | p'\n"
160 //usage: "$ echo '72 9 / 8 * p' | dc\n"
164 #include "common_bufsiz.h"
166 #if ENABLE_FEATURE_DC_SMALL
170 #define DEBUG_LEXER 0
171 #define DEBUG_COMPILE 0
173 // This can be left enabled for production as well:
174 #define SANITY_CHECKS 1
177 static uint8_t lex_indent;
178 #define dbg_lex(...) \
180 fprintf(stderr, "%*s", lex_indent, ""); \
181 bb_error_msg(__VA_ARGS__); \
183 #define dbg_lex_enter(...) \
185 dbg_lex(__VA_ARGS__); \
188 #define dbg_lex_done(...) \
191 dbg_lex(__VA_ARGS__); \
194 # define dbg_lex(...) ((void)0)
195 # define dbg_lex_enter(...) ((void)0)
196 # define dbg_lex_done(...) ((void)0)
200 # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
202 # define dbg_compile(...) ((void)0)
206 # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
208 # define dbg_exec(...) ((void)0)
211 typedef enum BcStatus {
212 BC_STATUS_SUCCESS = 0,
213 BC_STATUS_FAILURE = 1,
214 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr_empty_ok() uses this
217 #define BC_VEC_INVALID_IDX ((size_t) -1)
218 #define BC_VEC_START_CAP (1 << 5)
220 typedef void (*BcVecFree)(void *) FAST_FUNC;
222 typedef struct BcVec {
230 typedef signed char BcDig;
232 typedef struct BcNum {
240 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
241 // larger value might speed up BIGNUM calculations a bit:
242 #define BC_NUM_DEF_SIZE (16)
243 #define BC_NUM_PRINT_WIDTH (69)
245 #define BC_NUM_KARATSUBA_LEN (32)
247 typedef enum BcInst {
254 XC_INST_NEG, // order
256 XC_INST_REL_EQ, // should
257 XC_INST_REL_LE, // match
258 XC_INST_REL_GE, // LEX
259 XC_INST_REL_NE, // constants
260 XC_INST_REL_LT, // for
261 XC_INST_REL_GT, // these
263 XC_INST_POWER, // operations
264 XC_INST_MULTIPLY, // |
266 XC_INST_MODULUS, // |
270 XC_INST_BOOL_NOT, // |
271 XC_INST_BOOL_OR, // |
272 XC_INST_BOOL_AND, // |
274 BC_INST_ASSIGN_POWER, // |
275 BC_INST_ASSIGN_MULTIPLY,// |
276 BC_INST_ASSIGN_DIVIDE, // |
277 BC_INST_ASSIGN_MODULUS, // |
278 BC_INST_ASSIGN_PLUS, // |
279 BC_INST_ASSIGN_MINUS, // |
289 XC_INST_IBASE, // order of these constans should match other enums
290 XC_INST_OBASE, // order of these constans should match other enums
291 XC_INST_SCALE, // order of these constans should match other enums
292 IF_BC(BC_INST_LAST,) // order of these constans should match other enums
323 DC_INST_PRINT_STREAM,
338 DC_INST_INVALID = -1,
342 typedef struct BcId {
347 typedef struct BcFunc {
353 IF_BC(size_t nparams;)
356 typedef enum BcResultType {
360 XC_RESULT_ARRAY_ELEM,
365 //code uses "inst - XC_INST_IBASE + XC_RESULT_IBASE" construct,
366 XC_RESULT_IBASE, // relative order should match for: XC_INST_IBASE
367 XC_RESULT_OBASE, // relative order should match for: XC_INST_OBASE
368 XC_RESULT_SCALE, // relative order should match for: XC_INST_SCALE
369 IF_BC(BC_RESULT_LAST,) // relative order should match for: BC_INST_LAST
371 IF_BC(BC_RESULT_ONE,)
374 typedef union BcResultData {
380 typedef struct BcResult {
385 typedef struct BcInstPtr {
388 IF_BC(size_t results_len_before_call;)
391 typedef enum BcLexType {
402 XC_LEX_NEG = XC_LEX_1st_op, // order
404 XC_LEX_OP_REL_EQ, // should
405 XC_LEX_OP_REL_LE, // match
406 XC_LEX_OP_REL_GE, // INST
407 XC_LEX_OP_REL_NE, // constants
408 XC_LEX_OP_REL_LT, // for
409 XC_LEX_OP_REL_GT, // these
411 XC_LEX_OP_POWER, // operations
412 XC_LEX_OP_MULTIPLY, // |
413 XC_LEX_OP_DIVIDE, // |
414 XC_LEX_OP_MODULUS, // |
416 XC_LEX_OP_MINUS, // |
417 XC_LEX_OP_last = XC_LEX_OP_MINUS,
419 BC_LEX_OP_BOOL_NOT, // |
420 BC_LEX_OP_BOOL_OR, // |
421 BC_LEX_OP_BOOL_AND, // |
423 BC_LEX_OP_ASSIGN_POWER, // |
424 BC_LEX_OP_ASSIGN_MULTIPLY, // |
425 BC_LEX_OP_ASSIGN_DIVIDE, // |
426 BC_LEX_OP_ASSIGN_MODULUS, // |
427 BC_LEX_OP_ASSIGN_PLUS, // |
428 BC_LEX_OP_ASSIGN_MINUS, // |
430 BC_LEX_OP_ASSIGN, // V
435 BC_LEX_LPAREN, // () are 0x28 and 0x29
436 BC_LEX_RPAREN, // must be LPAREN+1: code uses (c - '(' + BC_LEX_LPAREN)
438 BC_LEX_LBRACKET, // [] are 0x5B and 5D
440 BC_LEX_RBRACKET, // must be LBRACKET+2: code uses (c - '[' + BC_LEX_LBRACKET)
442 BC_LEX_LBRACE, // {} are 0x7B and 0x7D
444 BC_LEX_RBRACE, // must be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
446 BC_LEX_KEY_1st_keyword,
447 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
454 // code uses "type - BC_LEX_KEY_IBASE + XC_INST_IBASE" construct,
455 BC_LEX_KEY_IBASE, // relative order should match for: XC_INST_IBASE
456 BC_LEX_KEY_OBASE, // relative order should match for: XC_INST_OBASE
458 IF_BC(BC_LEX_KEY_LAST,) // relative order should match for: BC_INST_LAST
471 DC_LEX_OP_BOOL_NOT = XC_LEX_OP_last + 1,
503 // code uses "t - DC_LEX_STORE_IBASE + XC_INST_IBASE" construct,
504 DC_LEX_STORE_IBASE, // relative order should match for: XC_INST_IBASE
505 DC_LEX_STORE_OBASE, // relative order should match for: XC_INST_OBASE
506 DC_LEX_STORE_SCALE, // relative order should match for: XC_INST_SCALE
515 // must match order of BC_LEX_KEY_foo etc above
517 struct BcLexKeyword {
520 #define BC_LEX_KW_ENTRY(a, b) \
521 { .name8 = a /*, .posix = b */ }
522 static const struct BcLexKeyword bc_lex_kws[20] = {
523 BC_LEX_KW_ENTRY("auto" , 1), // 0
524 BC_LEX_KW_ENTRY("break" , 1), // 1
525 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
526 BC_LEX_KW_ENTRY("define" , 1), // 3
527 BC_LEX_KW_ENTRY("else" , 0), // 4
528 BC_LEX_KW_ENTRY("for" , 1), // 5
529 BC_LEX_KW_ENTRY("halt" , 0), // 6
530 BC_LEX_KW_ENTRY("ibase" , 1), // 7
531 BC_LEX_KW_ENTRY("obase" , 1), // 8
532 BC_LEX_KW_ENTRY("if" , 1), // 9
533 BC_LEX_KW_ENTRY("last" , 0), // 10
534 BC_LEX_KW_ENTRY("length" , 1), // 11
535 BC_LEX_KW_ENTRY("limits" , 0), // 12
536 BC_LEX_KW_ENTRY("print" , 0), // 13
537 BC_LEX_KW_ENTRY("quit" , 1), // 14
538 BC_LEX_KW_ENTRY("read" , 0), // 15
539 BC_LEX_KW_ENTRY("return" , 1), // 16
540 BC_LEX_KW_ENTRY("scale" , 1), // 17
541 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
542 BC_LEX_KW_ENTRY("while" , 1), // 19
544 #undef BC_LEX_KW_ENTRY
545 #define STRING_else (bc_lex_kws[4].name8)
546 #define STRING_for (bc_lex_kws[5].name8)
547 #define STRING_if (bc_lex_kws[9].name8)
548 #define STRING_while (bc_lex_kws[19].name8)
572 #define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
574 // This is a bit array that corresponds to token types. An entry is
575 // true if the token is valid in an expression, false otherwise.
576 // Used to figure out when expr parsing should stop *without error message*
577 // - 0 element indicates this condition. 1 means "this token is to be eaten
578 // as part of the expression", it can then still be determined to be invalid
579 // by later processing.
581 #define EXBITS(a,b,c,d,e,f,g,h) \
582 ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
583 BC_PARSE_EXPRS_BITS = 0 // corresponding BC_LEX_xyz:
584 + (EXBITS(0,0,0,0,0,1,1,1) << (0*8)) // 0: EOF INVAL NL WS STR NAME NUM -
585 + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: == <= >= != < > ^ *
586 + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: / % + - ! || && ^=
587 + (EXBITS(1,1,1,1,1,1,1,1) << (3*8)) // 24: *= /= %= += -= = ++ --
588 + (EXBITS(1,1,0,0,0,0,0,0) << (4*8)) // 32: ( ) [ , ] { ; }
589 + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
590 + (EXBITS(1,0,1,1,0,0,0,1) << (6*8)) // 48: obase if last length limits print quit read
591 + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
594 static ALWAYS_INLINE long lex_allowed_in_bc_expr(unsigned i)
596 #if ULONG_MAX > 0xffffffff
597 // 64-bit version (will not work correctly for 32-bit longs!)
598 return BC_PARSE_EXPRS_BITS & (1UL << i);
601 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
603 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
606 return m & (1UL << i);
610 // This is an array of data for operators that correspond to
611 // [XC_LEX_1st_op...] token types.
612 static const uint8_t bc_parse_ops[] = {
613 #define OP(p,l) ((int)(l) * 0x10 + (p))
615 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
617 OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
618 OP(4, true ), OP( 4, true ), // + -
620 OP(7, true ), OP( 7, true ), // or and
621 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
622 OP(5, false), OP( 5, false ), // -= =
623 OP(0, false), OP( 0, false ), // inc dec
626 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
627 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
631 static const //BcLexType - should be this type
635 XC_LEX_OP_MODULUS, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_LPAREN,
637 XC_LEX_INVALID, XC_LEX_OP_MULTIPLY, XC_LEX_OP_PLUS, XC_LEX_INVALID,
639 XC_LEX_OP_MINUS, XC_LEX_INVALID, XC_LEX_OP_DIVIDE,
641 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
642 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
643 XC_LEX_INVALID, XC_LEX_INVALID,
645 DC_LEX_COLON, DC_LEX_SCOLON, XC_LEX_OP_REL_GT, XC_LEX_OP_REL_EQ,
646 XC_LEX_OP_REL_LT, DC_LEX_READ, XC_LEX_INVALID,
648 XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
649 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_EQ_NO_REG, XC_LEX_INVALID,
651 DC_LEX_IBASE, XC_LEX_INVALID, DC_LEX_SCALE, DC_LEX_LOAD_POP,
652 XC_LEX_INVALID, DC_LEX_OP_BOOL_NOT, DC_LEX_OBASE, DC_LEX_PRINT_STREAM,
654 DC_LEX_NQUIT, DC_LEX_POP, DC_LEX_STORE_PUSH, XC_LEX_INVALID, XC_LEX_INVALID,
655 XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_SCALE_FACTOR, XC_LEX_INVALID,
657 DC_LEX_LENGTH, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
659 XC_LEX_OP_POWER, XC_LEX_NEG, XC_LEX_INVALID,
661 DC_LEX_ASCIIFY, XC_LEX_INVALID, DC_LEX_CLEAR_STACK, DC_LEX_DUPLICATE,
662 DC_LEX_ELSE, DC_LEX_PRINT_STACK, XC_LEX_INVALID, XC_LEX_INVALID,
664 DC_LEX_STORE_IBASE, XC_LEX_INVALID, DC_LEX_STORE_SCALE, DC_LEX_LOAD,
665 XC_LEX_INVALID, DC_LEX_PRINT_POP, DC_LEX_STORE_OBASE, DC_LEX_PRINT,
667 DC_LEX_QUIT, DC_LEX_SWAP, DC_LEX_OP_ASSIGN, XC_LEX_INVALID,
668 XC_LEX_INVALID, DC_LEX_SQRT, XC_LEX_INVALID, DC_LEX_EXECUTE,
670 XC_LEX_INVALID, DC_LEX_STACK_LEVEL,
672 DC_LEX_LBRACE, DC_LEX_OP_MODEXP, XC_LEX_INVALID, DC_LEX_OP_DIVMOD,
674 static const //BcInst - should be this type. Using signed narrow type since DC_INST_INVALID is -1
676 dc_LEX_to_INST[] = { // starts at XC_LEX_OP_POWER // corresponding XC/DC_LEX_xyz:
677 XC_INST_POWER, XC_INST_MULTIPLY, // OP_POWER OP_MULTIPLY
678 XC_INST_DIVIDE, XC_INST_MODULUS, // OP_DIVIDE OP_MODULUS
679 XC_INST_PLUS, XC_INST_MINUS, // OP_PLUS OP_MINUS
680 XC_INST_BOOL_NOT, // DC_LEX_OP_BOOL_NOT
681 DC_INST_INVALID, // DC_LEX_OP_ASSIGN
682 XC_INST_REL_GT, // DC_LEX_LPAREN
683 DC_INST_INVALID, // DC_LEX_SCOLON
684 DC_INST_INVALID, // DC_LEX_READ
685 XC_INST_IBASE, // DC_LEX_IBASE
686 XC_INST_SCALE, // DC_LEX_SCALE
687 XC_INST_OBASE, // DC_LEX_OBASE
688 XC_INST_LENGTH, // DC_LEX_LENGTH
689 XC_INST_PRINT, // DC_LEX_PRINT
690 DC_INST_QUIT, // DC_LEX_QUIT
691 XC_INST_SQRT, // DC_LEX_SQRT
692 XC_INST_REL_GE, // DC_LEX_LBRACE
693 XC_INST_REL_EQ, // DC_LEX_EQ_NO_REG
694 DC_INST_MODEXP, DC_INST_DIVMOD, // OP_MODEXP OP_DIVMOD
695 DC_INST_INVALID, DC_INST_INVALID, // COLON ELSE
696 DC_INST_EXECUTE, // EXECUTE
697 DC_INST_PRINT_STACK, DC_INST_CLEAR_STACK, // PRINT_STACK CLEAR_STACK
698 DC_INST_STACK_LEN, DC_INST_DUPLICATE, // STACK_LEVEL DUPLICATE
699 DC_INST_SWAP, XC_INST_POP, // SWAP POP
700 DC_INST_ASCIIFY, DC_INST_PRINT_STREAM, // ASCIIFY PRINT_STREAM
701 DC_INST_INVALID, DC_INST_INVALID, // STORE_IBASE STORE_OBASE
702 DC_INST_INVALID, DC_INST_INVALID, // STORE_SCALE LOAD
703 DC_INST_INVALID, DC_INST_INVALID, // LOAD_POP STORE_PUSH
704 XC_INST_PRINT, DC_INST_NQUIT, // PRINT_POP NQUIT
705 XC_INST_SCALE_FUNC, // SCALE_FACTOR
706 // DC_INST_INVALID in this table either means that corresponding LEX
707 // is not possible for dc, or that it does not compile one-to-one
712 typedef struct BcLex {
714 const char *lex_next_at; // last lex_next() was called at this string
719 smallint lex; // was BcLexType
720 smallint lex_last; // was BcLexType
724 #define BC_PARSE_STREND (0xff)
727 # define BC_PARSE_REL (1 << 0)
728 # define BC_PARSE_PRINT (1 << 1)
729 # define BC_PARSE_ARRAY (1 << 2)
730 # define BC_PARSE_NOCALL (1 << 3)
733 typedef struct BcParse {
743 IF_BC(size_t in_funcdef;)
746 typedef struct BcProgram {
776 #define BC_PROG_MAIN (0)
777 #define BC_PROG_READ (1)
779 #define BC_PROG_REQ_FUNCS (2)
782 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
783 #define BC_PROG_NUM(r, n) \
784 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
786 #define BC_FLAG_W (1 << 0)
787 #define BC_FLAG_V (1 << 1)
788 #define BC_FLAG_S (1 << 2)
789 #define BC_FLAG_Q (1 << 3)
790 #define BC_FLAG_L (1 << 4)
791 #define BC_FLAG_I (1 << 5)
792 #define DC_FLAG_X (1 << 6)
794 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
795 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
797 #define BC_MAX_OBASE ((unsigned) 999)
798 #define BC_MAX_DIM ((unsigned) INT_MAX)
799 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
800 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
801 #define BC_MAX_NUM BC_MAX_STRING
802 // Unused apart from "limits" message. Just show a "biggish number" there.
803 //#define BC_MAX_NAME BC_MAX_STRING
804 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
805 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
806 #define BC_MAX_NAME_STR "999999999"
807 #define BC_MAX_EXP_STR "999999999"
808 #define BC_MAX_VARS_STR "999999999"
810 #define BC_MAX_OBASE_STR "999"
812 #if INT_MAX == 2147483647
813 # define BC_MAX_DIM_STR "2147483647"
814 #elif INT_MAX == 9223372036854775807
815 # define BC_MAX_DIM_STR "9223372036854775807"
817 # error Strange INT_MAX
820 #if UINT_MAX == 4294967295
821 # define BC_MAX_SCALE_STR "4294967295"
822 # define BC_MAX_STRING_STR "4294967294"
823 #elif UINT_MAX == 18446744073709551615
824 # define BC_MAX_SCALE_STR "18446744073709551615"
825 # define BC_MAX_STRING_STR "18446744073709551614"
827 # error Strange UINT_MAX
829 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
832 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
833 IF_FEATURE_CLEAN_UP(smallint exiting;)
838 // For error messages. Can be set to current parsed line,
839 // or [TODO] to current executing line (can be before last parsed one)
848 #if ENABLE_FEATURE_EDITING
849 line_input_t *line_input_state;
852 #define G (*ptr_to_globals)
853 #define INIT_G() do { \
854 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
856 #define FREE_G() do { \
857 FREE_PTR_TO_GLOBALS(); \
859 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
860 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
861 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
862 #if ENABLE_FEATURE_BC_SIGNALS
863 # define G_interrupt bb_got_signal
864 # define G_ttyin G.ttyin
866 # define G_interrupt 0
869 #if ENABLE_FEATURE_CLEAN_UP
870 # define G_exiting G.exiting
874 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
875 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
877 // In configurations where errors abort instead of propagating error
878 // return code up the call chain, functions returning BC_STATUS
879 // actually don't return anything, they always succeed and return "void".
880 // A macro wrapper is provided, which makes this statement work:
882 // and makes it visible to the compiler that s is always zero,
883 // allowing compiler to optimize dead code after the statement.
885 // To make code more readable, each such function has a "z"
886 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
888 #if ENABLE_FEATURE_BC_SIGNALS || ENABLE_FEATURE_CLEAN_UP
889 # define ERRORS_ARE_FATAL 0
890 # define ERRORFUNC /*nothing*/
891 # define IF_ERROR_RETURN_POSSIBLE(a) a
892 # define BC_STATUS BcStatus
893 # define RETURN_STATUS(v) return (v)
894 # define COMMA_SUCCESS /*nothing*/
896 # define ERRORS_ARE_FATAL 1
897 # define ERRORFUNC NORETURN
898 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
899 # define BC_STATUS void
900 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
901 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
908 static void fflush_and_check(void)
911 if (ferror(stdout) || ferror(stderr))
912 bb_perror_msg_and_die("output error");
915 #if ENABLE_FEATURE_CLEAN_UP
916 #define QUIT_OR_RETURN_TO_MAIN \
918 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
920 return BC_STATUS_FAILURE; \
923 #define QUIT_OR_RETURN_TO_MAIN quit()
926 static void quit(void) NORETURN;
927 static void quit(void)
930 bb_perror_msg_and_die("input error");
932 dbg_exec("quit(): exiting with exitcode SUCCESS");
936 static void bc_verror_msg(const char *fmt, va_list p)
938 const char *sv = sv; // for compiler
941 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
943 bb_verror_msg(fmt, p, NULL);
945 free((char*)applet_name);
950 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
955 bc_verror_msg(fmt, p);
958 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
959 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
964 static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
968 // Are non-POSIX constructs totally ok?
969 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
970 RETURN_STATUS(BC_STATUS_SUCCESS); // yes
973 bc_verror_msg(fmt, p);
976 // Do we treat non-POSIX constructs as errors?
977 if (!(option_mask32 & BC_FLAG_S))
978 RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
980 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
981 RETURN_STATUS(BC_STATUS_FAILURE);
984 #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
987 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
988 // This idiom begs for tail-call optimization, but for it to work,
989 // function must not have caller-cleaned parameters on stack.
990 // Unfortunately, vararg function API does exactly that on most arches.
991 // Thus, use these shims for the cases when we have no vararg PARAMS:
992 static ERRORFUNC int bc_error(const char *msg)
994 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
996 static ERRORFUNC int bc_error_bad_character(char c)
999 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
1000 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
1002 static ERRORFUNC int bc_error_bad_expression(void)
1004 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
1006 static ERRORFUNC int bc_error_bad_token(void)
1008 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
1010 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1012 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1014 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1016 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1019 static BC_STATUS zbc_POSIX_requires(const char *msg)
1021 RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
1023 #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
1024 static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
1026 RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
1028 #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
1029 static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1031 RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg));
1033 #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)
1034 static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1036 RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg));
1038 #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)
1041 static void bc_vec_grow(BcVec *v, size_t n)
1043 size_t cap = v->cap * 2;
1044 while (cap < v->len + n) cap *= 2;
1045 v->v = xrealloc(v->v, v->size * cap);
1049 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1052 v->cap = BC_VEC_START_CAP;
1055 v->v = xmalloc(esize * BC_VEC_START_CAP);
1058 static void bc_char_vec_init(BcVec *v)
1060 bc_vec_init(v, sizeof(char), NULL);
1063 static void bc_vec_expand(BcVec *v, size_t req)
1066 v->v = xrealloc(v->v, v->size * req);
1071 static void bc_vec_pop(BcVec *v)
1075 v->dtor(v->v + (v->size * v->len));
1078 static void bc_vec_npop(BcVec *v, size_t n)
1083 size_t len = v->len - n;
1084 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1088 static void bc_vec_pop_all(BcVec *v)
1090 bc_vec_npop(v, v->len);
1093 static size_t bc_vec_push(BcVec *v, const void *data)
1095 size_t len = v->len;
1096 if (len >= v->cap) bc_vec_grow(v, 1);
1097 memmove(v->v + (v->size * len), data, v->size);
1102 // G.prog.results often needs "pop old operand, push result" idiom.
1103 // Can do this without a few extra ops
1104 static size_t bc_result_pop_and_push(const void *data)
1106 BcVec *v = &G.prog.results;
1108 size_t len = v->len - 1;
1110 last = v->v + (v->size * len);
1113 memmove(last, data, v->size);
1117 static size_t bc_vec_pushByte(BcVec *v, char data)
1119 return bc_vec_push(v, &data);
1122 static size_t bc_vec_pushZeroByte(BcVec *v)
1124 //return bc_vec_pushByte(v, '\0');
1126 return bc_vec_push(v, &const_int_0);
1129 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1132 bc_vec_push(v, data);
1136 if (v->len == v->cap) bc_vec_grow(v, 1);
1138 ptr = v->v + v->size * idx;
1140 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1141 memmove(ptr, data, v->size);
1145 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1148 bc_vec_expand(v, len + 1);
1149 memcpy(v->v, str, len);
1152 bc_vec_pushZeroByte(v);
1155 #if ENABLE_FEATURE_BC_SIGNALS && ENABLE_FEATURE_EDITING
1156 static void bc_vec_concat(BcVec *v, const char *str)
1160 if (v->len == 0) bc_vec_pushZeroByte(v);
1163 len = v->len + slen;
1165 if (v->cap < len) bc_vec_grow(v, slen);
1166 strcpy(v->v + v->len - 1, str);
1172 static void *bc_vec_item(const BcVec *v, size_t idx)
1174 return v->v + v->size * idx;
1177 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1179 return v->v + v->size * (v->len - idx - 1);
1182 static void *bc_vec_top(const BcVec *v)
1184 return v->v + v->size * (v->len - 1);
1187 static FAST_FUNC void bc_vec_free(void *vec)
1189 BcVec *v = (BcVec *) vec;
1194 static BcFunc* bc_program_func(size_t idx)
1196 return bc_vec_item(&G.prog.fns, idx);
1198 // BC_PROG_MAIN is zeroth element, so:
1199 #define bc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1202 static BcFunc* bc_program_current_func(void)
1204 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1205 BcFunc *func = bc_program_func(ip->func);
1210 static char** bc_program_str(size_t idx)
1214 BcFunc *func = bc_program_current_func();
1215 return bc_vec_item(&func->strs, idx);
1218 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1221 static char** bc_program_const(size_t idx)
1225 BcFunc *func = bc_program_current_func();
1226 return bc_vec_item(&func->consts, idx);
1229 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1232 static int bc_id_cmp(const void *e1, const void *e2)
1234 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1237 static FAST_FUNC void bc_id_free(void *id)
1239 free(((BcId *) id)->name);
1242 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1244 size_t low = 0, high = v->len;
1246 while (low < high) {
1247 size_t mid = (low + high) / 2;
1248 BcId *id = bc_vec_item(v, mid);
1249 int result = bc_id_cmp(ptr, id);
1262 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1264 size_t n = *i = bc_map_find_ge(v, ptr);
1267 bc_vec_push(v, ptr);
1268 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1269 return 0; // "was not inserted"
1271 bc_vec_pushAt(v, ptr, n);
1272 return 1; // "was inserted"
1276 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1278 size_t i = bc_map_find_ge(v, ptr);
1279 if (i >= v->len) return BC_VEC_INVALID_IDX;
1280 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1284 static void bc_num_setToZero(BcNum *n, size_t scale)
1291 static void bc_num_zero(BcNum *n)
1293 bc_num_setToZero(n, 0);
1296 static void bc_num_one(BcNum *n)
1298 bc_num_setToZero(n, 0);
1303 // Note: this also sets BcNum to zero
1304 static void bc_num_init(BcNum *n, size_t req)
1306 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1307 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1308 n->num = xmalloc(req);
1315 static void bc_num_init_DEF_SIZE(BcNum *n)
1317 bc_num_init(n, BC_NUM_DEF_SIZE);
1320 static void bc_num_expand(BcNum *n, size_t req)
1322 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1324 n->num = xrealloc(n->num, req);
1329 static FAST_FUNC void bc_num_free(void *num)
1331 free(((BcNum *) num)->num);
1334 static void bc_num_copy(BcNum *d, BcNum *s)
1337 bc_num_expand(d, s->cap);
1341 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1345 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1348 unsigned long result;
1352 while (i > n->rdx) {
1353 unsigned long prev = result;
1354 result = result * 10 + n->num[--i];
1355 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1356 // 0x1ff00000 * 10 is 0x13f600000,
1357 // or 0x3f600000 truncated to 32 bits. Which is larger.
1358 // However, (N*10)/8 < N check is always correct.
1359 if ((result / 8) < prev)
1360 RETURN_STATUS(bc_error("overflow"));
1364 RETURN_STATUS(BC_STATUS_SUCCESS);
1366 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1368 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1370 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1372 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1374 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1376 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1377 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1378 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1379 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1381 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1382 // would not hit realloc() code path - not good if num[] is not malloced
1384 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1390 if (val == 0) return;
1392 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1399 if (val == 0) break;
1403 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1406 for (i = 0; i < len; ++i) {
1408 for (j = i; a[j] < 0;) {
1415 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1433 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1434 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1435 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1436 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1437 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1439 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1441 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1442 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1444 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1447 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1449 size_t i, min, a_int, b_int, diff;
1450 BcDig *max_num, *min_num;
1454 if (a == b) return 0;
1455 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1456 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1458 if (a->neg != b->neg) // signs of a and b differ
1459 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1460 return (int)b->neg - (int)a->neg;
1461 neg = a->neg; // 1 if both negative, 0 if both positive
1463 a_int = BC_NUM_INT(a);
1464 b_int = BC_NUM_INT(b);
1467 if (a_int != 0) return (ssize_t) a_int;
1469 a_max = (a->rdx > b->rdx);
1472 diff = a->rdx - b->rdx;
1473 max_num = a->num + diff;
1475 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1478 diff = b->rdx - a->rdx;
1479 max_num = b->num + diff;
1481 neg = !neg; // same as "neg = (a_max == neg)"
1484 cmp = bc_num_compare(max_num, min_num, b_int + min);
1485 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1487 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1488 if (max_num[i]) return BC_NUM_NEG(1, neg);
1494 static void bc_num_truncate(BcNum *n, size_t places)
1496 if (places == 0) return;
1502 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1506 static void bc_num_extend(BcNum *n, size_t places)
1508 size_t len = n->len + places;
1511 if (n->cap < len) bc_num_expand(n, len);
1513 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1514 memset(n->num, 0, sizeof(BcDig) * places);
1521 static void bc_num_clean(BcNum *n)
1523 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1526 else if (n->len < n->rdx)
1530 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1533 bc_num_extend(n, scale - n->rdx);
1535 bc_num_truncate(n, n->rdx - scale);
1538 if (n->len != 0) n->neg = !neg1 != !neg2;
1541 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1545 b->len = n->len - idx;
1547 a->rdx = b->rdx = 0;
1549 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1550 memcpy(a->num, n->num, idx * sizeof(BcDig));
1560 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1562 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1564 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1565 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1566 if (places + n->len > BC_MAX_NUM)
1567 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1570 if (n->rdx >= places)
1573 bc_num_extend(n, places - n->rdx);
1579 RETURN_STATUS(BC_STATUS_SUCCESS);
1581 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1583 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1585 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1586 BcNumBinaryOp op, size_t req)
1589 BcNum num2, *ptr_a, *ptr_b;
1594 memcpy(ptr_a, c, sizeof(BcNum));
1602 memcpy(ptr_b, c, sizeof(BcNum));
1609 bc_num_init(c, req);
1611 bc_num_expand(c, req);
1613 s = BC_STATUS_SUCCESS;
1614 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1616 if (init) bc_num_free(&num2);
1620 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1622 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1623 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1624 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1625 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1626 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1627 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1629 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1631 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1633 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1636 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1638 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1640 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1643 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1645 size_t req = BC_NUM_MREQ(a, b, scale);
1646 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1649 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1651 size_t req = BC_NUM_MREQ(a, b, scale);
1652 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1655 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1657 size_t req = BC_NUM_MREQ(a, b, scale);
1658 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1661 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1663 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1666 static const BcNumBinaryOp zbc_program_ops[] = {
1667 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1669 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1670 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1671 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1672 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1673 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1674 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1676 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1685 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1687 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1689 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1691 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1692 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1695 // Because this function doesn't need to use scale (per the bc spec),
1696 // I am hijacking it to say whether it's doing an add or a subtract.
1700 if (sub && c->len) c->neg = !c->neg;
1701 RETURN_STATUS(BC_STATUS_SUCCESS);
1705 RETURN_STATUS(BC_STATUS_SUCCESS);
1709 c->rdx = BC_MAX(a->rdx, b->rdx);
1710 min_rdx = BC_MIN(a->rdx, b->rdx);
1713 if (a->rdx > b->rdx) {
1714 diff = a->rdx - b->rdx;
1716 ptr_a = a->num + diff;
1719 diff = b->rdx - a->rdx;
1722 ptr_b = b->num + diff;
1726 for (i = 0; i < diff; ++i, ++c->len)
1730 a_int = BC_NUM_INT(a);
1731 b_int = BC_NUM_INT(b);
1733 if (a_int > b_int) {
1744 for (i = 0; i < min_rdx + min_int; ++i) {
1745 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1747 ptr_c[i] = (BcDig)(in % 10);
1749 for (; i < max + min_rdx; ++i) {
1750 unsigned in = (unsigned)ptr[i] + carry;
1752 ptr_c[i] = (BcDig)(in % 10);
1756 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1758 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1761 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1764 BcNum *minuend, *subtrahend;
1766 bool aneg, bneg, neg;
1768 // Because this function doesn't need to use scale (per the bc spec),
1769 // I am hijacking it to say whether it's doing an add or a subtract.
1773 if (sub && c->len) c->neg = !c->neg;
1774 RETURN_STATUS(BC_STATUS_SUCCESS);
1778 RETURN_STATUS(BC_STATUS_SUCCESS);
1783 a->neg = b->neg = false;
1785 cmp = bc_num_cmp(a, b);
1791 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1792 RETURN_STATUS(BC_STATUS_SUCCESS);
1800 if (sub) neg = !neg;
1805 bc_num_copy(c, minuend);
1808 if (c->rdx < subtrahend->rdx) {
1809 bc_num_extend(c, subtrahend->rdx - c->rdx);
1812 start = c->rdx - subtrahend->rdx;
1814 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1818 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1821 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1823 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1826 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1827 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1830 if (a->len == 0 || b->len == 0) {
1832 RETURN_STATUS(BC_STATUS_SUCCESS);
1834 aone = BC_NUM_ONE(a);
1835 if (aone || BC_NUM_ONE(b)) {
1836 bc_num_copy(c, aone ? b : a);
1837 RETURN_STATUS(BC_STATUS_SUCCESS);
1840 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1841 || a->len < BC_NUM_KARATSUBA_LEN
1842 || b->len < BC_NUM_KARATSUBA_LEN
1846 bc_num_expand(c, a->len + b->len + 1);
1848 memset(c->num, 0, sizeof(BcDig) * c->cap);
1851 for (i = 0; i < b->len; ++i) {
1853 for (j = 0; j < a->len; ++j) {
1854 unsigned in = c->num[i + j];
1855 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1856 // note: compilers prefer _unsigned_ div/const
1858 c->num[i + j] = (BcDig)(in % 10);
1861 c->num[i + j] += (BcDig) carry;
1862 len = BC_MAX(len, i + j + !!carry);
1864 #if ENABLE_FEATURE_BC_SIGNALS
1866 // a*a <- without check below, this will not be interruptible
1867 if (G_interrupt) return BC_STATUS_FAILURE;
1873 RETURN_STATUS(BC_STATUS_SUCCESS);
1876 bc_num_init(&l1, max);
1877 bc_num_init(&h1, max);
1878 bc_num_init(&l2, max);
1879 bc_num_init(&h2, max);
1880 bc_num_init(&m1, max);
1881 bc_num_init(&m2, max);
1882 bc_num_init(&z0, max);
1883 bc_num_init(&z1, max);
1884 bc_num_init(&z2, max);
1885 bc_num_init(&temp, max + max);
1887 bc_num_split(a, max2, &l1, &h1);
1888 bc_num_split(b, max2, &l2, &h2);
1890 s = zbc_num_add(&h1, &l1, &m1, 0);
1892 s = zbc_num_add(&h2, &l2, &m2, 0);
1895 s = zbc_num_k(&h1, &h2, &z0);
1897 s = zbc_num_k(&m1, &m2, &z1);
1899 s = zbc_num_k(&l1, &l2, &z2);
1902 s = zbc_num_sub(&z1, &z0, &temp, 0);
1904 s = zbc_num_sub(&temp, &z2, &z1, 0);
1907 s = zbc_num_shift(&z0, max2 * 2);
1909 s = zbc_num_shift(&z1, max2);
1911 s = zbc_num_add(&z0, &z1, &temp, 0);
1913 s = zbc_num_add(&temp, &z2, c, 0);
1928 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1932 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1934 scale = BC_MAX(scale, a->rdx);
1935 scale = BC_MAX(scale, b->rdx);
1936 scale = BC_MIN(a->rdx + b->rdx, scale);
1937 maxrdx = BC_MAX(maxrdx, scale);
1939 bc_num_init(&cpa, a->len);
1940 bc_num_init(&cpb, b->len);
1942 bc_num_copy(&cpa, a);
1943 bc_num_copy(&cpb, b);
1944 cpa.neg = cpb.neg = false;
1946 s = zbc_num_shift(&cpa, maxrdx);
1948 s = zbc_num_shift(&cpb, maxrdx);
1950 s = zbc_num_k(&cpa, &cpb, c);
1954 bc_num_expand(c, c->len + maxrdx);
1956 if (c->len < maxrdx) {
1957 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1962 bc_num_retireMul(c, scale, a->neg, b->neg);
1968 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1970 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1977 RETURN_STATUS(bc_error("divide by zero"));
1979 bc_num_setToZero(c, scale);
1980 RETURN_STATUS(BC_STATUS_SUCCESS);
1982 if (BC_NUM_ONE(b)) {
1984 bc_num_retireMul(c, scale, a->neg, b->neg);
1985 RETURN_STATUS(BC_STATUS_SUCCESS);
1988 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1989 bc_num_copy(&cp, a);
1993 bc_num_expand(&cp, len + 2);
1994 bc_num_extend(&cp, len - cp.len);
1997 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1999 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
2001 if (b->rdx == b->len) {
2003 if (len == 0) break;
2005 if (b->num[len] != 0)
2011 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
2013 // We want an extra zero in front to make things simpler.
2014 cp.num[cp.len++] = 0;
2017 bc_num_expand(c, cp.len);
2020 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2024 s = BC_STATUS_SUCCESS;
2025 for (i = end - 1; i < end; --i) {
2028 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2029 bc_num_subArrays(n, b->num, len);
2031 #if ENABLE_FEATURE_BC_SIGNALS
2034 // 1/a <- without check below, this will not be interruptible
2036 s = BC_STATUS_FAILURE;
2042 bc_num_retireMul(c, scale, a->neg, b->neg);
2047 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2049 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2050 BcNum *restrict d, size_t scale, size_t ts)
2057 RETURN_STATUS(bc_error("divide by zero"));
2060 bc_num_setToZero(d, ts);
2061 RETURN_STATUS(BC_STATUS_SUCCESS);
2064 bc_num_init(&temp, d->cap);
2065 s = zbc_num_d(a, b, c, scale);
2068 if (scale != 0) scale = ts;
2070 s = zbc_num_m(c, b, &temp, scale);
2072 s = zbc_num_sub(a, &temp, d, scale);
2075 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2078 bc_num_retireMul(d, ts, a->neg, b->neg);
2084 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2086 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2090 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2092 bc_num_init(&c1, len);
2093 s = zbc_num_r(a, b, &c1, c, scale, ts);
2098 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2100 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2102 BcStatus s = BC_STATUS_SUCCESS;
2105 size_t i, powrdx, resrdx;
2108 // GNU bc does not allow 2^2.0 - we do
2109 for (i = 0; i < b->rdx; i++)
2111 RETURN_STATUS(bc_error("not an integer"));
2115 RETURN_STATUS(BC_STATUS_SUCCESS);
2118 bc_num_setToZero(c, scale);
2119 RETURN_STATUS(BC_STATUS_SUCCESS);
2121 if (BC_NUM_ONE(b)) {
2125 s = zbc_num_inv(a, c, scale);
2130 s = zbc_num_ulong_abs(b, &pow);
2131 if (s) RETURN_STATUS(s);
2132 // b is not used beyond this point
2134 bc_num_init(©, a->len);
2135 bc_num_copy(©, a);
2140 if (a->rdx * pow < scale)
2141 scale = a->rdx * pow;
2145 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2147 s = zbc_num_mul(©, ©, ©, powrdx);
2149 // Not needed: zbc_num_mul() has a check for ^C:
2150 //if (G_interrupt) {
2151 // s = BC_STATUS_FAILURE;
2156 bc_num_copy(c, ©);
2158 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2160 s = zbc_num_mul(©, ©, ©, powrdx);
2165 s = zbc_num_mul(c, ©, c, resrdx);
2168 // Not needed: zbc_num_mul() has a check for ^C:
2169 //if (G_interrupt) {
2170 // s = BC_STATUS_FAILURE;
2176 s = zbc_num_inv(c, c, scale);
2180 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2182 // We can't use bc_num_clean() here.
2183 for (i = 0; i < c->len; ++i)
2186 bc_num_setToZero(c, scale);
2193 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2195 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2198 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2199 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2200 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2202 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2203 bc_num_expand(b, req);
2206 bc_num_setToZero(b, scale);
2207 RETURN_STATUS(BC_STATUS_SUCCESS);
2210 RETURN_STATUS(bc_error("negative number"));
2212 if (BC_NUM_ONE(a)) {
2214 bc_num_extend(b, scale);
2215 RETURN_STATUS(BC_STATUS_SUCCESS);
2218 scale = BC_MAX(scale, a->rdx) + 1;
2219 len = a->len + scale;
2221 bc_num_init(&num1, len);
2222 bc_num_init(&num2, len);
2223 bc_num_init_DEF_SIZE(&half);
2229 bc_num_init(&f, len);
2230 bc_num_init(&fprime, len);
2236 pow = BC_NUM_INT(a);
2244 pow -= 2 - (pow & 1);
2246 bc_num_extend(x0, pow);
2248 // Make sure to move the radix back.
2252 x0->rdx = digs = digs1 = 0;
2254 len = BC_NUM_INT(x0) + resrdx - 1;
2256 while (cmp != 0 || digs < len) {
2257 s = zbc_num_div(a, x0, &f, resrdx);
2259 s = zbc_num_add(x0, &f, &fprime, resrdx);
2261 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2264 cmp = bc_num_cmp(x1, x0);
2265 digs = x1->len - (unsigned long long) llabs(cmp);
2267 if (cmp == cmp2 && digs == digs1)
2272 resrdx += times > 4;
2285 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2287 bc_num_free(&fprime);
2294 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2296 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2302 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2305 memcpy(&num2, c, sizeof(BcNum));
2307 bc_num_init(c, len);
2311 bc_num_expand(c, len);
2314 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2316 if (init) bc_num_free(&num2);
2320 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2323 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2326 BcNum base, exp, two, temp;
2330 RETURN_STATUS(bc_error("divide by zero"));
2331 if (a->rdx || b->rdx || c->rdx)
2332 RETURN_STATUS(bc_error("not an integer"));
2334 RETURN_STATUS(bc_error("negative number"));
2336 bc_num_expand(d, c->len);
2337 bc_num_init(&base, c->len);
2338 bc_num_init(&exp, b->len);
2339 bc_num_init(&temp, b->len);
2341 two.cap = ARRAY_SIZE(two_digs);
2348 s = zbc_num_rem(a, c, &base, 0);
2350 bc_num_copy(&exp, b);
2352 while (exp.len != 0) {
2353 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2356 if (BC_NUM_ONE(&temp)) {
2357 s = zbc_num_mul(d, &base, &temp, 0);
2359 s = zbc_num_rem(&temp, c, d, 0);
2363 s = zbc_num_mul(&base, &base, &temp, 0);
2365 s = zbc_num_rem(&temp, c, &base, 0);
2374 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2377 static FAST_FUNC void bc_string_free(void *string)
2379 free(*(char**)string);
2382 static void bc_func_init(BcFunc *f)
2384 bc_char_vec_init(&f->code);
2385 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2386 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2387 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2388 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2389 IF_BC(f->nparams = 0;)
2392 static FAST_FUNC void bc_func_free(void *func)
2394 BcFunc *f = (BcFunc *) func;
2395 bc_vec_free(&f->code);
2396 IF_BC(bc_vec_free(&f->labels);)
2397 IF_BC(bc_vec_free(&f->autos);)
2398 IF_BC(bc_vec_free(&f->strs);)
2399 IF_BC(bc_vec_free(&f->consts);)
2402 static void bc_array_expand(BcVec *a, size_t len);
2404 static void bc_array_init(BcVec *a, bool nums)
2407 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2409 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2410 bc_array_expand(a, 1);
2413 static void bc_array_expand(BcVec *a, size_t len)
2415 if (a->dtor == bc_num_free
2416 // && a->size == sizeof(BcNum) - always true
2419 while (len > a->len) {
2420 bc_num_init_DEF_SIZE(&n);
2425 while (len > a->len) {
2426 bc_array_init(&v, true);
2432 static void bc_array_copy(BcVec *d, const BcVec *s)
2438 bc_vec_expand(d, s->cap);
2443 for (i = 0; i < s->len; i++, dnum++, snum++) {
2444 bc_num_init(dnum, snum->len);
2445 bc_num_copy(dnum, snum);
2450 static void dc_result_copy(BcResult *d, BcResult *src)
2455 case XC_RESULT_TEMP:
2456 case XC_RESULT_IBASE:
2457 case XC_RESULT_SCALE:
2458 case XC_RESULT_OBASE:
2459 bc_num_init(&d->d.n, src->d.n.len);
2460 bc_num_copy(&d->d.n, &src->d.n);
2463 case XC_RESULT_ARRAY:
2464 case XC_RESULT_ARRAY_ELEM:
2465 d->d.id.name = xstrdup(src->d.id.name);
2467 case XC_RESULT_CONSTANT:
2468 IF_BC(case BC_RESULT_LAST:)
2469 IF_BC(case BC_RESULT_ONE:)
2471 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2477 static FAST_FUNC void bc_result_free(void *result)
2479 BcResult *r = (BcResult *) result;
2482 case XC_RESULT_TEMP:
2483 case XC_RESULT_IBASE:
2484 case XC_RESULT_SCALE:
2485 case XC_RESULT_OBASE:
2486 bc_num_free(&r->d.n);
2489 case XC_RESULT_ARRAY:
2490 case XC_RESULT_ARRAY_ELEM:
2499 static int bad_input_byte(char c)
2501 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2504 bc_error_fmt("illegal character 0x%02x", c);
2510 // Note: it _appends_ data from fp to vec.
2511 static void bc_read_line(BcVec *vec, FILE *fp)
2516 #if ENABLE_FEATURE_BC_SIGNALS
2517 if (G_interrupt) { // ^C was pressed
2520 // ^C while running a script (bc SCRIPT): die.
2521 // We do not return to interactive prompt:
2522 // user might be running us from a shell,
2523 // and SCRIPT might be intended to terminate
2524 // (e.g. contain a "halt" stmt).
2525 // ^C dropping user into a bc prompt instead of
2526 // the shell would be unexpected.
2529 // ^C while interactive input
2531 // GNU bc says "interrupted execution."
2532 // GNU dc says "Interrupt!"
2533 fputs("\ninterrupted execution\n", stderr);
2536 # if ENABLE_FEATURE_EDITING
2537 if (G_ttyin && fp == stdin) {
2539 # define line_buf bb_common_bufsiz1
2540 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2541 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2544 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2549 char c = line_buf[i++];
2551 if (bad_input_byte(c)) goto again;
2553 bc_vec_concat(vec, line_buf);
2561 size_t len = vec->len;
2564 #if ENABLE_FEATURE_BC_SIGNALS
2566 // ^C was pressed: ignore entire line, get another one
2571 do c = fgetc(fp); while (c == '\0');
2574 bb_perror_msg_and_die("input error");
2575 // Note: EOF does not append '\n'
2578 bad_chars |= bad_input_byte(c);
2579 bc_vec_pushByte(vec, (char)c);
2580 } while (c != '\n');
2583 // Bad chars on this line
2584 if (!G.prog.file) { // stdin
2585 // ignore entire line, get another one
2589 bb_perror_msg_and_die("file '%s' is not text", G.prog.file);
2591 bc_vec_pushZeroByte(vec);
2599 static bool bc_num_strValid(const char *val, size_t base)
2604 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2611 if (radix) return false;
2615 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2621 // Note: n is already "bc_num_zero()"ed,
2622 // leading zeroes in "val" are removed
2623 static void bc_num_parseDecimal(BcNum *n, const char *val)
2632 bc_num_expand(n, len);
2634 ptr = strchr(val, '.');
2638 n->rdx = (size_t)((val + len) - (ptr + 1));
2640 for (i = 0; val[i]; ++i) {
2641 if (val[i] != '0' && val[i] != '.') {
2642 // Not entirely zero value - convert it, and exit
2645 n->num[n->len] = val[i] - '0';
2649 if (val[--i] == '.') goto skip_dot;
2654 // if for() exits without hitting if(), the value is entirely zero
2657 // Note: n is already "bc_num_zero()"ed,
2658 // leading zeroes in "val" are removed
2659 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2662 BcNum temp, mult, result;
2664 BcDig base_digs[ULONG_NUM_BUFSIZE];
2669 for (i = 0; ; ++i) {
2672 if (val[i] != '.' && val[i] != '0')
2676 bc_num_init_DEF_SIZE(&temp);
2677 bc_num_init_DEF_SIZE(&mult);
2678 base.cap = ARRAY_SIZE(base_digs);
2679 base.num = base_digs;
2680 bc_num_ulong2num(&base, base_t);
2684 if (c == '\0') goto int_err;
2685 if (c == '.') break;
2687 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2689 s = zbc_num_mul(n, &base, &mult, 0);
2690 if (s) goto int_err;
2691 bc_num_ulong2num(&temp, v);
2692 s = zbc_num_add(&mult, &temp, n, 0);
2693 if (s) goto int_err;
2696 bc_num_init(&result, base.len);
2697 //bc_num_zero(&result); - already is
2703 if (c == '\0') break;
2706 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2708 s = zbc_num_mul(&result, &base, &result, 0);
2710 bc_num_ulong2num(&temp, v);
2711 s = zbc_num_add(&result, &temp, &result, 0);
2713 s = zbc_num_mul(&mult, &base, &mult, 0);
2717 s = zbc_num_div(&result, &mult, &result, digits);
2719 s = zbc_num_add(n, &result, n, digits);
2723 if (n->rdx < digits)
2724 bc_num_extend(n, digits - n->rdx);
2728 bc_num_free(&result);
2734 static BC_STATUS zbc_num_parse(BcNum *n, const char *val, unsigned base_t)
2736 if (!bc_num_strValid(val, base_t))
2737 RETURN_STATUS(bc_error("bad number string"));
2740 while (*val == '0') val++;
2743 bc_num_parseDecimal(n, val);
2745 bc_num_parseBase(n, val, base_t);
2747 RETURN_STATUS(BC_STATUS_SUCCESS);
2749 #define zbc_num_parse(...) (zbc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2751 static void bc_lex_lineComment(BcLex *l)
2753 // Try: echo -n '#foo' | bc
2755 l->lex = XC_LEX_WHITESPACE;
2757 while (i < l->len && l->buf[i] != '\n')
2762 static void bc_lex_whitespace(BcLex *l)
2764 l->lex = XC_LEX_WHITESPACE;
2766 char c = l->buf[l->i];
2767 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2775 static BC_STATUS zbc_lex_number(BcLex *l, char start)
2777 const char *buf = l->buf + l->i;
2778 size_t len, i, ccnt;
2781 pt = (start == '.');
2782 l->lex = XC_LEX_NUMBER;
2788 if (c == '\\' && buf[i + 1] == '\n') {
2790 //number_of_backslashes++ - see comment below
2793 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2794 if (c != '.') break;
2795 // if '.' was already seen, stop on second one:
2799 // buf[i] is one of "0-9A-F."
2804 //ccnt is the number of chars in the number string, excluding possible
2805 //trailing "[\<newline>].[\<newline>]" (with any number of \<NL> repetitions).
2806 //i is buf[i] index of the first not-yet-parsed char after that.
2809 // This might overestimate the size, if there are "\<NL>"'s
2810 // in the number. Subtracting number_of_backslashes*2 correctly
2811 // is not that easy: consider that in the case of "NNN.\<NL>"
2812 // loop above will count "\<NL>" before it realizes it is not
2813 // in fact *inside* the number:
2814 len = ccnt + 1; // +1 byte for NUL termination
2816 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2817 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2818 if (len > BC_MAX_NUM)
2819 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
2822 bc_vec_pop_all(&l->lex_buf);
2823 bc_vec_expand(&l->lex_buf, 1 + len);
2824 bc_vec_push(&l->lex_buf, &start);
2827 // If we have hit a backslash, skip it. We don't have
2828 // to check for a newline because it's guaranteed.
2834 bc_vec_push(&l->lex_buf, buf);
2839 bc_vec_pushZeroByte(&l->lex_buf);
2841 RETURN_STATUS(BC_STATUS_SUCCESS);
2843 #define zbc_lex_number(...) (zbc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2845 static void bc_lex_name(BcLex *l)
2850 l->lex = XC_LEX_NAME;
2853 buf = l->buf + l->i - 1;
2856 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2860 #if 0 // We do not protect against people with gigabyte-long names
2861 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2862 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2863 if (i > BC_MAX_STRING)
2864 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2867 bc_vec_string(&l->lex_buf, i, buf);
2869 // Increment the index. We minus 1 because it has already been incremented.
2872 //return BC_STATUS_SUCCESS;
2875 static void bc_lex_init(BcLex *l)
2877 bc_char_vec_init(&l->lex_buf);
2880 static void bc_lex_free(BcLex *l)
2882 bc_vec_free(&l->lex_buf);
2885 static void bc_lex_file(BcLex *l)
2887 G.err_line = l->line = 1;
2891 static bool bc_lex_more_input(BcLex *l)
2896 bc_vec_pop_all(&G.input_buffer);
2898 // This loop is complex because the vm tries not to send any lines that end
2899 // with a backslash to the parser. The reason for that is because the parser
2900 // treats a backslash+newline combo as whitespace, per the bc spec. In that
2901 // case, and for strings and comments, the parser will expect more stuff.
2905 size_t prevlen = G.input_buffer.len;
2908 bc_read_line(&G.input_buffer, G.input_fp);
2909 // No more input means EOF
2910 if (G.input_buffer.len <= prevlen + 1) // (we expect +1 for NUL byte)
2913 string = G.input_buffer.v + prevlen;
2916 if (string == G.input_buffer.v || string[-1] != '\\') {
2927 if (c == '/' && *string == '*') {
2932 if (c == '*' && *string == '/') {
2937 if (str != 0 || comment) {
2938 G.input_buffer.len--; // backstep over the trailing NUL byte
2942 // Check for backslash+newline.
2943 // we do not check that last char is '\n' -
2944 // if it is not, then it's EOF, and looping back
2945 // to bc_read_line() will detect it:
2947 if (string >= G.input_buffer.v && *string == '\\') {
2948 G.input_buffer.len--;
2955 l->buf = G.input_buffer.v;
2957 // bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2958 l->len = G.input_buffer.len - 1; // do not include NUL
2963 IF_BC(static BC_STATUS zbc_lex_token(BcLex *l);)
2964 IF_DC(static BC_STATUS zdc_lex_token(BcLex *l);)
2965 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2966 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2968 static BC_STATUS zbc_lex_next(BcLex *l)
2972 l->lex_last = l->lex;
2973 if (l->lex_last == XC_LEX_EOF) RETURN_STATUS(bc_error("end of file"));
2975 l->line += l->newline;
2976 G.err_line = l->line;
2979 // Loop until failure or we don't have whitespace. This
2980 // is so the parser doesn't get inundated with whitespace.
2981 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2982 s = BC_STATUS_SUCCESS;
2984 if (l->i == l->len) {
2985 l->lex = XC_LEX_EOF;
2987 RETURN_STATUS(BC_STATUS_SUCCESS);
2988 if (!bc_lex_more_input(l)) {
2990 RETURN_STATUS(BC_STATUS_SUCCESS);
2992 // here it's guaranteed that l->i is below l->len
2994 l->lex_next_at = l->buf + l->i;
2995 dbg_lex("next string to parse:'%.*s'",
2996 (int)(strchrnul(l->lex_next_at, '\n') - l->lex_next_at),
3000 IF_BC(s = zbc_lex_token(l));
3002 IF_DC(s = zdc_lex_token(l));
3004 } while (!s && l->lex == XC_LEX_WHITESPACE);
3005 dbg_lex("l->lex from string:%d", l->lex);
3009 #define zbc_lex_next(...) (zbc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
3012 static BC_STATUS zbc_lex_skip_if_at_NLINE(BcLex *l)
3014 if (l->lex == XC_LEX_NLINE)
3015 RETURN_STATUS(zbc_lex_next(l));
3016 RETURN_STATUS(BC_STATUS_SUCCESS);
3018 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3020 static BC_STATUS zbc_lex_next_and_skip_NLINE(BcLex *l)
3023 s = zbc_lex_next(l);
3024 if (s) RETURN_STATUS(s);
3025 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
3026 s = zbc_lex_skip_if_at_NLINE(l);
3029 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3032 static BC_STATUS zbc_lex_text_init(BcLex *l, const char *text)
3036 l->len = strlen(text);
3037 l->lex = l->lex_last = XC_LEX_INVALID;
3038 RETURN_STATUS(zbc_lex_next(l));
3040 #define zbc_lex_text_init(...) (zbc_lex_text_init(__VA_ARGS__) COMMA_SUCCESS)
3043 static BC_STATUS zbc_lex_identifier(BcLex *l)
3047 const char *buf = l->buf + l->i - 1;
3049 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3050 const char *keyword8 = bc_lex_kws[i].name8;
3052 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3054 if (j == 8) goto match;
3056 if (keyword8[j] != '\0')
3059 // buf starts with keyword bc_lex_kws[i]
3060 if (isalnum(buf[j]) || buf[j]=='_')
3061 continue; // "ifz" does not match "if" keyword, "if." does
3062 l->lex = BC_LEX_KEY_1st_keyword + i;
3063 if (!bc_lex_kws_POSIX(i)) {
3064 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3065 if (s) RETURN_STATUS(s);
3068 // We minus 1 because the index has already been incremented.
3070 RETURN_STATUS(BC_STATUS_SUCCESS);
3074 s = BC_STATUS_SUCCESS;
3076 if (l->lex_buf.len > 2) {
3079 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3081 unsigned len = strchrnul(buf, '\n') - buf;
3082 s = zbc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3087 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3089 static BC_STATUS zbc_lex_string(BcLex *l)
3093 l->lex = XC_LEX_STR;
3101 RETURN_STATUS(bc_error("string end could not be found"));
3110 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3111 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3112 if (len > BC_MAX_STRING)
3113 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3115 bc_vec_string(&l->lex_buf, len, l->buf + l->i);
3119 G.err_line = l->line;
3121 RETURN_STATUS(BC_STATUS_SUCCESS);
3123 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3125 static void bc_lex_assign(BcLex *l, unsigned with_and_without)
3127 if (l->buf[l->i] == '=') {
3129 with_and_without >>= 8; // store "with" value
3130 } // else store "without" value
3131 l->lex = (with_and_without & 0xff);
3133 #define bc_lex_assign(l, with, without) \
3134 bc_lex_assign(l, ((with)<<8)|(without))
3136 static BC_STATUS zbc_lex_comment(BcLex *l)
3139 const char *buf = l->buf;
3141 l->lex = XC_LEX_WHITESPACE;
3142 i = l->i; /* here buf[l->i] is the '*' of opening comment delimiter */
3154 RETURN_STATUS(bc_error("comment end could not be found"));
3161 G.err_line = l->line;
3163 RETURN_STATUS(BC_STATUS_SUCCESS);
3165 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3167 #undef zbc_lex_token
3168 static BC_STATUS zbc_lex_token(BcLex *l)
3170 BcStatus s = BC_STATUS_SUCCESS;
3171 char c = l->buf[l->i++], c2;
3173 // This is the workhorse of the lexer.
3175 // case '\0': // probably never reached
3177 // l->lex = XC_LEX_EOF;
3178 // l->newline = true;
3181 l->lex = XC_LEX_NLINE;
3189 bc_lex_whitespace(l);
3192 bc_lex_assign(l, XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3193 if (l->lex == BC_LEX_OP_BOOL_NOT) {
3194 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3195 if (s) RETURN_STATUS(s);
3199 s = zbc_lex_string(l);
3202 s = zbc_POSIX_does_not_allow("'#' script comments");
3203 if (s) RETURN_STATUS(s);
3204 bc_lex_lineComment(l);
3207 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3212 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3213 if (s) RETURN_STATUS(s);
3215 l->lex = BC_LEX_OP_BOOL_AND;
3217 l->lex = XC_LEX_INVALID;
3218 s = bc_error_bad_character('&');
3223 l->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3226 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3232 l->lex = BC_LEX_OP_INC;
3234 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3237 l->lex = BC_LEX_COMMA;
3243 l->lex = BC_LEX_OP_DEC;
3245 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3248 if (isdigit(l->buf[l->i]))
3249 s = zbc_lex_number(l, c);
3251 l->lex = BC_LEX_KEY_LAST;
3252 s = zbc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3258 s = zbc_lex_comment(l);
3260 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3278 s = zbc_lex_number(l, c);
3281 l->lex = BC_LEX_SCOLON;
3284 bc_lex_assign(l, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3287 bc_lex_assign(l, XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3290 bc_lex_assign(l, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3294 l->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3297 if (l->buf[l->i] == '\n') {
3298 l->lex = XC_LEX_WHITESPACE;
3301 s = bc_error_bad_character(c);
3304 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3332 s = zbc_lex_identifier(l);
3336 l->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3341 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3342 if (s) RETURN_STATUS(s);
3344 l->lex = BC_LEX_OP_BOOL_OR;
3346 l->lex = XC_LEX_INVALID;
3347 s = bc_error_bad_character(c);
3351 l->lex = XC_LEX_INVALID;
3352 s = bc_error_bad_character(c);
3358 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3362 static BC_STATUS zdc_lex_register(BcLex *l)
3364 if (G_exreg && isspace(l->buf[l->i])) {
3365 bc_lex_whitespace(l); // eats whitespace (but not newline)
3366 l->i++; // bc_lex_name() expects this
3369 bc_vec_pop_all(&l->lex_buf);
3370 bc_vec_push(&l->lex_buf, &l->buf[l->i++]);
3371 bc_vec_pushZeroByte(&l->lex_buf);
3372 l->lex = XC_LEX_NAME;
3375 RETURN_STATUS(BC_STATUS_SUCCESS);
3377 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3379 static BC_STATUS zdc_lex_string(BcLex *l)
3381 size_t depth, nls, i;
3383 l->lex = XC_LEX_STR;
3384 bc_vec_pop_all(&l->lex_buf);
3393 RETURN_STATUS(bc_error("string end could not be found"));
3396 if (i == l->i || l->buf[i - 1] != '\\') {
3397 if (c == '[') depth++;
3402 bc_vec_push(&l->lex_buf, &l->buf[i]);
3407 bc_vec_pushZeroByte(&l->lex_buf);
3408 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3409 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3410 if (i - l->i > BC_MAX_STRING)
3411 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3416 G.err_line = l->line;
3418 RETURN_STATUS(BC_STATUS_SUCCESS);
3420 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3422 #undef zdc_lex_token
3423 static BC_STATUS zdc_lex_token(BcLex *l)
3425 static const //BcLexType - should be this type, but narrower type saves size:
3428 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3429 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3430 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3438 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3439 if (l->lex_last == dc_lex_regs[i])
3440 RETURN_STATUS(zdc_lex_register(l));
3443 s = BC_STATUS_SUCCESS;
3445 if (c >= '%' && c <= '~'
3446 && (l->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3451 // This is the workhorse of the lexer.
3453 // case '\0': // probably never reached
3454 // l->lex = XC_LEX_EOF;
3457 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3458 // (and "case '\n':" is not just empty here)
3459 // only to allow interactive dc have a way to exit
3460 // "parse" stage of "parse,execute" loop
3461 // on <enter>, not on _next_ token (which would mean
3462 // commands are not executed on pressing <enter>).
3463 // IOW: typing "1p<enter>" should print "1" _at once_,
3464 // not after some more input.
3465 l->lex = XC_LEX_NLINE;
3473 l->newline = 0; // was (c == '\n')
3474 bc_lex_whitespace(l);
3479 l->lex = XC_LEX_OP_REL_NE;
3481 l->lex = XC_LEX_OP_REL_LE;
3483 l->lex = XC_LEX_OP_REL_GE;
3485 RETURN_STATUS(bc_error_bad_character(c));
3489 bc_lex_lineComment(l);
3492 if (isdigit(l->buf[l->i]))
3493 s = zbc_lex_number(l, c);
3495 s = bc_error_bad_character(c);
3513 s = zbc_lex_number(l, c);
3516 s = zdc_lex_string(l);
3519 l->lex = XC_LEX_INVALID;
3520 s = bc_error_bad_character(c);
3526 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3529 static void bc_parse_push(BcParse *p, char i)
3531 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, p->func->code.len, i);
3532 bc_vec_pushByte(&p->func->code, i);
3535 static void bc_parse_pushName(BcParse *p, char *name)
3538 bc_parse_push(p, *name++);
3539 bc_parse_push(p, BC_PARSE_STREND);
3542 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3547 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3548 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3551 if (idx & mask) break;
3556 bc_parse_push(p, amt);
3559 bc_parse_push(p, (unsigned char)idx);
3565 static void bc_parse_pushJUMP(BcParse *p, size_t idx)
3567 bc_parse_push(p, BC_INST_JUMP);
3568 bc_parse_pushIndex(p, idx);
3571 static void bc_parse_pushJUMP_ZERO(BcParse *p, size_t idx)
3573 bc_parse_push(p, BC_INST_JUMP_ZERO);
3574 bc_parse_pushIndex(p, idx);
3577 static BC_STATUS zbc_parse_pushSTR(BcParse *p)
3579 char *str = xstrdup(p->l.lex_buf.v);
3581 bc_parse_push(p, XC_INST_STR);
3582 bc_parse_pushIndex(p, p->func->strs.len);
3583 bc_vec_push(&p->func->strs, &str);
3585 RETURN_STATUS(zbc_lex_next(&p->l));
3587 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3590 static void bc_parse_pushNUM(BcParse *p)
3592 char *num = xstrdup(p->l.lex_buf.v);
3593 #if ENABLE_BC && ENABLE_DC
3594 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3596 size_t idx = bc_vec_push(&p->func->consts, &num);
3598 size_t idx = bc_vec_push(&G.prog.consts, &num);
3600 bc_parse_push(p, XC_INST_NUM);
3601 bc_parse_pushIndex(p, idx);
3604 static BC_STATUS zbc_parse_text_init(BcParse *p, const char *text)
3606 p->func = bc_program_func(p->fidx);
3608 RETURN_STATUS(zbc_lex_text_init(&p->l, text));
3610 #define zbc_parse_text_init(...) (zbc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3612 // Called when parsing or execution detects a failure,
3613 // resets execution structures.
3614 static void bc_program_reset(void)
3619 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3620 bc_vec_pop_all(&G.prog.results);
3622 f = bc_program_func_BC_PROG_MAIN();
3623 ip = bc_vec_top(&G.prog.exestack);
3624 ip->inst_idx = f->code.len;
3627 // Called when parsing code detects a failure,
3628 // resets parsing structures.
3629 static void bc_parse_reset(BcParse *p)
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 = bc_program_func_BC_PROG_MAIN();
3640 p->l.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 bc_parse_free(BcParse *p)
3651 IF_BC(bc_vec_free(&p->exits);)
3652 IF_BC(bc_vec_free(&p->conds);)
3653 IF_BC(bc_vec_free(&p->ops);)
3657 static void bc_parse_create(BcParse *p, size_t fidx)
3659 memset(p, 0, sizeof(BcParse));
3662 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3663 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3664 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3667 p->func = bc_program_func(fidx);
3670 static void bc_program_add_fn(void)
3676 bc_vec_push(&G.prog.fns, &f);
3682 // Note: takes ownership of 'name' (must be malloced)
3683 static size_t bc_program_addFunc(char *name)
3686 BcId entry, *entry_ptr;
3690 entry.idx = G.prog.fns.len;
3692 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3693 if (!inserted) free(name);
3695 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3696 idx = entry_ptr->idx;
3699 // There is already a function with this name.
3700 // It'll be redefined now, clear old definition.
3701 BcFunc *func = bc_program_func(entry_ptr->idx);
3705 bc_program_add_fn();
3711 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3712 // We can calculate the conversion between tokens and exprs by subtracting the
3713 // position of the first operator in the lex enum and adding the position of the
3714 // first in the expr enum. Note: This only works for binary operators.
3715 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3717 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags);
3719 static BC_STATUS zbc_parse_expr(BcParse *p, uint8_t flags)
3723 s = bc_parse_expr_empty_ok(p, flags);
3724 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3725 RETURN_STATUS(bc_error("empty expression"));
3728 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3730 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed);
3731 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3733 static BC_STATUS zbc_parse_stmt(BcParse *p)
3735 RETURN_STATUS(zbc_parse_stmt_possibly_auto(p, false));
3737 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3739 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(BcParse *p, const char *after_X)
3741 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3742 // Same for "else", "while()", "for()".
3743 BcStatus s = zbc_lex_next_and_skip_NLINE(&p->l);
3744 if (s) RETURN_STATUS(s);
3745 if (p->l.lex == XC_LEX_NLINE)
3746 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3748 RETURN_STATUS(zbc_parse_stmt(p));
3750 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3752 static void bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3755 char l, r = bc_parse_op_PREC(type - XC_LEX_1st_op);
3756 bool left = bc_parse_op_LEFT(type - XC_LEX_1st_op);
3758 while (p->ops.len > start) {
3759 BcLexType t = BC_PARSE_TOP_OP(p);
3760 if (t == BC_LEX_LPAREN) break;
3762 l = bc_parse_op_PREC(t - XC_LEX_1st_op);
3763 if (l >= r && (l != r || !left)) break;
3765 bc_parse_push(p, BC_TOKEN_2_INST(t));
3766 bc_vec_pop(&p->ops);
3767 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3770 bc_vec_push(&p->ops, &type);
3773 static BC_STATUS zbc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3777 if (p->ops.len <= ops_bgn)
3778 RETURN_STATUS(bc_error_bad_expression());
3779 top = BC_PARSE_TOP_OP(p);
3781 while (top != BC_LEX_LPAREN) {
3782 bc_parse_push(p, BC_TOKEN_2_INST(top));
3784 bc_vec_pop(&p->ops);
3785 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3787 if (p->ops.len <= ops_bgn)
3788 RETURN_STATUS(bc_error_bad_expression());
3789 top = BC_PARSE_TOP_OP(p);
3792 bc_vec_pop(&p->ops);
3794 RETURN_STATUS(BC_STATUS_SUCCESS);
3796 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3798 static BC_STATUS zbc_parse_params(BcParse *p, uint8_t flags)
3803 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
3804 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3806 s = zbc_lex_next(&p->l);
3807 if (s) RETURN_STATUS(s);
3810 if (p->l.lex != BC_LEX_RPAREN) {
3812 s = zbc_parse_expr(p, flags);
3813 if (s) RETURN_STATUS(s);
3815 if (p->l.lex != BC_LEX_COMMA) {
3816 if (p->l.lex == BC_LEX_RPAREN)
3818 RETURN_STATUS(bc_error_bad_token());
3820 s = zbc_lex_next(&p->l);
3821 if (s) RETURN_STATUS(s);
3825 bc_parse_push(p, BC_INST_CALL);
3826 bc_parse_pushIndex(p, nparams);
3828 RETURN_STATUS(BC_STATUS_SUCCESS);
3830 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3832 // Note: takes ownership of 'name' (must be malloced)
3833 static BC_STATUS zbc_parse_call(BcParse *p, char *name, uint8_t flags)
3836 BcId entry, *entry_ptr;
3841 s = zbc_parse_params(p, flags);
3844 if (p->l.lex != BC_LEX_RPAREN) {
3845 s = bc_error_bad_token();
3849 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3851 if (idx == BC_VEC_INVALID_IDX) {
3852 // No such function exists, create an empty one
3853 bc_program_addFunc(name);
3854 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3858 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3859 bc_parse_pushIndex(p, entry_ptr->idx);
3861 RETURN_STATUS(zbc_lex_next(&p->l));
3866 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3868 static BC_STATUS zbc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3873 name = xstrdup(p->l.lex_buf.v);
3874 s = zbc_lex_next(&p->l);
3877 if (p->l.lex == BC_LEX_LBRACKET) {
3878 s = zbc_lex_next(&p->l);
3881 if (p->l.lex == BC_LEX_RBRACKET) {
3882 if (!(flags & BC_PARSE_ARRAY)) {
3883 s = bc_error_bad_expression();
3886 *type = XC_INST_ARRAY;
3888 *type = XC_INST_ARRAY_ELEM;
3889 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3890 s = zbc_parse_expr(p, flags);
3893 s = zbc_lex_next(&p->l);
3895 bc_parse_push(p, *type);
3896 bc_parse_pushName(p, name);
3898 } else if (p->l.lex == BC_LEX_LPAREN) {
3899 if (flags & BC_PARSE_NOCALL) {
3900 s = bc_error_bad_token();
3903 *type = BC_INST_CALL;
3904 s = zbc_parse_call(p, name, flags);
3906 *type = XC_INST_VAR;
3907 bc_parse_push(p, XC_INST_VAR);
3908 bc_parse_pushName(p, name);
3917 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3919 static BC_STATUS zbc_parse_read(BcParse *p)
3923 s = zbc_lex_next(&p->l);
3924 if (s) RETURN_STATUS(s);
3925 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3927 s = zbc_lex_next(&p->l);
3928 if (s) RETURN_STATUS(s);
3929 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3931 bc_parse_push(p, XC_INST_READ);
3935 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3937 static BC_STATUS zbc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3942 s = zbc_lex_next(&p->l);
3943 if (s) RETURN_STATUS(s);
3944 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3946 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3948 s = zbc_lex_next(&p->l);
3949 if (s) RETURN_STATUS(s);
3951 s = zbc_parse_expr(p, flags);
3952 if (s) RETURN_STATUS(s);
3954 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3956 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3957 bc_parse_push(p, *prev);
3961 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3963 static BC_STATUS zbc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3967 s = zbc_lex_next(&p->l);
3968 if (s) RETURN_STATUS(s);
3970 if (p->l.lex != BC_LEX_LPAREN) {
3971 *type = XC_INST_SCALE;
3972 bc_parse_push(p, XC_INST_SCALE);
3973 RETURN_STATUS(BC_STATUS_SUCCESS);
3976 *type = XC_INST_SCALE_FUNC;
3977 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3979 s = zbc_lex_next(&p->l);
3980 if (s) RETURN_STATUS(s);
3982 s = zbc_parse_expr(p, flags);
3983 if (s) RETURN_STATUS(s);
3984 if (p->l.lex != BC_LEX_RPAREN)
3985 RETURN_STATUS(bc_error_bad_token());
3986 bc_parse_push(p, XC_INST_SCALE_FUNC);
3988 RETURN_STATUS(zbc_lex_next(&p->l));
3990 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3992 static BC_STATUS zbc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3993 size_t *nexprs, uint8_t flags)
3998 BcInst etype = *prev;
4000 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
4001 || etype == XC_INST_SCALE || etype == BC_INST_LAST
4002 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
4004 *prev = inst = BC_INST_INC_POST + (p->l.lex != BC_LEX_OP_INC);
4005 bc_parse_push(p, inst);
4006 s = zbc_lex_next(&p->l);
4008 *prev = inst = BC_INST_INC_PRE + (p->l.lex != BC_LEX_OP_INC);
4011 s = zbc_lex_next(&p->l);
4012 if (s) RETURN_STATUS(s);
4015 // Because we parse the next part of the expression
4016 // right here, we need to increment this.
4017 *nexprs = *nexprs + 1;
4021 s = zbc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4023 case BC_LEX_KEY_IBASE:
4024 case BC_LEX_KEY_LAST:
4025 case BC_LEX_KEY_OBASE:
4026 bc_parse_push(p, type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4027 s = zbc_lex_next(&p->l);
4029 case BC_LEX_KEY_SCALE:
4030 s = zbc_lex_next(&p->l);
4031 if (s) RETURN_STATUS(s);
4032 if (p->l.lex == BC_LEX_LPAREN)
4033 s = bc_error_bad_token();
4035 bc_parse_push(p, XC_INST_SCALE);
4038 s = bc_error_bad_token();
4042 if (!s) bc_parse_push(p, inst);
4047 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4050 #define BC_PARSE_LEAF(p, rparen) \
4052 || ((p) >= XC_INST_NUM && (p) <= XC_INST_SQRT) \
4053 || (p) == BC_INST_INC_POST \
4054 || (p) == BC_INST_DEC_POST \
4057 static int ok_in_expr(BcInst p)
4059 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
4060 || p == BC_INST_INC_POST
4061 || p == BC_INST_DEC_POST
4064 #define BC_PARSE_LEAF(p, rparen) ((rparen) || ok_in_expr(p))
4067 static BC_STATUS zbc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4068 bool rparen, size_t *nexprs)
4072 BcInst etype = *prev;
4074 s = zbc_lex_next(&p->l);
4075 if (s) RETURN_STATUS(s);
4077 type = BC_PARSE_LEAF(etype, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
4078 *prev = BC_TOKEN_2_INST(type);
4080 // We can just push onto the op stack because this is the largest
4081 // precedence operator that gets pushed. Inc/dec does not.
4082 if (type != XC_LEX_OP_MINUS)
4083 bc_vec_push(&p->ops, &type);
4085 bc_parse_operator(p, type, ops_bgn, nexprs);
4089 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4091 static BC_STATUS zbc_parse_print(BcParse *p)
4097 s = zbc_lex_next(&p->l);
4098 if (s) RETURN_STATUS(s);
4100 if (type == XC_LEX_STR) {
4101 s = zbc_parse_pushSTR(p);
4103 s = zbc_parse_expr(p, 0);
4105 if (s) RETURN_STATUS(s);
4106 bc_parse_push(p, XC_INST_PRINT_POP);
4107 if (p->l.lex != BC_LEX_COMMA)
4113 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4115 static BC_STATUS zbc_parse_return(BcParse *p)
4120 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4121 s = zbc_lex_next(&p->l);
4122 if (s) RETURN_STATUS(s);
4125 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON)
4126 bc_parse_push(p, BC_INST_RET0);
4128 bool paren = (t == BC_LEX_LPAREN);
4129 s = bc_parse_expr_empty_ok(p, 0);
4130 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4131 bc_parse_push(p, BC_INST_RET0);
4132 s = zbc_lex_next(&p->l);
4134 if (s) RETURN_STATUS(s);
4136 if (!paren || p->l.lex_last != BC_LEX_RPAREN) {
4137 s = zbc_POSIX_requires("parentheses around return expressions");
4138 if (s) RETURN_STATUS(s);
4141 bc_parse_push(p, XC_INST_RET);
4144 dbg_lex_done("%s:%d done", __func__, __LINE__);
4147 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4149 static void rewrite_label_to_current(BcParse *p, size_t idx)
4151 size_t *label = bc_vec_item(&p->func->labels, idx);
4152 *label = p->func->code.len;
4155 static BC_STATUS zbc_parse_if(BcParse *p)
4160 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4161 s = zbc_lex_next(&p->l);
4162 if (s) RETURN_STATUS(s);
4163 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4165 s = zbc_lex_next(&p->l);
4166 if (s) RETURN_STATUS(s);
4167 s = zbc_parse_expr(p, BC_PARSE_REL);
4168 if (s) RETURN_STATUS(s);
4169 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4171 // Encode "if zero, jump to ..."
4172 // Pushed value (destination of the jump) is uninitialized,
4173 // will be rewritten to be address of "end of if()" or of "else".
4174 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4175 bc_parse_pushJUMP_ZERO(p, ip_idx);
4177 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_if);
4178 if (s) RETURN_STATUS(s);
4180 dbg_lex("%s:%d in if after stmt: p->l.lex:%d", __func__, __LINE__, p->l.lex);
4181 if (p->l.lex == BC_LEX_KEY_ELSE) {
4184 // Encode "after then_stmt, jump to end of if()"
4185 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4186 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4187 bc_parse_pushJUMP(p, ip2_idx);
4189 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4190 rewrite_label_to_current(p, ip_idx);
4194 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_else);
4195 if (s) RETURN_STATUS(s);
4198 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4199 rewrite_label_to_current(p, ip_idx);
4201 dbg_lex_done("%s:%d done", __func__, __LINE__);
4204 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4206 static BC_STATUS zbc_parse_while(BcParse *p)
4212 s = zbc_lex_next(&p->l);
4213 if (s) RETURN_STATUS(s);
4214 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4215 s = zbc_lex_next(&p->l);
4216 if (s) RETURN_STATUS(s);
4218 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4219 ip_idx = cond_idx + 1;
4220 bc_vec_push(&p->conds, &cond_idx);
4222 bc_vec_push(&p->exits, &ip_idx);
4223 bc_vec_push(&p->func->labels, &ip_idx);
4225 s = zbc_parse_expr(p, BC_PARSE_REL);
4226 if (s) RETURN_STATUS(s);
4227 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4229 bc_parse_pushJUMP_ZERO(p, ip_idx);
4231 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_while);
4232 if (s) RETURN_STATUS(s);
4234 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4235 bc_parse_pushJUMP(p, cond_idx);
4237 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4238 rewrite_label_to_current(p, ip_idx);
4240 bc_vec_pop(&p->exits);
4241 bc_vec_pop(&p->conds);
4245 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4247 static BC_STATUS zbc_parse_for(BcParse *p)
4250 size_t cond_idx, exit_idx, body_idx, update_idx;
4252 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
4253 s = zbc_lex_next(&p->l);
4254 if (s) RETURN_STATUS(s);
4255 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4256 s = zbc_lex_next(&p->l);
4257 if (s) RETURN_STATUS(s);
4259 if (p->l.lex != BC_LEX_SCOLON) {
4260 s = zbc_parse_expr(p, 0);
4261 bc_parse_push(p, XC_INST_POP);
4262 if (s) RETURN_STATUS(s);
4264 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4265 if (s) RETURN_STATUS(s);
4268 if (p->l.lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4269 s = zbc_lex_next(&p->l);
4270 if (s) RETURN_STATUS(s);
4272 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4273 update_idx = cond_idx + 1;
4274 body_idx = update_idx + 1;
4275 exit_idx = body_idx + 1;
4277 if (p->l.lex != BC_LEX_SCOLON)
4278 s = zbc_parse_expr(p, BC_PARSE_REL);
4280 // Set this for the next call to bc_parse_pushNUM().
4281 // This is safe to set because the current token is a semicolon,
4282 // which has no string requirement.
4283 bc_vec_string(&p->l.lex_buf, 1, "1");
4284 bc_parse_pushNUM(p);
4285 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4287 if (s) RETURN_STATUS(s);
4289 if (p->l.lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4291 s = zbc_lex_next(&p->l);
4292 if (s) RETURN_STATUS(s);
4294 bc_parse_pushJUMP_ZERO(p, exit_idx);
4295 bc_parse_pushJUMP(p, body_idx);
4297 bc_vec_push(&p->conds, &update_idx);
4298 bc_vec_push(&p->func->labels, &p->func->code.len);
4300 if (p->l.lex != BC_LEX_RPAREN) {
4301 s = zbc_parse_expr(p, 0);
4302 if (s) RETURN_STATUS(s);
4303 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4304 bc_parse_push(p, XC_INST_POP);
4306 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4307 if (s) RETURN_STATUS(s);
4310 bc_parse_pushJUMP(p, cond_idx);
4311 bc_vec_push(&p->func->labels, &p->func->code.len);
4313 bc_vec_push(&p->exits, &exit_idx);
4314 bc_vec_push(&p->func->labels, &exit_idx);
4316 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_for);
4317 if (s) RETURN_STATUS(s);
4319 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4320 bc_parse_pushJUMP(p, update_idx);
4322 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4323 rewrite_label_to_current(p, exit_idx);
4325 bc_vec_pop(&p->exits);
4326 bc_vec_pop(&p->conds);
4328 RETURN_STATUS(BC_STATUS_SUCCESS);
4330 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4332 static BC_STATUS zbc_parse_break_or_continue(BcParse *p, BcLexType type)
4336 if (type == BC_LEX_KEY_BREAK) {
4337 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4338 RETURN_STATUS(bc_error_bad_token());
4339 i = *(size_t*)bc_vec_top(&p->exits);
4341 i = *(size_t*)bc_vec_top(&p->conds);
4343 bc_parse_pushJUMP(p, i);
4345 RETURN_STATUS(zbc_lex_next(&p->l));
4347 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4349 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4355 autoid = (void*)f->autos.v;
4356 for (i = 0; i < f->autos.len; i++, autoid++) {
4357 if (strcmp(name, autoid->name) == 0)
4358 RETURN_STATUS(bc_error("function parameter or auto var has the same name as another"));
4364 bc_vec_push(&f->autos, &a);
4366 RETURN_STATUS(BC_STATUS_SUCCESS);
4368 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4370 static BC_STATUS zbc_parse_funcdef(BcParse *p)
4373 bool var, comma = false;
4376 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4377 s = zbc_lex_next(&p->l);
4378 if (s) RETURN_STATUS(s);
4379 if (p->l.lex != XC_LEX_NAME)
4380 RETURN_STATUS(bc_error("bad function definition"));
4382 name = xstrdup(p->l.lex_buf.v);
4383 p->fidx = bc_program_addFunc(name);
4384 p->func = bc_program_func(p->fidx);
4386 s = zbc_lex_next(&p->l);
4387 if (s) RETURN_STATUS(s);
4388 if (p->l.lex != BC_LEX_LPAREN)
4389 RETURN_STATUS(bc_error("bad function definition"));
4390 s = zbc_lex_next(&p->l);
4391 if (s) RETURN_STATUS(s);
4393 while (p->l.lex != BC_LEX_RPAREN) {
4394 if (p->l.lex != XC_LEX_NAME)
4395 RETURN_STATUS(bc_error("bad function definition"));
4399 name = xstrdup(p->l.lex_buf.v);
4400 s = zbc_lex_next(&p->l);
4403 var = p->l.lex != BC_LEX_LBRACKET;
4406 s = zbc_lex_next(&p->l);
4409 if (p->l.lex != BC_LEX_RBRACKET) {
4410 s = bc_error("bad function definition");
4414 s = zbc_lex_next(&p->l);
4418 comma = p->l.lex == BC_LEX_COMMA;
4420 s = zbc_lex_next(&p->l);
4424 s = zbc_func_insert(p->func, name, var);
4428 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4430 s = zbc_lex_next(&p->l);
4431 if (s) RETURN_STATUS(s);
4433 if (p->l.lex != BC_LEX_LBRACE) {
4434 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4435 if (s) RETURN_STATUS(s);
4438 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4439 s = zbc_lex_skip_if_at_NLINE(&p->l);
4440 if (s) RETURN_STATUS(s);
4441 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4442 if (p->l.lex != BC_LEX_LBRACE)
4443 RETURN_STATUS(bc_error("function { body } expected"));
4445 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4446 s = zbc_parse_stmt_possibly_auto(p, true);
4448 if (s) RETURN_STATUS(s);
4450 bc_parse_push(p, BC_INST_RET0);
4452 // Subsequent code generation is into main program
4453 p->fidx = BC_PROG_MAIN;
4454 p->func = bc_program_func_BC_PROG_MAIN();
4456 dbg_lex_done("%s:%d done", __func__, __LINE__);
4459 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4463 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4465 static BC_STATUS zbc_parse_auto(BcParse *p)
4470 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4471 s = zbc_lex_next(&p->l);
4472 if (s) RETURN_STATUS(s);
4477 if (p->l.lex != XC_LEX_NAME)
4478 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4480 name = xstrdup(p->l.lex_buf.v);
4481 s = zbc_lex_next(&p->l);
4484 var = (p->l.lex != BC_LEX_LBRACKET);
4486 s = zbc_lex_next(&p->l);
4489 if (p->l.lex != BC_LEX_RBRACKET) {
4490 s = bc_error("bad 'auto' syntax");
4493 s = zbc_lex_next(&p->l);
4497 s = zbc_func_insert(p->func, name, var);
4500 if (p->l.lex == XC_LEX_NLINE
4501 || p->l.lex == BC_LEX_SCOLON
4502 //|| p->l.lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4506 if (p->l.lex != BC_LEX_COMMA)
4507 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4508 s = zbc_lex_next(&p->l); // skip comma
4509 if (s) RETURN_STATUS(s);
4512 dbg_lex_done("%s:%d done", __func__, __LINE__);
4513 RETURN_STATUS(BC_STATUS_SUCCESS);
4516 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4519 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4521 #undef zbc_parse_stmt_possibly_auto
4522 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed)
4524 BcStatus s = BC_STATUS_SUCCESS;
4526 dbg_lex_enter("%s:%d entered, p->l.lex:%d", __func__, __LINE__, p->l.lex);
4528 if (p->l.lex == XC_LEX_NLINE) {
4529 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4530 RETURN_STATUS(zbc_lex_next(&p->l));
4532 if (p->l.lex == BC_LEX_SCOLON) {
4533 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4534 RETURN_STATUS(zbc_lex_next(&p->l));
4537 if (p->l.lex == BC_LEX_LBRACE) {
4538 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4540 s = zbc_lex_next(&p->l);
4541 if (s) RETURN_STATUS(s);
4542 } while (p->l.lex == XC_LEX_NLINE);
4543 if (auto_allowed && p->l.lex == BC_LEX_KEY_AUTO) {
4544 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4545 s = zbc_parse_auto(p);
4546 if (s) RETURN_STATUS(s);
4548 while (p->l.lex != BC_LEX_RBRACE) {
4549 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4550 s = zbc_parse_stmt(p);
4551 if (s) RETURN_STATUS(s);
4553 s = zbc_lex_next(&p->l);
4554 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4558 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
4560 case XC_LEX_OP_MINUS:
4563 case BC_LEX_OP_BOOL_NOT:
4567 case BC_LEX_KEY_IBASE:
4568 case BC_LEX_KEY_LAST:
4569 case BC_LEX_KEY_LENGTH:
4570 case BC_LEX_KEY_OBASE:
4571 case BC_LEX_KEY_READ:
4572 case BC_LEX_KEY_SCALE:
4573 case BC_LEX_KEY_SQRT:
4574 s = zbc_parse_expr(p, BC_PARSE_PRINT);
4577 s = zbc_parse_pushSTR(p);
4578 bc_parse_push(p, XC_INST_PRINT_STR);
4580 case BC_LEX_KEY_BREAK:
4581 case BC_LEX_KEY_CONTINUE:
4582 s = zbc_parse_break_or_continue(p, p->l.lex);
4584 case BC_LEX_KEY_FOR:
4585 s = zbc_parse_for(p);
4587 case BC_LEX_KEY_HALT:
4588 bc_parse_push(p, BC_INST_HALT);
4589 s = zbc_lex_next(&p->l);
4592 s = zbc_parse_if(p);
4594 case BC_LEX_KEY_LIMITS:
4595 // "limits" is a compile-time command,
4596 // the output is produced at _parse time_.
4598 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4599 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4600 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4601 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4602 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4603 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4604 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4605 "Number of vars = "BC_MAX_VARS_STR "\n"
4607 s = zbc_lex_next(&p->l);
4609 case BC_LEX_KEY_PRINT:
4610 s = zbc_parse_print(p);
4612 case BC_LEX_KEY_QUIT:
4613 // "quit" is a compile-time command. For example,
4614 // "if (0 == 1) quit" terminates when parsing the statement,
4615 // not when it is executed
4616 QUIT_OR_RETURN_TO_MAIN;
4617 case BC_LEX_KEY_RETURN:
4619 RETURN_STATUS(bc_error("'return' not in a function"));
4620 s = zbc_parse_return(p);
4622 case BC_LEX_KEY_WHILE:
4623 s = zbc_parse_while(p);
4626 s = bc_error_bad_token();
4630 dbg_lex_done("%s:%d done", __func__, __LINE__);
4633 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4635 static BC_STATUS zbc_parse_stmt_or_funcdef(BcParse *p)
4639 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4640 if (p->l.lex == XC_LEX_EOF)
4641 s = bc_error("end of file");
4642 else if (p->l.lex == BC_LEX_KEY_DEFINE) {
4643 dbg_lex("%s:%d p->l.lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4644 s = zbc_parse_funcdef(p);
4646 dbg_lex("%s:%d p->l.lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->l.lex);
4647 s = zbc_parse_stmt(p);
4650 dbg_lex_done("%s:%d done", __func__, __LINE__);
4653 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4655 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4656 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags)
4658 BcInst prev = XC_INST_PRINT;
4659 size_t nexprs = 0, ops_bgn = p->ops.len;
4660 unsigned nparens, nrelops;
4661 bool paren_first, paren_expr, rprn, assign, bin_last;
4663 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4664 paren_first = (p->l.lex == BC_LEX_LPAREN);
4665 nparens = nrelops = 0;
4666 paren_expr = rprn = assign = false;
4672 BcLexType t = p->l.lex;
4674 if (!lex_allowed_in_bc_expr(t))
4677 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4679 s = BC_STATUS_SUCCESS;
4683 s = zbc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4684 rprn = bin_last = false;
4685 //get_token = false; - already is
4687 case XC_LEX_OP_MINUS:
4688 s = zbc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4690 //get_token = false; - already is
4691 bin_last = (prev == XC_INST_MINUS);
4693 case BC_LEX_OP_ASSIGN_POWER:
4694 case BC_LEX_OP_ASSIGN_MULTIPLY:
4695 case BC_LEX_OP_ASSIGN_DIVIDE:
4696 case BC_LEX_OP_ASSIGN_MODULUS:
4697 case BC_LEX_OP_ASSIGN_PLUS:
4698 case BC_LEX_OP_ASSIGN_MINUS:
4699 case BC_LEX_OP_ASSIGN:
4700 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4701 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4702 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4704 return bc_error("bad assignment:"
4705 " left side must be variable"
4707 ); // note: shared string
4710 case XC_LEX_OP_POWER:
4711 case XC_LEX_OP_MULTIPLY:
4712 case XC_LEX_OP_DIVIDE:
4713 case XC_LEX_OP_MODULUS:
4714 case XC_LEX_OP_PLUS:
4715 case XC_LEX_OP_REL_EQ:
4716 case XC_LEX_OP_REL_LE:
4717 case XC_LEX_OP_REL_GE:
4718 case XC_LEX_OP_REL_NE:
4719 case XC_LEX_OP_REL_LT:
4720 case XC_LEX_OP_REL_GT:
4721 case BC_LEX_OP_BOOL_NOT:
4722 case BC_LEX_OP_BOOL_OR:
4723 case BC_LEX_OP_BOOL_AND:
4724 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4725 || (t != BC_LEX_OP_BOOL_NOT && prev == XC_INST_BOOL_NOT)
4727 return bc_error_bad_expression();
4729 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4730 prev = BC_TOKEN_2_INST(t);
4731 bc_parse_operator(p, t, ops_bgn, &nexprs);
4732 s = zbc_lex_next(&p->l);
4734 //get_token = false; - already is
4735 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4738 if (BC_PARSE_LEAF(prev, rprn))
4739 return bc_error_bad_expression();
4740 bc_vec_push(&p->ops, &t);
4744 rprn = bin_last = false;
4747 if (bin_last || prev == XC_INST_BOOL_NOT)
4748 return bc_error_bad_expression();
4753 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4754 return BC_STATUS_PARSE_EMPTY_EXP;
4756 s = zbc_parse_rightParen(p, ops_bgn, &nexprs);
4759 paren_expr = rprn = true;
4763 if (BC_PARSE_LEAF(prev, rprn))
4764 return bc_error_bad_expression();
4765 s = zbc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4767 rprn = bin_last = false;
4768 //get_token = false; - already is
4772 if (BC_PARSE_LEAF(prev, rprn))
4773 return bc_error_bad_expression();
4774 bc_parse_pushNUM(p);
4778 rprn = bin_last = false;
4781 case BC_LEX_KEY_IBASE:
4782 case BC_LEX_KEY_LAST:
4783 case BC_LEX_KEY_OBASE:
4784 if (BC_PARSE_LEAF(prev, rprn))
4785 return bc_error_bad_expression();
4786 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4787 bc_parse_push(p, (char) prev);
4790 rprn = bin_last = false;
4793 case BC_LEX_KEY_LENGTH:
4794 case BC_LEX_KEY_SQRT:
4795 if (BC_PARSE_LEAF(prev, rprn))
4796 return bc_error_bad_expression();
4797 s = zbc_parse_builtin(p, t, flags, &prev);
4800 rprn = bin_last = false;
4803 case BC_LEX_KEY_READ:
4804 if (BC_PARSE_LEAF(prev, rprn))
4805 return bc_error_bad_expression();
4806 s = zbc_parse_read(p);
4807 prev = XC_INST_READ;
4810 rprn = bin_last = false;
4813 case BC_LEX_KEY_SCALE:
4814 if (BC_PARSE_LEAF(prev, rprn))
4815 return bc_error_bad_expression();
4816 s = zbc_parse_scale(p, &prev, flags);
4817 prev = XC_INST_SCALE;
4818 //get_token = false; - already is
4820 rprn = bin_last = false;
4824 return bc_error_bad_token();
4827 if (s || G_interrupt) // error, or ^C: stop parsing
4828 return BC_STATUS_FAILURE;
4830 s = zbc_lex_next(&p->l);
4836 while (p->ops.len > ops_bgn) {
4837 BcLexType top = BC_PARSE_TOP_OP(p);
4838 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4840 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4841 return bc_error_bad_expression();
4843 bc_parse_push(p, BC_TOKEN_2_INST(top));
4845 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4846 bc_vec_pop(&p->ops);
4849 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4850 return bc_error_bad_expression();
4852 if (!(flags & BC_PARSE_REL) && nrelops) {
4854 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4856 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4858 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4862 if (flags & BC_PARSE_PRINT) {
4863 if (paren_first || !assign)
4864 bc_parse_push(p, XC_INST_PRINT);
4865 bc_parse_push(p, XC_INST_POP);
4868 dbg_lex_done("%s:%d done", __func__, __LINE__);
4869 return BC_STATUS_SUCCESS;
4876 static BC_STATUS zdc_parse_register(BcParse *p)
4880 s = zbc_lex_next(&p->l);
4881 if (s) RETURN_STATUS(s);
4882 if (p->l.lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4884 bc_parse_pushName(p, p->l.lex_buf.v);
4888 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4890 static void dc_parse_string(BcParse *p)
4893 size_t len = G.prog.strs.len;
4895 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4897 str = xstrdup(p->l.lex_buf.v);
4898 bc_parse_push(p, XC_INST_STR);
4899 bc_parse_pushIndex(p, len);
4900 bc_vec_push(&G.prog.strs, &str);
4902 // Explanation needed here
4903 bc_program_add_fn();
4904 p->func = bc_program_func(p->fidx);
4906 dbg_lex_done("%s:%d done", __func__, __LINE__);
4909 static BC_STATUS zdc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
4913 bc_parse_push(p, inst);
4915 s = zdc_parse_register(p);
4916 if (s) RETURN_STATUS(s);
4920 bc_parse_push(p, DC_INST_SWAP);
4921 bc_parse_push(p, XC_INST_ASSIGN);
4922 bc_parse_push(p, XC_INST_POP);
4925 RETURN_STATUS(BC_STATUS_SUCCESS);
4927 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4929 static BC_STATUS zdc_parse_cond(BcParse *p, uint8_t inst)
4933 bc_parse_push(p, inst);
4934 bc_parse_push(p, DC_INST_EXEC_COND);
4936 s = zdc_parse_register(p);
4937 if (s) RETURN_STATUS(s);
4939 s = zbc_lex_next(&p->l);
4940 if (s) RETURN_STATUS(s);
4942 // Note that 'else' part can not be on the next line:
4943 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4944 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4945 if (p->l.lex == DC_LEX_ELSE) {
4946 s = zdc_parse_register(p);
4947 if (s) RETURN_STATUS(s);
4948 s = zbc_lex_next(&p->l);
4950 bc_parse_push(p, BC_PARSE_STREND);
4955 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4957 static BC_STATUS zdc_parse_token(BcParse *p, BcLexType t)
4961 bool assign, get_token;
4963 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4964 s = BC_STATUS_SUCCESS;
4967 case XC_LEX_OP_REL_EQ:
4968 case XC_LEX_OP_REL_LE:
4969 case XC_LEX_OP_REL_GE:
4970 case XC_LEX_OP_REL_NE:
4971 case XC_LEX_OP_REL_LT:
4972 case XC_LEX_OP_REL_GT:
4973 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
4974 s = zdc_parse_cond(p, t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
4979 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
4980 s = zdc_parse_mem(p, XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
4983 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
4987 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
4988 s = zbc_lex_next(&p->l);
4989 if (s) RETURN_STATUS(s);
4990 if (p->l.lex != XC_LEX_NUMBER)
4991 RETURN_STATUS(bc_error_bad_token());
4992 bc_parse_pushNUM(p);
4993 bc_parse_push(p, XC_INST_NEG);
4996 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4997 bc_parse_pushNUM(p);
5000 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
5001 bc_parse_push(p, XC_INST_READ);
5003 case DC_LEX_OP_ASSIGN:
5004 case DC_LEX_STORE_PUSH:
5005 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
5006 assign = (t == DC_LEX_OP_ASSIGN);
5007 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
5008 s = zdc_parse_mem(p, inst, true, assign);
5011 case DC_LEX_LOAD_POP:
5012 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
5013 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
5014 s = zdc_parse_mem(p, inst, true, false);
5016 case DC_LEX_STORE_IBASE:
5017 case DC_LEX_STORE_SCALE:
5018 case DC_LEX_STORE_OBASE:
5019 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
5020 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
5021 s = zdc_parse_mem(p, inst, false, true);
5024 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
5025 RETURN_STATUS(bc_error_bad_token());
5028 if (!s && get_token) s = zbc_lex_next(&p->l);
5030 dbg_lex_done("%s:%d done", __func__, __LINE__);
5033 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
5035 static BC_STATUS zdc_parse_expr(BcParse *p)
5039 i = (int)p->l.lex - (int)XC_LEX_OP_POWER;
5041 BcInst inst = dc_LEX_to_INST[i];
5042 if (inst != DC_INST_INVALID) {
5043 bc_parse_push(p, inst);
5044 RETURN_STATUS(zbc_lex_next(&p->l));
5047 RETURN_STATUS(zdc_parse_token(p, p->l.lex));
5049 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
5051 static BC_STATUS zdc_parse_exprs_until_eof(BcParse *p)
5053 dbg_lex_enter("%s:%d entered, p->l.lex:%d", __func__, __LINE__, p->l.lex);
5054 while (p->l.lex != XC_LEX_EOF) {
5055 BcStatus s = zdc_parse_expr(p);
5056 if (s) RETURN_STATUS(s);
5059 dbg_lex_done("%s:%d done", __func__, __LINE__);
5060 RETURN_STATUS(BC_STATUS_SUCCESS);
5062 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5070 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5071 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5073 static BcVec* bc_program_search(char *id, bool var)
5080 v = var ? &G.prog.vars : &G.prog.arrs;
5081 map = var ? &G.prog.var_map : &G.prog.arr_map;
5085 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5089 bc_array_init(&v2, var);
5090 bc_vec_push(v, &v2);
5093 ptr = bc_vec_item(map, i);
5094 if (new) ptr->name = xstrdup(e.name);
5095 return bc_vec_item(v, ptr->idx);
5098 // 'num' need not be initialized on entry
5099 static BC_STATUS zbc_program_num(BcResult *r, BcNum **num, bool hex)
5103 case XC_RESULT_TEMP:
5104 case XC_RESULT_IBASE:
5105 case XC_RESULT_SCALE:
5106 case XC_RESULT_OBASE:
5109 case XC_RESULT_CONSTANT: {
5115 str = *bc_program_const(r->d.id.idx);
5118 bc_num_init(&r->d.n, len);
5120 hex = hex && len == 1;
5121 base_t = hex ? 16 : G.prog.ib_t;
5122 s = zbc_num_parse(&r->d.n, str, base_t);
5124 bc_num_free(&r->d.n);
5128 r->t = XC_RESULT_TEMP;
5132 case XC_RESULT_ARRAY:
5133 case XC_RESULT_ARRAY_ELEM: {
5136 v = bc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5138 if (r->t == XC_RESULT_ARRAY_ELEM) {
5140 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5141 *num = bc_vec_item(v, r->d.id.idx);
5143 *num = bc_vec_top(v);
5147 case BC_RESULT_LAST:
5148 *num = &G.prog.last;
5156 // Testing the theory that dc does not reach LAST/ONE
5157 bb_error_msg_and_die("BUG:%d", r->t);
5161 RETURN_STATUS(BC_STATUS_SUCCESS);
5163 #define zbc_program_num(...) (zbc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5165 static BC_STATUS zbc_program_binOpPrep(BcResult **l, BcNum **ln,
5166 BcResult **r, BcNum **rn, bool assign)
5170 BcResultType lt, rt;
5172 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5173 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5175 *r = bc_vec_item_rev(&G.prog.results, 0);
5176 *l = bc_vec_item_rev(&G.prog.results, 1);
5180 hex = assign && (lt == XC_RESULT_IBASE || lt == XC_RESULT_OBASE);
5182 s = zbc_program_num(*l, ln, false);
5183 if (s) RETURN_STATUS(s);
5184 s = zbc_program_num(*r, rn, hex);
5185 if (s) RETURN_STATUS(s);
5187 // We run this again under these conditions in case any vector has been
5188 // reallocated out from under the BcNums or arrays we had.
5189 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5190 s = zbc_program_num(*l, ln, false);
5191 if (s) RETURN_STATUS(s);
5194 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5195 RETURN_STATUS(bc_error_variable_is_wrong_type());
5196 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5197 RETURN_STATUS(bc_error_variable_is_wrong_type());
5201 #define zbc_program_binOpPrep(...) (zbc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5203 static void bc_program_binOpRetire(BcResult *r)
5205 r->t = XC_RESULT_TEMP;
5206 bc_vec_pop(&G.prog.results);
5207 bc_result_pop_and_push(r);
5210 // Note: *r and *n need not be initialized by caller
5211 static BC_STATUS zbc_program_prep(BcResult **r, BcNum **n)
5215 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5216 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5217 *r = bc_vec_top(&G.prog.results);
5219 s = zbc_program_num(*r, n, false);
5220 if (s) RETURN_STATUS(s);
5222 if (!BC_PROG_NUM((*r), (*n)))
5223 RETURN_STATUS(bc_error_variable_is_wrong_type());
5227 #define zbc_program_prep(...) (zbc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5229 static void bc_program_retire(BcResult *r, BcResultType t)
5232 bc_result_pop_and_push(r);
5235 static BC_STATUS zbc_program_op(char inst)
5238 BcResult *opd1, *opd2, res;
5241 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5242 if (s) RETURN_STATUS(s);
5243 bc_num_init_DEF_SIZE(&res.d.n);
5245 s = BC_STATUS_SUCCESS;
5246 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5248 bc_program_binOpRetire(&res);
5252 bc_num_free(&res.d.n);
5255 #define zbc_program_op(...) (zbc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5257 static BC_STATUS zbc_program_read(void)
5259 const char *sv_file;
5266 f = bc_program_func(BC_PROG_READ);
5267 bc_vec_pop_all(&f->code);
5269 sv_file = G.prog.file;
5272 bc_char_vec_init(&buf);
5273 bc_read_line(&buf, stdin);
5275 bc_parse_create(&parse, BC_PROG_READ);
5276 bc_lex_file(&parse.l);
5278 s = zbc_parse_text_init(&parse, buf.v);
5279 if (s) goto exec_err;
5281 IF_BC(s = zbc_parse_expr(&parse, 0));
5283 IF_DC(s = zdc_parse_exprs_until_eof(&parse));
5285 if (s) goto exec_err;
5287 if (parse.l.lex != XC_LEX_NLINE && parse.l.lex != XC_LEX_EOF) {
5288 s = bc_error("bad read() expression");
5292 ip.func = BC_PROG_READ;
5294 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5296 bc_parse_push(&parse, XC_INST_RET);
5297 bc_vec_push(&G.prog.exestack, &ip);
5299 bc_parse_free(&parse);
5300 G.prog.file = sv_file;
5304 #define zbc_program_read(...) (zbc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5306 static size_t bc_program_index(char *code, size_t *bgn)
5308 unsigned char *bytes = (void*)(code + *bgn);
5318 for (i = 0; i < amt; i += 8)
5319 res |= (size_t)(*bytes++) << i;
5324 static char *bc_program_name(char *code, size_t *bgn)
5330 s = xmalloc(strchr(code, BC_PARSE_STREND) - code + 1);
5334 if (c == BC_PARSE_STREND)
5344 static void bc_program_printString(const char *str)
5348 // Example: echo '[]ap' | dc
5349 // should print two bytes: 0x00, 0x0A
5356 if (c != '\\' || !*str)
5376 G.prog.nchars = SIZE_MAX;
5388 // Just print the backslash and following character.
5399 static void bc_num_printNewline(void)
5401 if (G.prog.nchars == G.prog.len - 1) {
5409 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5412 bb_putchar((char) num);
5413 G.prog.nchars += width;
5417 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5421 bc_num_printNewline();
5422 bb_putchar(radix ? '.' : ' ');
5425 bc_num_printNewline();
5426 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5429 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5431 bc_num_printNewline();
5434 bb_putchar(((char) dig) + '0');
5438 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5441 bc_num_printNewline();
5446 bc_num_printNewline();
5447 bb_putchar(bb_hexdigits_upcase[num]);
5448 G.prog.nchars += width;
5451 static void bc_num_printDecimal(BcNum *n)
5453 size_t i, rdx = n->rdx - 1;
5460 for (i = n->len - 1; i < n->len; --i)
5461 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5464 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5466 static BC_STATUS zbc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5471 BcDig base_digs[ULONG_NUM_BUFSIZE];
5472 BcNum intp, fracp, digit, frac_len;
5473 unsigned long dig, *ptr;
5478 print(0, width, false);
5479 RETURN_STATUS(BC_STATUS_SUCCESS);
5482 bc_vec_init(&stack, sizeof(long), NULL);
5483 bc_num_init(&intp, n->len);
5484 bc_num_init(&fracp, n->rdx);
5485 bc_num_init(&digit, width);
5486 bc_num_init(&frac_len, BC_NUM_INT(n));
5487 bc_num_copy(&intp, n);
5488 bc_num_one(&frac_len);
5489 base.cap = ARRAY_SIZE(base_digs);
5490 base.num = base_digs;
5491 bc_num_ulong2num(&base, base_t);
5493 bc_num_truncate(&intp, intp.rdx);
5494 s = zbc_num_sub(n, &intp, &fracp, 0);
5497 while (intp.len != 0) {
5498 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5500 s = zbc_num_ulong(&digit, &dig);
5502 bc_vec_push(&stack, &dig);
5505 for (i = 0; i < stack.len; ++i) {
5506 ptr = bc_vec_item_rev(&stack, i);
5507 print(*ptr, width, false);
5510 if (!n->rdx) goto err;
5512 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5513 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5515 s = zbc_num_ulong(&fracp, &dig);
5517 bc_num_ulong2num(&intp, dig);
5518 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5520 print(dig, width, radix);
5521 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5525 bc_num_free(&frac_len);
5526 bc_num_free(&digit);
5527 bc_num_free(&fracp);
5529 bc_vec_free(&stack);
5532 #define zbc_num_printNum(...) (zbc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5534 static BC_STATUS zbc_num_printBase(BcNum *n)
5548 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5550 print = bc_num_printHex;
5552 unsigned i = G.prog.ob_t - 1;
5560 print = bc_num_printDigits;
5563 s = zbc_num_printNum(n, G.prog.ob_t, width, print);
5568 #define zbc_num_printBase(...) (zbc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5570 static BC_STATUS zbc_num_print(BcNum *n, bool newline)
5572 BcStatus s = BC_STATUS_SUCCESS;
5574 bc_num_printNewline();
5579 } else if (G.prog.ob_t == 10)
5580 bc_num_printDecimal(n);
5582 s = zbc_num_printBase(n);
5591 #define zbc_num_print(...) (zbc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5593 static BC_STATUS zbc_program_print(char inst, size_t idx)
5598 bool pop = (inst != XC_INST_PRINT);
5600 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5601 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5603 r = bc_vec_item_rev(&G.prog.results, idx);
5604 s = zbc_program_num(r, &num, false);
5605 if (s) RETURN_STATUS(s);
5607 if (BC_PROG_NUM(r, num)) {
5608 s = zbc_num_print(num, !pop);
5610 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5615 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5616 str = *bc_program_str(idx);
5618 if (inst == XC_INST_PRINT_STR) {
5621 if (c == '\0') break;
5624 if (c == '\n') G.prog.nchars = 0;
5627 bc_program_printString(str);
5628 if (inst == XC_INST_PRINT) bb_putchar('\n');
5632 if (!s && pop) bc_vec_pop(&G.prog.results);
5636 #define zbc_program_print(...) (zbc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5638 static BC_STATUS zbc_program_negate(void)
5644 s = zbc_program_prep(&ptr, &num);
5645 if (s) RETURN_STATUS(s);
5647 bc_num_init(&res.d.n, num->len);
5648 bc_num_copy(&res.d.n, num);
5649 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5651 bc_program_retire(&res, XC_RESULT_TEMP);
5655 #define zbc_program_negate(...) (zbc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5657 static BC_STATUS zbc_program_logical(char inst)
5660 BcResult *opd1, *opd2, res;
5664 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5665 if (s) RETURN_STATUS(s);
5667 bc_num_init_DEF_SIZE(&res.d.n);
5669 if (inst == XC_INST_BOOL_AND)
5670 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5671 else if (inst == XC_INST_BOOL_OR)
5672 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5674 cond = bc_num_cmp(n1, n2);
5676 case XC_INST_REL_EQ:
5679 case XC_INST_REL_LE:
5682 case XC_INST_REL_GE:
5685 case XC_INST_REL_LT:
5688 case XC_INST_REL_GT:
5691 default: // = case XC_INST_REL_NE:
5692 //cond = (cond != 0); - not needed
5697 if (cond) bc_num_one(&res.d.n);
5698 //else bc_num_zero(&res.d.n); - already is
5700 bc_program_binOpRetire(&res);
5704 #define zbc_program_logical(...) (zbc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5707 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5712 memset(&n2, 0, sizeof(BcNum));
5713 n2.rdx = res.d.id.idx = r->d.id.idx;
5714 res.t = XC_RESULT_STR;
5717 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5718 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5720 bc_vec_pop(&G.prog.results);
5723 bc_result_pop_and_push(&res);
5724 bc_vec_push(v, &n2);
5726 RETURN_STATUS(BC_STATUS_SUCCESS);
5728 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5731 static BC_STATUS zbc_program_copyToVar(char *name, bool var)
5738 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5739 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5741 ptr = bc_vec_top(&G.prog.results);
5742 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5743 RETURN_STATUS(bc_error_variable_is_wrong_type());
5744 v = bc_program_search(name, var);
5747 if (ptr->t == XC_RESULT_STR && !var)
5748 RETURN_STATUS(bc_error_variable_is_wrong_type());
5749 if (ptr->t == XC_RESULT_STR)
5750 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5753 s = zbc_program_num(ptr, &n, false);
5754 if (s) RETURN_STATUS(s);
5756 // Do this once more to make sure that pointers were not invalidated.
5757 v = bc_program_search(name, var);
5760 bc_num_init_DEF_SIZE(&r.d.n);
5761 bc_num_copy(&r.d.n, n);
5763 bc_array_init(&r.d.v, true);
5764 bc_array_copy(&r.d.v, (BcVec *) n);
5767 bc_vec_push(v, &r.d);
5768 bc_vec_pop(&G.prog.results);
5772 #define zbc_program_copyToVar(...) (zbc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5774 static BC_STATUS zbc_program_assign(char inst)
5777 BcResult *left, *right, res;
5779 bool assign = (inst == XC_INST_ASSIGN);
5782 s = zbc_program_binOpPrep(&left, &l, &right, &r, assign);
5783 if (s) RETURN_STATUS(s);
5785 ib = left->t == XC_RESULT_IBASE;
5786 sc = left->t == XC_RESULT_SCALE;
5789 if (right->t == XC_RESULT_STR) {
5792 if (left->t != XC_RESULT_VAR)
5793 RETURN_STATUS(bc_error_variable_is_wrong_type());
5794 v = bc_program_search(left->d.id.name, true);
5796 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5800 if (left->t == XC_RESULT_CONSTANT || left->t == XC_RESULT_TEMP)
5801 RETURN_STATUS(bc_error("bad assignment:"
5802 " left side must be variable"
5804 )); // note: shared string
5807 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5808 RETURN_STATUS(bc_error("divide by zero"));
5813 s = BC_STATUS_SUCCESS;
5814 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5816 if (s) RETURN_STATUS(s);
5821 if (ib || sc || left->t == XC_RESULT_OBASE) {
5822 static const char *const msg[] = {
5823 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5824 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5825 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5831 s = zbc_num_ulong(l, &val);
5832 if (s) RETURN_STATUS(s);
5833 s = left->t - XC_RESULT_IBASE;
5836 ptr = &G.prog.scale;
5839 RETURN_STATUS(bc_error(msg[s]));
5840 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5841 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5845 RETURN_STATUS(bc_error(msg[s]));
5847 *ptr = (size_t) val;
5848 s = BC_STATUS_SUCCESS;
5851 bc_num_init(&res.d.n, l->len);
5852 bc_num_copy(&res.d.n, l);
5853 bc_program_binOpRetire(&res);
5857 #define zbc_program_assign(...) (zbc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5860 #define bc_program_pushVar(code, bgn, pop, copy) \
5861 bc_program_pushVar(code, bgn)
5862 // for bc, 'pop' and 'copy' are always false
5864 static BC_STATUS bc_program_pushVar(char *code, size_t *bgn,
5865 bool pop, bool copy)
5868 char *name = bc_program_name(code, bgn);
5870 r.t = XC_RESULT_VAR;
5875 BcVec *v = bc_program_search(name, true);
5876 BcNum *num = bc_vec_top(v);
5879 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5880 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5883 if (!BC_PROG_STR(num)) {
5884 r.t = XC_RESULT_TEMP;
5885 bc_num_init_DEF_SIZE(&r.d.n);
5886 bc_num_copy(&r.d.n, num);
5888 r.t = XC_RESULT_STR;
5889 r.d.id.idx = num->rdx;
5892 if (!copy) bc_vec_pop(v);
5896 bc_vec_push(&G.prog.results, &r);
5898 RETURN_STATUS(BC_STATUS_SUCCESS);
5900 #define zbc_program_pushVar(...) (bc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5902 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5904 BcStatus s = BC_STATUS_SUCCESS;
5908 r.d.id.name = bc_program_name(code, bgn);
5910 if (inst == XC_INST_ARRAY) {
5911 r.t = XC_RESULT_ARRAY;
5912 bc_vec_push(&G.prog.results, &r);
5917 s = zbc_program_prep(&operand, &num);
5919 s = zbc_num_ulong(num, &temp);
5922 if (temp > BC_MAX_DIM) {
5923 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5927 r.d.id.idx = (size_t) temp;
5928 bc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5931 if (s) free(r.d.id.name);
5934 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5937 static BC_STATUS zbc_program_incdec(char inst)
5940 BcResult *ptr, res, copy;
5944 s = zbc_program_prep(&ptr, &num);
5945 if (s) RETURN_STATUS(s);
5947 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5948 copy.t = XC_RESULT_TEMP;
5949 bc_num_init(©.d.n, num->len);
5950 bc_num_copy(©.d.n, num);
5953 res.t = BC_RESULT_ONE;
5954 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
5955 ? BC_INST_ASSIGN_PLUS
5956 : BC_INST_ASSIGN_MINUS;
5958 bc_vec_push(&G.prog.results, &res);
5959 s = zbc_program_assign(inst);
5960 if (s) RETURN_STATUS(s);
5962 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5963 bc_result_pop_and_push(©);
5968 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5970 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5978 nparams = bc_program_index(code, idx);
5980 ip.func = bc_program_index(code, idx);
5981 func = bc_program_func(ip.func);
5983 if (func->code.len == 0) {
5984 RETURN_STATUS(bc_error("undefined function"));
5986 if (nparams != func->nparams) {
5987 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5989 ip.results_len_before_call = G.prog.results.len - nparams;
5991 for (i = 0; i < nparams; ++i) {
5994 a = bc_vec_item(&func->autos, nparams - 1 - i);
5995 arg = bc_vec_top(&G.prog.results);
5997 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) || arg->t == XC_RESULT_STR)
5998 RETURN_STATUS(bc_error_variable_is_wrong_type());
6000 s = zbc_program_copyToVar(a->name, a->idx);
6001 if (s) RETURN_STATUS(s);
6004 a = bc_vec_item(&func->autos, i);
6005 for (; i < func->autos.len; i++, a++) {
6008 v = bc_program_search(a->name, a->idx);
6011 bc_num_init_DEF_SIZE(&n2);
6012 bc_vec_push(v, &n2);
6015 bc_array_init(&v2, true);
6016 bc_vec_push(v, &v2);
6020 bc_vec_push(&G.prog.exestack, &ip);
6022 RETURN_STATUS(BC_STATUS_SUCCESS);
6024 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
6026 static BC_STATUS zbc_program_return(char inst)
6032 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6034 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == XC_INST_RET)))
6035 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6037 f = bc_program_func(ip->func);
6038 res.t = XC_RESULT_TEMP;
6040 if (inst == XC_INST_RET) {
6043 BcResult *operand = bc_vec_top(&G.prog.results);
6045 s = zbc_program_num(operand, &num, false);
6046 if (s) RETURN_STATUS(s);
6047 bc_num_init(&res.d.n, num->len);
6048 bc_num_copy(&res.d.n, num);
6050 bc_num_init_DEF_SIZE(&res.d.n);
6051 //bc_num_zero(&res.d.n); - already is
6054 // We need to pop arguments as well, so this takes that into account.
6055 a = (void*)f->autos.v;
6056 for (i = 0; i < f->autos.len; i++, a++) {
6058 v = bc_program_search(a->name, a->idx);
6062 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
6063 bc_vec_push(&G.prog.results, &res);
6064 bc_vec_pop(&G.prog.exestack);
6066 RETURN_STATUS(BC_STATUS_SUCCESS);
6068 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6071 static unsigned long bc_program_scale(BcNum *n)
6073 return (unsigned long) n->rdx;
6076 static unsigned long bc_program_len(BcNum *n)
6078 size_t len = n->len;
6080 if (n->rdx != len) return len;
6082 if (len == 0) break;
6084 if (n->num[len] != 0) break;
6089 static BC_STATUS zbc_program_builtin(char inst)
6095 bool len = (inst == XC_INST_LENGTH);
6097 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6098 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6099 opnd = bc_vec_top(&G.prog.results);
6101 s = zbc_program_num(opnd, &num, false);
6102 if (s) RETURN_STATUS(s);
6105 if (!BC_PROG_NUM(opnd, num) && !len)
6106 RETURN_STATUS(bc_error_variable_is_wrong_type());
6109 bc_num_init_DEF_SIZE(&res.d.n);
6111 if (inst == XC_INST_SQRT)
6112 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6114 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6115 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6119 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6121 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6123 str = bc_program_str(idx);
6124 bc_num_ulong2num(&res.d.n, strlen(*str));
6128 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6131 bc_program_retire(&res, XC_RESULT_TEMP);
6135 #define zbc_program_builtin(...) (zbc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6138 static BC_STATUS zdc_program_divmod(void)
6141 BcResult *opd1, *opd2, res, res2;
6144 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6145 if (s) RETURN_STATUS(s);
6147 bc_num_init_DEF_SIZE(&res.d.n);
6148 bc_num_init(&res2.d.n, n2->len);
6150 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6153 bc_program_binOpRetire(&res2);
6154 res.t = XC_RESULT_TEMP;
6155 bc_vec_push(&G.prog.results, &res);
6159 bc_num_free(&res2.d.n);
6160 bc_num_free(&res.d.n);
6163 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6165 static BC_STATUS zdc_program_modexp(void)
6168 BcResult *r1, *r2, *r3, res;
6169 BcNum *n1, *n2, *n3;
6171 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6172 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6173 s = zbc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6174 if (s) RETURN_STATUS(s);
6176 r1 = bc_vec_item_rev(&G.prog.results, 2);
6177 s = zbc_program_num(r1, &n1, false);
6178 if (s) RETURN_STATUS(s);
6179 if (!BC_PROG_NUM(r1, n1))
6180 RETURN_STATUS(bc_error_variable_is_wrong_type());
6182 // Make sure that the values have their pointers updated, if necessary.
6183 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6184 if (r1->t == r2->t) {
6185 s = zbc_program_num(r2, &n2, false);
6186 if (s) RETURN_STATUS(s);
6188 if (r1->t == r3->t) {
6189 s = zbc_program_num(r3, &n3, false);
6190 if (s) RETURN_STATUS(s);
6194 bc_num_init(&res.d.n, n3->len);
6195 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6198 bc_vec_pop(&G.prog.results);
6199 bc_program_binOpRetire(&res);
6203 bc_num_free(&res.d.n);
6206 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6208 static void dc_program_stackLen(void)
6211 size_t len = G.prog.results.len;
6213 res.t = XC_RESULT_TEMP;
6215 bc_num_init_DEF_SIZE(&res.d.n);
6216 bc_num_ulong2num(&res.d.n, len);
6217 bc_vec_push(&G.prog.results, &res);
6220 static BC_STATUS zdc_program_asciify(void)
6230 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6231 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6232 r = bc_vec_top(&G.prog.results);
6234 s = zbc_program_num(r, &num, false);
6235 if (s) RETURN_STATUS(s);
6237 if (BC_PROG_NUM(r, num)) {
6240 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6242 bc_num_init_DEF_SIZE(&n);
6243 bc_num_copy(&n, num);
6244 bc_num_truncate(&n, n.rdx);
6246 strmb.cap = ARRAY_SIZE(strmb_digs);
6247 strmb.num = strmb_digs;
6248 bc_num_ulong2num(&strmb, 0x100);
6249 s = zbc_num_mod(&n, &strmb, &n, 0);
6251 if (s) goto num_err;
6252 s = zbc_num_ulong(&n, &val);
6253 if (s) goto num_err;
6260 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6261 sp = *bc_program_str(idx);
6265 strs = (void*)G.prog.strs.v;
6266 for (idx = 0; idx < G.prog.strs.len; idx++) {
6267 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6273 //str[1] = '\0'; - already is
6274 bc_vec_push(&G.prog.strs, &str);
6276 res.t = XC_RESULT_STR;
6278 bc_result_pop_and_push(&res);
6280 RETURN_STATUS(BC_STATUS_SUCCESS);
6285 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6287 static BC_STATUS zdc_program_printStream(void)
6294 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6295 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6296 r = bc_vec_top(&G.prog.results);
6298 s = zbc_program_num(r, &n, false);
6299 if (s) RETURN_STATUS(s);
6301 if (BC_PROG_NUM(r, n)) {
6302 s = zbc_num_printNum(n, 0x100, 1, dc_num_printChar);
6305 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6306 str = *bc_program_str(idx);
6312 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6314 static BC_STATUS zdc_program_nquit(void)
6321 s = zbc_program_prep(&opnd, &num);
6322 if (s) RETURN_STATUS(s);
6323 s = zbc_num_ulong(num, &val);
6324 if (s) RETURN_STATUS(s);
6326 bc_vec_pop(&G.prog.results);
6328 if (G.prog.exestack.len < val)
6329 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6330 if (G.prog.exestack.len == val) {
6331 QUIT_OR_RETURN_TO_MAIN;
6334 bc_vec_npop(&G.prog.exestack, val);
6338 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6340 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6342 BcStatus s = BC_STATUS_SUCCESS;
6348 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6349 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6351 r = bc_vec_top(&G.prog.results);
6354 BcNum *n = n; // for compiler
6357 char *then_name = bc_program_name(code, bgn);
6358 char *else_name = NULL;
6360 if (code[*bgn] == BC_PARSE_STREND)
6363 else_name = bc_program_name(code, bgn);
6365 exec = r->d.n.len != 0;
6367 if (!exec && else_name != NULL) {
6374 v = bc_program_search(name, true);
6381 if (!exec) goto exit;
6382 if (!BC_PROG_STR(n)) {
6383 s = bc_error_variable_is_wrong_type();
6389 if (r->t == XC_RESULT_STR) {
6391 } else if (r->t == XC_RESULT_VAR) {
6393 s = zbc_program_num(r, &n, false);
6394 if (s || !BC_PROG_STR(n)) goto exit;
6400 fidx = sidx + BC_PROG_REQ_FUNCS;
6402 f = bc_program_func(fidx);
6404 if (f->code.len == 0) {
6409 bc_parse_create(&prs, fidx);
6410 str = *bc_program_str(sidx);
6411 s = zbc_parse_text_init(&prs, str);
6414 sv_input_fp = G.input_fp;
6415 G.input_fp = NULL; // "do not read from input file when <EOL> reached"
6416 s = zdc_parse_exprs_until_eof(&prs);
6417 G.input_fp = sv_input_fp;
6420 if (prs.l.lex != XC_LEX_EOF) {
6421 s = bc_error_bad_expression();
6423 bc_parse_free(&prs);
6424 bc_vec_pop_all(&f->code);
6427 bc_parse_push(&prs, DC_INST_POP_EXEC);
6428 bc_parse_free(&prs);
6434 bc_vec_pop(&G.prog.results);
6435 bc_vec_push(&G.prog.exestack, &ip);
6437 RETURN_STATUS(BC_STATUS_SUCCESS);
6439 bc_vec_pop(&G.prog.results);
6442 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6445 static void bc_program_pushGlobal(char inst)
6450 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6451 if (inst == XC_INST_IBASE)
6452 val = (unsigned long) G.prog.ib_t;
6453 else if (inst == XC_INST_SCALE)
6454 val = (unsigned long) G.prog.scale;
6456 val = (unsigned long) G.prog.ob_t;
6458 bc_num_init_DEF_SIZE(&res.d.n);
6459 bc_num_ulong2num(&res.d.n, val);
6460 bc_vec_push(&G.prog.results, &res);
6463 static BC_STATUS zbc_program_exec(void)
6466 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6467 BcFunc *func = bc_program_func(ip->func);
6468 char *code = func->code.v;
6470 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6471 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6472 while (ip->inst_idx < func->code.len) {
6473 BcStatus s = BC_STATUS_SUCCESS;
6474 char inst = code[ip->inst_idx++];
6476 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6479 case BC_INST_JUMP_ZERO: {
6482 dbg_exec("BC_INST_JUMP_ZERO:");
6483 s = zbc_program_prep(&ptr, &num);
6484 if (s) RETURN_STATUS(s);
6485 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6486 bc_vec_pop(&G.prog.results);
6488 bc_program_index(code, &ip->inst_idx);
6491 // else: fall through
6493 case BC_INST_JUMP: {
6494 size_t idx = bc_program_index(code, &ip->inst_idx);
6495 size_t *addr = bc_vec_item(&func->labels, idx);
6496 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6497 ip->inst_idx = *addr;
6501 dbg_exec("BC_INST_CALL:");
6502 s = zbc_program_call(code, &ip->inst_idx);
6503 goto read_updated_ip;
6504 case BC_INST_INC_PRE:
6505 case BC_INST_DEC_PRE:
6506 case BC_INST_INC_POST:
6507 case BC_INST_DEC_POST:
6508 dbg_exec("BC_INST_INCDEC:");
6509 s = zbc_program_incdec(inst);
6512 dbg_exec("BC_INST_HALT:");
6513 QUIT_OR_RETURN_TO_MAIN;
6517 dbg_exec("BC_INST_RET[0]:");
6518 s = zbc_program_return(inst);
6519 goto read_updated_ip;
6520 case XC_INST_BOOL_OR:
6521 case XC_INST_BOOL_AND:
6523 case XC_INST_REL_EQ:
6524 case XC_INST_REL_LE:
6525 case XC_INST_REL_GE:
6526 case XC_INST_REL_NE:
6527 case XC_INST_REL_LT:
6528 case XC_INST_REL_GT:
6529 dbg_exec("BC_INST_BOOL:");
6530 s = zbc_program_logical(inst);
6533 dbg_exec("XC_INST_READ:");
6534 s = zbc_program_read();
6535 goto read_updated_ip;
6537 dbg_exec("XC_INST_VAR:");
6538 s = zbc_program_pushVar(code, &ip->inst_idx, false, false);
6540 case XC_INST_ARRAY_ELEM:
6542 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6543 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6547 dbg_exec("BC_INST_LAST:");
6548 r.t = BC_RESULT_LAST;
6549 bc_vec_push(&G.prog.results, &r);
6555 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6556 bc_program_pushGlobal(inst);
6558 case XC_INST_SCALE_FUNC:
6559 case XC_INST_LENGTH:
6561 dbg_exec("BC_INST_builtin:");
6562 s = zbc_program_builtin(inst);
6565 dbg_exec("XC_INST_NUM:");
6566 r.t = XC_RESULT_CONSTANT;
6567 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6568 bc_vec_push(&G.prog.results, &r);
6571 dbg_exec("XC_INST_POP:");
6572 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6573 s = bc_error_stack_has_too_few_elements();
6575 bc_vec_pop(&G.prog.results);
6578 case XC_INST_PRINT_POP:
6579 case XC_INST_PRINT_STR:
6580 dbg_exec("XC_INST_PRINTxyz:");
6581 s = zbc_program_print(inst, 0);
6584 dbg_exec("XC_INST_STR:");
6585 r.t = XC_RESULT_STR;
6586 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6587 bc_vec_push(&G.prog.results, &r);
6590 case XC_INST_MULTIPLY:
6591 case XC_INST_DIVIDE:
6592 case XC_INST_MODULUS:
6595 dbg_exec("BC_INST_binaryop:");
6596 s = zbc_program_op(inst);
6598 case XC_INST_BOOL_NOT: {
6600 dbg_exec("XC_INST_BOOL_NOT:");
6601 s = zbc_program_prep(&ptr, &num);
6602 if (s) RETURN_STATUS(s);
6603 bc_num_init_DEF_SIZE(&r.d.n);
6604 if (bc_num_cmp(num, &G.prog.zero) == 0)
6606 //else bc_num_zero(&r.d.n); - already is
6607 bc_program_retire(&r, XC_RESULT_TEMP);
6611 dbg_exec("XC_INST_NEG:");
6612 s = zbc_program_negate();
6615 case BC_INST_ASSIGN_POWER:
6616 case BC_INST_ASSIGN_MULTIPLY:
6617 case BC_INST_ASSIGN_DIVIDE:
6618 case BC_INST_ASSIGN_MODULUS:
6619 case BC_INST_ASSIGN_PLUS:
6620 case BC_INST_ASSIGN_MINUS:
6622 case XC_INST_ASSIGN:
6623 dbg_exec("BC_INST_ASSIGNxyz:");
6624 s = zbc_program_assign(inst);
6627 case DC_INST_POP_EXEC:
6628 dbg_exec("DC_INST_POP_EXEC:");
6629 bc_vec_pop(&G.prog.exestack);
6630 goto read_updated_ip;
6631 case DC_INST_MODEXP:
6632 dbg_exec("DC_INST_MODEXP:");
6633 s = zdc_program_modexp();
6635 case DC_INST_DIVMOD:
6636 dbg_exec("DC_INST_DIVMOD:");
6637 s = zdc_program_divmod();
6639 case DC_INST_EXECUTE:
6640 case DC_INST_EXEC_COND:
6641 dbg_exec("DC_INST_EXEC[_COND]:");
6642 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6643 goto read_updated_ip;
6644 case DC_INST_PRINT_STACK: {
6646 dbg_exec("DC_INST_PRINT_STACK:");
6647 for (idx = 0; idx < G.prog.results.len; ++idx) {
6648 s = zbc_program_print(XC_INST_PRINT, idx);
6653 case DC_INST_CLEAR_STACK:
6654 dbg_exec("DC_INST_CLEAR_STACK:");
6655 bc_vec_pop_all(&G.prog.results);
6657 case DC_INST_STACK_LEN:
6658 dbg_exec("DC_INST_STACK_LEN:");
6659 dc_program_stackLen();
6661 case DC_INST_DUPLICATE:
6662 dbg_exec("DC_INST_DUPLICATE:");
6663 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6664 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6665 ptr = bc_vec_top(&G.prog.results);
6666 dc_result_copy(&r, ptr);
6667 bc_vec_push(&G.prog.results, &r);
6669 case DC_INST_SWAP: {
6671 dbg_exec("DC_INST_SWAP:");
6672 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6673 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6674 ptr = bc_vec_item_rev(&G.prog.results, 0);
6675 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6676 memcpy(&r, ptr, sizeof(BcResult));
6677 memcpy(ptr, ptr2, sizeof(BcResult));
6678 memcpy(ptr2, &r, sizeof(BcResult));
6681 case DC_INST_ASCIIFY:
6682 dbg_exec("DC_INST_ASCIIFY:");
6683 s = zdc_program_asciify();
6685 case DC_INST_PRINT_STREAM:
6686 dbg_exec("DC_INST_PRINT_STREAM:");
6687 s = zdc_program_printStream();
6690 case DC_INST_PUSH_VAR: {
6691 bool copy = inst == DC_INST_LOAD;
6692 s = zbc_program_pushVar(code, &ip->inst_idx, true, copy);
6695 case DC_INST_PUSH_TO_VAR: {
6696 char *name = bc_program_name(code, &ip->inst_idx);
6697 s = zbc_program_copyToVar(name, true);
6702 dbg_exec("DC_INST_QUIT:");
6703 if (G.prog.exestack.len <= 2)
6704 QUIT_OR_RETURN_TO_MAIN;
6705 bc_vec_npop(&G.prog.exestack, 2);
6706 goto read_updated_ip;
6708 dbg_exec("DC_INST_NQUIT:");
6709 s = zdc_program_nquit();
6710 //goto read_updated_ip; - just fall through to it
6713 // Instruction stack has changed, read new pointers
6714 ip = bc_vec_top(&G.prog.exestack);
6715 func = bc_program_func(ip->func);
6716 code = func->code.v;
6717 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6720 if (s || G_interrupt) {
6728 RETURN_STATUS(BC_STATUS_SUCCESS);
6730 #define zbc_program_exec(...) (zbc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6732 static unsigned bc_vm_envLen(const char *var)
6738 len = BC_NUM_PRINT_WIDTH;
6739 if (!lenv) return len;
6741 len = bb_strtou(lenv, NULL, 10) - 1;
6742 if (errno || len < 2 || len >= INT_MAX)
6743 len = BC_NUM_PRINT_WIDTH;
6748 static BC_STATUS zbc_vm_process(const char *text)
6752 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6753 s = zbc_parse_text_init(&G.prs, text); // does the first zbc_lex_next()
6754 if (s) RETURN_STATUS(s);
6756 while (G.prs.l.lex != XC_LEX_EOF) {
6760 dbg_lex("%s:%d G.prs.l.lex:%d, parsing...", __func__, __LINE__, G.prs.l.lex);
6763 s = zbc_parse_stmt_or_funcdef(&G.prs);
6766 // Check that next token is not bogus, and skip over
6767 // stmt delimiter(s) - newlines and semicolons
6768 s = 1; // s == 1 on first iteration only
6770 if (G.prs.l.lex == XC_LEX_EOF)
6771 goto execute; // this goto avoids resetting 's' to zero
6772 if (G.prs.l.lex != BC_LEX_SCOLON
6773 && G.prs.l.lex != XC_LEX_NLINE
6776 // Not newline and not semicolon
6777 if (s == 0) // saw at least one NL/semicolon before it?
6779 //TODO: commolalize for other parse errors:
6780 err_at = G.prs.l.lex_next_at ? G.prs.l.lex_next_at : "UNKNOWN";
6781 bc_error_fmt("bad statement terminator at '%.*s'",
6782 (int)(strchrnul(err_at, '\n') - err_at),
6787 // NL or semicolon: skip it, set s = 0, repeat
6788 s = zbc_lex_next(&G.prs.l);
6794 // Most of dc parsing assumes all whitespace,
6795 // including '\n', is eaten.
6796 while (G.prs.l.lex == XC_LEX_NLINE) {
6797 s = zbc_lex_next(&G.prs.l);
6799 if (G.prs.l.lex == XC_LEX_EOF)
6802 s = zdc_parse_expr(&G.prs);
6805 if (s || G_interrupt) {
6807 bc_parse_reset(&G.prs); // includes bc_program_reset()
6808 RETURN_STATUS(BC_STATUS_FAILURE);
6811 dbg_lex("%s:%d executing...", __func__, __LINE__);
6812 s = zbc_program_exec();
6818 ip = (void*)G.prog.exestack.v;
6820 if (G.prog.exestack.len != 1) // should have only main's IP
6821 bb_error_msg_and_die("BUG:call stack");
6822 if (ip->func != BC_PROG_MAIN)
6823 bb_error_msg_and_die("BUG:not MAIN");
6825 f = bc_program_func_BC_PROG_MAIN();
6826 // bc discards strings, constants and code after each
6827 // top-level statement in the "main program".
6828 // This prevents "yes 1 | bc" from growing its memory
6829 // without bound. This can be done because data stack
6830 // is empty and thus can't hold any references to
6831 // strings or constants, there is no generated code
6832 // which can hold references (after we discard one
6833 // we just executed). Code of functions can have references,
6834 // but bc stores function strings/constants in per-function
6838 if (G.prog.results.len != 0) // should be empty
6839 bb_error_msg_and_die("BUG:data stack");
6841 IF_BC(bc_vec_pop_all(&f->strs);)
6842 IF_BC(bc_vec_pop_all(&f->consts);)
6844 if (G.prog.results.len == 0
6845 && G.prog.vars.len == 0
6847 // If stack is empty and no registers exist (TODO: or they are all empty),
6848 // we can get rid of accumulated strings and constants.
6849 // In this example dc process should not grow
6850 // its memory consumption with time:
6852 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6853 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6855 // The code is discarded always (below), thus this example
6856 // should also not grow its memory consumption with time,
6857 // even though its data stack is not empty:
6858 // { echo 1; yes dk; } | dc
6860 // We drop generated and executed code for both bc and dc:
6861 bc_vec_pop_all(&f->code);
6865 dbg_lex_done("%s:%d done", __func__, __LINE__);
6868 #define zbc_vm_process(...) (zbc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6870 static BC_STATUS zbc_vm_execute_FILE(FILE *fp, const char *filename)
6872 // So far bc/dc have no way to include a file from another file,
6873 // therefore we know G.prog.file == NULL on entry
6874 //const char *sv_file;
6877 G.prog.file = filename;
6879 bc_lex_file(&G.prs.l);
6882 s = zbc_vm_process("");
6883 // We do not stop looping on errors here if reading stdin.
6884 // Example: start interactive bc and enter "return".
6885 // It should say "'return' not in a function"
6886 // but should not exit.
6887 } while (G.input_fp == stdin);
6891 #define zbc_vm_execute_FILE(...) (zbc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6893 static BC_STATUS zbc_vm_file(const char *file)
6898 fp = xfopen_for_read(file);
6899 s = zbc_vm_execute_FILE(fp, file);
6904 #define zbc_vm_file(...) (zbc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6907 static void bc_vm_info(void)
6909 printf("%s "BB_VER"\n"
6910 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6914 static void bc_args(char **argv)
6920 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6921 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6922 "warn\0" No_argument "w"
6923 "version\0" No_argument "v"
6924 "standard\0" No_argument "s"
6925 "quiet\0" No_argument "q"
6926 "mathlib\0" No_argument "l"
6927 "interactive\0" No_argument "i"
6930 opts = option_mask32 |= getopt32(argv, "wvsqli");
6932 if (getenv("POSIXLY_CORRECT"))
6933 option_mask32 |= BC_FLAG_S;
6935 if (opts & BC_FLAG_V) {
6940 for (i = optind; argv[i]; ++i)
6941 bc_vec_push(&G.files, argv + i);
6944 static void bc_vm_envArgs(void)
6948 char *env_args = getenv("BC_ENV_ARGS");
6950 if (!env_args) return;
6952 G.env_args = xstrdup(env_args);
6955 bc_vec_init(&v, sizeof(char *), NULL);
6957 while (*(buf = skip_whitespace(buf)) != '\0') {
6958 bc_vec_push(&v, &buf);
6959 buf = skip_non_whitespace(buf);
6965 // NULL terminate, and pass argv[] so that first arg is argv[1]
6966 if (sizeof(int) == sizeof(char*)) {
6967 bc_vec_push(&v, &const_int_0);
6969 static char *const nullptr = NULL;
6970 bc_vec_push(&v, &nullptr);
6972 bc_args(((char **)v.v) - 1);
6977 static const char bc_lib[] ALIGN1 = {
6980 "\n" "auto b,s,n,r,d,i,p,f,v"
6981 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6982 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6983 //e(-.998896): GNU:.36828580434569428695
6984 // above code:.36828580434569428696
6985 // actual value:.3682858043456942869594...
6986 // but for now let's be "GNU compatible"
6995 "\n" "scale=scale(x)+1"
7005 "\n" "for(i=2;v;++i){"
7011 "\n" "while(d--)r*=r"
7014 "\n" "if(n)return(1/r)"
7018 "\n" "auto b,s,r,p,a,q,i,v"
7022 "\n" "r=(1-10^scale)/1"
7033 "\n" "while(x<=.5){"
7037 "\n" "r=a=(x-1)/(x+1)"
7040 "\n" "for(i=3;v;i+=2){"
7051 "\n" "auto b,s,r,a,q,i"
7052 "\n" "if(x<0)return(-s(-x))"
7056 "\n" "scale=1.1*s+2"
7065 "\n" "for(i=3;a;i+=2){"
7066 "\n" "a*=q/(i*(i-1))"
7079 "\n" "x=s(2*a(1)+x)"
7085 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7093 "\n" "if(scale<65){"
7094 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7095 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7105 "\n" "x=(x-.2)/(1+.2*x)"
7110 "\n" "for(i=3;t;i+=2){"
7117 "\n" "return((m*a+r)/n)"
7119 "\n" "define j(n,x){"
7120 "\n" "auto b,s,o,a,i,v,f"
7131 "\n" "for(i=2;i<=n;++i)a*=i"
7133 "\n" "a=(x^n)/2^n/a"
7136 "\n" "scale+=length(a)-scale(a)"
7137 "\n" "for(i=1;v;++i){"
7138 "\n" "v=v*f/i/(n+i)"
7144 "\n" "return(a*r/1)"
7149 static BC_STATUS zbc_vm_exec(void)
7156 if (option_mask32 & BC_FLAG_L) {
7157 // We know that internal library is not buggy,
7158 // thus error checking is normally disabled.
7159 # define DEBUG_LIB 0
7160 bc_lex_file(&G.prs.l);
7161 s = zbc_vm_process(bc_lib);
7162 if (DEBUG_LIB && s) RETURN_STATUS(s);
7166 s = BC_STATUS_SUCCESS;
7167 fname = (void*)G.files.v;
7168 for (i = 0; i < G.files.len; i++) {
7169 s = zbc_vm_file(*fname++);
7170 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7171 // Debug config, non-interactive mode:
7172 // return all the way back to main.
7173 // Non-debug builds do not come here
7174 // in non-interactive mode, they exit.
7179 if (IS_BC || (option_mask32 & BC_FLAG_I))
7180 s = zbc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7184 #define zbc_vm_exec(...) (zbc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7186 #if ENABLE_FEATURE_CLEAN_UP
7187 static void bc_program_free(void)
7189 bc_vec_free(&G.prog.fns);
7190 IF_BC(bc_vec_free(&G.prog.fn_map);)
7191 bc_vec_free(&G.prog.vars);
7192 bc_vec_free(&G.prog.var_map);
7193 bc_vec_free(&G.prog.arrs);
7194 bc_vec_free(&G.prog.arr_map);
7195 IF_DC(bc_vec_free(&G.prog.strs);)
7196 IF_DC(bc_vec_free(&G.prog.consts);)
7197 bc_vec_free(&G.prog.results);
7198 bc_vec_free(&G.prog.exestack);
7199 IF_BC(bc_num_free(&G.prog.last);)
7200 IF_BC(bc_num_free(&G.prog.zero);)
7201 IF_BC(bc_num_free(&G.prog.one);)
7202 bc_vec_free(&G.input_buffer);
7205 static void bc_vm_free(void)
7207 bc_vec_free(&G.files);
7209 bc_parse_free(&G.prs);
7214 static void bc_program_init(void)
7218 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7219 memset(&ip, 0, sizeof(BcInstPtr));
7221 // G.prog.nchars = G.prog.scale = 0; - already is
7225 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7226 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7228 bc_num_init_DEF_SIZE(&G.prog.zero);
7229 //bc_num_zero(&G.prog.zero); - already is
7231 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7232 IF_BC(bc_num_one(&G.prog.one);)
7234 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7235 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7238 // Names are chosen simply to be distinct and never match
7239 // a valid function name (and be short)
7240 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7241 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7243 // in dc, functions have no names
7244 bc_program_add_fn();
7245 bc_program_add_fn();
7248 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7249 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7251 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7252 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7254 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7255 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7256 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7257 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7258 bc_vec_push(&G.prog.exestack, &ip);
7260 bc_char_vec_init(&G.input_buffer);
7263 static int bc_vm_init(const char *env_len)
7265 #if ENABLE_FEATURE_EDITING
7266 G.line_input_state = new_line_input_t(DO_HISTORY);
7268 G.prog.len = bc_vm_envLen(env_len);
7270 bc_vec_init(&G.files, sizeof(char *), NULL);
7271 IF_BC(if (IS_BC) bc_vm_envArgs();)
7273 bc_parse_create(&G.prs, BC_PROG_MAIN);
7275 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7276 //-i option unconditionally enables this regardless of isatty():
7278 #if ENABLE_FEATURE_BC_SIGNALS
7280 // With SA_RESTART, most system calls will restart
7281 // (IOW: they won't fail with EINTR).
7282 // In particular, this means ^C won't cause
7283 // stdout to get into "error state" if SIGINT hits
7284 // within write() syscall.
7286 // The downside is that ^C while tty input is taken
7287 // will only be handled after [Enter] since read()
7288 // from stdin is not interrupted by ^C either,
7289 // it restarts, thus fgetc() does not return on ^C.
7290 // (This problem manifests only if line editing is disabled)
7291 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7293 // Without SA_RESTART, this exhibits a bug:
7294 // "while (1) print 1" and try ^C-ing it.
7295 // Intermittently, instead of returning to input line,
7296 // you'll get "output error: Interrupted system call"
7298 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7302 return 0; // "not a tty"
7305 static BcStatus bc_vm_run(void)
7307 BcStatus st = zbc_vm_exec();
7308 #if ENABLE_FEATURE_CLEAN_UP
7309 if (G_exiting) // it was actually "halt" or "quit"
7312 # if ENABLE_FEATURE_EDITING
7313 free_line_input_t(G.line_input_state);
7317 dbg_exec("exiting with exitcode %d", st);
7322 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7323 int bc_main(int argc UNUSED_PARAM, char **argv)
7329 is_tty = bc_vm_init("BC_LINE_LENGTH");
7333 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7341 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7342 int dc_main(int argc UNUSED_PARAM, char **argv)
7348 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7349 // 1 char wider than bc from the same package.
7350 // Both default width, and xC_LINE_LENGTH=N are wider:
7351 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7354 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7357 // Do the same, or it's a bug?
7358 bc_vm_init("DC_LINE_LENGTH");
7360 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7361 noscript = BC_FLAG_I;
7363 int n = getopt(argc, argv, "e:f:x");
7369 n = zbc_vm_process(optarg);
7374 n = zbc_vm_file(optarg);
7378 option_mask32 |= DC_FLAG_X;
7388 bc_vec_push(&G.files, argv++);
7391 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7397 #endif // not DC_SMALL