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 {
276 BC_INST_ASSIGN_POWER,
277 BC_INST_ASSIGN_MULTIPLY,
278 BC_INST_ASSIGN_DIVIDE,
279 BC_INST_ASSIGN_MODULUS,
281 BC_INST_ASSIGN_MINUS,
325 BC_INST_PRINT_STREAM,
340 BC_INST_INVALID = -1,
344 typedef struct BcId {
349 typedef struct BcFunc {
355 IF_BC(size_t nparams;)
358 typedef enum BcResultType {
362 BC_RESULT_ARRAY_ELEM,
367 //code uses "inst - BC_INST_IBASE + BC_RESULT_IBASE" construct,
368 BC_RESULT_IBASE, // relative order should match for: BC_INST_IBASE
369 BC_RESULT_SCALE, // relative order should match for: BC_INST_SCALE
370 BC_RESULT_LAST, // relative order should match for: BC_INST_LAST
373 BC_RESULT_OBASE, // relative order should match for: BC_INST_OBASE
376 typedef union BcResultData {
382 typedef struct BcResult {
387 typedef struct BcInstPtr {
390 IF_BC(size_t results_len_before_call;)
393 // BC_LEX_NEG is not used in lexing; it is only for parsing.
394 typedef enum BcLexType {
421 BC_LEX_OP_ASSIGN_POWER,
422 BC_LEX_OP_ASSIGN_MULTIPLY,
423 BC_LEX_OP_ASSIGN_DIVIDE,
424 BC_LEX_OP_ASSIGN_MODULUS,
425 BC_LEX_OP_ASSIGN_PLUS,
426 BC_LEX_OP_ASSIGN_MINUS,
439 BC_LEX_LBRACE, // '{' is 0x7B, '}' is 0x7D,
441 BC_LEX_RBRACE, // should be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
447 BC_LEX_KEY_1st_keyword,
448 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
455 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
456 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
458 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
461 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
488 // code uses "t - BC_LEX_STORE_IBASE + BC_INST_IBASE" construct,
489 BC_LEX_STORE_IBASE, // relative order should match for: BC_INST_IBASE
490 BC_LEX_STORE_SCALE, // relative order should match for: BC_INST_SCALE
494 BC_LEX_STORE_OBASE, // relative order should match for: BC_INST_OBASE
500 // must match order of BC_LEX_KEY_foo etc above
502 struct BcLexKeyword {
505 #define BC_LEX_KW_ENTRY(a, b) \
506 { .name8 = a /*, .posix = b */ }
507 static const struct BcLexKeyword bc_lex_kws[20] = {
508 BC_LEX_KW_ENTRY("auto" , 1), // 0
509 BC_LEX_KW_ENTRY("break" , 1), // 1
510 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
511 BC_LEX_KW_ENTRY("define" , 1), // 3
512 BC_LEX_KW_ENTRY("else" , 0), // 4
513 BC_LEX_KW_ENTRY("for" , 1), // 5
514 BC_LEX_KW_ENTRY("halt" , 0), // 6
515 BC_LEX_KW_ENTRY("ibase" , 1), // 7
516 BC_LEX_KW_ENTRY("if" , 1), // 8
517 BC_LEX_KW_ENTRY("last" , 0), // 9
518 BC_LEX_KW_ENTRY("length" , 1), // 10
519 BC_LEX_KW_ENTRY("limits" , 0), // 11
520 BC_LEX_KW_ENTRY("obase" , 1), // 12
521 BC_LEX_KW_ENTRY("print" , 0), // 13
522 BC_LEX_KW_ENTRY("quit" , 1), // 14
523 BC_LEX_KW_ENTRY("read" , 0), // 15
524 BC_LEX_KW_ENTRY("return" , 1), // 16
525 BC_LEX_KW_ENTRY("scale" , 1), // 17
526 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
527 BC_LEX_KW_ENTRY("while" , 1), // 19
529 #undef BC_LEX_KW_ENTRY
530 #define STRING_if (bc_lex_kws[8].name8)
531 #define STRING_else (bc_lex_kws[4].name8)
532 #define STRING_while (bc_lex_kws[19].name8)
533 #define STRING_for (bc_lex_kws[5].name8)
557 #define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
559 // This is a bit array that corresponds to token types. An entry is
560 // true if the token is valid in an expression, false otherwise.
561 // Used to figure out when expr parsing should stop *without error message*
562 // - 0 element indicates this condition. 1 means "this token is to be eaten
563 // as part of the expression", token can them still be determined to be invalid
564 // by later processing.
566 #define EXBITS(a,b,c,d,e,f,g,h) \
567 ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
568 BC_PARSE_EXPRS_BITS = 0
569 + (EXBITS(0,0,1,1,1,1,1,1) << (0*8)) // 0: eof inval ++ -- - ^ * /
570 + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: % + - == <= >= != <
571 + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: > ! || && ^= *= /= %=
572 + (EXBITS(1,1,1,0,0,1,1,0) << (3*8)) // 24: += -= = NL WS ( ) [
573 + (EXBITS(0,0,0,0,0,0,1,1) << (4*8)) // 32: , ] { ; } STR NAME NUM
574 + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
575 + (EXBITS(0,1,1,1,1,0,0,1) << (6*8)) // 48: if last len limits obase print quit read - bug, why "limits" is allowed?
576 + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
579 static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
581 #if ULONG_MAX > 0xffffffff
582 // 64-bit version (will not work correctly for 32-bit longs!)
583 return BC_PARSE_EXPRS_BITS & (1UL << i);
586 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
588 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
591 return m & (1UL << i);
595 // This is an array of data for operators that correspond to
596 // [BC_LEX_OP_INC...BC_LEX_OP_ASSIGN] token types.
597 static const uint8_t bc_parse_ops[] = {
598 #define OP(p,l) ((int)(l) * 0x10 + (p))
599 OP(0, false), OP( 0, false ), // inc dec
602 OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
603 OP(4, true ), OP( 4, true ), // + -
604 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
606 OP(7, true ), OP( 7, true ), // or and
607 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
608 OP(5, false), OP( 5, false ), // -= =
611 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
612 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
616 static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
619 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
620 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
621 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
622 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
623 BC_INST_INVALID, BC_INST_INVALID,
624 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
625 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
626 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
627 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
628 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
629 BC_INST_INVALID, BC_INST_INVALID,
630 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
631 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
632 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
633 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
634 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
635 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
636 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
637 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
638 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
639 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
640 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
641 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
645 typedef struct BcLex {
658 #define BC_PARSE_STREND (0xff)
661 # define BC_PARSE_REL (1 << 0)
662 # define BC_PARSE_PRINT (1 << 1)
663 # define BC_PARSE_ARRAY (1 << 2)
664 # define BC_PARSE_NOCALL (1 << 3)
667 typedef struct BcParse {
677 IF_BC(size_t in_funcdef;)
680 typedef struct BcProgram {
710 #define BC_PROG_MAIN (0)
711 #define BC_PROG_READ (1)
713 #define BC_PROG_REQ_FUNCS (2)
716 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
717 #define BC_PROG_NUM(r, n) \
718 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
720 #define BC_FLAG_W (1 << 0)
721 #define BC_FLAG_V (1 << 1)
722 #define BC_FLAG_S (1 << 2)
723 #define BC_FLAG_Q (1 << 3)
724 #define BC_FLAG_L (1 << 4)
725 #define BC_FLAG_I (1 << 5)
726 #define DC_FLAG_X (1 << 6)
728 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
729 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
731 #define BC_MAX_OBASE ((unsigned) 999)
732 #define BC_MAX_DIM ((unsigned) INT_MAX)
733 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
734 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
735 #define BC_MAX_NUM BC_MAX_STRING
736 // Unused apart from "limits" message. Just show a "biggish number" there.
737 //#define BC_MAX_NAME BC_MAX_STRING
738 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
739 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
740 #define BC_MAX_NAME_STR "999999999"
741 #define BC_MAX_EXP_STR "999999999"
742 #define BC_MAX_VARS_STR "999999999"
744 #define BC_MAX_OBASE_STR "999"
746 #if INT_MAX == 2147483647
747 # define BC_MAX_DIM_STR "2147483647"
748 #elif INT_MAX == 9223372036854775807
749 # define BC_MAX_DIM_STR "9223372036854775807"
751 # error Strange INT_MAX
754 #if UINT_MAX == 4294967295
755 # define BC_MAX_SCALE_STR "4294967295"
756 # define BC_MAX_STRING_STR "4294967294"
757 #elif UINT_MAX == 18446744073709551615
758 # define BC_MAX_SCALE_STR "18446744073709551615"
759 # define BC_MAX_STRING_STR "18446744073709551614"
761 # error Strange UINT_MAX
763 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
766 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
767 IF_FEATURE_CLEAN_UP(smallint exiting;)
772 // For error messages. Can be set to current parsed line,
773 // or [TODO] to current executing line (can be before last parsed one)
782 #if ENABLE_FEATURE_EDITING
783 line_input_t *line_input_state;
786 #define G (*ptr_to_globals)
787 #define INIT_G() do { \
788 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
790 #define FREE_G() do { \
791 FREE_PTR_TO_GLOBALS(); \
793 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
794 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
795 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
796 #if ENABLE_FEATURE_BC_SIGNALS
797 # define G_interrupt bb_got_signal
798 # define G_ttyin G.ttyin
800 # define G_interrupt 0
803 #if ENABLE_FEATURE_CLEAN_UP
804 # define G_exiting G.exiting
808 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
809 #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
811 // In configurations where errors abort instead of propagating error
812 // return code up the call chain, functions returning BC_STATUS
813 // actually don't return anything, they always succeed and return "void".
814 // A macro wrapper is provided, which makes this statement work:
816 // and makes it visible to the compiler that s is always zero,
817 // allowing compiler to optimize dead code after the statement.
819 // To make code more readable, each such function has a "z"
820 // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
822 #if ENABLE_FEATURE_BC_SIGNALS || ENABLE_FEATURE_CLEAN_UP
823 # define ERRORS_ARE_FATAL 0
824 # define ERRORFUNC /*nothing*/
825 # define IF_ERROR_RETURN_POSSIBLE(a) a
826 # define BC_STATUS BcStatus
827 # define RETURN_STATUS(v) return (v)
828 # define COMMA_SUCCESS /*nothing*/
830 # define ERRORS_ARE_FATAL 1
831 # define ERRORFUNC NORETURN
832 # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
833 # define BC_STATUS void
834 # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
835 # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
838 #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
839 #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
841 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
842 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
843 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
844 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
845 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
847 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
849 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
850 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
852 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
855 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
857 typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
859 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
860 BcNumBinaryOp op, size_t req);
861 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
862 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
863 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
864 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
865 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
866 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
868 static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
870 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
872 RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
875 static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
877 BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
879 RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
882 static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
884 size_t req = BC_NUM_MREQ(a, b, scale);
885 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
888 static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
890 size_t req = BC_NUM_MREQ(a, b, scale);
891 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
894 static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
896 size_t req = BC_NUM_MREQ(a, b, scale);
897 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
900 static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
902 RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
905 static const BcNumBinaryOp zbc_program_ops[] = {
906 zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
908 #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
909 #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
910 #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
911 #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
912 #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
913 #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
915 static void fflush_and_check(void)
918 if (ferror(stdout) || ferror(stderr))
919 bb_perror_msg_and_die("output error");
922 #if ENABLE_FEATURE_CLEAN_UP
923 #define QUIT_OR_RETURN_TO_MAIN \
925 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
927 return BC_STATUS_FAILURE; \
930 #define QUIT_OR_RETURN_TO_MAIN quit()
933 static void quit(void) NORETURN;
934 static void quit(void)
937 bb_perror_msg_and_die("input error");
939 dbg_exec("quit(): exiting with exitcode SUCCESS");
943 static void bc_verror_msg(const char *fmt, va_list p)
945 const char *sv = sv; // for compiler
948 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
950 bb_verror_msg(fmt, p, NULL);
952 free((char*)applet_name);
957 static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
962 bc_verror_msg(fmt, p);
965 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
966 IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
971 static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
975 // Are non-POSIX constructs totally ok?
976 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
977 return BC_STATUS_SUCCESS; // yes
980 bc_verror_msg(fmt, p);
983 // Do we treat non-POSIX constructs as errors?
984 if (!(option_mask32 & BC_FLAG_S))
985 return BC_STATUS_SUCCESS; // no, it's a warning
986 if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
987 return BC_STATUS_FAILURE;
992 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
993 // This idiom begs for tail-call optimization, but for it to work,
994 // function must not have caller-cleaned parameters on stack.
995 // Unfortunately, vararg function API does exactly that on most arches.
996 // Thus, use these shims for the cases when we have no vararg PARAMS:
997 static ERRORFUNC int bc_error(const char *msg)
999 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
1001 static ERRORFUNC int bc_error_bad_character(char c)
1004 IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
1005 IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
1007 static ERRORFUNC int bc_error_bad_expression(void)
1009 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad expression");
1011 static ERRORFUNC int bc_error_bad_token(void)
1013 IF_ERROR_RETURN_POSSIBLE(return) bc_error("bad token");
1015 static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
1017 IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
1019 static ERRORFUNC int bc_error_variable_is_wrong_type(void)
1021 IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
1024 static int bc_POSIX_requires(const char *msg)
1026 return bc_posix_error_fmt("POSIX requires %s", msg);
1028 static int bc_POSIX_does_not_allow(const char *msg)
1030 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1032 static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1034 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1036 static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1038 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1042 static void bc_vec_grow(BcVec *v, size_t n)
1044 size_t cap = v->cap * 2;
1045 while (cap < v->len + n) cap *= 2;
1046 v->v = xrealloc(v->v, v->size * cap);
1050 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1053 v->cap = BC_VEC_START_CAP;
1056 v->v = xmalloc(esize * BC_VEC_START_CAP);
1059 static void bc_char_vec_init(BcVec *v)
1061 bc_vec_init(v, sizeof(char), NULL);
1064 static void bc_vec_expand(BcVec *v, size_t req)
1067 v->v = xrealloc(v->v, v->size * req);
1072 static void bc_vec_pop(BcVec *v)
1076 v->dtor(v->v + (v->size * v->len));
1079 static void bc_vec_npop(BcVec *v, size_t n)
1084 size_t len = v->len - n;
1085 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1089 static void bc_vec_pop_all(BcVec *v)
1091 bc_vec_npop(v, v->len);
1094 static size_t bc_vec_push(BcVec *v, const void *data)
1096 size_t len = v->len;
1097 if (len >= v->cap) bc_vec_grow(v, 1);
1098 memmove(v->v + (v->size * len), data, v->size);
1103 // G.prog.results often needs "pop old operand, push result" idiom.
1104 // Can do this without a few extra ops
1105 static size_t bc_result_pop_and_push(const void *data)
1107 BcVec *v = &G.prog.results;
1109 size_t len = v->len - 1;
1111 last = v->v + (v->size * len);
1114 memmove(last, data, v->size);
1118 static size_t bc_vec_pushByte(BcVec *v, char data)
1120 return bc_vec_push(v, &data);
1123 static size_t bc_vec_pushZeroByte(BcVec *v)
1125 //return bc_vec_pushByte(v, '\0');
1127 return bc_vec_push(v, &const_int_0);
1130 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1133 bc_vec_push(v, data);
1137 if (v->len == v->cap) bc_vec_grow(v, 1);
1139 ptr = v->v + v->size * idx;
1141 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1142 memmove(ptr, data, v->size);
1146 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1149 bc_vec_expand(v, len + 1);
1150 memcpy(v->v, str, len);
1153 bc_vec_pushZeroByte(v);
1156 #if ENABLE_FEATURE_BC_SIGNALS && ENABLE_FEATURE_EDITING
1157 static void bc_vec_concat(BcVec *v, const char *str)
1161 if (v->len == 0) bc_vec_pushZeroByte(v);
1164 len = v->len + slen;
1166 if (v->cap < len) bc_vec_grow(v, slen);
1167 strcpy(v->v + v->len - 1, str);
1173 static void *bc_vec_item(const BcVec *v, size_t idx)
1175 return v->v + v->size * idx;
1178 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1180 return v->v + v->size * (v->len - idx - 1);
1183 static void *bc_vec_top(const BcVec *v)
1185 return v->v + v->size * (v->len - 1);
1188 static FAST_FUNC void bc_vec_free(void *vec)
1190 BcVec *v = (BcVec *) vec;
1195 static BcFunc* bc_program_func(size_t idx)
1197 return bc_vec_item(&G.prog.fns, idx);
1199 // BC_PROG_MAIN is zeroth element, so:
1200 #define bc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
1203 static BcFunc* bc_program_current_func(void)
1205 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
1206 BcFunc *func = bc_program_func(ip->func);
1211 static char** bc_program_str(size_t idx)
1215 BcFunc *func = bc_program_current_func();
1216 return bc_vec_item(&func->strs, idx);
1219 IF_DC(return bc_vec_item(&G.prog.strs, idx);)
1222 static char** bc_program_const(size_t idx)
1226 BcFunc *func = bc_program_current_func();
1227 return bc_vec_item(&func->consts, idx);
1230 IF_DC(return bc_vec_item(&G.prog.consts, idx);)
1233 static int bc_id_cmp(const void *e1, const void *e2)
1235 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1238 static FAST_FUNC void bc_id_free(void *id)
1240 free(((BcId *) id)->name);
1243 static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
1245 size_t low = 0, high = v->len;
1247 while (low < high) {
1248 size_t mid = (low + high) / 2;
1249 BcId *id = bc_vec_item(v, mid);
1250 int result = bc_id_cmp(ptr, id);
1263 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1265 size_t n = *i = bc_map_find_ge(v, ptr);
1268 bc_vec_push(v, ptr);
1269 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1270 return 0; // "was not inserted"
1272 bc_vec_pushAt(v, ptr, n);
1273 return 1; // "was inserted"
1277 static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
1279 size_t i = bc_map_find_ge(v, ptr);
1280 if (i >= v->len) return BC_VEC_INVALID_IDX;
1281 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1285 static int bad_input_byte(char c)
1287 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1290 bc_error_fmt("illegal character 0x%02x", c);
1296 // Note: it _appends_ data from fp to vec.
1297 static void bc_read_line(BcVec *vec, FILE *fp)
1302 #if ENABLE_FEATURE_BC_SIGNALS
1303 if (G_interrupt) { // ^C was pressed
1306 // ^C while running a script (bc SCRIPT): die.
1307 // We do not return to interactive prompt:
1308 // user might be running us from a shell,
1309 // and SCRIPT might be intended to terminate
1310 // (e.g. contain a "halt" stmt).
1311 // ^C dropping user into a bc prompt instead of
1312 // the shell would be unexpected.
1315 // ^C while interactive input
1317 // GNU bc says "interrupted execution."
1318 // GNU dc says "Interrupt!"
1319 fputs("\ninterrupted execution\n", stderr);
1322 # if ENABLE_FEATURE_EDITING
1323 if (G_ttyin && fp == stdin) {
1325 # define line_buf bb_common_bufsiz1
1326 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
1327 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1330 bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
1335 char c = line_buf[i++];
1337 if (bad_input_byte(c)) goto again;
1339 bc_vec_concat(vec, line_buf);
1347 size_t len = vec->len;
1350 #if ENABLE_FEATURE_BC_SIGNALS
1352 // ^C was pressed: ignore entire line, get another one
1357 do c = fgetc(fp); while (c == '\0');
1360 bb_perror_msg_and_die("input error");
1361 // Note: EOF does not append '\n'
1364 bad_chars |= bad_input_byte(c);
1365 bc_vec_pushByte(vec, (char)c);
1366 } while (c != '\n');
1369 // Bad chars on this line
1370 if (!G.prog.file) { // stdin
1371 // ignore entire line, get another one
1375 bb_perror_msg_and_die("file '%s' is not text", G.prog.file);
1377 bc_vec_pushZeroByte(vec);
1381 static void bc_num_setToZero(BcNum *n, size_t scale)
1388 static void bc_num_zero(BcNum *n)
1390 bc_num_setToZero(n, 0);
1393 static void bc_num_one(BcNum *n)
1395 bc_num_setToZero(n, 0);
1400 // Note: this also sets BcNum to zero
1401 static void bc_num_init(BcNum *n, size_t req)
1403 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1404 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1405 n->num = xmalloc(req);
1412 static void bc_num_init_DEF_SIZE(BcNum *n)
1414 bc_num_init(n, BC_NUM_DEF_SIZE);
1417 static void bc_num_expand(BcNum *n, size_t req)
1419 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1421 n->num = xrealloc(n->num, req);
1426 static FAST_FUNC void bc_num_free(void *num)
1428 free(((BcNum *) num)->num);
1431 static void bc_num_copy(BcNum *d, BcNum *s)
1434 bc_num_expand(d, s->cap);
1438 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1442 static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
1445 unsigned long pow, result;
1447 if (n->neg) RETURN_STATUS(bc_error("negative number"));
1449 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1450 unsigned long prev = result, powprev = pow;
1452 result += ((unsigned long) n->num[i]) * pow;
1455 if (result < prev || pow < powprev)
1456 RETURN_STATUS(bc_error("overflow"));
1462 RETURN_STATUS(BC_STATUS_SUCCESS);
1464 #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
1466 #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
1467 # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
1468 #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
1469 # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
1471 // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
1472 // would not hit realloc() code path - not good if num[] is not malloced
1474 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1480 if (val == 0) return;
1482 bc_num_expand(n, ULONG_NUM_BUFSIZE);
1489 if (val == 0) break;
1493 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
1496 for (i = 0; i < len; ++i) {
1498 for (j = i; a[j] < 0;) {
1505 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1523 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1525 size_t i, min, a_int, b_int, diff;
1526 BcDig *max_num, *min_num;
1530 if (a == b) return 0;
1531 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1532 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1534 if (a->neg != b->neg) // signs of a and b differ
1535 // +a,-b = a>b = 1 or -a,+b = a<b = -1
1536 return (int)b->neg - (int)a->neg;
1537 neg = a->neg; // 1 if both negative, 0 if both positive
1539 a_int = BC_NUM_INT(a);
1540 b_int = BC_NUM_INT(b);
1543 if (a_int != 0) return (ssize_t) a_int;
1545 a_max = (a->rdx > b->rdx);
1548 diff = a->rdx - b->rdx;
1549 max_num = a->num + diff;
1551 // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
1554 diff = b->rdx - a->rdx;
1555 max_num = b->num + diff;
1557 neg = !neg; // same as "neg = (a_max == neg)"
1560 cmp = bc_num_compare(max_num, min_num, b_int + min);
1561 if (cmp != 0) return BC_NUM_NEG(cmp, neg);
1563 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1564 if (max_num[i]) return BC_NUM_NEG(1, neg);
1570 static void bc_num_truncate(BcNum *n, size_t places)
1572 if (places == 0) return;
1578 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1582 static void bc_num_extend(BcNum *n, size_t places)
1584 size_t len = n->len + places;
1587 if (n->cap < len) bc_num_expand(n, len);
1589 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1590 memset(n->num, 0, sizeof(BcDig) * places);
1597 static void bc_num_clean(BcNum *n)
1599 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1602 else if (n->len < n->rdx)
1606 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1609 bc_num_extend(n, scale - n->rdx);
1611 bc_num_truncate(n, n->rdx - scale);
1614 if (n->len != 0) n->neg = !neg1 != !neg2;
1617 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1621 b->len = n->len - idx;
1623 a->rdx = b->rdx = 0;
1625 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1626 memcpy(a->num, n->num, idx * sizeof(BcDig));
1636 static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
1638 if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
1640 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1641 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1642 if (places + n->len > BC_MAX_NUM)
1643 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
1646 if (n->rdx >= places)
1649 bc_num_extend(n, places - n->rdx);
1655 RETURN_STATUS(BC_STATUS_SUCCESS);
1657 #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
1659 static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
1668 RETURN_STATUS(zbc_num_div(&one, a, b, scale));
1670 #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
1672 static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1674 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1675 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1678 // Because this function doesn't need to use scale (per the bc spec),
1679 // I am hijacking it to say whether it's doing an add or a subtract.
1683 if (sub && c->len) c->neg = !c->neg;
1684 RETURN_STATUS(BC_STATUS_SUCCESS);
1688 RETURN_STATUS(BC_STATUS_SUCCESS);
1692 c->rdx = BC_MAX(a->rdx, b->rdx);
1693 min_rdx = BC_MIN(a->rdx, b->rdx);
1696 if (a->rdx > b->rdx) {
1697 diff = a->rdx - b->rdx;
1699 ptr_a = a->num + diff;
1702 diff = b->rdx - a->rdx;
1705 ptr_b = b->num + diff;
1709 for (i = 0; i < diff; ++i, ++c->len)
1713 a_int = BC_NUM_INT(a);
1714 b_int = BC_NUM_INT(b);
1716 if (a_int > b_int) {
1727 for (i = 0; i < min_rdx + min_int; ++i) {
1728 unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
1730 ptr_c[i] = (BcDig)(in % 10);
1732 for (; i < max + min_rdx; ++i) {
1733 unsigned in = (unsigned)ptr[i] + carry;
1735 ptr_c[i] = (BcDig)(in % 10);
1739 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1741 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1744 static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1747 BcNum *minuend, *subtrahend;
1749 bool aneg, bneg, neg;
1751 // Because this function doesn't need to use scale (per the bc spec),
1752 // I am hijacking it to say whether it's doing an add or a subtract.
1756 if (sub && c->len) c->neg = !c->neg;
1757 RETURN_STATUS(BC_STATUS_SUCCESS);
1761 RETURN_STATUS(BC_STATUS_SUCCESS);
1766 a->neg = b->neg = false;
1768 cmp = bc_num_cmp(a, b);
1774 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1775 RETURN_STATUS(BC_STATUS_SUCCESS);
1783 if (sub) neg = !neg;
1788 bc_num_copy(c, minuend);
1791 if (c->rdx < subtrahend->rdx) {
1792 bc_num_extend(c, subtrahend->rdx - c->rdx);
1795 start = c->rdx - subtrahend->rdx;
1797 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1801 RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
1804 static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
1806 #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
1809 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1810 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1813 if (a->len == 0 || b->len == 0) {
1815 RETURN_STATUS(BC_STATUS_SUCCESS);
1817 aone = BC_NUM_ONE(a);
1818 if (aone || BC_NUM_ONE(b)) {
1819 bc_num_copy(c, aone ? b : a);
1820 RETURN_STATUS(BC_STATUS_SUCCESS);
1823 if (a->len + b->len < BC_NUM_KARATSUBA_LEN
1824 || a->len < BC_NUM_KARATSUBA_LEN
1825 || b->len < BC_NUM_KARATSUBA_LEN
1829 bc_num_expand(c, a->len + b->len + 1);
1831 memset(c->num, 0, sizeof(BcDig) * c->cap);
1834 for (i = 0; i < b->len; ++i) {
1836 for (j = 0; j < a->len; ++j) {
1837 unsigned in = c->num[i + j];
1838 in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
1839 // note: compilers prefer _unsigned_ div/const
1841 c->num[i + j] = (BcDig)(in % 10);
1844 c->num[i + j] += (BcDig) carry;
1845 len = BC_MAX(len, i + j + !!carry);
1847 #if ENABLE_FEATURE_BC_SIGNALS
1849 // a*a <- without check below, this will not be interruptible
1850 if (G_interrupt) return BC_STATUS_FAILURE;
1856 RETURN_STATUS(BC_STATUS_SUCCESS);
1859 bc_num_init(&l1, max);
1860 bc_num_init(&h1, max);
1861 bc_num_init(&l2, max);
1862 bc_num_init(&h2, max);
1863 bc_num_init(&m1, max);
1864 bc_num_init(&m2, max);
1865 bc_num_init(&z0, max);
1866 bc_num_init(&z1, max);
1867 bc_num_init(&z2, max);
1868 bc_num_init(&temp, max + max);
1870 bc_num_split(a, max2, &l1, &h1);
1871 bc_num_split(b, max2, &l2, &h2);
1873 s = zbc_num_add(&h1, &l1, &m1, 0);
1875 s = zbc_num_add(&h2, &l2, &m2, 0);
1878 s = zbc_num_k(&h1, &h2, &z0);
1880 s = zbc_num_k(&m1, &m2, &z1);
1882 s = zbc_num_k(&l1, &l2, &z2);
1885 s = zbc_num_sub(&z1, &z0, &temp, 0);
1887 s = zbc_num_sub(&temp, &z2, &z1, 0);
1890 s = zbc_num_shift(&z0, max2 * 2);
1892 s = zbc_num_shift(&z1, max2);
1894 s = zbc_num_add(&z0, &z1, &temp, 0);
1896 s = zbc_num_add(&temp, &z2, c, 0);
1911 static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1915 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1917 scale = BC_MAX(scale, a->rdx);
1918 scale = BC_MAX(scale, b->rdx);
1919 scale = BC_MIN(a->rdx + b->rdx, scale);
1920 maxrdx = BC_MAX(maxrdx, scale);
1922 bc_num_init(&cpa, a->len);
1923 bc_num_init(&cpb, b->len);
1925 bc_num_copy(&cpa, a);
1926 bc_num_copy(&cpb, b);
1927 cpa.neg = cpb.neg = false;
1929 s = zbc_num_shift(&cpa, maxrdx);
1931 s = zbc_num_shift(&cpb, maxrdx);
1933 s = zbc_num_k(&cpa, &cpb, c);
1937 bc_num_expand(c, c->len + maxrdx);
1939 if (c->len < maxrdx) {
1940 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1945 bc_num_retireMul(c, scale, a->neg, b->neg);
1951 #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
1953 static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1960 RETURN_STATUS(bc_error("divide by zero"));
1962 bc_num_setToZero(c, scale);
1963 RETURN_STATUS(BC_STATUS_SUCCESS);
1965 if (BC_NUM_ONE(b)) {
1967 bc_num_retireMul(c, scale, a->neg, b->neg);
1968 RETURN_STATUS(BC_STATUS_SUCCESS);
1971 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1972 bc_num_copy(&cp, a);
1976 bc_num_expand(&cp, len + 2);
1977 bc_num_extend(&cp, len - cp.len);
1980 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1982 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1984 if (b->rdx == b->len) {
1986 if (len == 0) break;
1988 if (b->num[len] != 0)
1994 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1996 // We want an extra zero in front to make things simpler.
1997 cp.num[cp.len++] = 0;
2000 bc_num_expand(c, cp.len);
2003 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2007 s = BC_STATUS_SUCCESS;
2008 for (i = end - 1; i < end; --i) {
2011 for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
2012 bc_num_subArrays(n, b->num, len);
2014 #if ENABLE_FEATURE_BC_SIGNALS
2017 // 1/a <- without check below, this will not be interruptible
2019 s = BC_STATUS_FAILURE;
2025 bc_num_retireMul(c, scale, a->neg, b->neg);
2030 #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
2032 static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2033 BcNum *restrict d, size_t scale, size_t ts)
2040 RETURN_STATUS(bc_error("divide by zero"));
2043 bc_num_setToZero(d, ts);
2044 RETURN_STATUS(BC_STATUS_SUCCESS);
2047 bc_num_init(&temp, d->cap);
2048 s = zbc_num_d(a, b, c, scale);
2051 if (scale != 0) scale = ts;
2053 s = zbc_num_m(c, b, &temp, scale);
2055 s = zbc_num_sub(a, &temp, d, scale);
2058 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2061 bc_num_retireMul(d, ts, a->neg, b->neg);
2067 #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
2069 static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2073 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2075 bc_num_init(&c1, len);
2076 s = zbc_num_r(a, b, &c1, c, scale, ts);
2081 #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
2083 static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2085 BcStatus s = BC_STATUS_SUCCESS;
2088 size_t i, powrdx, resrdx;
2091 if (b->rdx) RETURN_STATUS(bc_error("non integer number"));
2095 RETURN_STATUS(BC_STATUS_SUCCESS);
2098 bc_num_setToZero(c, scale);
2099 RETURN_STATUS(BC_STATUS_SUCCESS);
2101 if (BC_NUM_ONE(b)) {
2105 s = zbc_num_inv(a, c, scale);
2112 s = zbc_num_ulong(b, &pow);
2113 if (s) RETURN_STATUS(s);
2115 bc_num_init(©, a->len);
2116 bc_num_copy(©, a);
2121 if (a->rdx * pow < scale)
2122 scale = a->rdx * pow;
2127 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2129 s = zbc_num_mul(©, ©, ©, powrdx);
2131 // Not needed: zbc_num_mul() has a check for ^C:
2132 //if (G_interrupt) {
2133 // s = BC_STATUS_FAILURE;
2138 bc_num_copy(c, ©);
2140 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2142 s = zbc_num_mul(©, ©, ©, powrdx);
2147 s = zbc_num_mul(c, ©, c, resrdx);
2150 // Not needed: zbc_num_mul() has a check for ^C:
2151 //if (G_interrupt) {
2152 // s = BC_STATUS_FAILURE;
2158 s = zbc_num_inv(c, c, scale);
2162 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2164 // We can't use bc_num_clean() here.
2165 for (i = 0; i < c->len; ++i)
2168 bc_num_setToZero(c, scale);
2175 #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
2177 static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2178 BcNumBinaryOp op, size_t req)
2181 BcNum num2, *ptr_a, *ptr_b;
2186 memcpy(ptr_a, c, sizeof(BcNum));
2194 memcpy(ptr_b, c, sizeof(BcNum));
2201 bc_num_init(c, req);
2203 bc_num_expand(c, req);
2205 s = BC_STATUS_SUCCESS;
2206 IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
2208 if (init) bc_num_free(&num2);
2212 #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
2214 static bool bc_num_strValid(const char *val, size_t base)
2219 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2226 if (radix) return false;
2230 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2236 // Note: n is already "bc_num_zero()"ed,
2237 // leading zeroes in "val" are removed
2238 static void bc_num_parseDecimal(BcNum *n, const char *val)
2247 bc_num_expand(n, len);
2249 ptr = strchr(val, '.');
2253 n->rdx = (size_t)((val + len) - (ptr + 1));
2255 for (i = 0; val[i]; ++i) {
2256 if (val[i] != '0' && val[i] != '.') {
2257 // Not entirely zero value - convert it, and exit
2260 n->num[n->len] = val[i] - '0';
2264 if (val[--i] == '.') goto skip_dot;
2269 // if for() exits without hitting if(), the value is entirely zero
2272 // Note: n is already "bc_num_zero()"ed,
2273 // leading zeroes in "val" are removed
2274 static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
2277 BcNum temp, mult, result;
2279 BcDig base_digs[ULONG_NUM_BUFSIZE];
2284 for (i = 0; ; ++i) {
2287 if (val[i] != '.' && val[i] != '0')
2291 bc_num_init_DEF_SIZE(&temp);
2292 bc_num_init_DEF_SIZE(&mult);
2293 base.cap = ARRAY_SIZE(base_digs);
2294 base.num = base_digs;
2295 bc_num_ulong2num(&base, base_t);
2299 if (c == '\0') goto int_err;
2300 if (c == '.') break;
2302 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2304 s = zbc_num_mul(n, &base, &mult, 0);
2305 if (s) goto int_err;
2306 bc_num_ulong2num(&temp, v);
2307 s = zbc_num_add(&mult, &temp, n, 0);
2308 if (s) goto int_err;
2311 bc_num_init(&result, base.len);
2312 //bc_num_zero(&result); - already is
2318 if (c == '\0') break;
2321 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2323 s = zbc_num_mul(&result, &base, &result, 0);
2325 bc_num_ulong2num(&temp, v);
2326 s = zbc_num_add(&result, &temp, &result, 0);
2328 s = zbc_num_mul(&mult, &base, &mult, 0);
2332 s = zbc_num_div(&result, &mult, &result, digits);
2334 s = zbc_num_add(n, &result, n, digits);
2338 if (n->rdx < digits)
2339 bc_num_extend(n, digits - n->rdx);
2343 bc_num_free(&result);
2349 static BC_STATUS zbc_num_parse(BcNum *n, const char *val, unsigned base_t)
2351 if (!bc_num_strValid(val, base_t))
2352 RETURN_STATUS(bc_error("bad number string"));
2355 while (*val == '0') val++;
2358 bc_num_parseDecimal(n, val);
2360 bc_num_parseBase(n, val, base_t);
2362 RETURN_STATUS(BC_STATUS_SUCCESS);
2364 #define zbc_num_parse(...) (zbc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
2366 static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2369 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2370 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2371 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2373 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2374 bc_num_expand(b, req);
2377 bc_num_setToZero(b, scale);
2378 RETURN_STATUS(BC_STATUS_SUCCESS);
2381 RETURN_STATUS(bc_error("negative number"));
2383 if (BC_NUM_ONE(a)) {
2385 bc_num_extend(b, scale);
2386 RETURN_STATUS(BC_STATUS_SUCCESS);
2389 scale = BC_MAX(scale, a->rdx) + 1;
2390 len = a->len + scale;
2392 bc_num_init(&num1, len);
2393 bc_num_init(&num2, len);
2394 bc_num_init_DEF_SIZE(&half);
2400 bc_num_init(&f, len);
2401 bc_num_init(&fprime, len);
2407 pow = BC_NUM_INT(a);
2415 pow -= 2 - (pow & 1);
2417 bc_num_extend(x0, pow);
2419 // Make sure to move the radix back.
2423 x0->rdx = digs = digs1 = 0;
2425 len = BC_NUM_INT(x0) + resrdx - 1;
2427 while (cmp != 0 || digs < len) {
2428 s = zbc_num_div(a, x0, &f, resrdx);
2430 s = zbc_num_add(x0, &f, &fprime, resrdx);
2432 s = zbc_num_mul(&fprime, &half, x1, resrdx);
2435 cmp = bc_num_cmp(x1, x0);
2436 digs = x1->len - (unsigned long long) llabs(cmp);
2438 if (cmp == cmp2 && digs == digs1)
2443 resrdx += times > 4;
2456 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2458 bc_num_free(&fprime);
2465 #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
2467 static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2473 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2476 memcpy(&num2, c, sizeof(BcNum));
2478 bc_num_init(c, len);
2482 bc_num_expand(c, len);
2485 s = zbc_num_r(ptr_a, b, c, d, scale, ts);
2487 if (init) bc_num_free(&num2);
2491 #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
2494 static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2497 BcNum base, exp, two, temp;
2500 RETURN_STATUS(bc_error("divide by zero"));
2501 if (a->rdx || b->rdx || c->rdx)
2502 RETURN_STATUS(bc_error("non integer number"));
2504 RETURN_STATUS(bc_error("negative number"));
2506 bc_num_expand(d, c->len);
2507 bc_num_init(&base, c->len);
2508 bc_num_init(&exp, b->len);
2509 bc_num_init_DEF_SIZE(&two);
2510 bc_num_init(&temp, b->len);
2516 s = zbc_num_rem(a, c, &base, 0);
2518 bc_num_copy(&exp, b);
2520 while (exp.len != 0) {
2521 s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
2524 if (BC_NUM_ONE(&temp)) {
2525 s = zbc_num_mul(d, &base, &temp, 0);
2527 s = zbc_num_rem(&temp, c, d, 0);
2531 s = zbc_num_mul(&base, &base, &temp, 0);
2533 s = zbc_num_rem(&temp, c, &base, 0);
2543 #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
2547 static BC_STATUS zbc_func_insert(BcFunc *f, char *name, bool var)
2553 autoid = (void*)f->autos.v;
2554 for (i = 0; i < f->autos.len; i++, autoid++) {
2555 if (strcmp(name, autoid->name) == 0)
2556 RETURN_STATUS(bc_error("function parameter or auto var has the same name as another"));
2562 bc_vec_push(&f->autos, &a);
2564 RETURN_STATUS(BC_STATUS_SUCCESS);
2566 #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
2569 static FAST_FUNC void bc_string_free(void *string)
2571 free(*(char**)string);
2574 static void bc_func_init(BcFunc *f)
2576 bc_char_vec_init(&f->code);
2577 IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
2578 IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
2579 IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
2580 IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
2581 IF_BC(f->nparams = 0;)
2584 static FAST_FUNC void bc_func_free(void *func)
2586 BcFunc *f = (BcFunc *) func;
2587 bc_vec_free(&f->code);
2588 IF_BC(bc_vec_free(&f->labels);)
2589 IF_BC(bc_vec_free(&f->autos);)
2590 IF_BC(bc_vec_free(&f->strs);)
2591 IF_BC(bc_vec_free(&f->consts);)
2594 static void bc_array_expand(BcVec *a, size_t len);
2596 static void bc_array_init(BcVec *a, bool nums)
2599 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2601 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2602 bc_array_expand(a, 1);
2605 static void bc_array_expand(BcVec *a, size_t len)
2607 if (a->dtor == bc_num_free
2608 // && a->size == sizeof(BcNum) - always true
2611 while (len > a->len) {
2612 bc_num_init_DEF_SIZE(&n);
2617 while (len > a->len) {
2618 bc_array_init(&v, true);
2624 static void bc_array_copy(BcVec *d, const BcVec *s)
2630 bc_vec_expand(d, s->cap);
2635 for (i = 0; i < s->len; i++, dnum++, snum++) {
2636 bc_num_init(dnum, snum->len);
2637 bc_num_copy(dnum, snum);
2642 static void dc_result_copy(BcResult *d, BcResult *src)
2647 case BC_RESULT_TEMP:
2648 case BC_RESULT_IBASE:
2649 case BC_RESULT_SCALE:
2650 case BC_RESULT_OBASE:
2651 bc_num_init(&d->d.n, src->d.n.len);
2652 bc_num_copy(&d->d.n, &src->d.n);
2655 case BC_RESULT_ARRAY:
2656 case BC_RESULT_ARRAY_ELEM:
2657 d->d.id.name = xstrdup(src->d.id.name);
2659 case BC_RESULT_CONSTANT:
2660 case BC_RESULT_LAST:
2663 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2669 static FAST_FUNC void bc_result_free(void *result)
2671 BcResult *r = (BcResult *) result;
2674 case BC_RESULT_TEMP:
2675 case BC_RESULT_IBASE:
2676 case BC_RESULT_SCALE:
2677 case BC_RESULT_OBASE:
2678 bc_num_free(&r->d.n);
2681 case BC_RESULT_ARRAY:
2682 case BC_RESULT_ARRAY_ELEM:
2691 static void bc_lex_lineComment(BcLex *l)
2693 // Try: echo -n '#foo' | bc
2695 l->t.t = BC_LEX_WHITESPACE;
2697 while (i < l->len && l->buf[i] != '\n')
2702 static void bc_lex_whitespace(BcLex *l)
2704 l->t.t = BC_LEX_WHITESPACE;
2706 char c = l->buf[l->i];
2707 if (c == '\n') // this is BC_LEX_NLINE, not BC_LEX_WHITESPACE
2715 static BC_STATUS zbc_lex_number(BcLex *l, char start)
2717 const char *buf = l->buf + l->i;
2718 size_t len, i, ccnt;
2721 pt = (start == '.');
2722 l->t.t = BC_LEX_NUMBER;
2728 if (c == '\\' && buf[i + 1] == '\n') {
2730 //number_of_backslashes++ - see comment below
2733 if (!isdigit(c) && (c < 'A' || c > 'F')) {
2734 if (c != '.') break;
2735 // if '.' was already seen, stop on second one:
2739 // buf[i] is one of "0-9A-F."
2744 //ccnt is the number of chars in the number string, excluding possible
2745 //trailing "[\<newline>].[\<newline>]" (with any number of \<NL> repetitions).
2746 //i is buf[i] index of the first not-yet-parsed char after that.
2749 // This might overestimate the size, if there are "\<NL>"'s
2750 // in the number. Subtracting number_of_backslashes*2 correctly
2751 // is not that easy: consider that in the case of "NNN.\<NL>"
2752 // loop above will count "\<NL>" before it realizes it is not
2753 // in fact *inside* the number:
2754 len = ccnt + 1; // +1 byte for NUL termination
2756 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2757 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2758 if (len > BC_MAX_NUM)
2759 RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
2762 bc_vec_pop_all(&l->t.v);
2763 bc_vec_expand(&l->t.v, 1 + len);
2764 bc_vec_push(&l->t.v, &start);
2767 // If we have hit a backslash, skip it. We don't have
2768 // to check for a newline because it's guaranteed.
2774 bc_vec_push(&l->t.v, buf);
2779 bc_vec_pushZeroByte(&l->t.v);
2781 RETURN_STATUS(BC_STATUS_SUCCESS);
2783 #define zbc_lex_number(...) (zbc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
2785 static void bc_lex_name(BcLex *l)
2790 l->t.t = BC_LEX_NAME;
2793 buf = l->buf + l->i - 1;
2796 if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
2800 #if 0 // We do not protect against people with gigabyte-long names
2801 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2802 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2803 if (i > BC_MAX_STRING)
2804 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2807 bc_vec_string(&l->t.v, i, buf);
2809 // Increment the index. We minus 1 because it has already been incremented.
2812 //return BC_STATUS_SUCCESS;
2815 static void bc_lex_init(BcLex *l)
2817 bc_char_vec_init(&l->t.v);
2820 static void bc_lex_free(BcLex *l)
2822 bc_vec_free(&l->t.v);
2825 static void bc_lex_file(BcLex *l)
2827 G.err_line = l->line = 1;
2831 static bool bc_lex_more_input(BcLex *l)
2836 bc_vec_pop_all(&G.input_buffer);
2838 // This loop is complex because the vm tries not to send any lines that end
2839 // with a backslash to the parser. The reason for that is because the parser
2840 // treats a backslash+newline combo as whitespace, per the bc spec. In that
2841 // case, and for strings and comments, the parser will expect more stuff.
2845 size_t prevlen = G.input_buffer.len;
2848 bc_read_line(&G.input_buffer, G.input_fp);
2849 // No more input means EOF
2850 if (G.input_buffer.len <= prevlen + 1) // (we expect +1 for NUL byte)
2853 string = G.input_buffer.v + prevlen;
2856 if (string == G.input_buffer.v || string[-1] != '\\') {
2867 if (c == '/' && *string == '*') {
2872 if (c == '*' && *string == '/') {
2877 if (str != 0 || comment) {
2878 G.input_buffer.len--; // backstep over the trailing NUL byte
2882 // Check for backslash+newline.
2883 // we do not check that last char is '\n' -
2884 // if it is not, then it's EOF, and looping back
2885 // to bc_read_line() will detect it:
2887 if (string >= G.input_buffer.v && *string == '\\') {
2888 G.input_buffer.len--;
2895 l->buf = G.input_buffer.v;
2897 // bb_error_msg("G.input_buffer.len:%d '%s'", G.input_buffer.len, G.input_buffer.v);
2898 l->len = G.input_buffer.len - 1; // do not include NUL
2903 IF_BC(static BC_STATUS zbc_lex_token(BcLex *l);)
2904 IF_DC(static BC_STATUS zdc_lex_token(BcLex *l);)
2905 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2906 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
2908 static BC_STATUS zbc_lex_next(BcLex *l)
2913 if (l->t.last == BC_LEX_EOF) RETURN_STATUS(bc_error("end of file"));
2915 l->line += l->newline;
2916 G.err_line = l->line;
2919 // Loop until failure or we don't have whitespace. This
2920 // is so the parser doesn't get inundated with whitespace.
2921 // Comments are also BC_LEX_WHITESPACE tokens and eaten here.
2922 s = BC_STATUS_SUCCESS;
2924 if (l->i == l->len) {
2925 l->t.t = BC_LEX_EOF;
2927 RETURN_STATUS(BC_STATUS_SUCCESS);
2928 if (!bc_lex_more_input(l)) {
2930 RETURN_STATUS(BC_STATUS_SUCCESS);
2932 // here it's guaranteed that l->i is below l->len
2934 dbg_lex("next string to parse:'%.*s'",
2935 (int)(strchrnul(l->buf + l->i, '\n') - (l->buf + l->i)),
2938 IF_BC(s = zbc_lex_token(l));
2940 IF_DC(s = zdc_lex_token(l));
2942 } while (!s && l->t.t == BC_LEX_WHITESPACE);
2943 dbg_lex("l->t.t from string:%d", l->t.t);
2947 #define zbc_lex_next(...) (zbc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
2950 static BC_STATUS zbc_lex_skip_if_at_NLINE(BcLex *l)
2952 if (l->t.t == BC_LEX_NLINE)
2953 RETURN_STATUS(zbc_lex_next(l));
2954 RETURN_STATUS(BC_STATUS_SUCCESS);
2956 #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2958 static BC_STATUS zbc_lex_next_and_skip_NLINE(BcLex *l)
2961 s = zbc_lex_next(l);
2962 if (s) RETURN_STATUS(s);
2963 // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
2964 s = zbc_lex_skip_if_at_NLINE(l);
2967 #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
2970 static BC_STATUS zbc_lex_text_init(BcLex *l, const char *text)
2974 l->len = strlen(text);
2975 l->t.t = l->t.last = BC_LEX_INVALID;
2976 RETURN_STATUS(zbc_lex_next(l));
2978 #define zbc_lex_text_init(...) (zbc_lex_text_init(__VA_ARGS__) COMMA_SUCCESS)
2981 static BC_STATUS zbc_lex_identifier(BcLex *l)
2985 const char *buf = l->buf + l->i - 1;
2987 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2988 const char *keyword8 = bc_lex_kws[i].name8;
2990 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2992 if (j == 8) goto match;
2994 if (keyword8[j] != '\0')
2997 // buf starts with keyword bc_lex_kws[i]
2998 if (isalnum(buf[j]) || buf[j]=='_')
2999 continue; // "ifz" does not match "if" keyword, "if." does
3000 l->t.t = BC_LEX_KEY_1st_keyword + i;
3001 if (!bc_lex_kws_POSIX(i)) {
3002 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3003 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3006 // We minus 1 because the index has already been incremented.
3008 RETURN_STATUS(BC_STATUS_SUCCESS);
3012 s = BC_STATUS_SUCCESS;
3014 if (l->t.v.len > 2) {
3017 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3019 unsigned len = strchrnul(buf, '\n') - buf;
3020 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3025 #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
3027 static BC_STATUS zbc_lex_string(BcLex *l)
3031 l->t.t = BC_LEX_STR;
3039 RETURN_STATUS(bc_error("string end could not be found"));
3048 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3049 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3050 if (len > BC_MAX_STRING)
3051 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3053 bc_vec_string(&l->t.v, len, l->buf + l->i);
3057 G.err_line = l->line;
3059 RETURN_STATUS(BC_STATUS_SUCCESS);
3061 #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3063 static void bc_lex_assign(BcLex *l, unsigned with_and_without)
3065 if (l->buf[l->i] == '=') {
3067 with_and_without >>= 8; // store "with" value
3068 } // else store "without" value
3069 l->t.t = (with_and_without & 0xff);
3071 #define bc_lex_assign(l, with, without) \
3072 bc_lex_assign(l, ((with)<<8)|(without))
3074 static BC_STATUS zbc_lex_comment(BcLex *l)
3077 const char *buf = l->buf;
3079 l->t.t = BC_LEX_WHITESPACE;
3080 i = l->i; /* here buf[l->i] is the '*' of opening comment delimiter */
3092 RETURN_STATUS(bc_error("comment end could not be found"));
3099 G.err_line = l->line;
3101 RETURN_STATUS(BC_STATUS_SUCCESS);
3103 #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
3105 #undef zbc_lex_token
3106 static BC_STATUS zbc_lex_token(BcLex *l)
3108 BcStatus s = BC_STATUS_SUCCESS;
3109 char c = l->buf[l->i++], c2;
3111 // This is the workhorse of the lexer.
3113 // case '\0': // probably never reached
3115 // l->t.t = BC_LEX_EOF;
3116 // l->newline = true;
3119 l->t.t = BC_LEX_NLINE;
3127 bc_lex_whitespace(l);
3130 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3131 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
3132 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3133 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3137 s = zbc_lex_string(l);
3140 s = bc_POSIX_does_not_allow("'#' script comments");
3141 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3142 bc_lex_lineComment(l);
3145 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3150 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3151 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3153 l->t.t = BC_LEX_OP_BOOL_AND;
3155 l->t.t = BC_LEX_INVALID;
3156 s = bc_error_bad_character('&');
3161 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3164 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3170 l->t.t = BC_LEX_OP_INC;
3172 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3175 l->t.t = BC_LEX_COMMA;
3181 l->t.t = BC_LEX_OP_DEC;
3183 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3186 if (isdigit(l->buf[l->i]))
3187 s = zbc_lex_number(l, c);
3189 l->t.t = BC_LEX_KEY_LAST;
3190 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3196 s = zbc_lex_comment(l);
3198 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3216 s = zbc_lex_number(l, c);
3219 l->t.t = BC_LEX_SCOLON;
3222 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3225 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3228 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3232 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3235 if (l->buf[l->i] == '\n') {
3236 l->t.t = BC_LEX_WHITESPACE;
3239 s = bc_error_bad_character(c);
3242 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3270 s = zbc_lex_identifier(l);
3274 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3279 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3280 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
3282 l->t.t = BC_LEX_OP_BOOL_OR;
3284 l->t.t = BC_LEX_INVALID;
3285 s = bc_error_bad_character(c);
3289 l->t.t = BC_LEX_INVALID;
3290 s = bc_error_bad_character(c);
3296 #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3300 static BC_STATUS zdc_lex_register(BcLex *l)
3302 if (isspace(l->buf[l->i - 1])) {
3303 bc_lex_whitespace(l);
3306 RETURN_STATUS(bc_error("extended register"));
3310 bc_vec_pop_all(&l->t.v);
3311 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
3312 bc_vec_pushZeroByte(&l->t.v);
3313 l->t.t = BC_LEX_NAME;
3316 RETURN_STATUS(BC_STATUS_SUCCESS);
3318 #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
3320 static BC_STATUS zdc_lex_string(BcLex *l)
3322 size_t depth, nls, i;
3324 l->t.t = BC_LEX_STR;
3325 bc_vec_pop_all(&l->t.v);
3334 RETURN_STATUS(bc_error("string end could not be found"));
3337 if (i == l->i || l->buf[i - 1] != '\\') {
3338 if (c == '[') depth++;
3343 bc_vec_push(&l->t.v, &l->buf[i]);
3348 bc_vec_pushZeroByte(&l->t.v);
3349 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3350 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3351 if (i - l->i > BC_MAX_STRING)
3352 RETURN_STATUS(bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]"));
3357 G.err_line = l->line;
3359 RETURN_STATUS(BC_STATUS_SUCCESS);
3361 #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
3363 #undef zdc_lex_token
3364 static BC_STATUS zdc_lex_token(BcLex *l)
3366 static const //BcLexType - should be this type, but narrower type saves size:
3369 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
3370 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
3371 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
3374 static const //BcLexType - should be this type
3378 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
3380 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
3382 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
3384 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3385 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3386 BC_LEX_INVALID, BC_LEX_INVALID,
3388 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
3389 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
3391 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3392 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
3394 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
3395 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
3397 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
3398 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
3400 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
3402 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
3404 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
3405 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
3407 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
3408 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
3410 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
3411 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
3413 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
3415 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
3418 BcStatus s = BC_STATUS_SUCCESS;
3419 char c = l->buf[l->i++], c2;
3422 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3423 if (l->t.last == dc_lex_regs[i])
3424 RETURN_STATUS(zdc_lex_register(l));
3427 if (c >= '%' && c <= '~'
3428 && (l->t.t = dc_lex_tokens[c - '%']) != BC_LEX_INVALID
3433 // This is the workhorse of the lexer.
3435 // case '\0': // probably never reached
3436 // l->t.t = BC_LEX_EOF;
3439 // '\n' is BC_LEX_NLINE, not BC_LEX_WHITESPACE
3440 // (and "case '\n'" is not just empty here)
3441 // only to allow interactive dc have a way to exit
3442 // "parse" stage of "parse,execute" loop
3443 // on '\n', not on _next_ token (which would mean
3444 // command are not executed on pressing <enter>).
3445 // IOW: typing "1p<enter>" should print "1" _at once_,
3446 // not after some more input.
3447 l->t.t = BC_LEX_NLINE;
3455 l->newline = (c == '\n');
3456 bc_lex_whitespace(l);
3461 l->t.t = BC_LEX_OP_REL_NE;
3463 l->t.t = BC_LEX_OP_REL_LE;
3465 l->t.t = BC_LEX_OP_REL_GE;
3467 RETURN_STATUS(bc_error_bad_character(c));
3471 bc_lex_lineComment(l);
3474 if (isdigit(l->buf[l->i]))
3475 s = zbc_lex_number(l, c);
3477 s = bc_error_bad_character(c);
3495 s = zbc_lex_number(l, c);
3498 s = zdc_lex_string(l);
3501 l->t.t = BC_LEX_INVALID;
3502 s = bc_error_bad_character(c);
3508 #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
3511 static void bc_parse_push(BcParse *p, char i)
3513 dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, p->func->code.len, i);
3514 bc_vec_pushByte(&p->func->code, i);
3517 static void bc_parse_pushName(BcParse *p, char *name)
3520 bc_parse_push(p, *name++);
3521 bc_parse_push(p, BC_PARSE_STREND);
3524 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3529 dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
3530 mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
3533 if (idx & mask) break;
3538 bc_parse_push(p, amt);
3541 bc_parse_push(p, (unsigned char)idx);
3547 static void bc_parse_pushJUMP(BcParse *p, size_t idx)
3549 bc_parse_push(p, BC_INST_JUMP);
3550 bc_parse_pushIndex(p, idx);
3553 static void bc_parse_pushJUMP_ZERO(BcParse *p, size_t idx)
3555 bc_parse_push(p, BC_INST_JUMP_ZERO);
3556 bc_parse_pushIndex(p, idx);
3559 static BC_STATUS zbc_parse_pushSTR(BcParse *p)
3561 char *str = xstrdup(p->l.t.v.v);
3563 bc_parse_push(p, BC_INST_STR);
3564 bc_parse_pushIndex(p, p->func->strs.len);
3565 bc_vec_push(&p->func->strs, &str);
3567 RETURN_STATUS(zbc_lex_next(&p->l));
3569 #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
3572 static void bc_parse_pushNUM(BcParse *p)
3574 char *num = xstrdup(p->l.t.v.v);
3575 #if ENABLE_BC && ENABLE_DC
3576 size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
3578 size_t idx = bc_vec_push(&p->func->consts, &num);
3580 size_t idx = bc_vec_push(&G.prog.consts, &num);
3582 bc_parse_push(p, BC_INST_NUM);
3583 bc_parse_pushIndex(p, idx);
3586 static BC_STATUS zbc_parse_text_init(BcParse *p, const char *text)
3588 p->func = bc_program_func(p->fidx);
3590 RETURN_STATUS(zbc_lex_text_init(&p->l, text));
3592 #define zbc_parse_text_init(...) (zbc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
3594 // Called when parsing or execution detects a failure,
3595 // resets execution structures.
3596 static void bc_program_reset(void)
3601 bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
3602 bc_vec_pop_all(&G.prog.results);
3604 f = bc_program_func_BC_PROG_MAIN();
3605 ip = bc_vec_top(&G.prog.exestack);
3606 ip->inst_idx = f->code.len;
3609 // Called when parsing code detects a failure,
3610 // resets parsing structures.
3611 static void bc_parse_reset(BcParse *p)
3613 if (p->fidx != BC_PROG_MAIN) {
3614 bc_func_free(p->func);
3615 bc_func_init(p->func);
3617 p->fidx = BC_PROG_MAIN;
3618 p->func = bc_program_func_BC_PROG_MAIN();
3622 p->l.t.t = BC_LEX_EOF;
3624 IF_BC(bc_vec_pop_all(&p->exits);)
3625 IF_BC(bc_vec_pop_all(&p->conds);)
3626 IF_BC(bc_vec_pop_all(&p->ops);)
3631 static void bc_parse_free(BcParse *p)
3633 IF_BC(bc_vec_free(&p->exits);)
3634 IF_BC(bc_vec_free(&p->conds);)
3635 IF_BC(bc_vec_free(&p->ops);)
3639 static void bc_parse_create(BcParse *p, size_t fidx)
3641 memset(p, 0, sizeof(BcParse));
3644 IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
3645 IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
3646 IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
3649 p->func = bc_program_func(fidx);
3652 static void bc_program_add_fn(void)
3658 bc_vec_push(&G.prog.fns, &f);
3664 // Note: takes ownership of 'name' (must be malloced)
3665 static size_t bc_program_addFunc(char *name)
3668 BcId entry, *entry_ptr;
3672 entry.idx = G.prog.fns.len;
3674 inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
3675 if (!inserted) free(name);
3677 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3678 idx = entry_ptr->idx;
3681 // There is already a function with this name.
3682 // It'll be redefined now, clear old definition.
3683 BcFunc *func = bc_program_func(entry_ptr->idx);
3687 bc_program_add_fn();
3693 #define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3694 #define BC_PARSE_LEAF(p, rparen) \
3695 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3696 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3698 // We can calculate the conversion between tokens and exprs by subtracting the
3699 // position of the first operator in the lex enum and adding the position of the
3700 // first in the expr enum. Note: This only works for binary operators.
3701 #define BC_TOKEN_2_INST(t) ((char) ((t) - BC_LEX_NEG + BC_INST_NEG))
3703 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags);
3705 static BC_STATUS zbc_parse_expr(BcParse *p, uint8_t flags)
3709 s = bc_parse_expr_empty_ok(p, flags);
3710 if (s == BC_STATUS_PARSE_EMPTY_EXP)
3711 RETURN_STATUS(bc_error("empty expression"));
3714 #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
3716 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed);
3717 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
3719 static BC_STATUS zbc_parse_stmt(BcParse *p)
3721 RETURN_STATUS(zbc_parse_stmt_possibly_auto(p, false));
3723 #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
3725 static BC_STATUS zbc_parse_stmt_allow_NLINE_before(BcParse *p, const char *after_X)
3727 // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
3728 // Same for "else", "while()", "for()".
3729 BcStatus s = zbc_lex_next_and_skip_NLINE(&p->l);
3730 if (s) RETURN_STATUS(s);
3731 if (p->l.t.t == BC_LEX_NLINE)
3732 RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
3734 RETURN_STATUS(zbc_parse_stmt(p));
3736 #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
3738 static void bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3741 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3742 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
3744 while (p->ops.len > start) {
3745 BcLexType t = BC_PARSE_TOP_OP(p);
3746 if (t == BC_LEX_LPAREN) break;
3748 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
3749 if (l >= r && (l != r || !left)) break;
3751 bc_parse_push(p, BC_TOKEN_2_INST(t));
3752 bc_vec_pop(&p->ops);
3753 *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG);
3756 bc_vec_push(&p->ops, &type);
3759 static BC_STATUS zbc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3763 if (p->ops.len <= ops_bgn)
3764 RETURN_STATUS(bc_error_bad_expression());
3765 top = BC_PARSE_TOP_OP(p);
3767 while (top != BC_LEX_LPAREN) {
3768 bc_parse_push(p, BC_TOKEN_2_INST(top));
3770 bc_vec_pop(&p->ops);
3771 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3773 if (p->ops.len <= ops_bgn)
3774 RETURN_STATUS(bc_error_bad_expression());
3775 top = BC_PARSE_TOP_OP(p);
3778 bc_vec_pop(&p->ops);
3780 RETURN_STATUS(zbc_lex_next(&p->l));
3782 #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
3784 static BC_STATUS zbc_parse_params(BcParse *p, uint8_t flags)
3789 dbg_lex("%s:%d p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
3790 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3792 s = zbc_lex_next(&p->l);
3793 if (s) RETURN_STATUS(s);
3796 if (p->l.t.t != BC_LEX_RPAREN) {
3798 s = zbc_parse_expr(p, flags);
3799 if (s) RETURN_STATUS(s);
3801 if (p->l.t.t != BC_LEX_COMMA) {
3802 if (p->l.t.t == BC_LEX_RPAREN)
3804 RETURN_STATUS(bc_error_bad_token());
3806 s = zbc_lex_next(&p->l);
3807 if (s) RETURN_STATUS(s);
3811 bc_parse_push(p, BC_INST_CALL);
3812 bc_parse_pushIndex(p, nparams);
3814 RETURN_STATUS(BC_STATUS_SUCCESS);
3816 #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
3818 // Note: takes ownership of 'name' (must be malloced)
3819 static BC_STATUS zbc_parse_call(BcParse *p, char *name, uint8_t flags)
3822 BcId entry, *entry_ptr;
3827 s = zbc_parse_params(p, flags);
3830 if (p->l.t.t != BC_LEX_RPAREN) {
3831 s = bc_error_bad_token();
3835 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3837 if (idx == BC_VEC_INVALID_IDX) {
3838 // No such function exists, create an empty one
3839 bc_program_addFunc(name);
3840 idx = bc_map_find_exact(&G.prog.fn_map, &entry);
3844 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3845 bc_parse_pushIndex(p, entry_ptr->idx);
3847 RETURN_STATUS(zbc_lex_next(&p->l));
3852 #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
3854 static BC_STATUS zbc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3859 name = xstrdup(p->l.t.v.v);
3860 s = zbc_lex_next(&p->l);
3863 if (p->l.t.t == BC_LEX_LBRACKET) {
3864 s = zbc_lex_next(&p->l);
3867 if (p->l.t.t == BC_LEX_RBRACKET) {
3868 if (!(flags & BC_PARSE_ARRAY)) {
3869 s = bc_error_bad_expression();
3872 *type = BC_INST_ARRAY;
3874 *type = BC_INST_ARRAY_ELEM;
3875 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3876 s = zbc_parse_expr(p, flags);
3879 s = zbc_lex_next(&p->l);
3881 bc_parse_push(p, *type);
3882 bc_parse_pushName(p, name);
3884 } else if (p->l.t.t == BC_LEX_LPAREN) {
3885 if (flags & BC_PARSE_NOCALL) {
3886 s = bc_error_bad_token();
3889 *type = BC_INST_CALL;
3890 s = zbc_parse_call(p, name, flags);
3892 *type = BC_INST_VAR;
3893 bc_parse_push(p, BC_INST_VAR);
3894 bc_parse_pushName(p, name);
3903 #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
3905 static BC_STATUS zbc_parse_read(BcParse *p)
3909 s = zbc_lex_next(&p->l);
3910 if (s) RETURN_STATUS(s);
3911 if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3913 s = zbc_lex_next(&p->l);
3914 if (s) RETURN_STATUS(s);
3915 if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3917 bc_parse_push(p, BC_INST_READ);
3919 RETURN_STATUS(zbc_lex_next(&p->l));
3921 #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
3923 static BC_STATUS zbc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3928 s = zbc_lex_next(&p->l);
3929 if (s) RETURN_STATUS(s);
3930 if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
3932 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3934 s = zbc_lex_next(&p->l);
3935 if (s) RETURN_STATUS(s);
3937 s = zbc_parse_expr(p, flags);
3938 if (s) RETURN_STATUS(s);
3940 if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
3942 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3943 bc_parse_push(p, *prev);
3945 RETURN_STATUS(zbc_lex_next(&p->l));
3947 #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
3949 static BC_STATUS zbc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3953 s = zbc_lex_next(&p->l);
3954 if (s) RETURN_STATUS(s);
3956 if (p->l.t.t != BC_LEX_LPAREN) {
3957 *type = BC_INST_SCALE;
3958 bc_parse_push(p, BC_INST_SCALE);
3959 RETURN_STATUS(BC_STATUS_SUCCESS);
3962 *type = BC_INST_SCALE_FUNC;
3963 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3965 s = zbc_lex_next(&p->l);
3966 if (s) RETURN_STATUS(s);
3968 s = zbc_parse_expr(p, flags);
3969 if (s) RETURN_STATUS(s);
3970 if (p->l.t.t != BC_LEX_RPAREN)
3971 RETURN_STATUS(bc_error_bad_token());
3972 bc_parse_push(p, BC_INST_SCALE_FUNC);
3974 RETURN_STATUS(zbc_lex_next(&p->l));
3976 #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
3978 static BC_STATUS zbc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3979 size_t *nexprs, uint8_t flags)
3984 BcInst etype = *prev;
3986 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM
3987 || etype == BC_INST_SCALE || etype == BC_INST_LAST
3988 || etype == BC_INST_IBASE || etype == BC_INST_OBASE
3990 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
3991 bc_parse_push(p, inst);
3992 s = zbc_lex_next(&p->l);
3994 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
3997 s = zbc_lex_next(&p->l);
3998 if (s) RETURN_STATUS(s);
4001 // Because we parse the next part of the expression
4002 // right here, we need to increment this.
4003 *nexprs = *nexprs + 1;
4007 s = zbc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4009 case BC_LEX_KEY_IBASE:
4010 case BC_LEX_KEY_LAST:
4011 case BC_LEX_KEY_OBASE:
4012 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4013 s = zbc_lex_next(&p->l);
4015 case BC_LEX_KEY_SCALE:
4016 s = zbc_lex_next(&p->l);
4017 if (s) RETURN_STATUS(s);
4018 if (p->l.t.t == BC_LEX_LPAREN)
4019 s = bc_error_bad_token();
4021 bc_parse_push(p, BC_INST_SCALE);
4024 s = bc_error_bad_token();
4028 if (!s) bc_parse_push(p, inst);
4033 #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
4035 static BC_STATUS zbc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4036 bool rparen, size_t *nexprs)
4040 BcInst etype = *prev;
4042 s = zbc_lex_next(&p->l);
4043 if (s) RETURN_STATUS(s);
4045 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4046 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4049 *prev = BC_TOKEN_2_INST(type);
4051 // We can just push onto the op stack because this is the largest
4052 // precedence operator that gets pushed. Inc/dec does not.
4053 if (type != BC_LEX_OP_MINUS)
4054 bc_vec_push(&p->ops, &type);
4056 bc_parse_operator(p, type, ops_bgn, nexprs);
4060 #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
4062 static BC_STATUS zbc_parse_print(BcParse *p)
4068 s = zbc_lex_next(&p->l);
4069 if (s) RETURN_STATUS(s);
4071 if (type == BC_LEX_STR) {
4072 s = zbc_parse_pushSTR(p);
4074 s = zbc_parse_expr(p, 0);
4076 if (s) RETURN_STATUS(s);
4077 bc_parse_push(p, BC_INST_PRINT_POP);
4078 if (p->l.t.t != BC_LEX_COMMA)
4084 #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
4086 static BC_STATUS zbc_parse_return(BcParse *p)
4091 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4092 s = zbc_lex_next(&p->l);
4093 if (s) RETURN_STATUS(s);
4096 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4097 bc_parse_push(p, BC_INST_RET0);
4099 bool paren = (t == BC_LEX_LPAREN);
4100 s = bc_parse_expr_empty_ok(p, 0);
4101 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4102 bc_parse_push(p, BC_INST_RET0);
4103 s = zbc_lex_next(&p->l);
4105 if (s) RETURN_STATUS(s);
4107 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
4108 s = bc_POSIX_requires("parentheses around return expressions");
4109 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s));
4112 bc_parse_push(p, BC_INST_RET);
4115 dbg_lex_done("%s:%d done", __func__, __LINE__);
4118 #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
4120 static void rewrite_label_to_current(BcParse *p, size_t idx)
4122 size_t *label = bc_vec_item(&p->func->labels, idx);
4123 *label = p->func->code.len;
4126 static BC_STATUS zbc_parse_if(BcParse *p)
4131 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4132 s = zbc_lex_next(&p->l);
4133 if (s) RETURN_STATUS(s);
4134 if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4136 s = zbc_lex_next(&p->l);
4137 if (s) RETURN_STATUS(s);
4138 s = zbc_parse_expr(p, BC_PARSE_REL);
4139 if (s) RETURN_STATUS(s);
4140 if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4142 // Encode "if zero, jump to ..."
4143 // Pushed value (destination of the jump) is uninitialized,
4144 // will be rewritten to be address of "end of if()" or of "else".
4145 ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
4146 bc_parse_pushJUMP_ZERO(p, ip_idx);
4148 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_if);
4149 if (s) RETURN_STATUS(s);
4151 dbg_lex("%s:%d in if after stmt: p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4152 if (p->l.t.t == BC_LEX_KEY_ELSE) {
4155 // Encode "after then_stmt, jump to end of if()"
4156 ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
4157 dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
4158 bc_parse_pushJUMP(p, ip2_idx);
4160 dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
4161 rewrite_label_to_current(p, ip_idx);
4165 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_else);
4166 if (s) RETURN_STATUS(s);
4169 dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
4170 rewrite_label_to_current(p, ip_idx);
4172 dbg_lex_done("%s:%d done", __func__, __LINE__);
4175 #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
4177 static BC_STATUS zbc_parse_while(BcParse *p)
4183 s = zbc_lex_next(&p->l);
4184 if (s) RETURN_STATUS(s);
4185 if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4186 s = zbc_lex_next(&p->l);
4187 if (s) RETURN_STATUS(s);
4189 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4190 ip_idx = cond_idx + 1;
4191 bc_vec_push(&p->conds, &cond_idx);
4193 bc_vec_push(&p->exits, &ip_idx);
4194 bc_vec_push(&p->func->labels, &ip_idx);
4196 s = zbc_parse_expr(p, BC_PARSE_REL);
4197 if (s) RETURN_STATUS(s);
4198 if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4200 bc_parse_pushJUMP_ZERO(p, ip_idx);
4202 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_while);
4203 if (s) RETURN_STATUS(s);
4205 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
4206 bc_parse_pushJUMP(p, cond_idx);
4208 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4209 rewrite_label_to_current(p, ip_idx);
4211 bc_vec_pop(&p->exits);
4212 bc_vec_pop(&p->conds);
4216 #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
4218 static BC_STATUS zbc_parse_for(BcParse *p)
4221 size_t cond_idx, exit_idx, body_idx, update_idx;
4223 dbg_lex("%s:%d p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4224 s = zbc_lex_next(&p->l);
4225 if (s) RETURN_STATUS(s);
4226 if (p->l.t.t != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
4227 s = zbc_lex_next(&p->l);
4228 if (s) RETURN_STATUS(s);
4230 if (p->l.t.t != BC_LEX_SCOLON) {
4231 s = zbc_parse_expr(p, 0);
4232 bc_parse_push(p, BC_INST_POP);
4233 if (s) RETURN_STATUS(s);
4235 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4236 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s);)
4239 if (p->l.t.t != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4240 s = zbc_lex_next(&p->l);
4241 if (s) RETURN_STATUS(s);
4243 cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
4244 update_idx = cond_idx + 1;
4245 body_idx = update_idx + 1;
4246 exit_idx = body_idx + 1;
4248 if (p->l.t.t != BC_LEX_SCOLON)
4249 s = zbc_parse_expr(p, BC_PARSE_REL);
4251 // Set this for the next call to bc_parse_pushNUM().
4252 // This is safe to set because the current token is a semicolon,
4253 // which has no string requirement.
4254 bc_vec_string(&p->l.t.v, 1, "1");
4255 bc_parse_pushNUM(p);
4256 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4258 if (s) RETURN_STATUS(s);
4260 if (p->l.t.t != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
4262 s = zbc_lex_next(&p->l);
4263 if (s) RETURN_STATUS(s);
4265 bc_parse_pushJUMP_ZERO(p, exit_idx);
4266 bc_parse_pushJUMP(p, body_idx);
4268 bc_vec_push(&p->conds, &update_idx);
4269 bc_vec_push(&p->func->labels, &p->func->code.len);
4271 if (p->l.t.t != BC_LEX_RPAREN) {
4272 s = zbc_parse_expr(p, 0);
4273 if (s) RETURN_STATUS(s);
4274 if (p->l.t.t != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
4275 bc_parse_push(p, BC_INST_POP);
4277 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4278 IF_ERROR_RETURN_POSSIBLE(if (s) RETURN_STATUS(s);)
4281 bc_parse_pushJUMP(p, cond_idx);
4282 bc_vec_push(&p->func->labels, &p->func->code.len);
4284 bc_vec_push(&p->exits, &exit_idx);
4285 bc_vec_push(&p->func->labels, &exit_idx);
4287 s = zbc_parse_stmt_allow_NLINE_before(p, STRING_for);
4288 if (s) RETURN_STATUS(s);
4290 dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
4291 bc_parse_pushJUMP(p, update_idx);
4293 dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
4294 rewrite_label_to_current(p, exit_idx);
4296 bc_vec_pop(&p->exits);
4297 bc_vec_pop(&p->conds);
4299 RETURN_STATUS(BC_STATUS_SUCCESS);
4301 #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
4303 static BC_STATUS zbc_parse_break_or_continue(BcParse *p, BcLexType type)
4308 if (type == BC_LEX_KEY_BREAK) {
4309 if (p->exits.len == 0) // none of the enclosing blocks is a loop
4310 RETURN_STATUS(bc_error_bad_token());
4311 i = *(size_t*)bc_vec_top(&p->exits);
4313 i = *(size_t*)bc_vec_top(&p->conds);
4316 bc_parse_pushJUMP(p, i);
4318 s = zbc_lex_next(&p->l);
4319 if (s) RETURN_STATUS(s);
4321 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
4322 RETURN_STATUS(bc_error_bad_token());
4324 RETURN_STATUS(zbc_lex_next(&p->l));
4326 #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
4328 static BC_STATUS zbc_parse_funcdef(BcParse *p)
4331 bool var, comma = false;
4334 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4335 s = zbc_lex_next(&p->l);
4336 if (s) RETURN_STATUS(s);
4337 if (p->l.t.t != BC_LEX_NAME)
4338 RETURN_STATUS(bc_error("bad function definition"));
4340 name = xstrdup(p->l.t.v.v);
4341 p->fidx = bc_program_addFunc(name);
4342 p->func = bc_program_func(p->fidx);
4344 s = zbc_lex_next(&p->l);
4345 if (s) RETURN_STATUS(s);
4346 if (p->l.t.t != BC_LEX_LPAREN)
4347 RETURN_STATUS(bc_error("bad function definition"));
4348 s = zbc_lex_next(&p->l);
4349 if (s) RETURN_STATUS(s);
4351 while (p->l.t.t != BC_LEX_RPAREN) {
4352 if (p->l.t.t != BC_LEX_NAME)
4353 RETURN_STATUS(bc_error("bad function definition"));
4357 name = xstrdup(p->l.t.v.v);
4358 s = zbc_lex_next(&p->l);
4361 var = p->l.t.t != BC_LEX_LBRACKET;
4364 s = zbc_lex_next(&p->l);
4367 if (p->l.t.t != BC_LEX_RBRACKET) {
4368 s = bc_error("bad function definition");
4372 s = zbc_lex_next(&p->l);
4376 comma = p->l.t.t == BC_LEX_COMMA;
4378 s = zbc_lex_next(&p->l);
4382 s = zbc_func_insert(p->func, name, var);
4386 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4388 s = zbc_lex_next(&p->l);
4389 if (s) RETURN_STATUS(s);
4391 if (p->l.t.t != BC_LEX_LBRACE)
4392 s = bc_POSIX_requires("the left brace be on the same line as the function header");
4394 // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
4395 s = zbc_lex_skip_if_at_NLINE(&p->l);
4396 if (s) RETURN_STATUS(s);
4397 //GNU bc requires a {} block even if function body has single stmt, enforce this?
4398 if (p->l.t.t != BC_LEX_LBRACE)
4399 RETURN_STATUS(bc_error("function { body } expected"));
4401 p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
4402 s = zbc_parse_stmt_possibly_auto(p, true);
4404 if (s) RETURN_STATUS(s);
4406 bc_parse_push(p, BC_INST_RET0);
4408 // Subsequent code generation is into main program
4409 p->fidx = BC_PROG_MAIN;
4410 p->func = bc_program_func_BC_PROG_MAIN();
4412 dbg_lex_done("%s:%d done", __func__, __LINE__);
4415 dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
4419 #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4421 static BC_STATUS zbc_parse_auto(BcParse *p)
4424 bool comma, var, one;
4427 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4428 s = zbc_lex_next(&p->l);
4429 if (s) RETURN_STATUS(s);
4432 one = p->l.t.t == BC_LEX_NAME;
4434 while (p->l.t.t == BC_LEX_NAME) {
4435 name = xstrdup(p->l.t.v.v);
4436 s = zbc_lex_next(&p->l);
4439 var = p->l.t.t != BC_LEX_LBRACKET;
4441 s = zbc_lex_next(&p->l);
4444 if (p->l.t.t != BC_LEX_RBRACKET) {
4445 s = bc_error("bad function definition");
4449 s = zbc_lex_next(&p->l);
4453 comma = p->l.t.t == BC_LEX_COMMA;
4455 s = zbc_lex_next(&p->l);
4459 s = zbc_func_insert(p->func, name, var);
4463 if (comma) RETURN_STATUS(bc_error("bad function definition"));
4464 if (!one) RETURN_STATUS(bc_error("no auto variable found"));
4466 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
4467 RETURN_STATUS(bc_error_bad_token());
4469 dbg_lex_done("%s:%d done", __func__, __LINE__);
4470 RETURN_STATUS(zbc_lex_next(&p->l));
4473 dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
4476 #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
4478 #undef zbc_parse_stmt_possibly_auto
4479 static BC_STATUS zbc_parse_stmt_possibly_auto(BcParse *p, bool auto_allowed)
4481 BcStatus s = BC_STATUS_SUCCESS;
4483 dbg_lex_enter("%s:%d entered, p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4485 if (p->l.t.t == BC_LEX_NLINE) {
4486 dbg_lex_done("%s:%d done (seen BC_LEX_NLINE)", __func__, __LINE__);
4487 RETURN_STATUS(zbc_lex_next(&p->l));
4489 if (p->l.t.t == BC_LEX_SCOLON) {
4490 dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
4491 RETURN_STATUS(zbc_lex_next(&p->l));
4494 if (p->l.t.t == BC_LEX_LBRACE) {
4495 dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
4497 s = zbc_lex_next(&p->l);
4498 if (s) RETURN_STATUS(s);
4499 } while (p->l.t.t == BC_LEX_NLINE);
4500 if (auto_allowed && p->l.t.t == BC_LEX_KEY_AUTO) {
4501 dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
4502 s = zbc_parse_auto(p);
4503 if (s) RETURN_STATUS(s);
4505 while (p->l.t.t != BC_LEX_RBRACE) {
4506 dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
4507 s = zbc_parse_stmt(p);
4508 if (s) RETURN_STATUS(s);
4510 s = zbc_lex_next(&p->l);
4511 dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
4515 dbg_lex("%s:%d p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4519 case BC_LEX_OP_MINUS:
4520 case BC_LEX_OP_BOOL_NOT:
4524 case BC_LEX_KEY_IBASE:
4525 case BC_LEX_KEY_LAST:
4526 case BC_LEX_KEY_LENGTH:
4527 case BC_LEX_KEY_OBASE:
4528 case BC_LEX_KEY_READ:
4529 case BC_LEX_KEY_SCALE:
4530 case BC_LEX_KEY_SQRT:
4531 s = zbc_parse_expr(p, BC_PARSE_PRINT);
4534 s = zbc_parse_pushSTR(p);
4535 bc_parse_push(p, BC_INST_PRINT_STR);
4537 case BC_LEX_KEY_BREAK:
4538 case BC_LEX_KEY_CONTINUE:
4539 s = zbc_parse_break_or_continue(p, p->l.t.t);
4541 case BC_LEX_KEY_FOR:
4542 s = zbc_parse_for(p);
4544 case BC_LEX_KEY_HALT:
4545 bc_parse_push(p, BC_INST_HALT);
4546 s = zbc_lex_next(&p->l);
4549 s = zbc_parse_if(p);
4551 case BC_LEX_KEY_LIMITS:
4552 // "limits" is a compile-time command,
4553 // the output is produced at _parse time_.
4555 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4556 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4557 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4558 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4559 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4560 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4561 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4562 "Number of vars = "BC_MAX_VARS_STR "\n"
4564 s = zbc_lex_next(&p->l);
4566 case BC_LEX_KEY_PRINT:
4567 s = zbc_parse_print(p);
4569 case BC_LEX_KEY_QUIT:
4570 // "quit" is a compile-time command. For example,
4571 // "if (0 == 1) quit" terminates when parsing the statement,
4572 // not when it is executed
4573 QUIT_OR_RETURN_TO_MAIN;
4574 case BC_LEX_KEY_RETURN:
4576 RETURN_STATUS(bc_error("'return' not in a function"));
4577 s = zbc_parse_return(p);
4579 case BC_LEX_KEY_WHILE:
4580 s = zbc_parse_while(p);
4583 s = bc_error_bad_token();
4587 dbg_lex_done("%s:%d done", __func__, __LINE__);
4590 #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
4592 static BC_STATUS zbc_parse_stmt_or_funcdef(BcParse *p)
4596 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4597 if (p->l.t.t == BC_LEX_EOF)
4598 s = bc_error("end of file");
4599 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
4600 dbg_lex("%s:%d p->l.t.t:BC_LEX_KEY_DEFINE", __func__, __LINE__);
4601 s = zbc_parse_funcdef(p);
4603 dbg_lex("%s:%d p->l.t.t:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->l.t.t);
4604 s = zbc_parse_stmt(p);
4607 dbg_lex_done("%s:%d done", __func__, __LINE__);
4610 #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
4612 // This is not a "z" function: can also return BC_STATUS_PARSE_EMPTY_EXP
4613 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags)
4615 BcStatus s = BC_STATUS_SUCCESS;
4616 BcInst prev = BC_INST_PRINT;
4617 BcLexType top, t = p->l.t.t;
4618 size_t nexprs = 0, ops_bgn = p->ops.len;
4619 unsigned nparens, nrelops;
4620 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4622 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4623 paren_first = p->l.t.t == BC_LEX_LPAREN;
4624 nparens = nrelops = 0;
4625 paren_expr = rprn = done = get_token = assign = false;
4628 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
4629 dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
4633 s = zbc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4634 rprn = get_token = bin_last = false;
4636 case BC_LEX_OP_MINUS:
4637 s = zbc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4638 rprn = get_token = false;
4639 bin_last = prev == BC_INST_MINUS;
4641 case BC_LEX_OP_ASSIGN_POWER:
4642 case BC_LEX_OP_ASSIGN_MULTIPLY:
4643 case BC_LEX_OP_ASSIGN_DIVIDE:
4644 case BC_LEX_OP_ASSIGN_MODULUS:
4645 case BC_LEX_OP_ASSIGN_PLUS:
4646 case BC_LEX_OP_ASSIGN_MINUS:
4647 case BC_LEX_OP_ASSIGN:
4648 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM
4649 && prev != BC_INST_SCALE && prev != BC_INST_IBASE
4650 && prev != BC_INST_OBASE && prev != BC_INST_LAST
4652 s = bc_error("bad assignment:"
4653 " left side must be variable"
4655 ); // note: shared string
4659 case BC_LEX_OP_POWER:
4660 case BC_LEX_OP_MULTIPLY:
4661 case BC_LEX_OP_DIVIDE:
4662 case BC_LEX_OP_MODULUS:
4663 case BC_LEX_OP_PLUS:
4664 case BC_LEX_OP_REL_EQ:
4665 case BC_LEX_OP_REL_LE:
4666 case BC_LEX_OP_REL_GE:
4667 case BC_LEX_OP_REL_NE:
4668 case BC_LEX_OP_REL_LT:
4669 case BC_LEX_OP_REL_GT:
4670 case BC_LEX_OP_BOOL_NOT:
4671 case BC_LEX_OP_BOOL_OR:
4672 case BC_LEX_OP_BOOL_AND:
4673 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4674 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4676 return bc_error_bad_expression();
4678 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4679 prev = BC_TOKEN_2_INST(t);
4680 bc_parse_operator(p, t, ops_bgn, &nexprs);
4681 s = zbc_lex_next(&p->l);
4682 rprn = get_token = false;
4683 bin_last = t != BC_LEX_OP_BOOL_NOT;
4686 if (BC_PARSE_LEAF(prev, rprn))
4687 return bc_error_bad_expression();
4689 paren_expr = rprn = bin_last = false;
4691 bc_vec_push(&p->ops, &t);
4694 if (bin_last || prev == BC_INST_BOOL_NOT)
4695 return bc_error_bad_expression();
4697 s = BC_STATUS_SUCCESS;
4703 dbg_lex_done("%s:%d done (returning EMPTY_EXP)", __func__, __LINE__);
4704 return BC_STATUS_PARSE_EMPTY_EXP;
4707 paren_expr = rprn = true;
4708 get_token = bin_last = false;
4709 s = zbc_parse_rightParen(p, ops_bgn, &nexprs);
4712 if (BC_PARSE_LEAF(prev, rprn))
4713 return bc_error_bad_expression();
4715 rprn = get_token = bin_last = false;
4716 s = zbc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4720 if (BC_PARSE_LEAF(prev, rprn))
4721 return bc_error_bad_expression();
4722 bc_parse_pushNUM(p);
4725 paren_expr = get_token = true;
4726 rprn = bin_last = false;
4728 case BC_LEX_KEY_IBASE:
4729 case BC_LEX_KEY_LAST:
4730 case BC_LEX_KEY_OBASE:
4731 if (BC_PARSE_LEAF(prev, rprn))
4732 return bc_error_bad_expression();
4733 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4734 bc_parse_push(p, (char) prev);
4735 paren_expr = get_token = true;
4736 rprn = bin_last = false;
4739 case BC_LEX_KEY_LENGTH:
4740 case BC_LEX_KEY_SQRT:
4741 if (BC_PARSE_LEAF(prev, rprn))
4742 return bc_error_bad_expression();
4743 s = zbc_parse_builtin(p, t, flags, &prev);
4745 rprn = get_token = bin_last = false;
4748 case BC_LEX_KEY_READ:
4749 if (BC_PARSE_LEAF(prev, rprn))
4750 return bc_error_bad_expression();
4752 s = zbc_parse_read(p);
4754 rprn = get_token = bin_last = false;
4756 prev = BC_INST_READ;
4758 case BC_LEX_KEY_SCALE:
4759 if (BC_PARSE_LEAF(prev, rprn))
4760 return bc_error_bad_expression();
4761 s = zbc_parse_scale(p, &prev, flags);
4763 rprn = get_token = bin_last = false;
4765 prev = BC_INST_SCALE;
4768 s = bc_error_bad_token();
4772 if (!s && get_token) s = zbc_lex_next(&p->l);
4776 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
4778 while (p->ops.len > ops_bgn) {
4779 top = BC_PARSE_TOP_OP(p);
4780 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
4782 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4783 return bc_error_bad_expression();
4785 bc_parse_push(p, BC_TOKEN_2_INST(top));
4787 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
4788 bc_vec_pop(&p->ops);
4791 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
4792 return bc_error_bad_expression();
4794 if (!(flags & BC_PARSE_REL) && nrelops) {
4795 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
4796 IF_ERROR_RETURN_POSSIBLE(if (s) return s);
4797 } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4798 s = bc_POSIX_requires("exactly one comparison operator per condition");
4799 IF_ERROR_RETURN_POSSIBLE(if (s) return s);
4802 if (flags & BC_PARSE_PRINT) {
4803 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
4804 bc_parse_push(p, BC_INST_POP);
4807 dbg_lex_done("%s:%d done", __func__, __LINE__);
4815 static BC_STATUS zdc_parse_register(BcParse *p)
4819 s = zbc_lex_next(&p->l);
4820 if (s) RETURN_STATUS(s);
4821 if (p->l.t.t != BC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
4823 bc_parse_pushName(p, p->l.t.v.v);
4827 #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
4829 static void dc_parse_string(BcParse *p)
4832 size_t len = G.prog.strs.len;
4834 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4836 str = xstrdup(p->l.t.v.v);
4837 bc_parse_push(p, BC_INST_STR);
4838 bc_parse_pushIndex(p, len);
4839 bc_vec_push(&G.prog.strs, &str);
4841 // Explanation needed here
4842 bc_program_add_fn();
4843 p->func = bc_program_func(p->fidx);
4845 dbg_lex_done("%s:%d done", __func__, __LINE__);
4848 static BC_STATUS zdc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
4852 bc_parse_push(p, inst);
4854 s = zdc_parse_register(p);
4855 if (s) RETURN_STATUS(s);
4859 bc_parse_push(p, BC_INST_SWAP);
4860 bc_parse_push(p, BC_INST_ASSIGN);
4861 bc_parse_push(p, BC_INST_POP);
4864 RETURN_STATUS(BC_STATUS_SUCCESS);
4866 #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
4868 static BC_STATUS zdc_parse_cond(BcParse *p, uint8_t inst)
4872 bc_parse_push(p, inst);
4873 bc_parse_push(p, BC_INST_EXEC_COND);
4875 s = zdc_parse_register(p);
4876 if (s) RETURN_STATUS(s);
4878 s = zbc_lex_next(&p->l);
4879 if (s) RETURN_STATUS(s);
4881 // Note that 'else' part can not be on the next line:
4882 // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
4883 // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
4884 if (p->l.t.t == BC_LEX_ELSE) {
4885 s = zdc_parse_register(p);
4886 if (s) RETURN_STATUS(s);
4887 s = zbc_lex_next(&p->l);
4889 bc_parse_push(p, BC_PARSE_STREND);
4894 #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
4896 static BC_STATUS zdc_parse_token(BcParse *p, BcLexType t)
4900 bool assign, get_token;
4902 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
4903 s = BC_STATUS_SUCCESS;
4906 case BC_LEX_OP_REL_EQ:
4907 case BC_LEX_OP_REL_LE:
4908 case BC_LEX_OP_REL_GE:
4909 case BC_LEX_OP_REL_NE:
4910 case BC_LEX_OP_REL_LT:
4911 case BC_LEX_OP_REL_GT:
4912 s = zdc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
4917 s = zdc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
4920 dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
4925 dbg_lex("%s:%d LEX_NEG/NUMBER", __func__, __LINE__);
4926 if (t == BC_LEX_NEG) {
4927 s = zbc_lex_next(&p->l);
4928 if (s) RETURN_STATUS(s);
4929 if (p->l.t.t != BC_LEX_NUMBER)
4930 RETURN_STATUS(bc_error_bad_token());
4932 bc_parse_pushNUM(p);
4933 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
4935 case BC_LEX_KEY_READ:
4936 bc_parse_push(p, BC_INST_READ);
4938 case BC_LEX_OP_ASSIGN:
4939 case BC_LEX_STORE_PUSH:
4940 assign = t == BC_LEX_OP_ASSIGN;
4941 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
4942 s = zdc_parse_mem(p, inst, true, assign);
4945 case BC_LEX_LOAD_POP:
4946 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
4947 s = zdc_parse_mem(p, inst, true, false);
4949 case BC_LEX_STORE_IBASE:
4950 case BC_LEX_STORE_SCALE:
4951 case BC_LEX_STORE_OBASE:
4952 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
4953 s = zdc_parse_mem(p, inst, false, true);
4956 dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
4957 RETURN_STATUS(bc_error_bad_token());
4960 if (!s && get_token) s = zbc_lex_next(&p->l);
4962 dbg_lex_done("%s:%d done", __func__, __LINE__);
4965 #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
4967 static BC_STATUS zdc_parse_expr(BcParse *p)
4972 inst = dc_parse_insts[p->l.t.t];
4973 if (inst != BC_INST_INVALID) {
4974 bc_parse_push(p, inst);
4975 s = zbc_lex_next(&p->l);
4977 s = zdc_parse_token(p, p->l.t.t);
4981 #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
4983 static BC_STATUS zdc_parse_exprs_until_eof(BcParse *p)
4985 dbg_lex_enter("%s:%d entered, p->l.t.t:%d", __func__, __LINE__, p->l.t.t);
4986 while (p->l.t.t != BC_LEX_EOF) {
4987 BcStatus s = zdc_parse_expr(p);
4988 if (s) RETURN_STATUS(s);
4991 dbg_lex_done("%s:%d done", __func__, __LINE__);
4992 RETURN_STATUS(BC_STATUS_SUCCESS);
4994 #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
4998 static BcVec* bc_program_search(char *id, bool var)
5005 v = var ? &G.prog.vars : &G.prog.arrs;
5006 map = var ? &G.prog.var_map : &G.prog.arr_map;
5010 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5014 bc_array_init(&v2, var);
5015 bc_vec_push(v, &v2);
5018 ptr = bc_vec_item(map, i);
5019 if (new) ptr->name = xstrdup(e.name);
5020 return bc_vec_item(v, ptr->idx);
5023 // 'num' need not be initialized on entry
5024 static BC_STATUS zbc_program_num(BcResult *r, BcNum **num, bool hex)
5028 case BC_RESULT_TEMP:
5029 case BC_RESULT_IBASE:
5030 case BC_RESULT_SCALE:
5031 case BC_RESULT_OBASE:
5034 case BC_RESULT_CONSTANT: {
5040 str = *bc_program_const(r->d.id.idx);
5043 bc_num_init(&r->d.n, len);
5045 hex = hex && len == 1;
5046 base_t = hex ? 16 : G.prog.ib_t;
5047 s = zbc_num_parse(&r->d.n, str, base_t);
5049 bc_num_free(&r->d.n);
5053 r->t = BC_RESULT_TEMP;
5057 case BC_RESULT_ARRAY:
5058 case BC_RESULT_ARRAY_ELEM: {
5061 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
5063 if (r->t == BC_RESULT_ARRAY_ELEM) {
5065 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5066 *num = bc_vec_item(v, r->d.id.idx);
5068 *num = bc_vec_top(v);
5072 case BC_RESULT_LAST:
5073 *num = &G.prog.last;
5080 // Testing the theory that dc does not reach LAST/ONE
5081 bb_error_msg_and_die("BUG:%d", r->t);
5084 RETURN_STATUS(BC_STATUS_SUCCESS);
5086 #define zbc_program_num(...) (zbc_program_num(__VA_ARGS__) COMMA_SUCCESS)
5088 static BC_STATUS zbc_program_binOpPrep(BcResult **l, BcNum **ln,
5089 BcResult **r, BcNum **rn, bool assign)
5093 BcResultType lt, rt;
5095 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5096 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5098 *r = bc_vec_item_rev(&G.prog.results, 0);
5099 *l = bc_vec_item_rev(&G.prog.results, 1);
5103 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5105 s = zbc_program_num(*l, ln, false);
5106 if (s) RETURN_STATUS(s);
5107 s = zbc_program_num(*r, rn, hex);
5108 if (s) RETURN_STATUS(s);
5110 // We run this again under these conditions in case any vector has been
5111 // reallocated out from under the BcNums or arrays we had.
5112 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
5113 s = zbc_program_num(*l, ln, false);
5114 if (s) RETURN_STATUS(s);
5117 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
5118 RETURN_STATUS(bc_error_variable_is_wrong_type());
5119 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5120 RETURN_STATUS(bc_error_variable_is_wrong_type());
5124 #define zbc_program_binOpPrep(...) (zbc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
5126 static void bc_program_binOpRetire(BcResult *r)
5128 r->t = BC_RESULT_TEMP;
5129 bc_vec_pop(&G.prog.results);
5130 bc_result_pop_and_push(r);
5133 static BC_STATUS zbc_program_prep(BcResult **r, BcNum **n)
5137 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5138 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5139 *r = bc_vec_top(&G.prog.results);
5141 s = zbc_program_num(*r, n, false);
5142 if (s) RETURN_STATUS(s);
5144 if (!BC_PROG_NUM((*r), (*n)))
5145 RETURN_STATUS(bc_error_variable_is_wrong_type());
5149 #define zbc_program_prep(...) (zbc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
5151 static void bc_program_retire(BcResult *r, BcResultType t)
5154 bc_result_pop_and_push(r);
5157 static BC_STATUS zbc_program_op(char inst)
5160 BcResult *opd1, *opd2, res;
5161 BcNum *n1, *n2 = NULL;
5163 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5164 if (s) RETURN_STATUS(s);
5165 bc_num_init_DEF_SIZE(&res.d.n);
5167 s = BC_STATUS_SUCCESS;
5168 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5170 bc_program_binOpRetire(&res);
5174 bc_num_free(&res.d.n);
5177 #define zbc_program_op(...) (zbc_program_op(__VA_ARGS__) COMMA_SUCCESS)
5179 static BC_STATUS zbc_program_read(void)
5181 const char *sv_file;
5188 f = bc_program_func(BC_PROG_READ);
5189 bc_vec_pop_all(&f->code);
5191 sv_file = G.prog.file;
5194 bc_char_vec_init(&buf);
5195 bc_read_line(&buf, stdin);
5197 bc_parse_create(&parse, BC_PROG_READ);
5198 bc_lex_file(&parse.l);
5200 s = zbc_parse_text_init(&parse, buf.v);
5201 if (s) goto exec_err;
5203 IF_BC(s = zbc_parse_expr(&parse, 0));
5205 IF_DC(s = zdc_parse_exprs_until_eof(&parse));
5207 if (s) goto exec_err;
5209 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
5210 s = bc_error("bad read() expression");
5214 ip.func = BC_PROG_READ;
5216 IF_BC(ip.results_len_before_call = G.prog.results.len;)
5218 bc_parse_push(&parse, BC_INST_RET);
5219 bc_vec_push(&G.prog.exestack, &ip);
5221 bc_parse_free(&parse);
5222 G.prog.file = sv_file;
5226 #define zbc_program_read(...) (zbc_program_read(__VA_ARGS__) COMMA_SUCCESS)
5228 static size_t bc_program_index(char *code, size_t *bgn)
5230 unsigned char *bytes = (void*)(code + *bgn);
5240 for (i = 0; i < amt; i += 8)
5241 res |= (size_t)(*bytes++) << i;
5246 static char *bc_program_name(char *code, size_t *bgn)
5252 s = xmalloc(strchr(code, BC_PARSE_STREND) - code + 1);
5256 if (c == BC_PARSE_STREND)
5266 static void bc_program_printString(const char *str)
5270 // Example: echo '[]ap' | dc
5271 // should print two bytes: 0x00, 0x0A
5278 if (c != '\\' || !*str)
5298 G.prog.nchars = SIZE_MAX;
5310 // Just print the backslash and following character.
5321 static void bc_num_printNewline(void)
5323 if (G.prog.nchars == G.prog.len - 1) {
5331 static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
5334 bb_putchar((char) num);
5335 G.prog.nchars += width;
5339 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
5343 bc_num_printNewline();
5344 bb_putchar(radix ? '.' : ' ');
5347 bc_num_printNewline();
5348 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
5351 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
5353 bc_num_printNewline();
5356 bb_putchar(((char) dig) + '0');
5360 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
5363 bc_num_printNewline();
5368 bc_num_printNewline();
5369 bb_putchar(bb_hexdigits_upcase[num]);
5370 G.prog.nchars += width;
5373 static void bc_num_printDecimal(BcNum *n)
5375 size_t i, rdx = n->rdx - 1;
5382 for (i = n->len - 1; i < n->len; --i)
5383 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
5386 static BC_STATUS zbc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
5391 BcDig base_digs[ULONG_NUM_BUFSIZE];
5392 BcNum intp, fracp, digit, frac_len;
5393 unsigned long dig, *ptr;
5398 print(0, width, false);
5399 RETURN_STATUS(BC_STATUS_SUCCESS);
5402 bc_vec_init(&stack, sizeof(long), NULL);
5403 bc_num_init(&intp, n->len);
5404 bc_num_init(&fracp, n->rdx);
5405 bc_num_init(&digit, width);
5406 bc_num_init(&frac_len, BC_NUM_INT(n));
5407 bc_num_copy(&intp, n);
5408 bc_num_one(&frac_len);
5409 base.cap = ARRAY_SIZE(base_digs);
5410 base.num = base_digs;
5411 bc_num_ulong2num(&base, base_t);
5413 bc_num_truncate(&intp, intp.rdx);
5414 s = zbc_num_sub(n, &intp, &fracp, 0);
5417 while (intp.len != 0) {
5418 s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
5420 s = zbc_num_ulong(&digit, &dig);
5422 bc_vec_push(&stack, &dig);
5425 for (i = 0; i < stack.len; ++i) {
5426 ptr = bc_vec_item_rev(&stack, i);
5427 print(*ptr, width, false);
5430 if (!n->rdx) goto err;
5432 for (radix = true; frac_len.len <= n->rdx; radix = false) {
5433 s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
5435 s = zbc_num_ulong(&fracp, &dig);
5437 bc_num_ulong2num(&intp, dig);
5438 s = zbc_num_sub(&fracp, &intp, &fracp, 0);
5440 print(dig, width, radix);
5441 s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
5445 bc_num_free(&frac_len);
5446 bc_num_free(&digit);
5447 bc_num_free(&fracp);
5449 bc_vec_free(&stack);
5452 #define zbc_num_printNum(...) (zbc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
5454 static BC_STATUS zbc_num_printBase(BcNum *n)
5468 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
5470 print = bc_num_printHex;
5472 unsigned i = G.prog.ob_t - 1;
5480 print = bc_num_printDigits;
5483 s = zbc_num_printNum(n, G.prog.ob_t, width, print);
5488 #define zbc_num_printBase(...) (zbc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
5490 static BC_STATUS zbc_num_print(BcNum *n, bool newline)
5492 BcStatus s = BC_STATUS_SUCCESS;
5494 bc_num_printNewline();
5499 } else if (G.prog.ob_t == 10)
5500 bc_num_printDecimal(n);
5502 s = zbc_num_printBase(n);
5511 #define zbc_num_print(...) (zbc_num_print(__VA_ARGS__) COMMA_SUCCESS)
5513 static BC_STATUS zbc_program_print(char inst, size_t idx)
5518 bool pop = inst != BC_INST_PRINT;
5520 if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
5521 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5523 r = bc_vec_item_rev(&G.prog.results, idx);
5524 s = zbc_program_num(r, &num, false);
5525 if (s) RETURN_STATUS(s);
5527 if (BC_PROG_NUM(r, num)) {
5528 s = zbc_num_print(num, !pop);
5530 if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
5535 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
5536 str = *bc_program_str(idx);
5538 if (inst == BC_INST_PRINT_STR) {
5541 if (c == '\0') break;
5544 if (c == '\n') G.prog.nchars = 0;
5547 bc_program_printString(str);
5548 if (inst == BC_INST_PRINT) bb_putchar('\n');
5552 if (!s && pop) bc_vec_pop(&G.prog.results);
5556 #define zbc_program_print(...) (zbc_program_print(__VA_ARGS__) COMMA_SUCCESS)
5558 static BC_STATUS zbc_program_negate(void)
5564 s = zbc_program_prep(&ptr, &num);
5565 if (s) RETURN_STATUS(s);
5567 bc_num_init(&res.d.n, num->len);
5568 bc_num_copy(&res.d.n, num);
5569 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5571 bc_program_retire(&res, BC_RESULT_TEMP);
5575 #define zbc_program_negate(...) (zbc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
5577 static BC_STATUS zbc_program_logical(char inst)
5580 BcResult *opd1, *opd2, res;
5584 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5585 if (s) RETURN_STATUS(s);
5587 bc_num_init_DEF_SIZE(&res.d.n);
5589 if (inst == BC_INST_BOOL_AND)
5590 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5591 else if (inst == BC_INST_BOOL_OR)
5592 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5594 cond = bc_num_cmp(n1, n2);
5596 case BC_INST_REL_EQ:
5599 case BC_INST_REL_LE:
5602 case BC_INST_REL_GE:
5605 case BC_INST_REL_LT:
5608 case BC_INST_REL_GT:
5611 default: // = case BC_INST_REL_NE:
5612 //cond = (cond != 0); - not needed
5617 if (cond) bc_num_one(&res.d.n);
5618 //else bc_num_zero(&res.d.n); - already is
5620 bc_program_binOpRetire(&res);
5624 #define zbc_program_logical(...) (zbc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
5627 static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
5632 memset(&n2, 0, sizeof(BcNum));
5633 n2.rdx = res.d.id.idx = r->d.id.idx;
5634 res.t = BC_RESULT_STR;
5637 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
5638 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5640 bc_vec_pop(&G.prog.results);
5643 bc_result_pop_and_push(&res);
5644 bc_vec_push(v, &n2);
5646 RETURN_STATUS(BC_STATUS_SUCCESS);
5648 #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
5651 static BC_STATUS zbc_program_copyToVar(char *name, bool var)
5658 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
5659 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5661 ptr = bc_vec_top(&G.prog.results);
5662 if ((ptr->t == BC_RESULT_ARRAY) != !var)
5663 RETURN_STATUS(bc_error_variable_is_wrong_type());
5664 v = bc_program_search(name, var);
5667 if (ptr->t == BC_RESULT_STR && !var)
5668 RETURN_STATUS(bc_error_variable_is_wrong_type());
5669 if (ptr->t == BC_RESULT_STR)
5670 RETURN_STATUS(zdc_program_assignStr(ptr, v, true));
5673 s = zbc_program_num(ptr, &n, false);
5674 if (s) RETURN_STATUS(s);
5676 // Do this once more to make sure that pointers were not invalidated.
5677 v = bc_program_search(name, var);
5680 bc_num_init_DEF_SIZE(&r.d.n);
5681 bc_num_copy(&r.d.n, n);
5683 bc_array_init(&r.d.v, true);
5684 bc_array_copy(&r.d.v, (BcVec *) n);
5687 bc_vec_push(v, &r.d);
5688 bc_vec_pop(&G.prog.results);
5692 #define zbc_program_copyToVar(...) (zbc_program_copyToVar(__VA_ARGS__) COMMA_SUCCESS)
5694 static BC_STATUS zbc_program_assign(char inst)
5697 BcResult *left, *right, res;
5698 BcNum *l = NULL, *r = NULL;
5699 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5701 s = zbc_program_binOpPrep(&left, &l, &right, &r, assign);
5702 if (s) RETURN_STATUS(s);
5704 ib = left->t == BC_RESULT_IBASE;
5705 sc = left->t == BC_RESULT_SCALE;
5708 if (right->t == BC_RESULT_STR) {
5711 if (left->t != BC_RESULT_VAR)
5712 RETURN_STATUS(bc_error_variable_is_wrong_type());
5713 v = bc_program_search(left->d.id.name, true);
5715 RETURN_STATUS(zdc_program_assignStr(right, v, false));
5719 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
5720 RETURN_STATUS(bc_error("bad assignment:"
5721 " left side must be variable"
5723 )); // note: shared string
5726 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5727 RETURN_STATUS(bc_error("divide by zero"));
5732 s = BC_STATUS_SUCCESS;
5733 IF_ERROR_RETURN_POSSIBLE(s =) zbc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5735 if (s) RETURN_STATUS(s);
5740 if (ib || sc || left->t == BC_RESULT_OBASE) {
5741 static const char *const msg[] = {
5742 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5743 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5744 NULL, //can't happen //BC_RESULT_LAST
5745 NULL, //can't happen //BC_RESULT_CONSTANT
5746 NULL, //can't happen //BC_RESULT_ONE
5747 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
5753 s = zbc_num_ulong(l, &val);
5754 if (s) RETURN_STATUS(s);
5755 s = left->t - BC_RESULT_IBASE;
5758 ptr = &G.prog.scale;
5761 RETURN_STATUS(bc_error(msg[s]));
5762 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5763 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5767 RETURN_STATUS(bc_error(msg[s]));
5769 *ptr = (size_t) val;
5770 s = BC_STATUS_SUCCESS;
5773 bc_num_init(&res.d.n, l->len);
5774 bc_num_copy(&res.d.n, l);
5775 bc_program_binOpRetire(&res);
5779 #define zbc_program_assign(...) (zbc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
5782 #define bc_program_pushVar(code, bgn, pop, copy) \
5783 bc_program_pushVar(code, bgn)
5784 // for bc, 'pop' and 'copy' are always false
5786 static BC_STATUS bc_program_pushVar(char *code, size_t *bgn,
5787 bool pop, bool copy)
5790 char *name = bc_program_name(code, bgn);
5792 r.t = BC_RESULT_VAR;
5797 BcVec *v = bc_program_search(name, true);
5798 BcNum *num = bc_vec_top(v);
5801 if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
5802 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5805 if (!BC_PROG_STR(num)) {
5806 r.t = BC_RESULT_TEMP;
5807 bc_num_init_DEF_SIZE(&r.d.n);
5808 bc_num_copy(&r.d.n, num);
5810 r.t = BC_RESULT_STR;
5811 r.d.id.idx = num->rdx;
5814 if (!copy) bc_vec_pop(v);
5818 bc_vec_push(&G.prog.results, &r);
5820 RETURN_STATUS(BC_STATUS_SUCCESS);
5822 #define zbc_program_pushVar(...) (bc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
5824 static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
5826 BcStatus s = BC_STATUS_SUCCESS;
5830 r.d.id.name = bc_program_name(code, bgn);
5832 if (inst == BC_INST_ARRAY) {
5833 r.t = BC_RESULT_ARRAY;
5834 bc_vec_push(&G.prog.results, &r);
5839 s = zbc_program_prep(&operand, &num);
5841 s = zbc_num_ulong(num, &temp);
5844 if (temp > BC_MAX_DIM) {
5845 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
5849 r.d.id.idx = (size_t) temp;
5850 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
5853 if (s) free(r.d.id.name);
5856 #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
5859 static BC_STATUS zbc_program_incdec(char inst)
5862 BcResult *ptr, res, copy;
5866 s = zbc_program_prep(&ptr, &num);
5867 if (s) RETURN_STATUS(s);
5869 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5870 copy.t = BC_RESULT_TEMP;
5871 bc_num_init(©.d.n, num->len);
5872 bc_num_copy(©.d.n, num);
5875 res.t = BC_RESULT_ONE;
5876 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
5877 BC_INST_ASSIGN_PLUS :
5878 BC_INST_ASSIGN_MINUS;
5880 bc_vec_push(&G.prog.results, &res);
5881 s = zbc_program_assign(inst);
5882 if (s) RETURN_STATUS(s);
5884 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5885 bc_result_pop_and_push(©);
5890 #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
5892 static BC_STATUS zbc_program_call(char *code, size_t *idx)
5900 nparams = bc_program_index(code, idx);
5902 ip.func = bc_program_index(code, idx);
5903 func = bc_program_func(ip.func);
5905 if (func->code.len == 0) {
5906 RETURN_STATUS(bc_error("undefined function"));
5908 if (nparams != func->nparams) {
5909 RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
5911 ip.results_len_before_call = G.prog.results.len - nparams;
5913 for (i = 0; i < nparams; ++i) {
5916 a = bc_vec_item(&func->autos, nparams - 1 - i);
5917 arg = bc_vec_top(&G.prog.results);
5919 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
5920 RETURN_STATUS(bc_error_variable_is_wrong_type());
5922 s = zbc_program_copyToVar(a->name, a->idx);
5923 if (s) RETURN_STATUS(s);
5926 a = bc_vec_item(&func->autos, i);
5927 for (; i < func->autos.len; i++, a++) {
5930 v = bc_program_search(a->name, a->idx);
5933 bc_num_init_DEF_SIZE(&n2);
5934 bc_vec_push(v, &n2);
5937 bc_array_init(&v2, true);
5938 bc_vec_push(v, &v2);
5942 bc_vec_push(&G.prog.exestack, &ip);
5944 RETURN_STATUS(BC_STATUS_SUCCESS);
5946 #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
5948 static BC_STATUS zbc_program_return(char inst)
5954 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
5956 if (!STACK_HAS_EQUAL_OR_MORE_THAN(&G.prog.results, ip->results_len_before_call + (inst == BC_INST_RET)))
5957 RETURN_STATUS(bc_error_stack_has_too_few_elements());
5959 f = bc_program_func(ip->func);
5960 res.t = BC_RESULT_TEMP;
5962 if (inst == BC_INST_RET) {
5965 BcResult *operand = bc_vec_top(&G.prog.results);
5967 s = zbc_program_num(operand, &num, false);
5968 if (s) RETURN_STATUS(s);
5969 bc_num_init(&res.d.n, num->len);
5970 bc_num_copy(&res.d.n, num);
5972 bc_num_init_DEF_SIZE(&res.d.n);
5973 //bc_num_zero(&res.d.n); - already is
5976 // We need to pop arguments as well, so this takes that into account.
5977 a = (void*)f->autos.v;
5978 for (i = 0; i < f->autos.len; i++, a++) {
5980 v = bc_program_search(a->name, a->idx);
5984 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->results_len_before_call);
5985 bc_vec_push(&G.prog.results, &res);
5986 bc_vec_pop(&G.prog.exestack);
5988 RETURN_STATUS(BC_STATUS_SUCCESS);
5990 #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
5993 static unsigned long bc_program_scale(BcNum *n)
5995 return (unsigned long) n->rdx;
5998 static unsigned long bc_program_len(BcNum *n)
6000 size_t len = n->len;
6002 if (n->rdx != len) return len;
6004 if (len == 0) break;
6006 if (n->num[len] != 0) break;
6011 static BC_STATUS zbc_program_builtin(char inst)
6017 bool len = inst == BC_INST_LENGTH;
6019 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6020 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6021 opnd = bc_vec_top(&G.prog.results);
6023 s = zbc_program_num(opnd, &num, false);
6024 if (s) RETURN_STATUS(s);
6027 if (!BC_PROG_NUM(opnd, num) && !len)
6028 RETURN_STATUS(bc_error_variable_is_wrong_type());
6031 bc_num_init_DEF_SIZE(&res.d.n);
6033 if (inst == BC_INST_SQRT)
6034 s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
6036 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
6037 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6041 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6043 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6045 str = bc_program_str(idx);
6046 bc_num_ulong2num(&res.d.n, strlen(*str));
6050 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6053 bc_program_retire(&res, BC_RESULT_TEMP);
6057 #define zbc_program_builtin(...) (zbc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
6060 static BC_STATUS zdc_program_divmod(void)
6063 BcResult *opd1, *opd2, res, res2;
6064 BcNum *n1, *n2 = NULL;
6066 s = zbc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6067 if (s) RETURN_STATUS(s);
6069 bc_num_init_DEF_SIZE(&res.d.n);
6070 bc_num_init(&res2.d.n, n2->len);
6072 s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6075 bc_program_binOpRetire(&res2);
6076 res.t = BC_RESULT_TEMP;
6077 bc_vec_push(&G.prog.results, &res);
6081 bc_num_free(&res2.d.n);
6082 bc_num_free(&res.d.n);
6085 #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
6087 static BC_STATUS zdc_program_modexp(void)
6090 BcResult *r1, *r2, *r3, res;
6091 BcNum *n1, *n2, *n3;
6093 if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
6094 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6095 s = zbc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6096 if (s) RETURN_STATUS(s);
6098 r1 = bc_vec_item_rev(&G.prog.results, 2);
6099 s = zbc_program_num(r1, &n1, false);
6100 if (s) RETURN_STATUS(s);
6101 if (!BC_PROG_NUM(r1, n1))
6102 RETURN_STATUS(bc_error_variable_is_wrong_type());
6104 // Make sure that the values have their pointers updated, if necessary.
6105 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6106 if (r1->t == r2->t) {
6107 s = zbc_program_num(r2, &n2, false);
6108 if (s) RETURN_STATUS(s);
6110 if (r1->t == r3->t) {
6111 s = zbc_program_num(r3, &n3, false);
6112 if (s) RETURN_STATUS(s);
6116 bc_num_init(&res.d.n, n3->len);
6117 s = zdc_num_modexp(n1, n2, n3, &res.d.n);
6120 bc_vec_pop(&G.prog.results);
6121 bc_program_binOpRetire(&res);
6125 bc_num_free(&res.d.n);
6128 #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
6130 static void dc_program_stackLen(void)
6133 size_t len = G.prog.results.len;
6135 res.t = BC_RESULT_TEMP;
6137 bc_num_init_DEF_SIZE(&res.d.n);
6138 bc_num_ulong2num(&res.d.n, len);
6139 bc_vec_push(&G.prog.results, &res);
6142 static BC_STATUS zdc_program_asciify(void)
6153 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6154 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6155 r = bc_vec_top(&G.prog.results);
6157 s = zbc_program_num(r, &num, false);
6158 if (s) RETURN_STATUS(s);
6160 if (BC_PROG_NUM(r, num)) {
6162 BcDig strmb_digs[ULONG_NUM_BUFSIZE];
6164 bc_num_init_DEF_SIZE(&n);
6165 bc_num_copy(&n, num);
6166 bc_num_truncate(&n, n.rdx);
6168 strmb.cap = ARRAY_SIZE(strmb_digs);
6169 strmb.num = strmb_digs;
6170 bc_num_ulong2num(&strmb, 0x100);
6171 s = zbc_num_mod(&n, &strmb, &n, 0);
6173 if (s) goto num_err;
6174 s = zbc_num_ulong(&n, &val);
6175 if (s) goto num_err;
6182 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
6183 sp = *bc_program_str(idx);
6187 strs = (void*)G.prog.strs.v;
6188 for (idx = 0; idx < G.prog.strs.len; idx++) {
6189 if (strs[idx][0] == c && strs[idx][1] == '\0') {
6195 //str[1] = '\0'; - already is
6196 bc_vec_push(&G.prog.strs, &str);
6198 res.t = BC_RESULT_STR;
6200 bc_result_pop_and_push(&res);
6202 RETURN_STATUS(BC_STATUS_SUCCESS);
6207 #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
6209 static BC_STATUS zdc_program_printStream(void)
6216 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6217 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6218 r = bc_vec_top(&G.prog.results);
6220 s = zbc_program_num(r, &n, false);
6221 if (s) RETURN_STATUS(s);
6223 if (BC_PROG_NUM(r, n)) {
6224 s = zbc_num_printNum(n, 0x100, 1, dc_num_printChar);
6227 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
6228 str = *bc_program_str(idx);
6234 #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
6236 static BC_STATUS zdc_program_nquit(void)
6243 s = zbc_program_prep(&opnd, &num);
6244 if (s) RETURN_STATUS(s);
6245 s = zbc_num_ulong(num, &val);
6246 if (s) RETURN_STATUS(s);
6248 bc_vec_pop(&G.prog.results);
6250 if (G.prog.exestack.len < val)
6251 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6252 if (G.prog.exestack.len == val) {
6253 QUIT_OR_RETURN_TO_MAIN;
6256 bc_vec_npop(&G.prog.exestack, val);
6260 #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
6262 static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
6264 BcStatus s = BC_STATUS_SUCCESS;
6270 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6271 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6273 r = bc_vec_top(&G.prog.results);
6276 BcNum *n = n; // for compiler
6279 char *then_name = bc_program_name(code, bgn);
6280 char *else_name = NULL;
6282 if (code[*bgn] == BC_PARSE_STREND)
6285 else_name = bc_program_name(code, bgn);
6287 exec = r->d.n.len != 0;
6289 if (!exec && else_name != NULL) {
6296 v = bc_program_search(name, true);
6303 if (!exec) goto exit;
6304 if (!BC_PROG_STR(n)) {
6305 s = bc_error_variable_is_wrong_type();
6311 if (r->t == BC_RESULT_STR) {
6313 } else if (r->t == BC_RESULT_VAR) {
6315 s = zbc_program_num(r, &n, false);
6316 if (s || !BC_PROG_STR(n)) goto exit;
6322 fidx = sidx + BC_PROG_REQ_FUNCS;
6324 f = bc_program_func(fidx);
6326 if (f->code.len == 0) {
6331 bc_parse_create(&prs, fidx);
6332 str = *bc_program_str(sidx);
6333 s = zbc_parse_text_init(&prs, str);
6336 sv_input_fp = G.input_fp;
6337 G.input_fp = NULL; // "do not read from input file when <EOL> reached"
6338 s = zdc_parse_exprs_until_eof(&prs);
6339 G.input_fp = sv_input_fp;
6342 if (prs.l.t.t != BC_LEX_EOF) {
6343 s = bc_error_bad_expression();
6345 bc_parse_free(&prs);
6346 bc_vec_pop_all(&f->code);
6349 bc_parse_push(&prs, BC_INST_POP_EXEC);
6350 bc_parse_free(&prs);
6356 bc_vec_pop(&G.prog.results);
6357 bc_vec_push(&G.prog.exestack, &ip);
6359 RETURN_STATUS(BC_STATUS_SUCCESS);
6361 bc_vec_pop(&G.prog.results);
6364 #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
6367 static void bc_program_pushGlobal(char inst)
6372 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6373 if (inst == BC_INST_IBASE)
6374 val = (unsigned long) G.prog.ib_t;
6375 else if (inst == BC_INST_SCALE)
6376 val = (unsigned long) G.prog.scale;
6378 val = (unsigned long) G.prog.ob_t;
6380 bc_num_init_DEF_SIZE(&res.d.n);
6381 bc_num_ulong2num(&res.d.n, val);
6382 bc_vec_push(&G.prog.results, &res);
6385 static BC_STATUS zbc_program_exec(void)
6389 BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
6390 BcFunc *func = bc_program_func(ip->func);
6391 char *code = func->code.v;
6393 dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
6394 ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
6395 while (ip->inst_idx < func->code.len) {
6396 BcStatus s = BC_STATUS_SUCCESS;
6397 char inst = code[ip->inst_idx++];
6399 dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
6402 case BC_INST_JUMP_ZERO: {
6404 dbg_exec("BC_INST_JUMP_ZERO:");
6405 s = zbc_program_prep(&ptr, &num);
6406 if (s) RETURN_STATUS(s);
6407 zero = (bc_num_cmp(num, &G.prog.zero) == 0);
6408 bc_vec_pop(&G.prog.results);
6410 bc_program_index(code, &ip->inst_idx);
6413 // else: fall through
6415 case BC_INST_JUMP: {
6416 size_t idx = bc_program_index(code, &ip->inst_idx);
6417 size_t *addr = bc_vec_item(&func->labels, idx);
6418 dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
6419 ip->inst_idx = *addr;
6423 dbg_exec("BC_INST_CALL:");
6424 s = zbc_program_call(code, &ip->inst_idx);
6425 goto read_updated_ip;
6426 case BC_INST_INC_PRE:
6427 case BC_INST_DEC_PRE:
6428 case BC_INST_INC_POST:
6429 case BC_INST_DEC_POST:
6430 dbg_exec("BC_INST_INCDEC:");
6431 s = zbc_program_incdec(inst);
6434 dbg_exec("BC_INST_HALT:");
6435 QUIT_OR_RETURN_TO_MAIN;
6439 dbg_exec("BC_INST_RET[0]:");
6440 s = zbc_program_return(inst);
6441 goto read_updated_ip;
6442 case BC_INST_BOOL_OR:
6443 case BC_INST_BOOL_AND:
6445 case BC_INST_REL_EQ:
6446 case BC_INST_REL_LE:
6447 case BC_INST_REL_GE:
6448 case BC_INST_REL_NE:
6449 case BC_INST_REL_LT:
6450 case BC_INST_REL_GT:
6451 dbg_exec("BC_INST_BOOL:");
6452 s = zbc_program_logical(inst);
6455 dbg_exec("BC_INST_READ:");
6456 s = zbc_program_read();
6457 goto read_updated_ip;
6459 dbg_exec("BC_INST_VAR:");
6460 s = zbc_program_pushVar(code, &ip->inst_idx, false, false);
6462 case BC_INST_ARRAY_ELEM:
6464 dbg_exec("BC_INST_ARRAY[_ELEM]:");
6465 s = zbc_program_pushArray(code, &ip->inst_idx, inst);
6468 //TODO: this can't happen on dc, right?
6469 dbg_exec("BC_INST_LAST:");
6470 r.t = BC_RESULT_LAST;
6471 bc_vec_push(&G.prog.results, &r);
6476 dbg_exec("BC_INST_internalvar:");
6477 bc_program_pushGlobal(inst);
6479 case BC_INST_SCALE_FUNC:
6480 case BC_INST_LENGTH:
6482 dbg_exec("BC_INST_builtin:");
6483 s = zbc_program_builtin(inst);
6486 dbg_exec("BC_INST_NUM:");
6487 r.t = BC_RESULT_CONSTANT;
6488 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6489 bc_vec_push(&G.prog.results, &r);
6492 dbg_exec("BC_INST_POP:");
6493 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6494 s = bc_error_stack_has_too_few_elements();
6496 bc_vec_pop(&G.prog.results);
6499 case BC_INST_PRINT_POP:
6500 case BC_INST_PRINT_STR:
6501 dbg_exec("BC_INST_PRINTxyz:");
6502 s = zbc_program_print(inst, 0);
6505 dbg_exec("BC_INST_STR:");
6506 r.t = BC_RESULT_STR;
6507 r.d.id.idx = bc_program_index(code, &ip->inst_idx);
6508 bc_vec_push(&G.prog.results, &r);
6511 case BC_INST_MULTIPLY:
6512 case BC_INST_DIVIDE:
6513 case BC_INST_MODULUS:
6516 dbg_exec("BC_INST_binaryop:");
6517 s = zbc_program_op(inst);
6519 case BC_INST_BOOL_NOT:
6520 dbg_exec("BC_INST_BOOL_NOT:");
6521 s = zbc_program_prep(&ptr, &num);
6522 if (s) RETURN_STATUS(s);
6523 bc_num_init_DEF_SIZE(&r.d.n);
6524 if (!bc_num_cmp(num, &G.prog.zero))
6526 //else bc_num_zero(&r.d.n); - already is
6527 bc_program_retire(&r, BC_RESULT_TEMP);
6530 dbg_exec("BC_INST_NEG:");
6531 s = zbc_program_negate();
6534 case BC_INST_ASSIGN_POWER:
6535 case BC_INST_ASSIGN_MULTIPLY:
6536 case BC_INST_ASSIGN_DIVIDE:
6537 case BC_INST_ASSIGN_MODULUS:
6538 case BC_INST_ASSIGN_PLUS:
6539 case BC_INST_ASSIGN_MINUS:
6541 case BC_INST_ASSIGN:
6542 dbg_exec("BC_INST_ASSIGNxyz:");
6543 s = zbc_program_assign(inst);
6546 case BC_INST_POP_EXEC:
6547 dbg_exec("BC_INST_POP_EXEC:");
6548 bc_vec_pop(&G.prog.exestack);
6549 goto read_updated_ip;
6550 case BC_INST_MODEXP:
6551 dbg_exec("BC_INST_MODEXP:");
6552 s = zdc_program_modexp();
6554 case BC_INST_DIVMOD:
6555 dbg_exec("BC_INST_DIVMOD:");
6556 s = zdc_program_divmod();
6558 case BC_INST_EXECUTE:
6559 case BC_INST_EXEC_COND:
6560 dbg_exec("BC_INST_EXEC[_COND]:");
6561 s = zdc_program_execStr(code, &ip->inst_idx, inst == BC_INST_EXEC_COND);
6562 goto read_updated_ip;
6563 case BC_INST_PRINT_STACK: {
6565 dbg_exec("BC_INST_PRINT_STACK:");
6566 for (idx = 0; idx < G.prog.results.len; ++idx) {
6567 s = zbc_program_print(BC_INST_PRINT, idx);
6572 case BC_INST_CLEAR_STACK:
6573 dbg_exec("BC_INST_CLEAR_STACK:");
6574 bc_vec_pop_all(&G.prog.results);
6576 case BC_INST_STACK_LEN:
6577 dbg_exec("BC_INST_STACK_LEN:");
6578 dc_program_stackLen();
6580 case BC_INST_DUPLICATE:
6581 dbg_exec("BC_INST_DUPLICATE:");
6582 if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
6583 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6584 ptr = bc_vec_top(&G.prog.results);
6585 dc_result_copy(&r, ptr);
6586 bc_vec_push(&G.prog.results, &r);
6588 case BC_INST_SWAP: {
6590 dbg_exec("BC_INST_SWAP:");
6591 if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
6592 RETURN_STATUS(bc_error_stack_has_too_few_elements());
6593 ptr = bc_vec_item_rev(&G.prog.results, 0);
6594 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6595 memcpy(&r, ptr, sizeof(BcResult));
6596 memcpy(ptr, ptr2, sizeof(BcResult));
6597 memcpy(ptr2, &r, sizeof(BcResult));
6600 case BC_INST_ASCIIFY:
6601 dbg_exec("BC_INST_ASCIIFY:");
6602 s = zdc_program_asciify();
6604 case BC_INST_PRINT_STREAM:
6605 dbg_exec("BC_INST_STREAM:");
6606 s = zdc_program_printStream();
6609 case BC_INST_PUSH_VAR: {
6610 bool copy = inst == BC_INST_LOAD;
6611 s = zbc_program_pushVar(code, &ip->inst_idx, true, copy);
6614 case BC_INST_PUSH_TO_VAR: {
6615 char *name = bc_program_name(code, &ip->inst_idx);
6616 s = zbc_program_copyToVar(name, true);
6621 dbg_exec("BC_INST_QUIT:");
6622 if (G.prog.exestack.len <= 2)
6623 QUIT_OR_RETURN_TO_MAIN;
6624 bc_vec_npop(&G.prog.exestack, 2);
6625 goto read_updated_ip;
6627 dbg_exec("BC_INST_NQUIT:");
6628 s = zdc_program_nquit();
6629 //goto read_updated_ip; - just fall through to it
6632 // Instruction stack has changed, read new pointers
6633 ip = bc_vec_top(&G.prog.exestack);
6634 func = bc_program_func(ip->func);
6635 code = func->code.v;
6636 dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
6639 if (s || G_interrupt) {
6647 RETURN_STATUS(BC_STATUS_SUCCESS);
6649 #define zbc_program_exec(...) (zbc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
6651 static unsigned bc_vm_envLen(const char *var)
6657 len = BC_NUM_PRINT_WIDTH;
6658 if (!lenv) return len;
6660 len = bb_strtou(lenv, NULL, 10) - 1;
6661 if (errno || len < 2 || len >= INT_MAX)
6662 len = BC_NUM_PRINT_WIDTH;
6667 static BC_STATUS zbc_vm_process(const char *text)
6671 dbg_lex_enter("%s:%d entered", __func__, __LINE__);
6672 s = zbc_parse_text_init(&G.prs, text); // does the first zbc_lex_next()
6673 if (s) RETURN_STATUS(s);
6675 while (G.prs.l.t.t != BC_LEX_EOF) {
6676 dbg_lex("%s:%d G.prs.l.t.t:%d, parsing...", __func__, __LINE__, G.prs.l.t.t);
6678 // FIXME: "eating" of stmt delimiters is coded inconsistently
6679 // (sometimes zbc_parse_stmt() eats the delimiter, sometimes don't),
6680 // which causes bugs such as "print 1 print 2" erroneously accepted,
6681 // or "print 1 else 2" detecting parse error only after executing
6683 IF_BC(s = zbc_parse_stmt_or_funcdef(&G.prs));
6685 IF_DC(s = zdc_parse_expr(&G.prs));
6687 if (s || G_interrupt) {
6688 bc_parse_reset(&G.prs); // includes bc_program_reset()
6689 RETURN_STATUS(BC_STATUS_FAILURE);
6692 dbg_lex("%s:%d executing...", __func__, __LINE__);
6693 s = zbc_program_exec();
6698 // bc discards strings, constants and code after each
6699 // top-level statement in the "main program".
6700 // This prevents "yes 1 | bc" from growing its memory
6701 // without bound. This can be done because data stack
6702 // is empty and thus can't hold any references to
6703 // strings or constants, there is no generated code
6704 // which can hold references (after we discard one
6705 // we just executed). Code of functions can have references,
6706 // but bc stores function strings/constants in per-function
6710 BcInstPtr *ip = (void*)G.prog.exestack.v;
6713 if (G.prog.results.len != 0) // should be empty
6714 bb_error_msg_and_die("BUG:data stack");
6715 if (G.prog.exestack.len != 1) // should have only main's IP
6716 bb_error_msg_and_die("BUG:call stack");
6717 if (ip->func != BC_PROG_MAIN)
6718 bb_error_msg_and_die("BUG:not MAIN");
6720 //bb_error_msg("ip->func:%d >idx:%d >len:%d", ip->func, ip->inst_idx, ip->len);
6721 f = bc_program_func_BC_PROG_MAIN();
6722 //bb_error_msg("MAIN->code.len:%d >strs.len:%d >consts.len:%d", f->code.len, f->strs.len, f->consts.len); // labels, autos, nparams
6723 bc_vec_pop_all(&f->code);
6725 IF_BC(bc_vec_pop_all(&f->strs);)
6726 IF_BC(bc_vec_pop_all(&f->consts);)
6728 // Most of dc parsing assumes all whitespace,
6729 // including '\n', is eaten.
6730 if (G.prs.l.t.t == BC_LEX_NLINE) {
6731 s = zbc_lex_next(&G.prs.l);
6732 if (s) RETURN_STATUS(s);
6737 dbg_lex_done("%s:%d done", __func__, __LINE__);
6740 #define zbc_vm_process(...) (zbc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
6742 static BC_STATUS zbc_vm_execute_FILE(FILE *fp, const char *filename)
6744 // So far bc/dc have no way to include a file from another file,
6745 // therefore we know G.prog.file == NULL on entry
6746 //const char *sv_file;
6749 G.prog.file = filename;
6751 bc_lex_file(&G.prs.l);
6754 s = zbc_vm_process("");
6755 // We do not stop looping on errors here if reading stdin.
6756 // Example: start interactive bc and enter "return".
6757 // It should say "'return' not in a function"
6758 // but should not exit.
6759 } while (G.input_fp == stdin);
6763 #define zbc_vm_execute_FILE(...) (zbc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
6765 static BC_STATUS zbc_vm_file(const char *file)
6770 fp = xfopen_for_read(file);
6771 s = zbc_vm_execute_FILE(fp, file);
6776 #define zbc_vm_file(...) (zbc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
6779 static void bc_vm_info(void)
6781 printf("%s "BB_VER"\n"
6782 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6786 static void bc_args(char **argv)
6792 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6793 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6794 "warn\0" No_argument "w"
6795 "version\0" No_argument "v"
6796 "standard\0" No_argument "s"
6797 "quiet\0" No_argument "q"
6798 "mathlib\0" No_argument "l"
6799 "interactive\0" No_argument "i"
6802 opts = option_mask32 |= getopt32(argv, "wvsqli");
6804 if (getenv("POSIXLY_CORRECT"))
6805 option_mask32 |= BC_FLAG_S;
6807 if (opts & BC_FLAG_V) {
6812 for (i = optind; argv[i]; ++i)
6813 bc_vec_push(&G.files, argv + i);
6816 static void bc_vm_envArgs(void)
6820 char *env_args = getenv("BC_ENV_ARGS");
6822 if (!env_args) return;
6824 G.env_args = xstrdup(env_args);
6827 bc_vec_init(&v, sizeof(char *), NULL);
6829 while (*(buf = skip_whitespace(buf)) != '\0') {
6830 bc_vec_push(&v, &buf);
6831 buf = skip_non_whitespace(buf);
6837 // NULL terminate, and pass argv[] so that first arg is argv[1]
6838 if (sizeof(int) == sizeof(char*)) {
6839 bc_vec_push(&v, &const_int_0);
6841 static char *const nullptr = NULL;
6842 bc_vec_push(&v, &nullptr);
6844 bc_args(((char **)v.v) - 1);
6849 static const char bc_lib[] ALIGN1 = {
6852 "\n" "auto b,s,n,r,d,i,p,f,v"
6853 ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
6854 //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
6855 //e(-.998896): GNU:.36828580434569428695
6856 // above code:.36828580434569428696
6857 // actual value:.3682858043456942869594...
6858 // but for now let's be "GNU compatible"
6867 "\n" "scale=scale(x)+1"
6877 "\n" "for(i=2;v;++i){"
6883 "\n" "while(d--)r*=r"
6886 "\n" "if(n)return(1/r)"
6890 "\n" "auto b,s,r,p,a,q,i,v"
6894 "\n" "r=(1-10^scale)/1"
6905 "\n" "while(x<=.5){"
6909 "\n" "r=a=(x-1)/(x+1)"
6912 "\n" "for(i=3;v;i+=2){"
6923 "\n" "auto b,s,r,a,q,i"
6924 "\n" "if(x<0)return(-s(-x))"
6928 "\n" "scale=1.1*s+2"
6937 "\n" "for(i=3;a;i+=2){"
6938 "\n" "a*=q/(i*(i-1))"
6951 "\n" "x=s(2*a(1)+x)"
6957 "\n" "auto b,s,r,n,a,m,t,f,i,u"
6965 "\n" "if(scale<65){"
6966 "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
6967 "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
6977 "\n" "x=(x-.2)/(1+.2*x)"
6982 "\n" "for(i=3;t;i+=2){"
6989 "\n" "return((m*a+r)/n)"
6991 "\n" "define j(n,x){"
6992 "\n" "auto b,s,o,a,i,v,f"
7003 "\n" "for(i=2;i<=n;++i)a*=i"
7005 "\n" "a=(x^n)/2^n/a"
7008 "\n" "scale+=length(a)-scale(a)"
7009 "\n" "for(i=1;v;++i){"
7010 "\n" "v=v*f/i/(n+i)"
7016 "\n" "return(a*r/1)"
7021 static BC_STATUS zbc_vm_exec(void)
7028 if (option_mask32 & BC_FLAG_L) {
7029 // We know that internal library is not buggy,
7030 // thus error checking is normally disabled.
7031 # define DEBUG_LIB 0
7032 bc_lex_file(&G.prs.l);
7033 s = zbc_vm_process(bc_lib);
7034 if (DEBUG_LIB && s) RETURN_STATUS(s);
7038 s = BC_STATUS_SUCCESS;
7039 fname = (void*)G.files.v;
7040 for (i = 0; i < G.files.len; i++) {
7041 s = zbc_vm_file(*fname++);
7042 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
7043 // Debug config, non-interactive mode:
7044 // return all the way back to main.
7045 // Non-debug builds do not come here
7046 // in non-interactive mode, they exit.
7051 if (IS_BC || (option_mask32 & BC_FLAG_I))
7052 s = zbc_vm_execute_FILE(stdin, /*filename:*/ NULL);
7056 #define zbc_vm_exec(...) (zbc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
7058 #if ENABLE_FEATURE_CLEAN_UP
7059 static void bc_program_free(void)
7061 bc_vec_free(&G.prog.fns);
7062 IF_BC(bc_vec_free(&G.prog.fn_map);)
7063 bc_vec_free(&G.prog.vars);
7064 bc_vec_free(&G.prog.var_map);
7065 bc_vec_free(&G.prog.arrs);
7066 bc_vec_free(&G.prog.arr_map);
7067 IF_DC(bc_vec_free(&G.prog.strs);)
7068 IF_DC(bc_vec_free(&G.prog.consts);)
7069 bc_vec_free(&G.prog.results);
7070 bc_vec_free(&G.prog.exestack);
7071 IF_BC(bc_num_free(&G.prog.last);)
7072 IF_BC(bc_num_free(&G.prog.zero);)
7073 IF_BC(bc_num_free(&G.prog.one);)
7074 bc_vec_free(&G.input_buffer);
7077 static void bc_vm_free(void)
7079 bc_vec_free(&G.files);
7081 bc_parse_free(&G.prs);
7086 static void bc_program_init(void)
7090 // memset(&G.prog, 0, sizeof(G.prog)); - already is
7091 memset(&ip, 0, sizeof(BcInstPtr));
7093 // G.prog.nchars = G.prog.scale = 0; - already is
7097 IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
7098 //IF_BC(bc_num_zero(&G.prog.last);) - already is
7100 bc_num_init_DEF_SIZE(&G.prog.zero);
7101 //bc_num_zero(&G.prog.zero); - already is
7103 IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
7104 IF_BC(bc_num_one(&G.prog.one);)
7106 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7107 IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
7110 // Names are chosen simply to be distinct and never match
7111 // a valid function name (and be short)
7112 IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
7113 IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
7115 // in dc, functions have no names
7116 bc_program_add_fn();
7117 bc_program_add_fn();
7120 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7121 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7123 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7124 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7126 IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
7127 IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
7128 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7129 bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
7130 bc_vec_push(&G.prog.exestack, &ip);
7132 bc_char_vec_init(&G.input_buffer);
7135 static int bc_vm_init(const char *env_len)
7137 #if ENABLE_FEATURE_EDITING
7138 G.line_input_state = new_line_input_t(DO_HISTORY);
7140 G.prog.len = bc_vm_envLen(env_len);
7142 bc_vec_init(&G.files, sizeof(char *), NULL);
7143 IF_BC(if (IS_BC) bc_vm_envArgs();)
7145 bc_parse_create(&G.prs, BC_PROG_MAIN);
7147 //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
7148 //-i option unconditionally enables this regardless of isatty():
7150 #if ENABLE_FEATURE_BC_SIGNALS
7152 // With SA_RESTART, most system calls will restart
7153 // (IOW: they won't fail with EINTR).
7154 // In particular, this means ^C won't cause
7155 // stdout to get into "error state" if SIGINT hits
7156 // within write() syscall.
7158 // The downside is that ^C while tty input is taken
7159 // will only be handled after [Enter] since read()
7160 // from stdin is not interrupted by ^C either,
7161 // it restarts, thus fgetc() does not return on ^C.
7162 // (This problem manifests only if line editing is disabled)
7163 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7165 // Without SA_RESTART, this exhibits a bug:
7166 // "while (1) print 1" and try ^C-ing it.
7167 // Intermittently, instead of returning to input line,
7168 // you'll get "output error: Interrupted system call"
7170 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7174 return 0; // "not a tty"
7177 static BcStatus bc_vm_run(void)
7179 BcStatus st = zbc_vm_exec();
7180 #if ENABLE_FEATURE_CLEAN_UP
7181 if (G_exiting) // it was actually "halt" or "quit"
7184 # if ENABLE_FEATURE_EDITING
7185 free_line_input_t(G.line_input_state);
7189 dbg_exec("exiting with exitcode %d", st);
7194 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7195 int bc_main(int argc UNUSED_PARAM, char **argv)
7201 is_tty = bc_vm_init("BC_LINE_LENGTH");
7205 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7213 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7214 int dc_main(int argc UNUSED_PARAM, char **argv)
7220 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7221 // 1 char wider than bc from the same package.
7222 // Both default width, and xC_LINE_LENGTH=N are wider:
7223 // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7226 // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7229 // Do the same, or it's a bug?
7230 bc_vm_init("DC_LINE_LENGTH");
7232 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7233 noscript = BC_FLAG_I;
7235 int n = getopt(argc, argv, "e:f:x");
7241 n = zbc_vm_process(optarg);
7246 n = zbc_vm_file(optarg);
7250 option_mask32 |= DC_FLAG_X;
7260 bc_vec_push(&G.files, argv++);
7263 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7269 #endif // not DC_SMALL