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 {
718 smallint lex; // was BcLexType
719 smallint lex_last; // was BcLexType
723 #define BC_PARSE_STREND (0xff)
726 # define BC_PARSE_REL (1 << 0)
727 # define BC_PARSE_PRINT (1 << 1)
728 # define BC_PARSE_ARRAY (1 << 2)
729 # define BC_PARSE_NOCALL (1 << 3)
732 typedef struct BcParse {
742 IF_BC(size_t in_funcdef;)
745 typedef struct BcProgram {
775 #define BC_PROG_MAIN (0)
776 #define BC_PROG_READ (1)
778 #define BC_PROG_REQ_FUNCS (2)
781 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
782 #define BC_PROG_NUM(r, n) \
783 ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
785 #define BC_FLAG_W (1 << 0)
786 #define BC_FLAG_V (1 << 1)
787 #define BC_FLAG_S (1 << 2)
788 #define BC_FLAG_Q (1 << 3)
789 #define BC_FLAG_L (1 << 4)
790 #define BC_FLAG_I (1 << 5)
791 #define DC_FLAG_X (1 << 6)
793 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
794 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
796 #define BC_MAX_OBASE ((unsigned) 999)
797 #define BC_MAX_DIM ((unsigned) INT_MAX)
798 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
799 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
800 #define BC_MAX_NUM BC_MAX_STRING
801 // Unused apart from "limits" message. Just show a "biggish number" there.
802 //#define BC_MAX_NAME BC_MAX_STRING
803 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
804 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
805 #define BC_MAX_NAME_STR "999999999"
806 #define BC_MAX_EXP_STR "999999999"
807 #define BC_MAX_VARS_STR "999999999"
809 #define BC_MAX_OBASE_STR "999"
811 #if INT_MAX == 2147483647
812 # define BC_MAX_DIM_STR "2147483647"
813 #elif INT_MAX == 9223372036854775807
814 # define BC_MAX_DIM_STR "9223372036854775807"
816 # error Strange INT_MAX
819 #if UINT_MAX == 4294967295
820 # define BC_MAX_SCALE_STR "4294967295"
821 # define BC_MAX_STRING_STR "4294967294"
822 #elif UINT_MAX == 18446744073709551615
823 # define BC_MAX_SCALE_STR "18446744073709551615"
824 # define BC_MAX_STRING_STR "18446744073709551614"
826 # error Strange UINT_MAX
828 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
831 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
832 IF_FEATURE_CLEAN_UP(smallint exiting;)
837 // For error messages. Can be set to current parsed line,
838 // or [TODO] to current executing line (can be before last parsed one)
847 #if ENABLE_FEATURE_EDITING
848 line_input_t *line_input_state;
851 #define G (*ptr_to_globals)
852 #define INIT_G() do { \
853 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
855 #define FREE_G() do { \
856 FREE_PTR_TO_GLOBALS(); \
858 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
859 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
860 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
861 #if ENABLE_FEATURE_BC_SIGNALS
862 # define G_interrupt bb_got_signal
863 # define G_ttyin G.ttyin
865 # define G_interrupt 0
868 #if ENABLE_FEATURE_CLEAN_UP
869 # define G_exiting G.exiting
873 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
874 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
876 // In configurations where errors abort instead of propagating error
877 // return code up the call chain, functions returning BC_STATUS
878 // actually don't return anything, they always succeed and return "void".
879 // A macro wrapper is provided, which makes this statement work:
881 // and makes it visible to the compiler that s is always zero,
882 // allowing compiler to optimize dead code after the statement.
884 // To make code more readable, each such function has a "z"
885 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
887 #if ENABLE_FEATURE_BC_SIGNALS || ENABLE_FEATURE_CLEAN_UP
888 # define ERRORS_ARE_FATAL 0
889 # define ERRORFUNC /*nothing*/
890 # define IF_ERROR_RETURN_POSSIBLE(a) a
891 # define BC_STATUS BcStatus
892 # define RETURN_STATUS(v) return (v)
893 # define COMMA_SUCCESS /*nothing*/
895 # define ERRORS_ARE_FATAL 1
896 # define ERRORFUNC NORETURN
897 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
898 # define BC_STATUS void
899 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
900 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
907 static void fflush_and_check(void)
910 if (ferror(stdout) || ferror(stderr))
911 bb_perror_msg_and_die("output error");
914 #if ENABLE_FEATURE_CLEAN_UP
915 #define QUIT_OR_RETURN_TO_MAIN \
917 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
919 return BC_STATUS_FAILURE; \
922 #define QUIT_OR_RETURN_TO_MAIN quit()
925 static void quit(void) NORETURN;
926 static void quit(void)
929 bb_perror_msg_and_die("input error");
931 dbg_exec("quit(): exiting with exitcode SUCCESS");
935 static void bc_verror_msg(const char *fmt, va_list p)
937 const char *sv = sv; // for compiler
940 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
942 bb_verror_msg(fmt, p, NULL);
944 free((char*)applet_name);
949 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
954 bc_verror_msg(fmt, p);
957 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
958 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
963 static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
967 // Are non-POSIX constructs totally ok?
968 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
969 RETURN_STATUS(BC_STATUS_SUCCESS); // yes
972 bc_verror_msg(fmt, p);
975 // Do we treat non-POSIX constructs as errors?
976 if (!(option_mask32 & BC_FLAG_S))
977 RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
979 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
980 RETURN_STATUS(BC_STATUS_FAILURE);
983 #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
986 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
987 // This idiom begs for tail-call optimization, but for it to work,
988 // function must not have caller-cleaned parameters on stack.
989 // Unfortunately, vararg function API does exactly that on most arches.
990 // Thus, use these shims for the cases when we have no vararg PARAMS:
991 static ERRORFUNC int bc_error(const char *msg)
993 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
995 static ERRORFUNC int bc_error_bad_character(char c)
998 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
999 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
1001 static ERRORFUNC int bc_error_bad_expression(void)
1003 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
1005 static ERRORFUNC int bc_error_bad_token(void)
1007 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
1009 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1011 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1013 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1015 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1018 static BC_STATUS zbc_POSIX_requires(const char *msg)
1020 RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
1022 #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
1023 static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
1025 RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
1027 #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
1028 static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1030 RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg));
1032 #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)
1033 static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1035 RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg));
1037 #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)
1040 static void bc_vec_grow(BcVec *v, size_t n)
1042 size_t cap = v->cap * 2;
1043 while (cap < v->len + n) cap *= 2;
1044 v->v = xrealloc(v->v, v->size * cap);
1048 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1051 v->cap = BC_VEC_START_CAP;
1054 v->v = xmalloc(esize * BC_VEC_START_CAP);
1057 static void bc_char_vec_init(BcVec *v)
1059 bc_vec_init(v, sizeof(char), NULL);
1062 static void bc_vec_expand(BcVec *v, size_t req)
1065 v->v = xrealloc(v->v, v->size * req);
1070 static void bc_vec_pop(BcVec *v)
1074 v->dtor(v->v + (v->size * v->len));
1077 static void bc_vec_npop(BcVec *v, size_t n)
1082 size_t len = v->len - n;
1083 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1087 static void bc_vec_pop_all(BcVec *v)
1089 bc_vec_npop(v, v->len);
1092 static size_t bc_vec_push(BcVec *v, const void *data)
1094 size_t len = v->len;
1095 if (len >= v->cap) bc_vec_grow(v, 1);
1096 memmove(v->v + (v->size * len), data, v->size);
1101 // G.prog.results often needs "pop old operand, push result" idiom.
1102 // Can do this without a few extra ops
1103 static size_t bc_result_pop_and_push(const void *data)
1105 BcVec *v = &G.prog.results;
1107 size_t len = v->len - 1;
1109 last = v->v + (v->size * len);
1112 memmove(last, data, v->size);
1116 static size_t bc_vec_pushByte(BcVec *v, char data)
1118 return bc_vec_push(v, &data);
1121 static size_t bc_vec_pushZeroByte(BcVec *v)
1123 //return bc_vec_pushByte(v, '\0');
1125 return bc_vec_push(v, &const_int_0);
1128 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1131 bc_vec_push(v, data);
1135 if (v->len == v->cap) bc_vec_grow(v, 1);
1137 ptr = v->v + v->size * idx;
1139 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1140 memmove(ptr, data, v->size);
1144 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1147 bc_vec_expand(v, len + 1);
1148 memcpy(v->v, str, len);
1151 bc_vec_pushZeroByte(v);
1154 #if ENABLE_FEATURE_BC_SIGNALS && ENABLE_FEATURE_EDITING
1155 static void bc_vec_concat(BcVec *v, const char *str)
1159 if (v->len == 0) bc_vec_pushZeroByte(v);
1162 len = v->len + slen;
1164 if (v->cap < len) bc_vec_grow(v, slen);
1165 strcpy(v->v + v->len - 1, str);
1171 static void *bc_vec_item(const BcVec *v, size_t idx)
1173 return v->v + v->size * idx;
1176 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1178 return v->v + v->size * (v->len - idx - 1);
1181 static void *bc_vec_top(const BcVec *v)
1183 return v->v + v->size * (v->len - 1);
1186 static FAST_FUNC void bc_vec_free(void *vec)
1188 BcVec *v = (BcVec *) vec;
1193 static BcFunc* bc_program_func(size_t idx)
1195 return bc_vec_item(&G.prog.fns, idx);
1197 // BC_PROG_MAIN is zeroth element, so:
1198 #define bc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1201 static BcFunc* bc_program_current_func(void)
1203 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1204 BcFunc *func = bc_program_func(ip->func);
1209 static char** bc_program_str(size_t idx)
1213 BcFunc *func = bc_program_current_func();
1214 return bc_vec_item(&func->strs, idx);
1217 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1220 static char** bc_program_const(size_t idx)
1224 BcFunc *func = bc_program_current_func();
1225 return bc_vec_item(&func->consts, idx);
1228 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1231 static int bc_id_cmp(const void *e1, const void *e2)
1233 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1236 static FAST_FUNC void bc_id_free(void *id)
1238 free(((BcId *) id)->name);
1241 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1243 size_t low = 0, high = v->len;
1245 while (low < high) {
1246 size_t mid = (low + high) / 2;
1247 BcId *id = bc_vec_item(v, mid);
1248 int result = bc_id_cmp(ptr, id);
1261 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1263 size_t n = *i = bc_map_find_ge(v, ptr);
1266 bc_vec_push(v, ptr);
1267 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1268 return 0; // "was not inserted"
1270 bc_vec_pushAt(v, ptr, n);
1271 return 1; // "was inserted"
1275 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1277 size_t i = bc_map_find_ge(v, ptr);
1278 if (i >= v->len) return BC_VEC_INVALID_IDX;
1279 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1283 static void bc_num_setToZero(BcNum *n, size_t scale)
1290 static void bc_num_zero(BcNum *n)
1292 bc_num_setToZero(n, 0);
1295 static void bc_num_one(BcNum *n)
1297 bc_num_setToZero(n, 0);
1302 // Note: this also sets BcNum to zero
1303 static void bc_num_init(BcNum *n, size_t req)
1305 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1306 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1307 n->num = xmalloc(req);
1314 static void bc_num_init_DEF_SIZE(BcNum *n)
1316 bc_num_init(n, BC_NUM_DEF_SIZE);
1319 static void bc_num_expand(BcNum *n, size_t req)
1321 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1323 n->num = xrealloc(n->num, req);
1328 static FAST_FUNC void bc_num_free(void *num)
1330 free(((BcNum *) num)->num);
1333 static void bc_num_copy(BcNum *d, BcNum *s)
1336 bc_num_expand(d, s->cap);
1340 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1344 static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
1347 unsigned long result;
1351 while (i > n->rdx) {
1352 unsigned long prev = result;
1353 result = result * 10 + n->num[--i];
1354 // Even overflowed N*10 can still satisfy N*10>=N. For example,
1355 // 0x1ff00000 * 10 is 0x13f600000,
1356 // or 0x3f600000 truncated to 32 bits. Which is larger.
1357 // However, (N*10)/8 < N check is always correct.
1358 if ((result / 8) < prev)
1359 RETURN_STATUS(bc_error("overflow"));
1363 RETURN_STATUS(BC_STATUS_SUCCESS);
1365 #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
1367 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1369 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1371 RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
1373 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1375 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1376 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1377 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1378 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1380 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1381 // would not hit realloc() code path - not good if num[] is not malloced
1383 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1389 if (val == 0) return;
1391 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1398 if (val == 0) break;
1402 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1405 for (i = 0; i < len; ++i) {
1407 for (j = i; a[j] < 0;) {
1414 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1432 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1433 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1434 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1435 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1436 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1438 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1440 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1441 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1443 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1446 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1448 size_t i, min, a_int, b_int, diff;
1449 BcDig *max_num, *min_num;
1453 if (a == b) return 0;
1454 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1455 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1457 if (a->neg != b->neg) // signs of a and b differ
1458 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1459 return (int)b->neg - (int)a->neg;
1460 neg = a->neg; // 1 if both negative, 0 if both positive
1462 a_int = BC_NUM_INT(a);
1463 b_int = BC_NUM_INT(b);
1466 if (a_int != 0) return (ssize_t) a_int;
1468 a_max = (a->rdx > b->rdx);
1471 diff = a->rdx - b->rdx;
1472 max_num = a->num + diff;
1474 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1477 diff = b->rdx - a->rdx;
1478 max_num = b->num + diff;
1480 neg = !neg; // same as "neg = (a_max == neg)"
1483 cmp = bc_num_compare(max_num, min_num, b_int + min);
1484 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1486 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1487 if (max_num[i]) return BC_NUM_NEG(1, neg);
1493 static void bc_num_truncate(BcNum *n, size_t places)
1495 if (places == 0) return;
1501 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1505 static void bc_num_extend(BcNum *n, size_t places)
1507 size_t len = n->len + places;
1510 if (n->cap < len) bc_num_expand(n, len);
1512 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1513 memset(n->num, 0, sizeof(BcDig) * places);
1520 static void bc_num_clean(BcNum *n)
1522 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1525 else if (n->len < n->rdx)
1529 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1532 bc_num_extend(n, scale - n->rdx);
1534 bc_num_truncate(n, n->rdx - scale);
1537 if (n->len != 0) n->neg = !neg1 != !neg2;
1540 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1544 b->len = n->len - idx;
1546 a->rdx = b->rdx = 0;
1548 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1549 memcpy(a->num, n->num, idx * sizeof(BcDig));
1559 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1561 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1563 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1564 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1565 if (places + n->len > BC_MAX_NUM)
1566 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1569 if (n->rdx >= places)
1572 bc_num_extend(n, places - n->rdx);
1578 RETURN_STATUS(BC_STATUS_SUCCESS);
1580 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1582 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
1584 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
1585 BcNumBinaryOp op, size_t req)
1588 BcNum num2, *ptr_a, *ptr_b;
1593 memcpy(ptr_a, c, sizeof(BcNum));
1601 memcpy(ptr_b, c, sizeof(BcNum));
1608 bc_num_init(c, req);
1610 bc_num_expand(c, req);
1612 s = BC_STATUS_SUCCESS;
1613 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
1615 if (init) bc_num_free(&num2);
1619 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
1621 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1622 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1623 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1624 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1625 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1626 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
1628 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1630 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
1632 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
1635 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1637 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
1639 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
1642 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1644 size_t req = BC_NUM_MREQ(a, b, scale);
1645 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
1648 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1650 size_t req = BC_NUM_MREQ(a, b, scale);
1651 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
1654 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1656 size_t req = BC_NUM_MREQ(a, b, scale);
1657 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
1660 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
1662 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
1665 static const BcNumBinaryOp zbc_program_ops[] = {
1666 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
1668 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
1669 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
1670 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
1671 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
1672 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
1673 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
1675 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1684 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1686 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1688 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1690 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1691 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1694 // Because this function doesn't need to use scale (per the bc spec),
1695 // I am hijacking it to say whether it's doing an add or a subtract.
1699 if (sub && c->len) c->neg = !c->neg;
1700 RETURN_STATUS(BC_STATUS_SUCCESS);
1704 RETURN_STATUS(BC_STATUS_SUCCESS);
1708 c->rdx = BC_MAX(a->rdx, b->rdx);
1709 min_rdx = BC_MIN(a->rdx, b->rdx);
1712 if (a->rdx > b->rdx) {
1713 diff = a->rdx - b->rdx;
1715 ptr_a = a->num + diff;
1718 diff = b->rdx - a->rdx;
1721 ptr_b = b->num + diff;
1725 for (i = 0; i < diff; ++i, ++c->len)
1729 a_int = BC_NUM_INT(a);
1730 b_int = BC_NUM_INT(b);
1732 if (a_int > b_int) {
1743 for (i = 0; i < min_rdx + min_int; ++i) {
1744 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1746 ptr_c[i] = (BcDig)(in % 10);
1748 for (; i < max + min_rdx; ++i) {
1749 unsigned in = (unsigned)ptr[i] + carry;
1751 ptr_c[i] = (BcDig)(in % 10);
1755 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1757 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1760 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1763 BcNum *minuend, *subtrahend;
1765 bool aneg, bneg, neg;
1767 // Because this function doesn't need to use scale (per the bc spec),
1768 // I am hijacking it to say whether it's doing an add or a subtract.
1772 if (sub && c->len) c->neg = !c->neg;
1773 RETURN_STATUS(BC_STATUS_SUCCESS);
1777 RETURN_STATUS(BC_STATUS_SUCCESS);
1782 a->neg = b->neg = false;
1784 cmp = bc_num_cmp(a, b);
1790 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1791 RETURN_STATUS(BC_STATUS_SUCCESS);
1799 if (sub) neg = !neg;
1804 bc_num_copy(c, minuend);
1807 if (c->rdx < subtrahend->rdx) {
1808 bc_num_extend(c, subtrahend->rdx - c->rdx);
1811 start = c->rdx - subtrahend->rdx;
1813 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1817 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1820 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1822 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1825 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1826 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1829 if (a->len == 0 || b->len == 0) {
1831 RETURN_STATUS(BC_STATUS_SUCCESS);
1833 aone = BC_NUM_ONE(a);
1834 if (aone || BC_NUM_ONE(b)) {
1835 bc_num_copy(c, aone ? b : a);
1836 RETURN_STATUS(BC_STATUS_SUCCESS);
1839 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1840 || a->len < BC_NUM_KARATSUBA_LEN
1841 || b->len < BC_NUM_KARATSUBA_LEN
1845 bc_num_expand(c, a->len + b->len + 1);
1847 memset(c->num, 0, sizeof(BcDig) * c->cap);
1850 for (i = 0; i < b->len; ++i) {
1852 for (j = 0; j < a->len; ++j) {
1853 unsigned in = c->num[i + j];
1854 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1855 // note: compilers prefer _unsigned_ div/const
1857 c->num[i + j] = (BcDig)(in % 10);
1860 c->num[i + j] += (BcDig) carry;
1861 len = BC_MAX(len, i + j + !!carry);
1863 #if ENABLE_FEATURE_BC_SIGNALS
1865 // a*a <- without check below, this will not be interruptible
1866 if (G_interrupt) return BC_STATUS_FAILURE;
1872 RETURN_STATUS(BC_STATUS_SUCCESS);
1875 bc_num_init(&l1, max);
1876 bc_num_init(&h1, max);
1877 bc_num_init(&l2, max);
1878 bc_num_init(&h2, max);
1879 bc_num_init(&m1, max);
1880 bc_num_init(&m2, max);
1881 bc_num_init(&z0, max);
1882 bc_num_init(&z1, max);
1883 bc_num_init(&z2, max);
1884 bc_num_init(&temp, max + max);
1886 bc_num_split(a, max2, &l1, &h1);
1887 bc_num_split(b, max2, &l2, &h2);
1889 s = zbc_num_add(&h1, &l1, &m1, 0);
1891 s = zbc_num_add(&h2, &l2, &m2, 0);
1894 s = zbc_num_k(&h1, &h2, &z0);
1896 s = zbc_num_k(&m1, &m2, &z1);
1898 s = zbc_num_k(&l1, &l2, &z2);
1901 s = zbc_num_sub(&z1, &z0, &temp, 0);
1903 s = zbc_num_sub(&temp, &z2, &z1, 0);
1906 s = zbc_num_shift(&z0, max2 * 2);
1908 s = zbc_num_shift(&z1, max2);
1910 s = zbc_num_add(&z0, &z1, &temp, 0);
1912 s = zbc_num_add(&temp, &z2, c, 0);
1927 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1931 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1933 scale = BC_MAX(scale, a->rdx);
1934 scale = BC_MAX(scale, b->rdx);
1935 scale = BC_MIN(a->rdx + b->rdx, scale);
1936 maxrdx = BC_MAX(maxrdx, scale);
1938 bc_num_init(&cpa, a->len);
1939 bc_num_init(&cpb, b->len);
1941 bc_num_copy(&cpa, a);
1942 bc_num_copy(&cpb, b);
1943 cpa.neg = cpb.neg = false;
1945 s = zbc_num_shift(&cpa, maxrdx);
1947 s = zbc_num_shift(&cpb, maxrdx);
1949 s = zbc_num_k(&cpa, &cpb, c);
1953 bc_num_expand(c, c->len + maxrdx);
1955 if (c->len < maxrdx) {
1956 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1961 bc_num_retireMul(c, scale, a->neg, b->neg);
1967 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1969 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1976 RETURN_STATUS(bc_error("divide by zero"));
1978 bc_num_setToZero(c, scale);
1979 RETURN_STATUS(BC_STATUS_SUCCESS);
1981 if (BC_NUM_ONE(b)) {
1983 bc_num_retireMul(c, scale, a->neg, b->neg);
1984 RETURN_STATUS(BC_STATUS_SUCCESS);
1987 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1988 bc_num_copy(&cp, a);
1992 bc_num_expand(&cp, len + 2);
1993 bc_num_extend(&cp, len - cp.len);
1996 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1998 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
2000 if (b->rdx == b->len) {
2002 if (len == 0) break;
2004 if (b->num[len] != 0)
2010 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
2012 // We want an extra zero in front to make things simpler.
2013 cp.num[cp.len++] = 0;
2016 bc_num_expand(c, cp.len);
2019 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2023 s = BC_STATUS_SUCCESS;
2024 for (i = end - 1; i < end; --i) {
2027 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2028 bc_num_subArrays(n, b->num, len);
2030 #if ENABLE_FEATURE_BC_SIGNALS
2033 // 1/a <- without check below, this will not be interruptible
2035 s = BC_STATUS_FAILURE;
2041 bc_num_retireMul(c, scale, a->neg, b->neg);
2046 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2048 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2049 BcNum *restrict d, size_t scale, size_t ts)
2056 RETURN_STATUS(bc_error("divide by zero"));
2059 bc_num_setToZero(d, ts);
2060 RETURN_STATUS(BC_STATUS_SUCCESS);
2063 bc_num_init(&temp, d->cap);
2064 s = zbc_num_d(a, b, c, scale);
2067 if (scale != 0) scale = ts;
2069 s = zbc_num_m(c, b, &temp, scale);
2071 s = zbc_num_sub(a, &temp, d, scale);
2074 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2077 bc_num_retireMul(d, ts, a->neg, b->neg);
2083 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2085 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2089 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2091 bc_num_init(&c1, len);
2092 s = zbc_num_r(a, b, &c1, c, scale, ts);
2097 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2099 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2101 BcStatus s = BC_STATUS_SUCCESS;
2104 size_t i, powrdx, resrdx;
2107 // GNU bc does not allow 2^2.0 - we do
2108 for (i = 0; i < b->rdx; i++)
2110 RETURN_STATUS(bc_error("not an integer"));
2114 RETURN_STATUS(BC_STATUS_SUCCESS);
2117 bc_num_setToZero(c, scale);
2118 RETURN_STATUS(BC_STATUS_SUCCESS);
2120 if (BC_NUM_ONE(b)) {
2124 s = zbc_num_inv(a, c, scale);
2129 s = zbc_num_ulong_abs(b, &pow);
2130 if (s) RETURN_STATUS(s);
2131 // b is not used beyond this point
2133 bc_num_init(©, a->len);
2134 bc_num_copy(©, a);
2139 if (a->rdx * pow < scale)
2140 scale = a->rdx * pow;
2144 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2146 s = zbc_num_mul(©, ©, ©, powrdx);
2148 // Not needed: zbc_num_mul() has a check for ^C:
2149 //if (G_interrupt) {
2150 // s = BC_STATUS_FAILURE;
2155 bc_num_copy(c, ©);
2157 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2159 s = zbc_num_mul(©, ©, ©, powrdx);
2164 s = zbc_num_mul(c, ©, c, resrdx);
2167 // Not needed: zbc_num_mul() has a check for ^C:
2168 //if (G_interrupt) {
2169 // s = BC_STATUS_FAILURE;
2175 s = zbc_num_inv(c, c, scale);
2179 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2181 // We can't use bc_num_clean() here.
2182 for (i = 0; i < c->len; ++i)
2185 bc_num_setToZero(c, scale);
2192 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2194 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2197 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2198 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2199 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2201 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2202 bc_num_expand(b, req);
2205 bc_num_setToZero(b, scale);
2206 RETURN_STATUS(BC_STATUS_SUCCESS);
2209 RETURN_STATUS(bc_error("negative number"));
2211 if (BC_NUM_ONE(a)) {
2213 bc_num_extend(b, scale);
2214 RETURN_STATUS(BC_STATUS_SUCCESS);
2217 scale = BC_MAX(scale, a->rdx) + 1;
2218 len = a->len + scale;
2220 bc_num_init(&num1, len);
2221 bc_num_init(&num2, len);
2222 bc_num_init_DEF_SIZE(&half);
2228 bc_num_init(&f, len);
2229 bc_num_init(&fprime, len);
2235 pow = BC_NUM_INT(a);
2243 pow -= 2 - (pow & 1);
2245 bc_num_extend(x0, pow);
2247 // Make sure to move the radix back.
2251 x0->rdx = digs = digs1 = 0;
2253 len = BC_NUM_INT(x0) + resrdx - 1;
2255 while (cmp != 0 || digs < len) {
2256 s = zbc_num_div(a, x0, &f, resrdx);
2258 s = zbc_num_add(x0, &f, &fprime, resrdx);
2260 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2263 cmp = bc_num_cmp(x1, x0);
2264 digs = x1->len - (unsigned long long) llabs(cmp);
2266 if (cmp == cmp2 && digs == digs1)
2271 resrdx += times > 4;
2284 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2286 bc_num_free(&fprime);
2293 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2295 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2301 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2304 memcpy(&num2, c, sizeof(BcNum));
2306 bc_num_init(c, len);
2310 bc_num_expand(c, len);
2313 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2315 if (init) bc_num_free(&num2);
2319 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2322 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2325 BcNum base, exp, two, temp;
2329 RETURN_STATUS(bc_error("divide by zero"));
2330 if (a->rdx || b->rdx || c->rdx)
2331 RETURN_STATUS(bc_error("not an integer"));
2333 RETURN_STATUS(bc_error("negative number"));
2335 bc_num_expand(d, c->len);
2336 bc_num_init(&base, c->len);
2337 bc_num_init(&exp, b->len);
2338 bc_num_init(&temp, b->len);
2340 two.cap = ARRAY_SIZE(two_digs);
2347 s = zbc_num_rem(a, c, &base, 0);
2349 bc_num_copy(&exp, b);
2351 while (exp.len != 0) {
2352 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2355 if (BC_NUM_ONE(&temp)) {
2356 s = zbc_num_mul(d, &base, &temp, 0);
2358 s = zbc_num_rem(&temp, c, d, 0);
2362 s = zbc_num_mul(&base, &base, &temp, 0);
2364 s = zbc_num_rem(&temp, c, &base, 0);
2373 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2376 static FAST_FUNC void bc_string_free(void *string)
2378 free(*(char**)string);
2381 static void bc_func_init(BcFunc *f)
2383 bc_char_vec_init(&f->code);
2384 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2385 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2386 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2387 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2388 IF_BC(f->nparams = 0;)
2391 static FAST_FUNC void bc_func_free(void *func)
2393 BcFunc *f = (BcFunc *) func;
2394 bc_vec_free(&f->code);
2395 IF_BC(bc_vec_free(&f->labels);)
2396 IF_BC(bc_vec_free(&f->autos);)
2397 IF_BC(bc_vec_free(&f->strs);)
2398 IF_BC(bc_vec_free(&f->consts);)
2401 static void bc_array_expand(BcVec *a, size_t len);
2403 static void bc_array_init(BcVec *a, bool nums)
2406 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2408 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2409 bc_array_expand(a, 1);
2412 static void bc_array_expand(BcVec *a, size_t len)
2414 if (a->dtor == bc_num_free
2415 // && a->size == sizeof(BcNum) - always true
2418 while (len > a->len) {
2419 bc_num_init_DEF_SIZE(&n);
2424 while (len > a->len) {
2425 bc_array_init(&v, true);
2431 static void bc_array_copy(BcVec *d, const BcVec *s)
2437 bc_vec_expand(d, s->cap);
2442 for (i = 0; i < s->len; i++, dnum++, snum++) {
2443 bc_num_init(dnum, snum->len);
2444 bc_num_copy(dnum, snum);
2449 static void dc_result_copy(BcResult *d, BcResult *src)
2454 case XC_RESULT_TEMP:
2455 case XC_RESULT_IBASE:
2456 case XC_RESULT_SCALE:
2457 case XC_RESULT_OBASE:
2458 bc_num_init(&d->d.n, src->d.n.len);
2459 bc_num_copy(&d->d.n, &src->d.n);
2462 case XC_RESULT_ARRAY:
2463 case XC_RESULT_ARRAY_ELEM:
2464 d->d.id.name = xstrdup(src->d.id.name);
2466 case XC_RESULT_CONSTANT:
2467 IF_BC(case BC_RESULT_LAST:)
2468 IF_BC(case BC_RESULT_ONE:)
2470 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2476 static FAST_FUNC void bc_result_free(void *result)
2478 BcResult *r = (BcResult *) result;
2481 case XC_RESULT_TEMP:
2482 case XC_RESULT_IBASE:
2483 case XC_RESULT_SCALE:
2484 case XC_RESULT_OBASE:
2485 bc_num_free(&r->d.n);
2488 case XC_RESULT_ARRAY:
2489 case XC_RESULT_ARRAY_ELEM:
2498 static int bad_input_byte(char c)
2500 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
2503 bc_error_fmt("illegal character 0x%02x", c);
2509 // Note: it _appends_ data from fp to vec.
2510 static void bc_read_line(BcVec *vec, FILE *fp)
2515 #if ENABLE_FEATURE_BC_SIGNALS
2516 if (G_interrupt) { // ^C was pressed
2519 // ^C while running a script (bc SCRIPT): die.
2520 // We do not return to interactive prompt:
2521 // user might be running us from a shell,
2522 // and SCRIPT might be intended to terminate
2523 // (e.g. contain a "halt" stmt).
2524 // ^C dropping user into a bc prompt instead of
2525 // the shell would be unexpected.
2528 // ^C while interactive input
2530 // GNU bc says "interrupted execution."
2531 // GNU dc says "Interrupt!"
2532 fputs("\ninterrupted execution\n", stderr);
2535 # if ENABLE_FEATURE_EDITING
2536 if (G_ttyin && fp == stdin) {
2538 # define line_buf bb_common_bufsiz1
2539 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
2540 if (n <= 0) { // read errors or EOF, or ^D, or ^C
2543 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
2548 char c = line_buf[i++];
2550 if (bad_input_byte(c)) goto again;
2552 bc_vec_concat(vec, line_buf);
2560 size_t len = vec->len;
2563 #if ENABLE_FEATURE_BC_SIGNALS
2565 // ^C was pressed: ignore entire line, get another one
2570 do c = fgetc(fp); while (c == '\0');
2573 bb_perror_msg_and_die("input error");
2574 // Note: EOF does not append '\n'
2577 bad_chars |= bad_input_byte(c);
2578 bc_vec_pushByte(vec, (char)c);
2579 } while (c != '\n');
2582 // Bad chars on this line
2583 if (!G.prog.file) { // stdin
2584 // ignore entire line, get another one
2588 bb_perror_msg_and_die("file '%s' is not text", G.prog.file);
2590 bc_vec_pushZeroByte(vec);
2598 static bool bc_num_strValid(const char *val, size_t base)
2603 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2610 if (radix) return false;
2614 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2620 // Note: n is already "bc_num_zero()"ed,
2621 // leading zeroes in "val" are removed
2622 static void bc_num_parseDecimal(BcNum *n, const char *val)
2631 bc_num_expand(n, len);
2633 ptr = strchr(val, '.');
2637 n->rdx = (size_t)((val + len) - (ptr + 1));
2639 for (i = 0; val[i]; ++i) {
2640 if (val[i] != '0' && val[i] != '.') {
2641 // Not entirely zero value - convert it, and exit
2644 n->num[n->len] = val[i] - '0';
2648 if (val[--i] == '.') goto skip_dot;
2653 // if for() exits without hitting if(), the value is entirely zero
2656 // Note: n is already "bc_num_zero()"ed,
2657 // leading zeroes in "val" are removed
2658 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2661 BcNum temp, mult, result;
2663 BcDig base_digs[ULONG_NUM_BUFSIZE];
2668 for (i = 0; ; ++i) {
2671 if (val[i] != '.' && val[i] != '0')
2675 bc_num_init_DEF_SIZE(&temp);
2676 bc_num_init_DEF_SIZE(&mult);
2677 base.cap = ARRAY_SIZE(base_digs);
2678 base.num = base_digs;
2679 bc_num_ulong2num(&base, base_t);
2683 if (c == '\0') goto int_err;
2684 if (c == '.') break;
2686 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2688 s = zbc_num_mul(n, &base, &mult, 0);
2689 if (s) goto int_err;
2690 bc_num_ulong2num(&temp, v);
2691 s = zbc_num_add(&mult, &temp, n, 0);
2692 if (s) goto int_err;
2695 bc_num_init(&result, base.len);
2696 //bc_num_zero(&result); - already is
2702 if (c == '\0') break;
2705 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2707 s = zbc_num_mul(&result, &base, &result, 0);
2709 bc_num_ulong2num(&temp, v);
2710 s = zbc_num_add(&result, &temp, &result, 0);
2712 s = zbc_num_mul(&mult, &base, &mult, 0);
2716 s = zbc_num_div(&result, &mult, &result, digits);
2718 s = zbc_num_add(n, &result, n, digits);
2722 if (n->rdx < digits)
2723 bc_num_extend(n, digits - n->rdx);
2727 bc_num_free(&result);
2733 static BC_STATUS zbc_num_parse(BcNum *n, const char *val, unsigned base_t)
2735 if (!bc_num_strValid(val, base_t))
2736 RETURN_STATUS(bc_error("bad number string"));
2739 while (*val == '0') val++;
2742 bc_num_parseDecimal(n, val);
2744 bc_num_parseBase(n, val, base_t);
2746 RETURN_STATUS(BC_STATUS_SUCCESS);
2748 #define zbc_num_parse(...) (zbc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2750 static void bc_lex_lineComment(BcLex *l)
2752 // Try: echo -n '#foo' | bc
2754 l->lex = XC_LEX_WHITESPACE;
2756 while (i < l->len && l->buf[i] != '\n')
2761 static void bc_lex_whitespace(BcLex *l)
2763 l->lex = XC_LEX_WHITESPACE;
2765 char c = l->buf[l->i];
2766 if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
2774 static BC_STATUS zbc_lex_number(BcLex *l, char start)
2776 const char *buf = l->buf + l->i;
2777 size_t len, i, ccnt;
2780 pt = (start == '.');
2781 l->lex = XC_LEX_NUMBER;
2787 if (c == '\\' && buf[i + 1] == '\n') {
2789 //number_of_backslashes++ - see comment below
2792 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2793 if (c != '.') break;
2794 // if '.' was already seen, stop on second one:
2798 // buf[i] is one of "0-9A-F."
2803 //ccnt is the number of chars in the number string, excluding possible
2804 //trailing "[\<newline>].[\<newline>]" (with any number of \<NL> repetitions).
2805 //i is buf[i] index of the first not-yet-parsed char after that.
2808 // This might overestimate the size, if there are "\<NL>"'s
2809 // in the number. Subtracting number_of_backslashes*2 correctly
2810 // is not that easy: consider that in the case of "NNN.\<NL>"
2811 // loop above will count "\<NL>" before it realizes it is not
2812 // in fact *inside* the number:
2813 len = ccnt + 1; // +1 byte for NUL termination
2815 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2816 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2817 if (len > BC_MAX_NUM)
2818 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
2821 bc_vec_pop_all(&l->lex_buf);
2822 bc_vec_expand(&l->lex_buf, 1 + len);
2823 bc_vec_push(&l->lex_buf, &start);
2826 // If we have hit a backslash, skip it. We don't have
2827 // to check for a newline because it's guaranteed.
2833 bc_vec_push(&l->lex_buf, buf);
2838 bc_vec_pushZeroByte(&l->lex_buf);
2840 RETURN_STATUS(BC_STATUS_SUCCESS);
2842 #define zbc_lex_number(...) (zbc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2844 static void bc_lex_name(BcLex *l)
2849 l->lex = XC_LEX_NAME;
2852 buf = l->buf + l->i - 1;
2855 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2859 #if 0 // We do not protect against people with gigabyte-long names
2860 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2861 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2862 if (i > BC_MAX_STRING)
2863 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2866 bc_vec_string(&l->lex_buf, i, buf);
2868 // Increment the index. We minus 1 because it has already been incremented.
2871 //return BC_STATUS_SUCCESS;
2874 static void bc_lex_init(BcLex *l)
2876 bc_char_vec_init(&l->lex_buf);
2879 static void bc_lex_free(BcLex *l)
2881 bc_vec_free(&l->lex_buf);
2884 static void bc_lex_file(BcLex *l)
2886 G.err_line = l->line = 1;
2890 static bool bc_lex_more_input(BcLex *l)
2895 bc_vec_pop_all(&G.input_buffer);
2897 // This loop is complex because the vm tries not to send any lines that end
2898 // with a backslash to the parser. The reason for that is because the parser
2899 // treats a backslash+newline combo as whitespace, per the bc spec. In that
2900 // case, and for strings and comments, the parser will expect more stuff.
2904 size_t prevlen = G.input_buffer.len;
2907 bc_read_line(&G.input_buffer, G.input_fp);
2908 // No more input means EOF
2909 if (G.input_buffer.len <= prevlen + 1) // (we expect +1 for NUL byte)
2912 string = G.input_buffer.v + prevlen;
2915 if (string == G.input_buffer.v || string[-1] != '\\') {
2926 if (c == '/' && *string == '*') {
2931 if (c == '*' && *string == '/') {
2936 if (str != 0 || comment) {
2937 G.input_buffer.len--; // backstep over the trailing NUL byte
2941 // Check for backslash+newline.
2942 // we do not check that last char is '\n' -
2943 // if it is not, then it's EOF, and looping back
2944 // to bc_read_line() will detect it:
2946 if (string >= G.input_buffer.v && *string == '\\') {
2947 G.input_buffer.len--;
2954 l->buf = G.input_buffer.v;
2956 // bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2957 l->len = G.input_buffer.len - 1; // do not include NUL
2962 IF_BC(static BC_STATUS zbc_lex_token(BcLex *l);)
2963 IF_DC(static BC_STATUS zdc_lex_token(BcLex *l);)
2964 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2965 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2967 static BC_STATUS zbc_lex_next(BcLex *l)
2971 l->lex_last = l->lex;
2972 if (l->lex_last == XC_LEX_EOF) RETURN_STATUS(bc_error("end of file"));
2974 l->line += l->newline;
2975 G.err_line = l->line;
2978 // Loop until failure or we don't have whitespace. This
2979 // is so the parser doesn't get inundated with whitespace.
2980 // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
2981 s = BC_STATUS_SUCCESS;
2983 if (l->i == l->len) {
2984 l->lex = XC_LEX_EOF;
2986 RETURN_STATUS(BC_STATUS_SUCCESS);
2987 if (!bc_lex_more_input(l)) {
2989 RETURN_STATUS(BC_STATUS_SUCCESS);
2991 // here it's guaranteed that l->i is below l->len
2993 dbg_lex("next string to parse:'%.*s'",
2994 (int)(strchrnul(l->buf + l->i, '\n') - (l->buf + l->i)),
2997 IF_BC(s = zbc_lex_token(l));
2999 IF_DC(s = zdc_lex_token(l));
3001 } while (!s && l->lex == XC_LEX_WHITESPACE);
3002 dbg_lex("l->lex from string:%d", l->lex);
3006 #define zbc_lex_next(...) (zbc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
3009 static BC_STATUS zbc_lex_skip_if_at_NLINE(BcLex *l)
3011 if (l->lex == XC_LEX_NLINE)
3012 RETURN_STATUS(zbc_lex_next(l));
3013 RETURN_STATUS(BC_STATUS_SUCCESS);
3015 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3017 static BC_STATUS zbc_lex_next_and_skip_NLINE(BcLex *l)
3020 s = zbc_lex_next(l);
3021 if (s) RETURN_STATUS(s);
3022 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
3023 s = zbc_lex_skip_if_at_NLINE(l);
3026 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
3029 static BC_STATUS zbc_lex_text_init(BcLex *l, const char *text)
3033 l->len = strlen(text);
3034 l->lex = l->lex_last = XC_LEX_INVALID;
3035 RETURN_STATUS(zbc_lex_next(l));
3037 #define zbc_lex_text_init(...) (zbc_lex_text_init(__VA_ARGS__) COMMA_SUCCESS)
3040 static BC_STATUS zbc_lex_identifier(BcLex *l)
3044 const char *buf = l->buf + l->i - 1;
3046 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3047 const char *keyword8 = bc_lex_kws[i].name8;
3049 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3051 if (j == 8) goto match;
3053 if (keyword8[j] != '\0')
3056 // buf starts with keyword bc_lex_kws[i]
3057 if (isalnum(buf[j]) || buf[j]=='_')
3058 continue; // "ifz" does not match "if" keyword, "if." does
3059 l->lex = BC_LEX_KEY_1st_keyword + i;
3060 if (!bc_lex_kws_POSIX(i)) {
3061 s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3062 if (s) RETURN_STATUS(s);
3065 // We minus 1 because the index has already been incremented.
3067 RETURN_STATUS(BC_STATUS_SUCCESS);
3071 s = BC_STATUS_SUCCESS;
3073 if (l->lex_buf.len > 2) {
3076 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3078 unsigned len = strchrnul(buf, '\n') - buf;
3079 s = zbc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3084 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3086 static BC_STATUS zbc_lex_string(BcLex *l)
3090 l->lex = XC_LEX_STR;
3098 RETURN_STATUS(bc_error("string end could not be found"));
3107 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3108 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3109 if (len > BC_MAX_STRING)
3110 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3112 bc_vec_string(&l->lex_buf, len, l->buf + l->i);
3116 G.err_line = l->line;
3118 RETURN_STATUS(BC_STATUS_SUCCESS);
3120 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3122 static void bc_lex_assign(BcLex *l, unsigned with_and_without)
3124 if (l->buf[l->i] == '=') {
3126 with_and_without >>= 8; // store "with" value
3127 } // else store "without" value
3128 l->lex = (with_and_without & 0xff);
3130 #define bc_lex_assign(l, with, without) \
3131 bc_lex_assign(l, ((with)<<8)|(without))
3133 static BC_STATUS zbc_lex_comment(BcLex *l)
3136 const char *buf = l->buf;
3138 l->lex = XC_LEX_WHITESPACE;
3139 i = l->i; /* here buf[l->i] is the '*' of opening comment delimiter */
3151 RETURN_STATUS(bc_error("comment end could not be found"));
3158 G.err_line = l->line;
3160 RETURN_STATUS(BC_STATUS_SUCCESS);
3162 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3164 #undef zbc_lex_token
3165 static BC_STATUS zbc_lex_token(BcLex *l)
3167 BcStatus s = BC_STATUS_SUCCESS;
3168 char c = l->buf[l->i++], c2;
3170 // This is the workhorse of the lexer.
3172 // case '\0': // probably never reached
3174 // l->lex = XC_LEX_EOF;
3175 // l->newline = true;
3178 l->lex = XC_LEX_NLINE;
3186 bc_lex_whitespace(l);
3189 bc_lex_assign(l, XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3190 if (l->lex == BC_LEX_OP_BOOL_NOT) {
3191 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3192 if (s) RETURN_STATUS(s);
3196 s = zbc_lex_string(l);
3199 s = zbc_POSIX_does_not_allow("'#' script comments");
3200 if (s) RETURN_STATUS(s);
3201 bc_lex_lineComment(l);
3204 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
3209 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3210 if (s) RETURN_STATUS(s);
3212 l->lex = BC_LEX_OP_BOOL_AND;
3214 l->lex = XC_LEX_INVALID;
3215 s = bc_error_bad_character('&');
3220 l->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3223 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
3229 l->lex = BC_LEX_OP_INC;
3231 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
3234 l->lex = BC_LEX_COMMA;
3240 l->lex = BC_LEX_OP_DEC;
3242 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
3245 if (isdigit(l->buf[l->i]))
3246 s = zbc_lex_number(l, c);
3248 l->lex = BC_LEX_KEY_LAST;
3249 s = zbc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3255 s = zbc_lex_comment(l);
3257 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
3275 s = zbc_lex_number(l, c);
3278 l->lex = BC_LEX_SCOLON;
3281 bc_lex_assign(l, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
3284 bc_lex_assign(l, XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3287 bc_lex_assign(l, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
3291 l->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3294 if (l->buf[l->i] == '\n') {
3295 l->lex = XC_LEX_WHITESPACE;
3298 s = bc_error_bad_character(c);
3301 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
3329 s = zbc_lex_identifier(l);
3333 l->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3338 s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3339 if (s) RETURN_STATUS(s);
3341 l->lex = BC_LEX_OP_BOOL_OR;
3343 l->lex = XC_LEX_INVALID;
3344 s = bc_error_bad_character(c);
3348 l->lex = XC_LEX_INVALID;
3349 s = bc_error_bad_character(c);
3355 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3359 static BC_STATUS zdc_lex_register(BcLex *l)
3361 if (G_exreg && isspace(l->buf[l->i])) {
3362 bc_lex_whitespace(l); // eats whitespace (but not newline)
3363 l->i++; // bc_lex_name() expects this
3366 bc_vec_pop_all(&l->lex_buf);
3367 bc_vec_push(&l->lex_buf, &l->buf[l->i++]);
3368 bc_vec_pushZeroByte(&l->lex_buf);
3369 l->lex = XC_LEX_NAME;
3372 RETURN_STATUS(BC_STATUS_SUCCESS);
3374 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3376 static BC_STATUS zdc_lex_string(BcLex *l)
3378 size_t depth, nls, i;
3380 l->lex = XC_LEX_STR;
3381 bc_vec_pop_all(&l->lex_buf);
3390 RETURN_STATUS(bc_error("string end could not be found"));
3393 if (i == l->i || l->buf[i - 1] != '\\') {
3394 if (c == '[') depth++;
3399 bc_vec_push(&l->lex_buf, &l->buf[i]);
3404 bc_vec_pushZeroByte(&l->lex_buf);
3405 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3406 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3407 if (i - l->i > BC_MAX_STRING)
3408 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3413 G.err_line = l->line;
3415 RETURN_STATUS(BC_STATUS_SUCCESS);
3417 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3419 #undef zdc_lex_token
3420 static BC_STATUS zdc_lex_token(BcLex *l)
3422 static const //BcLexType - should be this type, but narrower type saves size:
3425 XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
3426 XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
3427 DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
3435 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3436 if (l->lex_last == dc_lex_regs[i])
3437 RETURN_STATUS(zdc_lex_register(l));
3440 s = BC_STATUS_SUCCESS;
3442 if (c >= '%' && c <= '~'
3443 && (l->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
3448 // This is the workhorse of the lexer.
3450 // case '\0': // probably never reached
3451 // l->lex = XC_LEX_EOF;
3454 // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
3455 // (and "case '\n':" is not just empty here)
3456 // only to allow interactive dc have a way to exit
3457 // "parse" stage of "parse,execute" loop
3458 // on <enter>, not on _next_ token (which would mean
3459 // commands are not executed on pressing <enter>).
3460 // IOW: typing "1p<enter>" should print "1" _at once_,
3461 // not after some more input.
3462 l->lex = XC_LEX_NLINE;
3470 l->newline = 0; // was (c == '\n')
3471 bc_lex_whitespace(l);
3476 l->lex = XC_LEX_OP_REL_NE;
3478 l->lex = XC_LEX_OP_REL_LE;
3480 l->lex = XC_LEX_OP_REL_GE;
3482 RETURN_STATUS(bc_error_bad_character(c));
3486 bc_lex_lineComment(l);
3489 if (isdigit(l->buf[l->i]))
3490 s = zbc_lex_number(l, c);
3492 s = bc_error_bad_character(c);
3510 s = zbc_lex_number(l, c);
3513 s = zdc_lex_string(l);
3516 l->lex = XC_LEX_INVALID;
3517 s = bc_error_bad_character(c);
3523 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3526 static void bc_parse_push(BcParse *p, char i)
3528 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, p->func->code.len, i);
3529 bc_vec_pushByte(&p->func->code, i);
3532 static void bc_parse_pushName(BcParse *p, char *name)
3535 bc_parse_push(p, *name++);
3536 bc_parse_push(p, BC_PARSE_STREND);
3539 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3544 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3545 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3548 if (idx & mask) break;
3553 bc_parse_push(p, amt);
3556 bc_parse_push(p, (unsigned char)idx);
3562 static void bc_parse_pushJUMP(BcParse *p, size_t idx)
3564 bc_parse_push(p, BC_INST_JUMP);
3565 bc_parse_pushIndex(p, idx);
3568 static void bc_parse_pushJUMP_ZERO(BcParse *p, size_t idx)
3570 bc_parse_push(p, BC_INST_JUMP_ZERO);
3571 bc_parse_pushIndex(p, idx);
3574 static BC_STATUS zbc_parse_pushSTR(BcParse *p)
3576 char *str = xstrdup(p->l.lex_buf.v);
3578 bc_parse_push(p, XC_INST_STR);
3579 bc_parse_pushIndex(p, p->func->strs.len);
3580 bc_vec_push(&p->func->strs, &str);
3582 RETURN_STATUS(zbc_lex_next(&p->l));
3584 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3587 static void bc_parse_pushNUM(BcParse *p)
3589 char *num = xstrdup(p->l.lex_buf.v);
3590 #if ENABLE_BC && ENABLE_DC
3591 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3593 size_t idx = bc_vec_push(&p->func->consts, &num);
3595 size_t idx = bc_vec_push(&G.prog.consts, &num);
3597 bc_parse_push(p, XC_INST_NUM);
3598 bc_parse_pushIndex(p, idx);
3601 static BC_STATUS zbc_parse_text_init(BcParse *p, const char *text)
3603 p->func = bc_program_func(p->fidx);
3605 RETURN_STATUS(zbc_lex_text_init(&p->l, text));
3607 #define zbc_parse_text_init(...) (zbc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3609 // Called when parsing or execution detects a failure,
3610 // resets execution structures.
3611 static void bc_program_reset(void)
3616 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3617 bc_vec_pop_all(&G.prog.results);
3619 f = bc_program_func_BC_PROG_MAIN();
3620 ip = bc_vec_top(&G.prog.exestack);
3621 ip->inst_idx = f->code.len;
3624 // Called when parsing code detects a failure,
3625 // resets parsing structures.
3626 static void bc_parse_reset(BcParse *p)
3628 if (p->fidx != BC_PROG_MAIN) {
3629 bc_func_free(p->func);
3630 bc_func_init(p->func);
3632 p->fidx = BC_PROG_MAIN;
3633 p->func = bc_program_func_BC_PROG_MAIN();
3637 p->l.lex = XC_LEX_EOF;
3639 IF_BC(bc_vec_pop_all(&p->exits);)
3640 IF_BC(bc_vec_pop_all(&p->conds);)
3641 IF_BC(bc_vec_pop_all(&p->ops);)
3646 static void bc_parse_free(BcParse *p)
3648 IF_BC(bc_vec_free(&p->exits);)
3649 IF_BC(bc_vec_free(&p->conds);)
3650 IF_BC(bc_vec_free(&p->ops);)
3654 static void bc_parse_create(BcParse *p, size_t fidx)
3656 memset(p, 0, sizeof(BcParse));
3659 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3660 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3661 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3664 p->func = bc_program_func(fidx);
3667 static void bc_program_add_fn(void)
3673 bc_vec_push(&G.prog.fns, &f);
3679 // Note: takes ownership of 'name' (must be malloced)
3680 static size_t bc_program_addFunc(char *name)
3683 BcId entry, *entry_ptr;
3687 entry.idx = G.prog.fns.len;
3689 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3690 if (!inserted) free(name);
3692 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3693 idx = entry_ptr->idx;
3696 // There is already a function with this name.
3697 // It'll be redefined now, clear old definition.
3698 BcFunc *func = bc_program_func(entry_ptr->idx);
3702 bc_program_add_fn();
3708 #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
3709 // We can calculate the conversion between tokens and exprs by subtracting the
3710 // position of the first operator in the lex enum and adding the position of the
3711 // first in the expr enum. Note: This only works for binary operators.
3712 #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
3714 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags);
3716 static BC_STATUS zbc_parse_expr(BcParse *p, uint8_t flags)
3720 s = bc_parse_expr_empty_ok(p, flags);
3721 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3722 RETURN_STATUS(bc_error("empty expression"));
3725 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3727 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed);
3728 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3730 static BC_STATUS zbc_parse_stmt(BcParse *p)
3732 RETURN_STATUS(zbc_parse_stmt_possibly_auto(p, false));
3734 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3736 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(BcParse *p, const char *after_X)
3738 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3739 // Same for "else", "while()", "for()".
3740 BcStatus s = zbc_lex_next_and_skip_NLINE(&p->l);
3741 if (s) RETURN_STATUS(s);
3742 if (p->l.lex == XC_LEX_NLINE)
3743 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3745 RETURN_STATUS(zbc_parse_stmt(p));
3747 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3749 static void bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3752 char l, r = bc_parse_op_PREC(type - XC_LEX_1st_op);
3753 bool left = bc_parse_op_LEFT(type - XC_LEX_1st_op);
3755 while (p->ops.len > start) {
3756 BcLexType t = BC_PARSE_TOP_OP(p);
3757 if (t == BC_LEX_LPAREN) break;
3759 l = bc_parse_op_PREC(t - XC_LEX_1st_op);
3760 if (l >= r && (l != r || !left)) break;
3762 bc_parse_push(p, BC_TOKEN_2_INST(t));
3763 bc_vec_pop(&p->ops);
3764 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
3767 bc_vec_push(&p->ops, &type);
3770 static BC_STATUS zbc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3774 if (p->ops.len <= ops_bgn)
3775 RETURN_STATUS(bc_error_bad_expression());
3776 top = BC_PARSE_TOP_OP(p);
3778 while (top != BC_LEX_LPAREN) {
3779 bc_parse_push(p, BC_TOKEN_2_INST(top));
3781 bc_vec_pop(&p->ops);
3782 *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
3784 if (p->ops.len <= ops_bgn)
3785 RETURN_STATUS(bc_error_bad_expression());
3786 top = BC_PARSE_TOP_OP(p);
3789 bc_vec_pop(&p->ops);
3791 RETURN_STATUS(BC_STATUS_SUCCESS);
3793 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3795 static BC_STATUS zbc_parse_params(BcParse *p, uint8_t flags)
3800 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
3801 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3803 s = zbc_lex_next(&p->l);
3804 if (s) RETURN_STATUS(s);
3807 if (p->l.lex != BC_LEX_RPAREN) {
3809 s = zbc_parse_expr(p, flags);
3810 if (s) RETURN_STATUS(s);
3812 if (p->l.lex != BC_LEX_COMMA) {
3813 if (p->l.lex == BC_LEX_RPAREN)
3815 RETURN_STATUS(bc_error_bad_token());
3817 s = zbc_lex_next(&p->l);
3818 if (s) RETURN_STATUS(s);
3822 bc_parse_push(p, BC_INST_CALL);
3823 bc_parse_pushIndex(p, nparams);
3825 RETURN_STATUS(BC_STATUS_SUCCESS);
3827 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3829 // Note: takes ownership of 'name' (must be malloced)
3830 static BC_STATUS zbc_parse_call(BcParse *p, char *name, uint8_t flags)
3833 BcId entry, *entry_ptr;
3838 s = zbc_parse_params(p, flags);
3841 if (p->l.lex != BC_LEX_RPAREN) {
3842 s = bc_error_bad_token();
3846 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3848 if (idx == BC_VEC_INVALID_IDX) {
3849 // No such function exists, create an empty one
3850 bc_program_addFunc(name);
3851 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3855 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3856 bc_parse_pushIndex(p, entry_ptr->idx);
3858 RETURN_STATUS(zbc_lex_next(&p->l));
3863 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3865 static BC_STATUS zbc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3870 name = xstrdup(p->l.lex_buf.v);
3871 s = zbc_lex_next(&p->l);
3874 if (p->l.lex == BC_LEX_LBRACKET) {
3875 s = zbc_lex_next(&p->l);
3878 if (p->l.lex == BC_LEX_RBRACKET) {
3879 if (!(flags & BC_PARSE_ARRAY)) {
3880 s = bc_error_bad_expression();
3883 *type = XC_INST_ARRAY;
3885 *type = XC_INST_ARRAY_ELEM;
3886 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3887 s = zbc_parse_expr(p, flags);
3890 s = zbc_lex_next(&p->l);
3892 bc_parse_push(p, *type);
3893 bc_parse_pushName(p, name);
3895 } else if (p->l.lex == BC_LEX_LPAREN) {
3896 if (flags & BC_PARSE_NOCALL) {
3897 s = bc_error_bad_token();
3900 *type = BC_INST_CALL;
3901 s = zbc_parse_call(p, name, flags);
3903 *type = XC_INST_VAR;
3904 bc_parse_push(p, XC_INST_VAR);
3905 bc_parse_pushName(p, name);
3914 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3916 static BC_STATUS zbc_parse_read(BcParse *p)
3920 s = zbc_lex_next(&p->l);
3921 if (s) RETURN_STATUS(s);
3922 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3924 s = zbc_lex_next(&p->l);
3925 if (s) RETURN_STATUS(s);
3926 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3928 bc_parse_push(p, XC_INST_READ);
3932 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3934 static BC_STATUS zbc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3939 s = zbc_lex_next(&p->l);
3940 if (s) RETURN_STATUS(s);
3941 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3943 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3945 s = zbc_lex_next(&p->l);
3946 if (s) RETURN_STATUS(s);
3948 s = zbc_parse_expr(p, flags);
3949 if (s) RETURN_STATUS(s);
3951 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3953 *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
3954 bc_parse_push(p, *prev);
3958 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3960 static BC_STATUS zbc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3964 s = zbc_lex_next(&p->l);
3965 if (s) RETURN_STATUS(s);
3967 if (p->l.lex != BC_LEX_LPAREN) {
3968 *type = XC_INST_SCALE;
3969 bc_parse_push(p, XC_INST_SCALE);
3970 RETURN_STATUS(BC_STATUS_SUCCESS);
3973 *type = XC_INST_SCALE_FUNC;
3974 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3976 s = zbc_lex_next(&p->l);
3977 if (s) RETURN_STATUS(s);
3979 s = zbc_parse_expr(p, flags);
3980 if (s) RETURN_STATUS(s);
3981 if (p->l.lex != BC_LEX_RPAREN)
3982 RETURN_STATUS(bc_error_bad_token());
3983 bc_parse_push(p, XC_INST_SCALE_FUNC);
3985 RETURN_STATUS(zbc_lex_next(&p->l));
3987 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3989 static BC_STATUS zbc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3990 size_t *nexprs, uint8_t flags)
3995 BcInst etype = *prev;
3997 if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
3998 || etype == XC_INST_SCALE || etype == BC_INST_LAST
3999 || etype == XC_INST_IBASE || etype == XC_INST_OBASE
4001 *prev = inst = BC_INST_INC_POST + (p->l.lex != BC_LEX_OP_INC);
4002 bc_parse_push(p, inst);
4003 s = zbc_lex_next(&p->l);
4005 *prev = inst = BC_INST_INC_PRE + (p->l.lex != BC_LEX_OP_INC);
4008 s = zbc_lex_next(&p->l);
4009 if (s) RETURN_STATUS(s);
4012 // Because we parse the next part of the expression
4013 // right here, we need to increment this.
4014 *nexprs = *nexprs + 1;
4018 s = zbc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4020 case BC_LEX_KEY_IBASE:
4021 case BC_LEX_KEY_LAST:
4022 case BC_LEX_KEY_OBASE:
4023 bc_parse_push(p, type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4024 s = zbc_lex_next(&p->l);
4026 case BC_LEX_KEY_SCALE:
4027 s = zbc_lex_next(&p->l);
4028 if (s) RETURN_STATUS(s);
4029 if (p->l.lex == BC_LEX_LPAREN)
4030 s = bc_error_bad_token();
4032 bc_parse_push(p, XC_INST_SCALE);
4035 s = bc_error_bad_token();
4039 if (!s) bc_parse_push(p, inst);
4044 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4047 #define BC_PARSE_LEAF(p, rparen) \
4049 || ((p) >= XC_INST_NUM && (p) <= XC_INST_SQRT) \
4050 || (p) == BC_INST_INC_POST \
4051 || (p) == BC_INST_DEC_POST \
4054 static int ok_in_expr(BcInst p)
4056 return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
4057 || p == BC_INST_INC_POST
4058 || p == BC_INST_DEC_POST
4061 #define BC_PARSE_LEAF(p, rparen) ((rparen) || ok_in_expr(p))
4064 static BC_STATUS zbc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4065 bool rparen, size_t *nexprs)
4069 BcInst etype = *prev;
4071 s = zbc_lex_next(&p->l);
4072 if (s) RETURN_STATUS(s);
4074 type = BC_PARSE_LEAF(etype, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
4075 *prev = BC_TOKEN_2_INST(type);
4077 // We can just push onto the op stack because this is the largest
4078 // precedence operator that gets pushed. Inc/dec does not.
4079 if (type != XC_LEX_OP_MINUS)
4080 bc_vec_push(&p->ops, &type);
4082 bc_parse_operator(p, type, ops_bgn, nexprs);
4086 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4088 static BC_STATUS zbc_parse_print(BcParse *p)
4094 s = zbc_lex_next(&p->l);
4095 if (s) RETURN_STATUS(s);
4097 if (type == XC_LEX_STR) {
4098 s = zbc_parse_pushSTR(p);
4100 s = zbc_parse_expr(p, 0);
4102 if (s) RETURN_STATUS(s);
4103 bc_parse_push(p, XC_INST_PRINT_POP);
4104 if (p->l.lex != BC_LEX_COMMA)
4110 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4112 static BC_STATUS zbc_parse_return(BcParse *p)
4117 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4118 s = zbc_lex_next(&p->l);
4119 if (s) RETURN_STATUS(s);
4122 if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON)
4123 bc_parse_push(p, BC_INST_RET0);
4125 bool paren = (t == BC_LEX_LPAREN);
4126 s = bc_parse_expr_empty_ok(p, 0);
4127 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4128 bc_parse_push(p, BC_INST_RET0);
4129 s = zbc_lex_next(&p->l);
4131 if (s) RETURN_STATUS(s);
4133 if (!paren || p->l.lex_last != BC_LEX_RPAREN) {
4134 s = zbc_POSIX_requires("parentheses around return expressions");
4135 if (s) RETURN_STATUS(s);
4138 bc_parse_push(p, XC_INST_RET);
4141 dbg_lex_done("%s:%d done", __func__, __LINE__);
4144 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4146 static void rewrite_label_to_current(BcParse *p, size_t idx)
4148 size_t *label = bc_vec_item(&p->func->labels, idx);
4149 *label = p->func->code.len;
4152 static BC_STATUS zbc_parse_if(BcParse *p)
4157 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4158 s = zbc_lex_next(&p->l);
4159 if (s) RETURN_STATUS(s);
4160 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4162 s = zbc_lex_next(&p->l);
4163 if (s) RETURN_STATUS(s);
4164 s = zbc_parse_expr(p, BC_PARSE_REL);
4165 if (s) RETURN_STATUS(s);
4166 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4168 // Encode "if zero, jump to ..."
4169 // Pushed value (destination of the jump) is uninitialized,
4170 // will be rewritten to be address of "end of if()" or of "else".
4171 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4172 bc_parse_pushJUMP_ZERO(p, ip_idx);
4174 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_if);
4175 if (s) RETURN_STATUS(s);
4177 dbg_lex("%s:%d in if after stmt: p->l.lex:%d", __func__, __LINE__, p->l.lex);
4178 if (p->l.lex == BC_LEX_KEY_ELSE) {
4181 // Encode "after then_stmt, jump to end of if()"
4182 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4183 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4184 bc_parse_pushJUMP(p, ip2_idx);
4186 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4187 rewrite_label_to_current(p, ip_idx);
4191 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_else);
4192 if (s) RETURN_STATUS(s);
4195 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4196 rewrite_label_to_current(p, ip_idx);
4198 dbg_lex_done("%s:%d done", __func__, __LINE__);
4201 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4203 static BC_STATUS zbc_parse_while(BcParse *p)
4209 s = zbc_lex_next(&p->l);
4210 if (s) RETURN_STATUS(s);
4211 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4212 s = zbc_lex_next(&p->l);
4213 if (s) RETURN_STATUS(s);
4215 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4216 ip_idx = cond_idx + 1;
4217 bc_vec_push(&p->conds, &cond_idx);
4219 bc_vec_push(&p->exits, &ip_idx);
4220 bc_vec_push(&p->func->labels, &ip_idx);
4222 s = zbc_parse_expr(p, BC_PARSE_REL);
4223 if (s) RETURN_STATUS(s);
4224 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4226 bc_parse_pushJUMP_ZERO(p, ip_idx);
4228 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_while);
4229 if (s) RETURN_STATUS(s);
4231 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4232 bc_parse_pushJUMP(p, cond_idx);
4234 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4235 rewrite_label_to_current(p, ip_idx);
4237 bc_vec_pop(&p->exits);
4238 bc_vec_pop(&p->conds);
4242 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4244 static BC_STATUS zbc_parse_for(BcParse *p)
4247 size_t cond_idx, exit_idx, body_idx, update_idx;
4249 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
4250 s = zbc_lex_next(&p->l);
4251 if (s) RETURN_STATUS(s);
4252 if (p->l.lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4253 s = zbc_lex_next(&p->l);
4254 if (s) RETURN_STATUS(s);
4256 if (p->l.lex != BC_LEX_SCOLON) {
4257 s = zbc_parse_expr(p, 0);
4258 bc_parse_push(p, XC_INST_POP);
4259 if (s) RETURN_STATUS(s);
4261 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4262 if (s) RETURN_STATUS(s);
4265 if (p->l.lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4266 s = zbc_lex_next(&p->l);
4267 if (s) RETURN_STATUS(s);
4269 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4270 update_idx = cond_idx + 1;
4271 body_idx = update_idx + 1;
4272 exit_idx = body_idx + 1;
4274 if (p->l.lex != BC_LEX_SCOLON)
4275 s = zbc_parse_expr(p, BC_PARSE_REL);
4277 // Set this for the next call to bc_parse_pushNUM().
4278 // This is safe to set because the current token is a semicolon,
4279 // which has no string requirement.
4280 bc_vec_string(&p->l.lex_buf, 1, "1");
4281 bc_parse_pushNUM(p);
4282 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4284 if (s) RETURN_STATUS(s);
4286 if (p->l.lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4288 s = zbc_lex_next(&p->l);
4289 if (s) RETURN_STATUS(s);
4291 bc_parse_pushJUMP_ZERO(p, exit_idx);
4292 bc_parse_pushJUMP(p, body_idx);
4294 bc_vec_push(&p->conds, &update_idx);
4295 bc_vec_push(&p->func->labels, &p->func->code.len);
4297 if (p->l.lex != BC_LEX_RPAREN) {
4298 s = zbc_parse_expr(p, 0);
4299 if (s) RETURN_STATUS(s);
4300 if (p->l.lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4301 bc_parse_push(p, XC_INST_POP);
4303 s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4304 if (s) RETURN_STATUS(s);
4307 bc_parse_pushJUMP(p, cond_idx);
4308 bc_vec_push(&p->func->labels, &p->func->code.len);
4310 bc_vec_push(&p->exits, &exit_idx);
4311 bc_vec_push(&p->func->labels, &exit_idx);
4313 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_for);
4314 if (s) RETURN_STATUS(s);
4316 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4317 bc_parse_pushJUMP(p, update_idx);
4319 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4320 rewrite_label_to_current(p, exit_idx);
4322 bc_vec_pop(&p->exits);
4323 bc_vec_pop(&p->conds);
4325 RETURN_STATUS(BC_STATUS_SUCCESS);
4327 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4329 static BC_STATUS zbc_parse_break_or_continue(BcParse *p, BcLexType type)
4333 if (type == BC_LEX_KEY_BREAK) {
4334 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4335 RETURN_STATUS(bc_error_bad_token());
4336 i = *(size_t*)bc_vec_top(&p->exits);
4338 i = *(size_t*)bc_vec_top(&p->conds);
4340 bc_parse_pushJUMP(p, i);
4342 RETURN_STATUS(zbc_lex_next(&p->l));
4344 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4346 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
4352 autoid = (void*)f->autos.v;
4353 for (i = 0; i < f->autos.len; i++, autoid++) {
4354 if (strcmp(name, autoid->name) == 0)
4355 RETURN_STATUS(bc_error("function parameter or auto var has the same name as another"));
4361 bc_vec_push(&f->autos, &a);
4363 RETURN_STATUS(BC_STATUS_SUCCESS);
4365 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
4367 static BC_STATUS zbc_parse_funcdef(BcParse *p)
4370 bool var, comma = false;
4373 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4374 s = zbc_lex_next(&p->l);
4375 if (s) RETURN_STATUS(s);
4376 if (p->l.lex != XC_LEX_NAME)
4377 RETURN_STATUS(bc_error("bad function definition"));
4379 name = xstrdup(p->l.lex_buf.v);
4380 p->fidx = bc_program_addFunc(name);
4381 p->func = bc_program_func(p->fidx);
4383 s = zbc_lex_next(&p->l);
4384 if (s) RETURN_STATUS(s);
4385 if (p->l.lex != BC_LEX_LPAREN)
4386 RETURN_STATUS(bc_error("bad function definition"));
4387 s = zbc_lex_next(&p->l);
4388 if (s) RETURN_STATUS(s);
4390 while (p->l.lex != BC_LEX_RPAREN) {
4391 if (p->l.lex != XC_LEX_NAME)
4392 RETURN_STATUS(bc_error("bad function definition"));
4396 name = xstrdup(p->l.lex_buf.v);
4397 s = zbc_lex_next(&p->l);
4400 var = p->l.lex != BC_LEX_LBRACKET;
4403 s = zbc_lex_next(&p->l);
4406 if (p->l.lex != BC_LEX_RBRACKET) {
4407 s = bc_error("bad function definition");
4411 s = zbc_lex_next(&p->l);
4415 comma = p->l.lex == BC_LEX_COMMA;
4417 s = zbc_lex_next(&p->l);
4421 s = zbc_func_insert(p->func, name, var);
4425 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4427 s = zbc_lex_next(&p->l);
4428 if (s) RETURN_STATUS(s);
4430 if (p->l.lex != BC_LEX_LBRACE) {
4431 s = zbc_POSIX_requires("the left brace be on the same line as the function header");
4432 if (s) RETURN_STATUS(s);
4435 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4436 s = zbc_lex_skip_if_at_NLINE(&p->l);
4437 if (s) RETURN_STATUS(s);
4438 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4439 if (p->l.lex != BC_LEX_LBRACE)
4440 RETURN_STATUS(bc_error("function { body } expected"));
4442 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4443 s = zbc_parse_stmt_possibly_auto(p, true);
4445 if (s) RETURN_STATUS(s);
4447 bc_parse_push(p, BC_INST_RET0);
4449 // Subsequent code generation is into main program
4450 p->fidx = BC_PROG_MAIN;
4451 p->func = bc_program_func_BC_PROG_MAIN();
4453 dbg_lex_done("%s:%d done", __func__, __LINE__);
4456 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4460 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4462 static BC_STATUS zbc_parse_auto(BcParse *p)
4467 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4468 s = zbc_lex_next(&p->l);
4469 if (s) RETURN_STATUS(s);
4474 if (p->l.lex != XC_LEX_NAME)
4475 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4477 name = xstrdup(p->l.lex_buf.v);
4478 s = zbc_lex_next(&p->l);
4481 var = (p->l.lex != BC_LEX_LBRACKET);
4483 s = zbc_lex_next(&p->l);
4486 if (p->l.lex != BC_LEX_RBRACKET) {
4487 s = bc_error("bad 'auto' syntax");
4490 s = zbc_lex_next(&p->l);
4494 s = zbc_func_insert(p->func, name, var);
4497 if (p->l.lex == XC_LEX_NLINE
4498 || p->l.lex == BC_LEX_SCOLON
4499 //|| p->l.lex == BC_LEX_RBRACE // allow "define f() {auto a}"
4503 if (p->l.lex != BC_LEX_COMMA)
4504 RETURN_STATUS(bc_error("bad 'auto' syntax"));
4505 s = zbc_lex_next(&p->l); // skip comma
4506 if (s) RETURN_STATUS(s);
4509 dbg_lex_done("%s:%d done", __func__, __LINE__);
4510 RETURN_STATUS(BC_STATUS_SUCCESS);
4513 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4516 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4518 #undef zbc_parse_stmt_possibly_auto
4519 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed)
4521 BcStatus s = BC_STATUS_SUCCESS;
4523 dbg_lex_enter("%s:%d entered, p->l.lex:%d", __func__, __LINE__, p->l.lex);
4525 if (p->l.lex == XC_LEX_NLINE) {
4526 dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
4527 RETURN_STATUS(zbc_lex_next(&p->l));
4529 if (p->l.lex == BC_LEX_SCOLON) {
4530 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4531 RETURN_STATUS(zbc_lex_next(&p->l));
4534 if (p->l.lex == BC_LEX_LBRACE) {
4535 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4537 s = zbc_lex_next(&p->l);
4538 if (s) RETURN_STATUS(s);
4539 } while (p->l.lex == XC_LEX_NLINE);
4540 if (auto_allowed && p->l.lex == BC_LEX_KEY_AUTO) {
4541 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4542 s = zbc_parse_auto(p);
4543 if (s) RETURN_STATUS(s);
4545 while (p->l.lex != BC_LEX_RBRACE) {
4546 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4547 s = zbc_parse_stmt(p);
4548 if (s) RETURN_STATUS(s);
4550 s = zbc_lex_next(&p->l);
4551 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4555 dbg_lex("%s:%d p->l.lex:%d", __func__, __LINE__, p->l.lex);
4557 case XC_LEX_OP_MINUS:
4560 case BC_LEX_OP_BOOL_NOT:
4564 case BC_LEX_KEY_IBASE:
4565 case BC_LEX_KEY_LAST:
4566 case BC_LEX_KEY_LENGTH:
4567 case BC_LEX_KEY_OBASE:
4568 case BC_LEX_KEY_READ:
4569 case BC_LEX_KEY_SCALE:
4570 case BC_LEX_KEY_SQRT:
4571 s = zbc_parse_expr(p, BC_PARSE_PRINT);
4574 s = zbc_parse_pushSTR(p);
4575 bc_parse_push(p, XC_INST_PRINT_STR);
4577 case BC_LEX_KEY_BREAK:
4578 case BC_LEX_KEY_CONTINUE:
4579 s = zbc_parse_break_or_continue(p, p->l.lex);
4581 case BC_LEX_KEY_FOR:
4582 s = zbc_parse_for(p);
4584 case BC_LEX_KEY_HALT:
4585 bc_parse_push(p, BC_INST_HALT);
4586 s = zbc_lex_next(&p->l);
4589 s = zbc_parse_if(p);
4591 case BC_LEX_KEY_LIMITS:
4592 // "limits" is a compile-time command,
4593 // the output is produced at _parse time_.
4595 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4596 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4597 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4598 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4599 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4600 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4601 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4602 "Number of vars = "BC_MAX_VARS_STR "\n"
4604 s = zbc_lex_next(&p->l);
4606 case BC_LEX_KEY_PRINT:
4607 s = zbc_parse_print(p);
4609 case BC_LEX_KEY_QUIT:
4610 // "quit" is a compile-time command. For example,
4611 // "if (0 == 1) quit" terminates when parsing the statement,
4612 // not when it is executed
4613 QUIT_OR_RETURN_TO_MAIN;
4614 case BC_LEX_KEY_RETURN:
4616 RETURN_STATUS(bc_error("'return' not in a function"));
4617 s = zbc_parse_return(p);
4619 case BC_LEX_KEY_WHILE:
4620 s = zbc_parse_while(p);
4623 s = bc_error_bad_token();
4627 dbg_lex_done("%s:%d done", __func__, __LINE__);
4630 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4632 static BC_STATUS zbc_parse_stmt_or_funcdef(BcParse *p)
4636 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4637 if (p->l.lex == XC_LEX_EOF)
4638 s = bc_error("end of file");
4639 else if (p->l.lex == BC_LEX_KEY_DEFINE) {
4640 dbg_lex("%s:%d p->l.lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4641 s = zbc_parse_funcdef(p);
4643 dbg_lex("%s:%d p->l.lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->l.lex);
4644 s = zbc_parse_stmt(p);
4647 dbg_lex_done("%s:%d done", __func__, __LINE__);
4650 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4652 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4653 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags)
4655 BcInst prev = XC_INST_PRINT;
4656 size_t nexprs = 0, ops_bgn = p->ops.len;
4657 unsigned nparens, nrelops;
4658 bool paren_first, paren_expr, rprn, assign, bin_last;
4660 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4661 paren_first = (p->l.lex == BC_LEX_LPAREN);
4662 nparens = nrelops = 0;
4663 paren_expr = rprn = assign = false;
4669 BcLexType t = p->l.lex;
4671 if (!lex_allowed_in_bc_expr(t))
4674 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4676 s = BC_STATUS_SUCCESS;
4680 s = zbc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4681 rprn = bin_last = false;
4682 //get_token = false; - already is
4684 case XC_LEX_OP_MINUS:
4685 s = zbc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4687 //get_token = false; - already is
4688 bin_last = (prev == XC_INST_MINUS);
4690 case BC_LEX_OP_ASSIGN_POWER:
4691 case BC_LEX_OP_ASSIGN_MULTIPLY:
4692 case BC_LEX_OP_ASSIGN_DIVIDE:
4693 case BC_LEX_OP_ASSIGN_MODULUS:
4694 case BC_LEX_OP_ASSIGN_PLUS:
4695 case BC_LEX_OP_ASSIGN_MINUS:
4696 case BC_LEX_OP_ASSIGN:
4697 if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
4698 && prev != XC_INST_SCALE && prev != XC_INST_IBASE
4699 && prev != XC_INST_OBASE && prev != BC_INST_LAST
4701 return bc_error("bad assignment:"
4702 " left side must be variable"
4704 ); // note: shared string
4707 case XC_LEX_OP_POWER:
4708 case XC_LEX_OP_MULTIPLY:
4709 case XC_LEX_OP_DIVIDE:
4710 case XC_LEX_OP_MODULUS:
4711 case XC_LEX_OP_PLUS:
4712 case XC_LEX_OP_REL_EQ:
4713 case XC_LEX_OP_REL_LE:
4714 case XC_LEX_OP_REL_GE:
4715 case XC_LEX_OP_REL_NE:
4716 case XC_LEX_OP_REL_LT:
4717 case XC_LEX_OP_REL_GT:
4718 case BC_LEX_OP_BOOL_NOT:
4719 case BC_LEX_OP_BOOL_OR:
4720 case BC_LEX_OP_BOOL_AND:
4721 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4722 || (t != BC_LEX_OP_BOOL_NOT && prev == XC_INST_BOOL_NOT)
4724 return bc_error_bad_expression();
4726 nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
4727 prev = BC_TOKEN_2_INST(t);
4728 bc_parse_operator(p, t, ops_bgn, &nexprs);
4729 s = zbc_lex_next(&p->l);
4731 //get_token = false; - already is
4732 bin_last = (t != BC_LEX_OP_BOOL_NOT);
4735 if (BC_PARSE_LEAF(prev, rprn))
4736 return bc_error_bad_expression();
4737 bc_vec_push(&p->ops, &t);
4741 rprn = bin_last = false;
4744 if (bin_last || prev == XC_INST_BOOL_NOT)
4745 return bc_error_bad_expression();
4750 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4751 return BC_STATUS_PARSE_EMPTY_EXP;
4753 s = zbc_parse_rightParen(p, ops_bgn, &nexprs);
4756 paren_expr = rprn = true;
4760 if (BC_PARSE_LEAF(prev, rprn))
4761 return bc_error_bad_expression();
4762 s = zbc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4764 rprn = bin_last = false;
4765 //get_token = false; - already is
4769 if (BC_PARSE_LEAF(prev, rprn))
4770 return bc_error_bad_expression();
4771 bc_parse_pushNUM(p);
4775 rprn = bin_last = false;
4778 case BC_LEX_KEY_IBASE:
4779 case BC_LEX_KEY_LAST:
4780 case BC_LEX_KEY_OBASE:
4781 if (BC_PARSE_LEAF(prev, rprn))
4782 return bc_error_bad_expression();
4783 prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
4784 bc_parse_push(p, (char) prev);
4787 rprn = bin_last = false;
4790 case BC_LEX_KEY_LENGTH:
4791 case BC_LEX_KEY_SQRT:
4792 if (BC_PARSE_LEAF(prev, rprn))
4793 return bc_error_bad_expression();
4794 s = zbc_parse_builtin(p, t, flags, &prev);
4797 rprn = bin_last = false;
4800 case BC_LEX_KEY_READ:
4801 if (BC_PARSE_LEAF(prev, rprn))
4802 return bc_error_bad_expression();
4803 s = zbc_parse_read(p);
4804 prev = XC_INST_READ;
4807 rprn = bin_last = false;
4810 case BC_LEX_KEY_SCALE:
4811 if (BC_PARSE_LEAF(prev, rprn))
4812 return bc_error_bad_expression();
4813 s = zbc_parse_scale(p, &prev, flags);
4814 prev = XC_INST_SCALE;
4815 //get_token = false; - already is
4817 rprn = bin_last = false;
4821 return bc_error_bad_token();
4824 if (s || G_interrupt) // error, or ^C: stop parsing
4825 return BC_STATUS_FAILURE;
4827 s = zbc_lex_next(&p->l);
4833 while (p->ops.len > ops_bgn) {
4834 BcLexType top = BC_PARSE_TOP_OP(p);
4835 assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
4837 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4838 return bc_error_bad_expression();
4840 bc_parse_push(p, BC_TOKEN_2_INST(top));
4842 nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
4843 bc_vec_pop(&p->ops);
4846 if (prev == XC_INST_BOOL_NOT || nexprs != 1)
4847 return bc_error_bad_expression();
4849 if (!(flags & BC_PARSE_REL) && nrelops) {
4851 s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
4853 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4855 s = zbc_POSIX_requires("exactly one comparison operator per condition");
4859 if (flags & BC_PARSE_PRINT) {
4860 if (paren_first || !assign)
4861 bc_parse_push(p, XC_INST_PRINT);
4862 bc_parse_push(p, XC_INST_POP);
4865 dbg_lex_done("%s:%d done", __func__, __LINE__);
4866 return BC_STATUS_SUCCESS;
4873 static BC_STATUS zdc_parse_register(BcParse *p)
4877 s = zbc_lex_next(&p->l);
4878 if (s) RETURN_STATUS(s);
4879 if (p->l.lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4881 bc_parse_pushName(p, p->l.lex_buf.v);
4885 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4887 static void dc_parse_string(BcParse *p)
4890 size_t len = G.prog.strs.len;
4892 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4894 str = xstrdup(p->l.lex_buf.v);
4895 bc_parse_push(p, XC_INST_STR);
4896 bc_parse_pushIndex(p, len);
4897 bc_vec_push(&G.prog.strs, &str);
4899 // Explanation needed here
4900 bc_program_add_fn();
4901 p->func = bc_program_func(p->fidx);
4903 dbg_lex_done("%s:%d done", __func__, __LINE__);
4906 static BC_STATUS zdc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
4910 bc_parse_push(p, inst);
4912 s = zdc_parse_register(p);
4913 if (s) RETURN_STATUS(s);
4917 bc_parse_push(p, DC_INST_SWAP);
4918 bc_parse_push(p, XC_INST_ASSIGN);
4919 bc_parse_push(p, XC_INST_POP);
4922 RETURN_STATUS(BC_STATUS_SUCCESS);
4924 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4926 static BC_STATUS zdc_parse_cond(BcParse *p, uint8_t inst)
4930 bc_parse_push(p, inst);
4931 bc_parse_push(p, DC_INST_EXEC_COND);
4933 s = zdc_parse_register(p);
4934 if (s) RETURN_STATUS(s);
4936 s = zbc_lex_next(&p->l);
4937 if (s) RETURN_STATUS(s);
4939 // Note that 'else' part can not be on the next line:
4940 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4941 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4942 if (p->l.lex == DC_LEX_ELSE) {
4943 s = zdc_parse_register(p);
4944 if (s) RETURN_STATUS(s);
4945 s = zbc_lex_next(&p->l);
4947 bc_parse_push(p, BC_PARSE_STREND);
4952 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4954 static BC_STATUS zdc_parse_token(BcParse *p, BcLexType t)
4958 bool assign, get_token;
4960 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4961 s = BC_STATUS_SUCCESS;
4964 case XC_LEX_OP_REL_EQ:
4965 case XC_LEX_OP_REL_LE:
4966 case XC_LEX_OP_REL_GE:
4967 case XC_LEX_OP_REL_NE:
4968 case XC_LEX_OP_REL_LT:
4969 case XC_LEX_OP_REL_GT:
4970 dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
4971 s = zdc_parse_cond(p, t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
4976 dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
4977 s = zdc_parse_mem(p, XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
4980 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
4984 dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
4985 s = zbc_lex_next(&p->l);
4986 if (s) RETURN_STATUS(s);
4987 if (p->l.lex != XC_LEX_NUMBER)
4988 RETURN_STATUS(bc_error_bad_token());
4989 bc_parse_pushNUM(p);
4990 bc_parse_push(p, XC_INST_NEG);
4993 dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
4994 bc_parse_pushNUM(p);
4997 dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
4998 bc_parse_push(p, XC_INST_READ);
5000 case DC_LEX_OP_ASSIGN:
5001 case DC_LEX_STORE_PUSH:
5002 dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
5003 assign = (t == DC_LEX_OP_ASSIGN);
5004 inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
5005 s = zdc_parse_mem(p, inst, true, assign);
5008 case DC_LEX_LOAD_POP:
5009 dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
5010 inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
5011 s = zdc_parse_mem(p, inst, true, false);
5013 case DC_LEX_STORE_IBASE:
5014 case DC_LEX_STORE_SCALE:
5015 case DC_LEX_STORE_OBASE:
5016 dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
5017 inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
5018 s = zdc_parse_mem(p, inst, false, true);
5021 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
5022 RETURN_STATUS(bc_error_bad_token());
5025 if (!s && get_token) s = zbc_lex_next(&p->l);
5027 dbg_lex_done("%s:%d done", __func__, __LINE__);
5030 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
5032 static BC_STATUS zdc_parse_expr(BcParse *p)
5036 i = (int)p->l.lex - (int)XC_LEX_OP_POWER;
5038 BcInst inst = dc_LEX_to_INST[i];
5039 if (inst != DC_INST_INVALID) {
5040 bc_parse_push(p, inst);
5041 RETURN_STATUS(zbc_lex_next(&p->l));
5044 RETURN_STATUS(zdc_parse_token(p, p->l.lex));
5046 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
5048 static BC_STATUS zdc_parse_exprs_until_eof(BcParse *p)
5050 dbg_lex_enter("%s:%d entered, p->l.lex:%d", __func__, __LINE__, p->l.lex);
5051 while (p->l.lex != XC_LEX_EOF) {
5052 BcStatus s = zdc_parse_expr(p);
5053 if (s) RETURN_STATUS(s);
5056 dbg_lex_done("%s:%d done", __func__, __LINE__);
5057 RETURN_STATUS(BC_STATUS_SUCCESS);
5059 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
5067 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
5068 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
5070 static BcVec* bc_program_search(char *id, bool var)
5077 v = var ? &G.prog.vars : &G.prog.arrs;
5078 map = var ? &G.prog.var_map : &G.prog.arr_map;
5082 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5086 bc_array_init(&v2, var);
5087 bc_vec_push(v, &v2);
5090 ptr = bc_vec_item(map, i);
5091 if (new) ptr->name = xstrdup(e.name);
5092 return bc_vec_item(v, ptr->idx);
5095 // 'num' need not be initialized on entry
5096 static BC_STATUS zbc_program_num(BcResult *r, BcNum **num, bool hex)
5100 case XC_RESULT_TEMP:
5101 case XC_RESULT_IBASE:
5102 case XC_RESULT_SCALE:
5103 case XC_RESULT_OBASE:
5106 case XC_RESULT_CONSTANT: {
5112 str = *bc_program_const(r->d.id.idx);
5115 bc_num_init(&r->d.n, len);
5117 hex = hex && len == 1;
5118 base_t = hex ? 16 : G.prog.ib_t;
5119 s = zbc_num_parse(&r->d.n, str, base_t);
5121 bc_num_free(&r->d.n);
5125 r->t = XC_RESULT_TEMP;
5129 case XC_RESULT_ARRAY:
5130 case XC_RESULT_ARRAY_ELEM: {
5133 v = bc_program_search(r->d.id.name, r->t == XC_RESULT_VAR);
5135 if (r->t == XC_RESULT_ARRAY_ELEM) {
5137 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5138 *num = bc_vec_item(v, r->d.id.idx);
5140 *num = bc_vec_top(v);
5144 case BC_RESULT_LAST:
5145 *num = &G.prog.last;
5153 // Testing the theory that dc does not reach LAST/ONE
5154 bb_error_msg_and_die("BUG:%d", r->t);
5158 RETURN_STATUS(BC_STATUS_SUCCESS);
5160 #define zbc_program_num(...) (zbc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5162 static BC_STATUS zbc_program_binOpPrep(BcResult **l, BcNum **ln,
5163 BcResult **r, BcNum **rn, bool assign)
5167 BcResultType lt, rt;
5169 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5170 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5172 *r = bc_vec_item_rev(&G.prog.results, 0);
5173 *l = bc_vec_item_rev(&G.prog.results, 1);
5177 hex = assign && (lt == XC_RESULT_IBASE || lt == XC_RESULT_OBASE);
5179 s = zbc_program_num(*l, ln, false);
5180 if (s) RETURN_STATUS(s);
5181 s = zbc_program_num(*r, rn, hex);
5182 if (s) RETURN_STATUS(s);
5184 // We run this again under these conditions in case any vector has been
5185 // reallocated out from under the BcNums or arrays we had.
5186 if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
5187 s = zbc_program_num(*l, ln, false);
5188 if (s) RETURN_STATUS(s);
5191 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
5192 RETURN_STATUS(bc_error_variable_is_wrong_type());
5193 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5194 RETURN_STATUS(bc_error_variable_is_wrong_type());
5198 #define zbc_program_binOpPrep(...) (zbc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5200 static void bc_program_binOpRetire(BcResult *r)
5202 r->t = XC_RESULT_TEMP;
5203 bc_vec_pop(&G.prog.results);
5204 bc_result_pop_and_push(r);
5207 // Note: *r and *n need not be initialized by caller
5208 static BC_STATUS zbc_program_prep(BcResult **r, BcNum **n)
5212 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5213 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5214 *r = bc_vec_top(&G.prog.results);
5216 s = zbc_program_num(*r, n, false);
5217 if (s) RETURN_STATUS(s);
5219 if (!BC_PROG_NUM((*r), (*n)))
5220 RETURN_STATUS(bc_error_variable_is_wrong_type());
5224 #define zbc_program_prep(...) (zbc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5226 static void bc_program_retire(BcResult *r, BcResultType t)
5229 bc_result_pop_and_push(r);
5232 static BC_STATUS zbc_program_op(char inst)
5235 BcResult *opd1, *opd2, res;
5238 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5239 if (s) RETURN_STATUS(s);
5240 bc_num_init_DEF_SIZE(&res.d.n);
5242 s = BC_STATUS_SUCCESS;
5243 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5245 bc_program_binOpRetire(&res);
5249 bc_num_free(&res.d.n);
5252 #define zbc_program_op(...) (zbc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5254 static BC_STATUS zbc_program_read(void)
5256 const char *sv_file;
5263 f = bc_program_func(BC_PROG_READ);
5264 bc_vec_pop_all(&f->code);
5266 sv_file = G.prog.file;
5269 bc_char_vec_init(&buf);
5270 bc_read_line(&buf, stdin);
5272 bc_parse_create(&parse, BC_PROG_READ);
5273 bc_lex_file(&parse.l);
5275 s = zbc_parse_text_init(&parse, buf.v);
5276 if (s) goto exec_err;
5278 IF_BC(s = zbc_parse_expr(&parse, 0));
5280 IF_DC(s = zdc_parse_exprs_until_eof(&parse));
5282 if (s) goto exec_err;
5284 if (parse.l.lex != XC_LEX_NLINE && parse.l.lex != XC_LEX_EOF) {
5285 s = bc_error("bad read() expression");
5289 ip.func = BC_PROG_READ;
5291 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5293 bc_parse_push(&parse, XC_INST_RET);
5294 bc_vec_push(&G.prog.exestack, &ip);
5296 bc_parse_free(&parse);
5297 G.prog.file = sv_file;
5301 #define zbc_program_read(...) (zbc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5303 static size_t bc_program_index(char *code, size_t *bgn)
5305 unsigned char *bytes = (void*)(code + *bgn);
5315 for (i = 0; i < amt; i += 8)
5316 res |= (size_t)(*bytes++) << i;
5321 static char *bc_program_name(char *code, size_t *bgn)
5327 s = xmalloc(strchr(code, BC_PARSE_STREND) - code + 1);
5331 if (c == BC_PARSE_STREND)
5341 static void bc_program_printString(const char *str)
5345 // Example: echo '[]ap' | dc
5346 // should print two bytes: 0x00, 0x0A
5353 if (c != '\\' || !*str)
5373 G.prog.nchars = SIZE_MAX;
5385 // Just print the backslash and following character.
5396 static void bc_num_printNewline(void)
5398 if (G.prog.nchars == G.prog.len - 1) {
5406 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5409 bb_putchar((char) num);
5410 G.prog.nchars += width;
5414 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5418 bc_num_printNewline();
5419 bb_putchar(radix ? '.' : ' ');
5422 bc_num_printNewline();
5423 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5426 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5428 bc_num_printNewline();
5431 bb_putchar(((char) dig) + '0');
5435 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5438 bc_num_printNewline();
5443 bc_num_printNewline();
5444 bb_putchar(bb_hexdigits_upcase[num]);
5445 G.prog.nchars += width;
5448 static void bc_num_printDecimal(BcNum *n)
5450 size_t i, rdx = n->rdx - 1;
5457 for (i = n->len - 1; i < n->len; --i)
5458 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5461 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
5463 static BC_STATUS zbc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5468 BcDig base_digs[ULONG_NUM_BUFSIZE];
5469 BcNum intp, fracp, digit, frac_len;
5470 unsigned long dig, *ptr;
5475 print(0, width, false);
5476 RETURN_STATUS(BC_STATUS_SUCCESS);
5479 bc_vec_init(&stack, sizeof(long), NULL);
5480 bc_num_init(&intp, n->len);
5481 bc_num_init(&fracp, n->rdx);
5482 bc_num_init(&digit, width);
5483 bc_num_init(&frac_len, BC_NUM_INT(n));
5484 bc_num_copy(&intp, n);
5485 bc_num_one(&frac_len);
5486 base.cap = ARRAY_SIZE(base_digs);
5487 base.num = base_digs;
5488 bc_num_ulong2num(&base, base_t);
5490 bc_num_truncate(&intp, intp.rdx);
5491 s = zbc_num_sub(n, &intp, &fracp, 0);
5494 while (intp.len != 0) {
5495 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5497 s = zbc_num_ulong(&digit, &dig);
5499 bc_vec_push(&stack, &dig);
5502 for (i = 0; i < stack.len; ++i) {
5503 ptr = bc_vec_item_rev(&stack, i);
5504 print(*ptr, width, false);
5507 if (!n->rdx) goto err;
5509 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5510 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5512 s = zbc_num_ulong(&fracp, &dig);
5514 bc_num_ulong2num(&intp, dig);
5515 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5517 print(dig, width, radix);
5518 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5522 bc_num_free(&frac_len);
5523 bc_num_free(&digit);
5524 bc_num_free(&fracp);
5526 bc_vec_free(&stack);
5529 #define zbc_num_printNum(...) (zbc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5531 static BC_STATUS zbc_num_printBase(BcNum *n)
5545 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5547 print = bc_num_printHex;
5549 unsigned i = G.prog.ob_t - 1;
5557 print = bc_num_printDigits;
5560 s = zbc_num_printNum(n, G.prog.ob_t, width, print);
5565 #define zbc_num_printBase(...) (zbc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5567 static BC_STATUS zbc_num_print(BcNum *n, bool newline)
5569 BcStatus s = BC_STATUS_SUCCESS;
5571 bc_num_printNewline();
5576 } else if (G.prog.ob_t == 10)
5577 bc_num_printDecimal(n);
5579 s = zbc_num_printBase(n);
5588 #define zbc_num_print(...) (zbc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5590 static BC_STATUS zbc_program_print(char inst, size_t idx)
5595 bool pop = (inst != XC_INST_PRINT);
5597 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5598 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5600 r = bc_vec_item_rev(&G.prog.results, idx);
5601 s = zbc_program_num(r, &num, false);
5602 if (s) RETURN_STATUS(s);
5604 if (BC_PROG_NUM(r, num)) {
5605 s = zbc_num_print(num, !pop);
5607 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5612 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
5613 str = *bc_program_str(idx);
5615 if (inst == XC_INST_PRINT_STR) {
5618 if (c == '\0') break;
5621 if (c == '\n') G.prog.nchars = 0;
5624 bc_program_printString(str);
5625 if (inst == XC_INST_PRINT) bb_putchar('\n');
5629 if (!s && pop) bc_vec_pop(&G.prog.results);
5633 #define zbc_program_print(...) (zbc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5635 static BC_STATUS zbc_program_negate(void)
5641 s = zbc_program_prep(&ptr, &num);
5642 if (s) RETURN_STATUS(s);
5644 bc_num_init(&res.d.n, num->len);
5645 bc_num_copy(&res.d.n, num);
5646 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5648 bc_program_retire(&res, XC_RESULT_TEMP);
5652 #define zbc_program_negate(...) (zbc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5654 static BC_STATUS zbc_program_logical(char inst)
5657 BcResult *opd1, *opd2, res;
5661 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5662 if (s) RETURN_STATUS(s);
5664 bc_num_init_DEF_SIZE(&res.d.n);
5666 if (inst == XC_INST_BOOL_AND)
5667 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5668 else if (inst == XC_INST_BOOL_OR)
5669 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5671 cond = bc_num_cmp(n1, n2);
5673 case XC_INST_REL_EQ:
5676 case XC_INST_REL_LE:
5679 case XC_INST_REL_GE:
5682 case XC_INST_REL_LT:
5685 case XC_INST_REL_GT:
5688 default: // = case XC_INST_REL_NE:
5689 //cond = (cond != 0); - not needed
5694 if (cond) bc_num_one(&res.d.n);
5695 //else bc_num_zero(&res.d.n); - already is
5697 bc_program_binOpRetire(&res);
5701 #define zbc_program_logical(...) (zbc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5704 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5709 memset(&n2, 0, sizeof(BcNum));
5710 n2.rdx = res.d.id.idx = r->d.id.idx;
5711 res.t = XC_RESULT_STR;
5714 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5715 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5717 bc_vec_pop(&G.prog.results);
5720 bc_result_pop_and_push(&res);
5721 bc_vec_push(v, &n2);
5723 RETURN_STATUS(BC_STATUS_SUCCESS);
5725 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5728 static BC_STATUS zbc_program_copyToVar(char *name, bool var)
5735 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5736 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5738 ptr = bc_vec_top(&G.prog.results);
5739 if ((ptr->t == XC_RESULT_ARRAY) != !var)
5740 RETURN_STATUS(bc_error_variable_is_wrong_type());
5741 v = bc_program_search(name, var);
5744 if (ptr->t == XC_RESULT_STR && !var)
5745 RETURN_STATUS(bc_error_variable_is_wrong_type());
5746 if (ptr->t == XC_RESULT_STR)
5747 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5750 s = zbc_program_num(ptr, &n, false);
5751 if (s) RETURN_STATUS(s);
5753 // Do this once more to make sure that pointers were not invalidated.
5754 v = bc_program_search(name, var);
5757 bc_num_init_DEF_SIZE(&r.d.n);
5758 bc_num_copy(&r.d.n, n);
5760 bc_array_init(&r.d.v, true);
5761 bc_array_copy(&r.d.v, (BcVec *) n);
5764 bc_vec_push(v, &r.d);
5765 bc_vec_pop(&G.prog.results);
5769 #define zbc_program_copyToVar(...) (zbc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5771 static BC_STATUS zbc_program_assign(char inst)
5774 BcResult *left, *right, res;
5776 bool assign = (inst == XC_INST_ASSIGN);
5779 s = zbc_program_binOpPrep(&left, &l, &right, &r, assign);
5780 if (s) RETURN_STATUS(s);
5782 ib = left->t == XC_RESULT_IBASE;
5783 sc = left->t == XC_RESULT_SCALE;
5786 if (right->t == XC_RESULT_STR) {
5789 if (left->t != XC_RESULT_VAR)
5790 RETURN_STATUS(bc_error_variable_is_wrong_type());
5791 v = bc_program_search(left->d.id.name, true);
5793 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5797 if (left->t == XC_RESULT_CONSTANT || left->t == XC_RESULT_TEMP)
5798 RETURN_STATUS(bc_error("bad assignment:"
5799 " left side must be variable"
5801 )); // note: shared string
5804 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5805 RETURN_STATUS(bc_error("divide by zero"));
5810 s = BC_STATUS_SUCCESS;
5811 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5813 if (s) RETURN_STATUS(s);
5818 if (ib || sc || left->t == XC_RESULT_OBASE) {
5819 static const char *const msg[] = {
5820 "bad ibase; must be [2,16]", //XC_RESULT_IBASE
5821 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
5822 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
5828 s = zbc_num_ulong(l, &val);
5829 if (s) RETURN_STATUS(s);
5830 s = left->t - XC_RESULT_IBASE;
5833 ptr = &G.prog.scale;
5836 RETURN_STATUS(bc_error(msg[s]));
5837 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5838 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5842 RETURN_STATUS(bc_error(msg[s]));
5844 *ptr = (size_t) val;
5845 s = BC_STATUS_SUCCESS;
5848 bc_num_init(&res.d.n, l->len);
5849 bc_num_copy(&res.d.n, l);
5850 bc_program_binOpRetire(&res);
5854 #define zbc_program_assign(...) (zbc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5857 #define bc_program_pushVar(code, bgn, pop, copy) \
5858 bc_program_pushVar(code, bgn)
5859 // for bc, 'pop' and 'copy' are always false
5861 static BC_STATUS bc_program_pushVar(char *code, size_t *bgn,
5862 bool pop, bool copy)
5865 char *name = bc_program_name(code, bgn);
5867 r.t = XC_RESULT_VAR;
5872 BcVec *v = bc_program_search(name, true);
5873 BcNum *num = bc_vec_top(v);
5876 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5877 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5880 if (!BC_PROG_STR(num)) {
5881 r.t = XC_RESULT_TEMP;
5882 bc_num_init_DEF_SIZE(&r.d.n);
5883 bc_num_copy(&r.d.n, num);
5885 r.t = XC_RESULT_STR;
5886 r.d.id.idx = num->rdx;
5889 if (!copy) bc_vec_pop(v);
5893 bc_vec_push(&G.prog.results, &r);
5895 RETURN_STATUS(BC_STATUS_SUCCESS);
5897 #define zbc_program_pushVar(...) (bc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5899 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5901 BcStatus s = BC_STATUS_SUCCESS;
5905 r.d.id.name = bc_program_name(code, bgn);
5907 if (inst == XC_INST_ARRAY) {
5908 r.t = XC_RESULT_ARRAY;
5909 bc_vec_push(&G.prog.results, &r);
5914 s = zbc_program_prep(&operand, &num);
5916 s = zbc_num_ulong(num, &temp);
5919 if (temp > BC_MAX_DIM) {
5920 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5924 r.d.id.idx = (size_t) temp;
5925 bc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
5928 if (s) free(r.d.id.name);
5931 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5934 static BC_STATUS zbc_program_incdec(char inst)
5937 BcResult *ptr, res, copy;
5941 s = zbc_program_prep(&ptr, &num);
5942 if (s) RETURN_STATUS(s);
5944 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5945 copy.t = XC_RESULT_TEMP;
5946 bc_num_init(©.d.n, num->len);
5947 bc_num_copy(©.d.n, num);
5950 res.t = BC_RESULT_ONE;
5951 inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
5952 ? BC_INST_ASSIGN_PLUS
5953 : BC_INST_ASSIGN_MINUS;
5955 bc_vec_push(&G.prog.results, &res);
5956 s = zbc_program_assign(inst);
5957 if (s) RETURN_STATUS(s);
5959 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5960 bc_result_pop_and_push(©);
5965 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5967 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5975 nparams = bc_program_index(code, idx);
5977 ip.func = bc_program_index(code, idx);
5978 func = bc_program_func(ip.func);
5980 if (func->code.len == 0) {
5981 RETURN_STATUS(bc_error("undefined function"));
5983 if (nparams != func->nparams) {
5984 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5986 ip.results_len_before_call = G.prog.results.len - nparams;
5988 for (i = 0; i < nparams; ++i) {
5991 a = bc_vec_item(&func->autos, nparams - 1 - i);
5992 arg = bc_vec_top(&G.prog.results);
5994 if ((!a->idx) != (arg->t == XC_RESULT_ARRAY) || arg->t == XC_RESULT_STR)
5995 RETURN_STATUS(bc_error_variable_is_wrong_type());
5997 s = zbc_program_copyToVar(a->name, a->idx);
5998 if (s) RETURN_STATUS(s);
6001 a = bc_vec_item(&func->autos, i);
6002 for (; i < func->autos.len; i++, a++) {
6005 v = bc_program_search(a->name, a->idx);
6008 bc_num_init_DEF_SIZE(&n2);
6009 bc_vec_push(v, &n2);
6012 bc_array_init(&v2, true);
6013 bc_vec_push(v, &v2);
6017 bc_vec_push(&G.prog.exestack, &ip);
6019 RETURN_STATUS(BC_STATUS_SUCCESS);
6021 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
6023 static BC_STATUS zbc_program_return(char inst)
6029 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6031 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == XC_INST_RET)))
6032 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6034 f = bc_program_func(ip->func);
6035 res.t = XC_RESULT_TEMP;
6037 if (inst == XC_INST_RET) {
6040 BcResult *operand = bc_vec_top(&G.prog.results);
6042 s = zbc_program_num(operand, &num, false);
6043 if (s) RETURN_STATUS(s);
6044 bc_num_init(&res.d.n, num->len);
6045 bc_num_copy(&res.d.n, num);
6047 bc_num_init_DEF_SIZE(&res.d.n);
6048 //bc_num_zero(&res.d.n); - already is
6051 // We need to pop arguments as well, so this takes that into account.
6052 a = (void*)f->autos.v;
6053 for (i = 0; i < f->autos.len; i++, a++) {
6055 v = bc_program_search(a->name, a->idx);
6059 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
6060 bc_vec_push(&G.prog.results, &res);
6061 bc_vec_pop(&G.prog.exestack);
6063 RETURN_STATUS(BC_STATUS_SUCCESS);
6065 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
6068 static unsigned long bc_program_scale(BcNum *n)
6070 return (unsigned long) n->rdx;
6073 static unsigned long bc_program_len(BcNum *n)
6075 size_t len = n->len;
6077 if (n->rdx != len) return len;
6079 if (len == 0) break;
6081 if (n->num[len] != 0) break;
6086 static BC_STATUS zbc_program_builtin(char inst)
6092 bool len = (inst == XC_INST_LENGTH);
6094 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6095 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6096 opnd = bc_vec_top(&G.prog.results);
6098 s = zbc_program_num(opnd, &num, false);
6099 if (s) RETURN_STATUS(s);
6102 if (!BC_PROG_NUM(opnd, num) && !len)
6103 RETURN_STATUS(bc_error_variable_is_wrong_type());
6106 bc_num_init_DEF_SIZE(&res.d.n);
6108 if (inst == XC_INST_SQRT)
6109 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6111 else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
6112 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6116 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6118 size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6120 str = bc_program_str(idx);
6121 bc_num_ulong2num(&res.d.n, strlen(*str));
6125 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6128 bc_program_retire(&res, XC_RESULT_TEMP);
6132 #define zbc_program_builtin(...) (zbc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6135 static BC_STATUS zdc_program_divmod(void)
6138 BcResult *opd1, *opd2, res, res2;
6141 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6142 if (s) RETURN_STATUS(s);
6144 bc_num_init_DEF_SIZE(&res.d.n);
6145 bc_num_init(&res2.d.n, n2->len);
6147 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6150 bc_program_binOpRetire(&res2);
6151 res.t = XC_RESULT_TEMP;
6152 bc_vec_push(&G.prog.results, &res);
6156 bc_num_free(&res2.d.n);
6157 bc_num_free(&res.d.n);
6160 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6162 static BC_STATUS zdc_program_modexp(void)
6165 BcResult *r1, *r2, *r3, res;
6166 BcNum *n1, *n2, *n3;
6168 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6169 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6170 s = zbc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6171 if (s) RETURN_STATUS(s);
6173 r1 = bc_vec_item_rev(&G.prog.results, 2);
6174 s = zbc_program_num(r1, &n1, false);
6175 if (s) RETURN_STATUS(s);
6176 if (!BC_PROG_NUM(r1, n1))
6177 RETURN_STATUS(bc_error_variable_is_wrong_type());
6179 // Make sure that the values have their pointers updated, if necessary.
6180 if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
6181 if (r1->t == r2->t) {
6182 s = zbc_program_num(r2, &n2, false);
6183 if (s) RETURN_STATUS(s);
6185 if (r1->t == r3->t) {
6186 s = zbc_program_num(r3, &n3, false);
6187 if (s) RETURN_STATUS(s);
6191 bc_num_init(&res.d.n, n3->len);
6192 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6195 bc_vec_pop(&G.prog.results);
6196 bc_program_binOpRetire(&res);
6200 bc_num_free(&res.d.n);
6203 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6205 static void dc_program_stackLen(void)
6208 size_t len = G.prog.results.len;
6210 res.t = XC_RESULT_TEMP;
6212 bc_num_init_DEF_SIZE(&res.d.n);
6213 bc_num_ulong2num(&res.d.n, len);
6214 bc_vec_push(&G.prog.results, &res);
6217 static BC_STATUS zdc_program_asciify(void)
6227 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6228 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6229 r = bc_vec_top(&G.prog.results);
6231 s = zbc_program_num(r, &num, false);
6232 if (s) RETURN_STATUS(s);
6234 if (BC_PROG_NUM(r, num)) {
6237 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6239 bc_num_init_DEF_SIZE(&n);
6240 bc_num_copy(&n, num);
6241 bc_num_truncate(&n, n.rdx);
6243 strmb.cap = ARRAY_SIZE(strmb_digs);
6244 strmb.num = strmb_digs;
6245 bc_num_ulong2num(&strmb, 0x100);
6246 s = zbc_num_mod(&n, &strmb, &n, 0);
6248 if (s) goto num_err;
6249 s = zbc_num_ulong(&n, &val);
6250 if (s) goto num_err;
6257 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
6258 sp = *bc_program_str(idx);
6262 strs = (void*)G.prog.strs.v;
6263 for (idx = 0; idx < G.prog.strs.len; idx++) {
6264 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6270 //str[1] = '\0'; - already is
6271 bc_vec_push(&G.prog.strs, &str);
6273 res.t = XC_RESULT_STR;
6275 bc_result_pop_and_push(&res);
6277 RETURN_STATUS(BC_STATUS_SUCCESS);
6282 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6284 static BC_STATUS zdc_program_printStream(void)
6291 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6292 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6293 r = bc_vec_top(&G.prog.results);
6295 s = zbc_program_num(r, &n, false);
6296 if (s) RETURN_STATUS(s);
6298 if (BC_PROG_NUM(r, n)) {
6299 s = zbc_num_printNum(n, 0x100, 1, dc_num_printChar);
6302 idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
6303 str = *bc_program_str(idx);
6309 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6311 static BC_STATUS zdc_program_nquit(void)
6318 s = zbc_program_prep(&opnd, &num);
6319 if (s) RETURN_STATUS(s);
6320 s = zbc_num_ulong(num, &val);
6321 if (s) RETURN_STATUS(s);
6323 bc_vec_pop(&G.prog.results);
6325 if (G.prog.exestack.len < val)
6326 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6327 if (G.prog.exestack.len == val) {
6328 QUIT_OR_RETURN_TO_MAIN;
6331 bc_vec_npop(&G.prog.exestack, val);
6335 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6337 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6339 BcStatus s = BC_STATUS_SUCCESS;
6345 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6346 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6348 r = bc_vec_top(&G.prog.results);
6351 BcNum *n = n; // for compiler
6354 char *then_name = bc_program_name(code, bgn);
6355 char *else_name = NULL;
6357 if (code[*bgn] == BC_PARSE_STREND)
6360 else_name = bc_program_name(code, bgn);
6362 exec = r->d.n.len != 0;
6364 if (!exec && else_name != NULL) {
6371 v = bc_program_search(name, true);
6378 if (!exec) goto exit;
6379 if (!BC_PROG_STR(n)) {
6380 s = bc_error_variable_is_wrong_type();
6386 if (r->t == XC_RESULT_STR) {
6388 } else if (r->t == XC_RESULT_VAR) {
6390 s = zbc_program_num(r, &n, false);
6391 if (s || !BC_PROG_STR(n)) goto exit;
6397 fidx = sidx + BC_PROG_REQ_FUNCS;
6399 f = bc_program_func(fidx);
6401 if (f->code.len == 0) {
6406 bc_parse_create(&prs, fidx);
6407 str = *bc_program_str(sidx);
6408 s = zbc_parse_text_init(&prs, str);
6411 sv_input_fp = G.input_fp;
6412 G.input_fp = NULL; // "do not read from input file when <EOL> reached"
6413 s = zdc_parse_exprs_until_eof(&prs);
6414 G.input_fp = sv_input_fp;
6417 if (prs.l.lex != XC_LEX_EOF) {
6418 s = bc_error_bad_expression();
6420 bc_parse_free(&prs);
6421 bc_vec_pop_all(&f->code);
6424 bc_parse_push(&prs, DC_INST_POP_EXEC);
6425 bc_parse_free(&prs);
6431 bc_vec_pop(&G.prog.results);
6432 bc_vec_push(&G.prog.exestack, &ip);
6434 RETURN_STATUS(BC_STATUS_SUCCESS);
6436 bc_vec_pop(&G.prog.results);
6439 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6442 static void bc_program_pushGlobal(char inst)
6447 res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
6448 if (inst == XC_INST_IBASE)
6449 val = (unsigned long) G.prog.ib_t;
6450 else if (inst == XC_INST_SCALE)
6451 val = (unsigned long) G.prog.scale;
6453 val = (unsigned long) G.prog.ob_t;
6455 bc_num_init_DEF_SIZE(&res.d.n);
6456 bc_num_ulong2num(&res.d.n, val);
6457 bc_vec_push(&G.prog.results, &res);
6460 static BC_STATUS zbc_program_exec(void)
6463 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6464 BcFunc *func = bc_program_func(ip->func);
6465 char *code = func->code.v;
6467 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6468 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6469 while (ip->inst_idx < func->code.len) {
6470 BcStatus s = BC_STATUS_SUCCESS;
6471 char inst = code[ip->inst_idx++];
6473 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6476 case BC_INST_JUMP_ZERO: {
6479 dbg_exec("BC_INST_JUMP_ZERO:");
6480 s = zbc_program_prep(&ptr, &num);
6481 if (s) RETURN_STATUS(s);
6482 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6483 bc_vec_pop(&G.prog.results);
6485 bc_program_index(code, &ip->inst_idx);
6488 // else: fall through
6490 case BC_INST_JUMP: {
6491 size_t idx = bc_program_index(code, &ip->inst_idx);
6492 size_t *addr = bc_vec_item(&func->labels, idx);
6493 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6494 ip->inst_idx = *addr;
6498 dbg_exec("BC_INST_CALL:");
6499 s = zbc_program_call(code, &ip->inst_idx);
6500 goto read_updated_ip;
6501 case BC_INST_INC_PRE:
6502 case BC_INST_DEC_PRE:
6503 case BC_INST_INC_POST:
6504 case BC_INST_DEC_POST:
6505 dbg_exec("BC_INST_INCDEC:");
6506 s = zbc_program_incdec(inst);
6509 dbg_exec("BC_INST_HALT:");
6510 QUIT_OR_RETURN_TO_MAIN;
6514 dbg_exec("BC_INST_RET[0]:");
6515 s = zbc_program_return(inst);
6516 goto read_updated_ip;
6517 case XC_INST_BOOL_OR:
6518 case XC_INST_BOOL_AND:
6520 case XC_INST_REL_EQ:
6521 case XC_INST_REL_LE:
6522 case XC_INST_REL_GE:
6523 case XC_INST_REL_NE:
6524 case XC_INST_REL_LT:
6525 case XC_INST_REL_GT:
6526 dbg_exec("BC_INST_BOOL:");
6527 s = zbc_program_logical(inst);
6530 dbg_exec("XC_INST_READ:");
6531 s = zbc_program_read();
6532 goto read_updated_ip;
6534 dbg_exec("XC_INST_VAR:");
6535 s = zbc_program_pushVar(code, &ip->inst_idx, false, false);
6537 case XC_INST_ARRAY_ELEM:
6539 dbg_exec("XC_INST_ARRAY[_ELEM]:");
6540 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6544 dbg_exec("BC_INST_LAST:");
6545 r.t = BC_RESULT_LAST;
6546 bc_vec_push(&G.prog.results, &r);
6552 dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
6553 bc_program_pushGlobal(inst);
6555 case XC_INST_SCALE_FUNC:
6556 case XC_INST_LENGTH:
6558 dbg_exec("BC_INST_builtin:");
6559 s = zbc_program_builtin(inst);
6562 dbg_exec("XC_INST_NUM:");
6563 r.t = XC_RESULT_CONSTANT;
6564 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6565 bc_vec_push(&G.prog.results, &r);
6568 dbg_exec("XC_INST_POP:");
6569 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6570 s = bc_error_stack_has_too_few_elements();
6572 bc_vec_pop(&G.prog.results);
6575 case XC_INST_PRINT_POP:
6576 case XC_INST_PRINT_STR:
6577 dbg_exec("XC_INST_PRINTxyz:");
6578 s = zbc_program_print(inst, 0);
6581 dbg_exec("XC_INST_STR:");
6582 r.t = XC_RESULT_STR;
6583 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6584 bc_vec_push(&G.prog.results, &r);
6587 case XC_INST_MULTIPLY:
6588 case XC_INST_DIVIDE:
6589 case XC_INST_MODULUS:
6592 dbg_exec("BC_INST_binaryop:");
6593 s = zbc_program_op(inst);
6595 case XC_INST_BOOL_NOT: {
6597 dbg_exec("XC_INST_BOOL_NOT:");
6598 s = zbc_program_prep(&ptr, &num);
6599 if (s) RETURN_STATUS(s);
6600 bc_num_init_DEF_SIZE(&r.d.n);
6601 if (bc_num_cmp(num, &G.prog.zero) == 0)
6603 //else bc_num_zero(&r.d.n); - already is
6604 bc_program_retire(&r, XC_RESULT_TEMP);
6608 dbg_exec("XC_INST_NEG:");
6609 s = zbc_program_negate();
6612 case BC_INST_ASSIGN_POWER:
6613 case BC_INST_ASSIGN_MULTIPLY:
6614 case BC_INST_ASSIGN_DIVIDE:
6615 case BC_INST_ASSIGN_MODULUS:
6616 case BC_INST_ASSIGN_PLUS:
6617 case BC_INST_ASSIGN_MINUS:
6619 case XC_INST_ASSIGN:
6620 dbg_exec("BC_INST_ASSIGNxyz:");
6621 s = zbc_program_assign(inst);
6624 case DC_INST_POP_EXEC:
6625 dbg_exec("DC_INST_POP_EXEC:");
6626 bc_vec_pop(&G.prog.exestack);
6627 goto read_updated_ip;
6628 case DC_INST_MODEXP:
6629 dbg_exec("DC_INST_MODEXP:");
6630 s = zdc_program_modexp();
6632 case DC_INST_DIVMOD:
6633 dbg_exec("DC_INST_DIVMOD:");
6634 s = zdc_program_divmod();
6636 case DC_INST_EXECUTE:
6637 case DC_INST_EXEC_COND:
6638 dbg_exec("DC_INST_EXEC[_COND]:");
6639 s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
6640 goto read_updated_ip;
6641 case DC_INST_PRINT_STACK: {
6643 dbg_exec("DC_INST_PRINT_STACK:");
6644 for (idx = 0; idx < G.prog.results.len; ++idx) {
6645 s = zbc_program_print(XC_INST_PRINT, idx);
6650 case DC_INST_CLEAR_STACK:
6651 dbg_exec("DC_INST_CLEAR_STACK:");
6652 bc_vec_pop_all(&G.prog.results);
6654 case DC_INST_STACK_LEN:
6655 dbg_exec("DC_INST_STACK_LEN:");
6656 dc_program_stackLen();
6658 case DC_INST_DUPLICATE:
6659 dbg_exec("DC_INST_DUPLICATE:");
6660 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6661 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6662 ptr = bc_vec_top(&G.prog.results);
6663 dc_result_copy(&r, ptr);
6664 bc_vec_push(&G.prog.results, &r);
6666 case DC_INST_SWAP: {
6668 dbg_exec("DC_INST_SWAP:");
6669 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6670 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6671 ptr = bc_vec_item_rev(&G.prog.results, 0);
6672 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6673 memcpy(&r, ptr, sizeof(BcResult));
6674 memcpy(ptr, ptr2, sizeof(BcResult));
6675 memcpy(ptr2, &r, sizeof(BcResult));
6678 case DC_INST_ASCIIFY:
6679 dbg_exec("DC_INST_ASCIIFY:");
6680 s = zdc_program_asciify();
6682 case DC_INST_PRINT_STREAM:
6683 dbg_exec("DC_INST_PRINT_STREAM:");
6684 s = zdc_program_printStream();
6687 case DC_INST_PUSH_VAR: {
6688 bool copy = inst == DC_INST_LOAD;
6689 s = zbc_program_pushVar(code, &ip->inst_idx, true, copy);
6692 case DC_INST_PUSH_TO_VAR: {
6693 char *name = bc_program_name(code, &ip->inst_idx);
6694 s = zbc_program_copyToVar(name, true);
6699 dbg_exec("DC_INST_QUIT:");
6700 if (G.prog.exestack.len <= 2)
6701 QUIT_OR_RETURN_TO_MAIN;
6702 bc_vec_npop(&G.prog.exestack, 2);
6703 goto read_updated_ip;
6705 dbg_exec("DC_INST_NQUIT:");
6706 s = zdc_program_nquit();
6707 //goto read_updated_ip; - just fall through to it
6710 // Instruction stack has changed, read new pointers
6711 ip = bc_vec_top(&G.prog.exestack);
6712 func = bc_program_func(ip->func);
6713 code = func->code.v;
6714 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6717 if (s || G_interrupt) {
6725 RETURN_STATUS(BC_STATUS_SUCCESS);
6727 #define zbc_program_exec(...) (zbc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6729 static unsigned bc_vm_envLen(const char *var)
6735 len = BC_NUM_PRINT_WIDTH;
6736 if (!lenv) return len;
6738 len = bb_strtou(lenv, NULL, 10) - 1;
6739 if (errno || len < 2 || len >= INT_MAX)
6740 len = BC_NUM_PRINT_WIDTH;
6745 static BC_STATUS zbc_vm_process(const char *text)
6749 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6750 s = zbc_parse_text_init(&G.prs, text); // does the first zbc_lex_next()
6751 if (s) RETURN_STATUS(s);
6753 while (G.prs.l.lex != XC_LEX_EOF) {
6757 dbg_lex("%s:%d G.prs.l.lex:%d, parsing...", __func__, __LINE__, G.prs.l.lex);
6759 // FIXME: "eating" of stmt delimiters is coded inconsistently
6760 // (sometimes zbc_parse_stmt() eats the delimiter, sometimes don't),
6761 // which causes bugs such as "print 1 print 2" erroneously accepted,
6762 // or "print 1 else 2" detecting parse error only after executing
6764 IF_BC(s = zbc_parse_stmt_or_funcdef(&G.prs));
6766 // Most of dc parsing assumes all whitespace,
6767 // including '\n', is eaten.
6768 while (G.prs.l.lex == XC_LEX_NLINE) {
6769 s = zbc_lex_next(&G.prs.l);
6771 if (G.prs.l.lex == XC_LEX_EOF)
6774 IF_DC(s = zdc_parse_expr(&G.prs));
6776 if (s || G_interrupt) {
6778 bc_parse_reset(&G.prs); // includes bc_program_reset()
6779 RETURN_STATUS(BC_STATUS_FAILURE);
6782 dbg_lex("%s:%d executing...", __func__, __LINE__);
6783 s = zbc_program_exec();
6789 ip = (void*)G.prog.exestack.v;
6791 if (G.prog.exestack.len != 1) // should have only main's IP
6792 bb_error_msg_and_die("BUG:call stack");
6793 if (ip->func != BC_PROG_MAIN)
6794 bb_error_msg_and_die("BUG:not MAIN");
6796 f = bc_program_func_BC_PROG_MAIN();
6797 // bc discards strings, constants and code after each
6798 // top-level statement in the "main program".
6799 // This prevents "yes 1 | bc" from growing its memory
6800 // without bound. This can be done because data stack
6801 // is empty and thus can't hold any references to
6802 // strings or constants, there is no generated code
6803 // which can hold references (after we discard one
6804 // we just executed). Code of functions can have references,
6805 // but bc stores function strings/constants in per-function
6809 if (G.prog.results.len != 0) // should be empty
6810 bb_error_msg_and_die("BUG:data stack");
6812 IF_BC(bc_vec_pop_all(&f->strs);)
6813 IF_BC(bc_vec_pop_all(&f->consts);)
6815 if (G.prog.results.len == 0
6816 && G.prog.vars.len == 0
6818 // If stack is empty and no registers exist (TODO: or they are all empty),
6819 // we can get rid of accumulated strings and constants.
6820 // In this example dc process should not grow
6821 // its memory consumption with time:
6823 IF_DC(bc_vec_pop_all(&G.prog.strs);)
6824 IF_DC(bc_vec_pop_all(&G.prog.consts);)
6826 // The code is discarded always (below), thus this example
6827 // should also not grow its memory consumption with time,
6828 // even though its data stack is not empty:
6829 // { echo 1; yes dk; } | dc
6831 // We drop generated and executed code for both bc and dc:
6832 bc_vec_pop_all(&f->code);
6836 dbg_lex_done("%s:%d done", __func__, __LINE__);
6839 #define zbc_vm_process(...) (zbc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6841 static BC_STATUS zbc_vm_execute_FILE(FILE *fp, const char *filename)
6843 // So far bc/dc have no way to include a file from another file,
6844 // therefore we know G.prog.file == NULL on entry
6845 //const char *sv_file;
6848 G.prog.file = filename;
6850 bc_lex_file(&G.prs.l);
6853 s = zbc_vm_process("");
6854 // We do not stop looping on errors here if reading stdin.
6855 // Example: start interactive bc and enter "return".
6856 // It should say "'return' not in a function"
6857 // but should not exit.
6858 } while (G.input_fp == stdin);
6862 #define zbc_vm_execute_FILE(...) (zbc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6864 static BC_STATUS zbc_vm_file(const char *file)
6869 fp = xfopen_for_read(file);
6870 s = zbc_vm_execute_FILE(fp, file);
6875 #define zbc_vm_file(...) (zbc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6878 static void bc_vm_info(void)
6880 printf("%s "BB_VER"\n"
6881 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6885 static void bc_args(char **argv)
6891 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6892 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6893 "warn\0" No_argument "w"
6894 "version\0" No_argument "v"
6895 "standard\0" No_argument "s"
6896 "quiet\0" No_argument "q"
6897 "mathlib\0" No_argument "l"
6898 "interactive\0" No_argument "i"
6901 opts = option_mask32 |= getopt32(argv, "wvsqli");
6903 if (getenv("POSIXLY_CORRECT"))
6904 option_mask32 |= BC_FLAG_S;
6906 if (opts & BC_FLAG_V) {
6911 for (i = optind; argv[i]; ++i)
6912 bc_vec_push(&G.files, argv + i);
6915 static void bc_vm_envArgs(void)
6919 char *env_args = getenv("BC_ENV_ARGS");
6921 if (!env_args) return;
6923 G.env_args = xstrdup(env_args);
6926 bc_vec_init(&v, sizeof(char *), NULL);
6928 while (*(buf = skip_whitespace(buf)) != '\0') {
6929 bc_vec_push(&v, &buf);
6930 buf = skip_non_whitespace(buf);
6936 // NULL terminate, and pass argv[] so that first arg is argv[1]
6937 if (sizeof(int) == sizeof(char*)) {
6938 bc_vec_push(&v, &const_int_0);
6940 static char *const nullptr = NULL;
6941 bc_vec_push(&v, &nullptr);
6943 bc_args(((char **)v.v) - 1);
6948 static const char bc_lib[] ALIGN1 = {
6951 "\n" "auto b,s,n,r,d,i,p,f,v"
6952 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6953 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6954 //e(-.998896): GNU:.36828580434569428695
6955 // above code:.36828580434569428696
6956 // actual value:.3682858043456942869594...
6957 // but for now let's be "GNU compatible"
6966 "\n" "scale=scale(x)+1"
6976 "\n" "for(i=2;v;++i){"
6982 "\n" "while(d--)r*=r"
6985 "\n" "if(n)return(1/r)"
6989 "\n" "auto b,s,r,p,a,q,i,v"
6993 "\n" "r=(1-10^scale)/1"
7004 "\n" "while(x<=.5){"
7008 "\n" "r=a=(x-1)/(x+1)"
7011 "\n" "for(i=3;v;i+=2){"
7022 "\n" "auto b,s,r,a,q,i"
7023 "\n" "if(x<0)return(-s(-x))"
7027 "\n" "scale=1.1*s+2"
7036 "\n" "for(i=3;a;i+=2){"
7037 "\n" "a*=q/(i*(i-1))"
7050 "\n" "x=s(2*a(1)+x)"
7056 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7064 "\n" "if(scale<65){"
7065 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7066 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7076 "\n" "x=(x-.2)/(1+.2*x)"
7081 "\n" "for(i=3;t;i+=2){"
7088 "\n" "return((m*a+r)/n)"
7090 "\n" "define j(n,x){"
7091 "\n" "auto b,s,o,a,i,v,f"
7102 "\n" "for(i=2;i<=n;++i)a*=i"
7104 "\n" "a=(x^n)/2^n/a"
7107 "\n" "scale+=length(a)-scale(a)"
7108 "\n" "for(i=1;v;++i){"
7109 "\n" "v=v*f/i/(n+i)"
7115 "\n" "return(a*r/1)"
7120 static BC_STATUS zbc_vm_exec(void)
7127 if (option_mask32 & BC_FLAG_L) {
7128 // We know that internal library is not buggy,
7129 // thus error checking is normally disabled.
7130 # define DEBUG_LIB 0
7131 bc_lex_file(&G.prs.l);
7132 s = zbc_vm_process(bc_lib);
7133 if (DEBUG_LIB && s) RETURN_STATUS(s);
7137 s = BC_STATUS_SUCCESS;
7138 fname = (void*)G.files.v;
7139 for (i = 0; i < G.files.len; i++) {
7140 s = zbc_vm_file(*fname++);
7141 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7142 // Debug config, non-interactive mode:
7143 // return all the way back to main.
7144 // Non-debug builds do not come here
7145 // in non-interactive mode, they exit.
7150 if (IS_BC || (option_mask32 & BC_FLAG_I))
7151 s = zbc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7155 #define zbc_vm_exec(...) (zbc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7157 #if ENABLE_FEATURE_CLEAN_UP
7158 static void bc_program_free(void)
7160 bc_vec_free(&G.prog.fns);
7161 IF_BC(bc_vec_free(&G.prog.fn_map);)
7162 bc_vec_free(&G.prog.vars);
7163 bc_vec_free(&G.prog.var_map);
7164 bc_vec_free(&G.prog.arrs);
7165 bc_vec_free(&G.prog.arr_map);
7166 IF_DC(bc_vec_free(&G.prog.strs);)
7167 IF_DC(bc_vec_free(&G.prog.consts);)
7168 bc_vec_free(&G.prog.results);
7169 bc_vec_free(&G.prog.exestack);
7170 IF_BC(bc_num_free(&G.prog.last);)
7171 IF_BC(bc_num_free(&G.prog.zero);)
7172 IF_BC(bc_num_free(&G.prog.one);)
7173 bc_vec_free(&G.input_buffer);
7176 static void bc_vm_free(void)
7178 bc_vec_free(&G.files);
7180 bc_parse_free(&G.prs);
7185 static void bc_program_init(void)
7189 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7190 memset(&ip, 0, sizeof(BcInstPtr));
7192 // G.prog.nchars = G.prog.scale = 0; - already is
7196 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7197 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7199 bc_num_init_DEF_SIZE(&G.prog.zero);
7200 //bc_num_zero(&G.prog.zero); - already is
7202 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7203 IF_BC(bc_num_one(&G.prog.one);)
7205 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7206 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7209 // Names are chosen simply to be distinct and never match
7210 // a valid function name (and be short)
7211 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7212 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7214 // in dc, functions have no names
7215 bc_program_add_fn();
7216 bc_program_add_fn();
7219 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7220 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7222 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7223 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7225 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7226 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7227 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7228 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7229 bc_vec_push(&G.prog.exestack, &ip);
7231 bc_char_vec_init(&G.input_buffer);
7234 static int bc_vm_init(const char *env_len)
7236 #if ENABLE_FEATURE_EDITING
7237 G.line_input_state = new_line_input_t(DO_HISTORY);
7239 G.prog.len = bc_vm_envLen(env_len);
7241 bc_vec_init(&G.files, sizeof(char *), NULL);
7242 IF_BC(if (IS_BC) bc_vm_envArgs();)
7244 bc_parse_create(&G.prs, BC_PROG_MAIN);
7246 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7247 //-i option unconditionally enables this regardless of isatty():
7249 #if ENABLE_FEATURE_BC_SIGNALS
7251 // With SA_RESTART, most system calls will restart
7252 // (IOW: they won't fail with EINTR).
7253 // In particular, this means ^C won't cause
7254 // stdout to get into "error state" if SIGINT hits
7255 // within write() syscall.
7257 // The downside is that ^C while tty input is taken
7258 // will only be handled after [Enter] since read()
7259 // from stdin is not interrupted by ^C either,
7260 // it restarts, thus fgetc() does not return on ^C.
7261 // (This problem manifests only if line editing is disabled)
7262 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7264 // Without SA_RESTART, this exhibits a bug:
7265 // "while (1) print 1" and try ^C-ing it.
7266 // Intermittently, instead of returning to input line,
7267 // you'll get "output error: Interrupted system call"
7269 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7273 return 0; // "not a tty"
7276 static BcStatus bc_vm_run(void)
7278 BcStatus st = zbc_vm_exec();
7279 #if ENABLE_FEATURE_CLEAN_UP
7280 if (G_exiting) // it was actually "halt" or "quit"
7283 # if ENABLE_FEATURE_EDITING
7284 free_line_input_t(G.line_input_state);
7288 dbg_exec("exiting with exitcode %d", st);
7293 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7294 int bc_main(int argc UNUSED_PARAM, char **argv)
7300 is_tty = bc_vm_init("BC_LINE_LENGTH");
7304 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7312 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7313 int dc_main(int argc UNUSED_PARAM, char **argv)
7319 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7320 // 1 char wider than bc from the same package.
7321 // Both default width, and xC_LINE_LENGTH=N are wider:
7322 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7325 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7328 // Do the same, or it's a bug?
7329 bc_vm_init("DC_LINE_LENGTH");
7331 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7332 noscript = BC_FLAG_I;
7334 int n = getopt(argc, argv, "e:f:x");
7340 n = zbc_vm_process(optarg);
7345 n = zbc_vm_file(optarg);
7349 option_mask32 |= DC_FLAG_X;
7359 bc_vec_push(&G.files, argv++);
7362 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7368 #endif // not DC_SMALL