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)
14 //config: for details.
16 //config: This bc has four differences to the GNU bc:
18 //config: 1) The period (.) can also be used as a shortcut for "last", as in
20 //config: 2) Arrays are copied before being passed as arguments to
21 //config: functions. This behavior is required by the bc spec.
22 //config: 3) Arrays can be passed to the builtin "length" function to get
23 //config: the number of elements currently in the array. The following
24 //config: example prints "1":
29 //config: 4) The precedence of the boolean "not" operator (!) is equal to
30 //config: that of the unary minus (-), or negation, operator. This still
31 //config: allows POSIX-compliant scripts to work while somewhat
32 //config: preserving expected behavior (versus C) and making parsing
37 //config: -i --interactive force interactive mode
38 //config: -l --mathlib use predefined math routines:
40 //config: s(expr) = sine of expr in radians
41 //config: c(expr) = cosine of expr in radians
42 //config: a(expr) = arctangent of expr, returning
44 //config: l(expr) = natural log of expr
45 //config: e(expr) = raises e to the power of expr
46 //config: j(n, x) = Bessel function of integer order
49 //config: -q --quiet don't print version and copyright.
50 //config: -s --standard error if any non-POSIX extensions are used.
51 //config: -w --warn warn if any non-POSIX extensions are used.
52 //config: -v --version print version and copyright and exit.
54 //config: Long options are only available if FEATURE_BC_LONG_OPTIONS is
58 //config: bool "dc (38 kb; 49 kb when combined with bc)"
61 //config: dc is a reverse-polish notation command-line calculator which
62 //config: supports unlimited precision arithmetic. See the FreeBSD man page
63 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
64 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
65 //config: for details.
67 //config: This dc has a few differences from the two above:
69 //config: 1) When printing a byte stream (command "P"), this bc follows what
70 //config: the FreeBSD dc does.
71 //config: 2) This dc implements the GNU extensions for divmod ("~") and
72 //config: modular exponentiation ("|").
73 //config: 3) This dc implements all FreeBSD extensions, except for "J" and
75 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
76 //config: However, they are implemented differently. When it encounters
77 //config: whitespace where a register should be, it skips the whitespace.
78 //config: If the character following is not a lowercase letter, an error
79 //config: is issued. Otherwise, the register name is parsed by the
80 //config: following regex:
82 //config: [a-z][a-z0-9_]*
84 //config: This generally means that register names will be surrounded by
89 //config: l idx s temp L index S temp2 < do_thing
91 //config: Also note that, like the FreeBSD dc, extended registers are not
92 //config: allowed unless the "-x" option is given.
94 //config:config FEATURE_DC_SMALL
95 //config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
96 //config: depends on DC && !BC
99 //config:config FEATURE_DC_LIBM
100 //config: bool "Enable power and exp functions (requires libm)"
102 //config: depends on FEATURE_DC_SMALL
104 //config: Enable power and exp functions.
105 //config: NOTE: This will require libm to be present for linking.
107 //config:config FEATURE_BC_SIGNALS
108 //config: bool "Enable bc/dc signal handling"
110 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
112 //config: Enable signal handling for bc and dc.
114 //config:config FEATURE_BC_LONG_OPTIONS
115 //config: bool "Enable bc/dc long options"
117 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
119 //config: Enable long options for bc and dc.
121 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
122 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
124 //kbuild:lib-$(CONFIG_BC) += bc.o
125 //kbuild:lib-$(CONFIG_DC) += bc.o
127 //See www.gnu.org/software/bc/manual/bc.html
128 //usage:#define bc_trivial_usage
129 //usage: "[-sqliw] FILE..."
131 //usage:#define bc_full_usage "\n"
132 //usage: "\nArbitrary precision calculator"
134 ///////: "\n -i Interactive" - has no effect for now
135 //usage: "\n -q Quiet"
136 //usage: "\n -l Load standard math library"
137 //usage: "\n -s Be POSIX compatible"
138 //usage: "\n -w Warn if extensions are used"
139 ///////: "\n -v Version"
141 //usage: "\n$BC_LINE_LENGTH changes output width"
143 //usage:#define bc_example_usage
144 //usage: "3 + 4.129\n"
145 //usage: "1903 - 2893\n"
146 //usage: "-129 * 213.28935\n"
147 //usage: "12 / -1932\n"
149 //usage: "34 ^ 189\n"
150 //usage: "scale = 13\n"
151 //usage: "ibase = 2\n"
152 //usage: "obase = A\n"
154 //usage:#define dc_trivial_usage
155 //usage: IF_NOT_FEATURE_DC_SMALL("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
157 //usage:#define dc_full_usage "\n"
158 //usage: "\nTiny RPN calculator. Operations:"
159 //usage: "\n+, -, *, /, %, ~, ^," IF_NOT_FEATURE_DC_SMALL(" |,")
160 //usage: "\np - print top of the stack (without popping)"
161 //usage: "\nf - print entire stack"
162 //usage: "\nk - pop the value and set the precision"
163 //usage: "\ni - pop the value and set input radix"
164 //usage: "\no - pop the value and set output radix"
165 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
167 //usage:#define dc_example_usage
168 //usage: "$ dc -e'2 2 + p'\n"
170 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
172 //usage: "$ dc -e'0 1 & p'\n"
174 //usage: "$ dc -e'0 1 | p'\n"
176 //usage: "$ echo '72 9 / 8 * p' | dc\n"
180 #include "common_bufsiz.h"
182 #if ENABLE_FEATURE_DC_SMALL
186 typedef enum BcStatus {
187 BC_STATUS_SUCCESS = 0,
188 BC_STATUS_FAILURE = 1,
189 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
190 BC_STATUS_EOF = 3, // bc_vm_stdin() uses this
193 #define BC_VEC_INVALID_IDX ((size_t) -1)
194 #define BC_VEC_START_CAP (1 << 5)
196 typedef void (*BcVecFree)(void *) FAST_FUNC;
198 typedef struct BcVec {
206 typedef signed char BcDig;
208 typedef struct BcNum {
216 #define BC_NUM_MIN_BASE ((unsigned long) 2)
217 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
218 // larger value might speed up BIGNUM calculations a bit:
219 #define BC_NUM_DEF_SIZE (16)
220 #define BC_NUM_PRINT_WIDTH (69)
222 #define BC_NUM_KARATSUBA_LEN (32)
224 typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
226 typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
228 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
229 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
230 static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
231 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
232 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
233 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale) FAST_FUNC;
234 static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
235 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
238 typedef enum BcInst {
268 BC_INST_ASSIGN_POWER,
269 BC_INST_ASSIGN_MULTIPLY,
270 BC_INST_ASSIGN_DIVIDE,
271 BC_INST_ASSIGN_MODULUS,
273 BC_INST_ASSIGN_MINUS,
319 BC_INST_PRINT_STREAM,
334 BC_INST_INVALID = -1,
339 typedef struct BcId {
344 typedef struct BcFunc {
351 typedef enum BcResultType {
356 BC_RESULT_ARRAY_ELEM,
365 // These are between to calculate ibase, obase, and last from instructions.
373 typedef union BcResultData {
379 typedef struct BcResult {
384 typedef struct BcInstPtr {
390 // BC_LEX_NEG is not used in lexing; it is only for parsing.
391 typedef enum BcLexType {
419 BC_LEX_OP_ASSIGN_POWER,
420 BC_LEX_OP_ASSIGN_MULTIPLY,
421 BC_LEX_OP_ASSIGN_DIVIDE,
422 BC_LEX_OP_ASSIGN_MODULUS,
423 BC_LEX_OP_ASSIGN_PLUS,
424 BC_LEX_OP_ASSIGN_MINUS,
445 BC_LEX_KEY_1st_keyword,
446 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
453 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
454 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
456 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
459 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
497 // must match order of BC_LEX_KEY_foo etc above
499 struct BcLexKeyword {
502 #define BC_LEX_KW_ENTRY(a, b) \
503 { .name8 = a /*, .posix = b */ }
504 static const struct BcLexKeyword bc_lex_kws[20] = {
505 BC_LEX_KW_ENTRY("auto" , 1), // 0
506 BC_LEX_KW_ENTRY("break" , 1), // 1
507 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
508 BC_LEX_KW_ENTRY("define" , 1), // 3
510 BC_LEX_KW_ENTRY("else" , 0), // 4
511 BC_LEX_KW_ENTRY("for" , 1), // 5
512 BC_LEX_KW_ENTRY("halt" , 0), // 6
513 BC_LEX_KW_ENTRY("ibase" , 1), // 7
515 BC_LEX_KW_ENTRY("if" , 1), // 8
516 BC_LEX_KW_ENTRY("last" , 0), // 9
517 BC_LEX_KW_ENTRY("length" , 1), // 10
518 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
525 BC_LEX_KW_ENTRY("return" , 1), // 16
526 BC_LEX_KW_ENTRY("scale" , 1), // 17
527 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
528 BC_LEX_KW_ENTRY("while" , 1), // 19
530 #undef BC_LEX_KW_ENTRY
558 #define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
562 typedef BcStatus (*BcLexNext)(struct BcLex *) FAST_FUNC;
564 typedef struct BcLex {
582 #define BC_PARSE_STREND ((char) UCHAR_MAX)
584 #define BC_PARSE_REL (1 << 0)
585 #define BC_PARSE_PRINT (1 << 1)
586 #define BC_PARSE_NOCALL (1 << 2)
587 #define BC_PARSE_NOREAD (1 << 3)
588 #define BC_PARSE_ARRAY (1 << 4)
590 #define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
591 #define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
593 #define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
594 #define BC_PARSE_FUNC_INNER(parse) \
595 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
597 #define BC_PARSE_FLAG_FUNC (1 << 1)
598 #define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
600 #define BC_PARSE_FLAG_BODY (1 << 2)
601 #define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
603 #define BC_PARSE_FLAG_LOOP (1 << 3)
604 #define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
606 #define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
607 #define BC_PARSE_LOOP_INNER(parse) \
608 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
610 #define BC_PARSE_FLAG_IF (1 << 5)
611 #define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
613 #define BC_PARSE_FLAG_ELSE (1 << 6)
614 #define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
616 #define BC_PARSE_FLAG_IF_END (1 << 7)
617 #define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
619 #define BC_PARSE_CAN_EXEC(parse) \
620 (!(BC_PARSE_TOP_FLAG(parse) & \
621 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
622 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
623 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
629 typedef BcStatus (*BcParseParse)(struct BcParse *) FAST_FUNC;
631 typedef struct BcParse {
652 typedef struct BcProgram {
693 #define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
695 #define BC_PROG_MAIN (0)
696 #define BC_PROG_READ (1)
698 #define BC_PROG_REQ_FUNCS (2)
701 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
702 #define BC_PROG_NUM(r, n) \
703 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
705 #define BC_FLAG_W (1 << 0)
706 #define BC_FLAG_V (1 << 1)
707 #define BC_FLAG_S (1 << 2)
708 #define BC_FLAG_Q (1 << 3)
709 #define BC_FLAG_L (1 << 4)
710 #define BC_FLAG_I (1 << 5)
711 #define DC_FLAG_X (1 << 6)
713 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
714 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
716 #define BC_MAX_OBASE ((unsigned) 999)
717 #define BC_MAX_DIM ((unsigned) INT_MAX)
718 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
719 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
720 #define BC_MAX_NUM BC_MAX_STRING
721 // Unused apart from "limits" message. Just show a "biggish number" there.
722 //#define BC_MAX_NAME BC_MAX_STRING
723 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
724 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
725 #define BC_MAX_NAME_STR "999999999"
726 #define BC_MAX_EXP_STR "999999999"
727 #define BC_MAX_VARS_STR "999999999"
729 #define BC_MAX_OBASE_STR "999"
731 #if INT_MAX == 2147483647
732 # define BC_MAX_DIM_STR "2147483647"
733 #elif INT_MAX == 9223372036854775807
734 # define BC_MAX_DIM_STR "9223372036854775807"
736 # error Strange INT_MAX
739 #if UINT_MAX == 4294967295
740 # define BC_MAX_SCALE_STR "4294967295"
741 # define BC_MAX_STRING_STR "4294967294"
742 #elif UINT_MAX == 18446744073709551615
743 # define BC_MAX_SCALE_STR "18446744073709551615"
744 # define BC_MAX_STRING_STR "18446744073709551614"
746 # error Strange UINT_MAX
748 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
751 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
752 IF_FEATURE_CLEAN_UP(smallint exiting;)
759 // For error messages. Can be set to current parsed line,
760 // or [TODO] to current executing line (can be before last parsed one)
767 #if ENABLE_FEATURE_EDITING
768 line_input_t *line_input_state;
771 #define G (*ptr_to_globals)
772 #define INIT_G() do { \
773 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
775 #define FREE_G() do { \
776 FREE_PTR_TO_GLOBALS(); \
778 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
779 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
780 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
781 #if ENABLE_FEATURE_BC_SIGNALS
782 # define G_interrupt bb_got_signal
783 # define G_ttyin G.ttyin
785 # define G_interrupt 0
788 #if ENABLE_FEATURE_CLEAN_UP
789 # define G_exiting G.exiting
793 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
797 // This is a bit array that corresponds to token types. An entry is
798 // true if the token is valid in an expression, false otherwise.
800 BC_PARSE_EXPRS_BITS = 0
801 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
802 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
803 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
804 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
805 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
806 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
807 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
808 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
810 static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
812 #if ULONG_MAX > 0xffffffff
813 // 64-bit version (will not work correctly for 32-bit longs!)
814 return BC_PARSE_EXPRS_BITS & (1UL << i);
817 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
819 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
822 return m & (1UL << i);
826 // This is an array of data for operators that correspond to token types.
827 static const uint8_t bc_parse_ops[] = {
828 #define OP(p,l) ((int)(l) * 0x10 + (p))
829 OP(0, false), OP( 0, false ), // inc dec
832 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
833 OP(4, true ), OP( 4, true ), // mod + -
834 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
836 OP(7, true ), OP( 7, true ), // or and
837 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
838 OP(5, false), OP( 5, false ), // -= =
841 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
842 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
844 // Byte array of up to 4 BC_LEX's, packed into 32-bit word
845 typedef uint32_t BcParseNext;
847 // These identify what tokens can come after expressions in certain cases.
849 #define BC_PARSE_NEXT4(a,b,c,d) ( (a) | ((b)<<8) | ((c)<<16) | ((((d)|0x80)<<24)) )
850 #define BC_PARSE_NEXT2(a,b) BC_PARSE_NEXT4(a,b,0xff,0xff)
851 #define BC_PARSE_NEXT1(a) BC_PARSE_NEXT4(a,0xff,0xff,0xff)
852 bc_parse_next_expr = BC_PARSE_NEXT4(BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF),
853 bc_parse_next_param = BC_PARSE_NEXT2(BC_LEX_RPAREN, BC_LEX_COMMA),
854 bc_parse_next_print = BC_PARSE_NEXT4(BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF),
855 bc_parse_next_rel = BC_PARSE_NEXT1(BC_LEX_RPAREN),
856 bc_parse_next_elem = BC_PARSE_NEXT1(BC_LEX_RBRACKET),
857 bc_parse_next_for = BC_PARSE_NEXT1(BC_LEX_SCOLON),
858 bc_parse_next_read = BC_PARSE_NEXT2(BC_LEX_NLINE, BC_LEX_EOF),
859 #undef BC_PARSE_NEXT4
860 #undef BC_PARSE_NEXT2
861 #undef BC_PARSE_NEXT1
866 static const //BcLexType - should be this type, but narrower type saves size:
869 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
870 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
871 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
875 static const //BcLexType - should be this type
878 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
879 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
880 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
881 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
882 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
883 BC_LEX_INVALID, BC_LEX_INVALID,
884 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
885 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
886 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
887 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
888 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
889 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
890 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
891 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
892 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
893 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
894 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
895 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
896 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
897 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
898 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
899 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
900 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
901 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
905 static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
908 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
909 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
910 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
911 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
912 BC_INST_INVALID, BC_INST_INVALID,
913 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
914 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
915 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
916 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
917 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
918 BC_INST_INVALID, BC_INST_INVALID,
919 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
920 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
921 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
922 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
923 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
924 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
925 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
926 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
927 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
928 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
929 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
930 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
934 static const BcNumBinaryOp bc_program_ops[] = {
935 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
938 static void fflush_and_check(void)
941 if (ferror(stdout) || ferror(stderr))
942 bb_perror_msg_and_die("output error");
945 #if ENABLE_FEATURE_CLEAN_UP
946 #define QUIT_OR_RETURN_TO_MAIN \
948 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
950 return BC_STATUS_FAILURE; \
953 #define QUIT_OR_RETURN_TO_MAIN quit()
956 static void quit(void) NORETURN;
957 static void quit(void)
960 bb_perror_msg_and_die("input error");
965 static void bc_verror_msg(const char *fmt, va_list p)
967 const char *sv = sv; /* for compiler */
970 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
972 bb_verror_msg(fmt, p, NULL);
974 free((char*)applet_name);
979 static NOINLINE int bc_error_fmt(const char *fmt, ...)
984 bc_verror_msg(fmt, p);
987 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
989 return BC_STATUS_FAILURE;
993 static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
997 // Are non-POSIX constructs totally ok?
998 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
999 return BC_STATUS_SUCCESS; // yes
1002 bc_verror_msg(fmt, p);
1005 // Do we treat non-POSIX constructs as errors?
1006 if (!(option_mask32 & BC_FLAG_S))
1007 return BC_STATUS_SUCCESS; // no, it's a warning
1008 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
1010 return BC_STATUS_FAILURE;
1014 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
1015 // This idiom begs for tail-call optimization, but for it to work,
1016 // function must not have caller-cleaned parameters on stack.
1017 // Unfortunately, vararg function API does exactly that on most arches.
1018 // Thus, use these shims for the cases when we have no vararg PARAMS:
1019 static int bc_error(const char *msg)
1021 return bc_error_fmt("%s", msg);
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);
1041 static int bc_error_bad_character(char c)
1043 return bc_error_fmt("bad character '%c'", c);
1045 static int bc_error_bad_expression(void)
1047 return bc_error("bad expression");
1049 static int bc_error_bad_token(void)
1051 return bc_error("bad token");
1053 static int bc_error_stack_has_too_few_elements(void)
1055 return bc_error("stack has too few elements");
1057 static int bc_error_variable_is_wrong_type(void)
1059 return bc_error("variable is wrong type");
1061 static int bc_error_nested_read_call(void)
1063 return bc_error("read() call inside of a read() call");
1066 static void bc_vec_grow(BcVec *v, size_t n)
1068 size_t cap = v->cap * 2;
1069 while (cap < v->len + n) cap *= 2;
1070 v->v = xrealloc(v->v, v->size * cap);
1074 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1077 v->cap = BC_VEC_START_CAP;
1080 v->v = xmalloc(esize * BC_VEC_START_CAP);
1083 static void bc_char_vec_init(BcVec *v)
1085 bc_vec_init(v, sizeof(char), NULL);
1088 static void bc_vec_expand(BcVec *v, size_t req)
1091 v->v = xrealloc(v->v, v->size * req);
1096 static void bc_vec_pop(BcVec *v)
1100 v->dtor(v->v + (v->size * v->len));
1103 static void bc_vec_npop(BcVec *v, size_t n)
1108 size_t len = v->len - n;
1109 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1113 static void bc_vec_pop_all(BcVec *v)
1115 bc_vec_npop(v, v->len);
1118 static void bc_vec_push(BcVec *v, const void *data)
1120 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1121 memmove(v->v + (v->size * v->len), data, v->size);
1125 static void bc_vec_pushByte(BcVec *v, char data)
1127 bc_vec_push(v, &data);
1130 static void bc_vec_pushZeroByte(BcVec *v)
1132 //bc_vec_pushByte(v, '\0');
1134 bc_vec_push(v, &const_int_0);
1137 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1140 bc_vec_push(v, data);
1145 if (v->len == v->cap) bc_vec_grow(v, 1);
1147 ptr = v->v + v->size * idx;
1149 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1150 memmove(ptr, data, v->size);
1154 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1157 bc_vec_expand(v, len + 1);
1158 memcpy(v->v, str, len);
1161 bc_vec_pushZeroByte(v);
1164 static void bc_vec_concat(BcVec *v, const char *str)
1168 if (v->len == 0) bc_vec_pushZeroByte(v);
1171 len = v->len + slen;
1173 if (v->cap < len) bc_vec_grow(v, slen);
1174 strcpy(v->v + v->len - 1, str);
1179 static void *bc_vec_item(const BcVec *v, size_t idx)
1181 return v->v + v->size * idx;
1184 static char** bc_program_str(size_t idx)
1186 return bc_vec_item(&G.prog.strs, idx);
1189 static BcFunc* bc_program_func(size_t idx)
1191 return bc_vec_item(&G.prog.fns, idx);
1194 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1196 return v->v + v->size * (v->len - idx - 1);
1199 static void *bc_vec_top(const BcVec *v)
1201 return v->v + v->size * (v->len - 1);
1204 static FAST_FUNC void bc_vec_free(void *vec)
1206 BcVec *v = (BcVec *) vec;
1211 static int bc_id_cmp(const void *e1, const void *e2)
1213 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1216 static FAST_FUNC void bc_id_free(void *id)
1218 free(((BcId *) id)->name);
1221 static size_t bc_map_find(const BcVec *v, const void *ptr)
1223 size_t low = 0, high = v->len;
1225 while (low < high) {
1227 size_t mid = (low + high) / 2;
1228 BcId *id = bc_vec_item(v, mid);
1229 int result = bc_id_cmp(ptr, id);
1233 else if (result < 0)
1242 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1244 size_t n = *i = bc_map_find(v, ptr);
1247 bc_vec_push(v, ptr);
1248 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1249 return 0; // "was not inserted"
1251 bc_vec_pushAt(v, ptr, n);
1252 return 1; // "was inserted"
1256 static size_t bc_map_index(const BcVec *v, const void *ptr)
1258 size_t i = bc_map_find(v, ptr);
1259 if (i >= v->len) return BC_VEC_INVALID_IDX;
1260 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1264 static int push_input_byte(BcVec *vec, char c)
1266 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1269 // Bad chars on this line, ignore entire line
1270 bc_error_fmt("illegal character 0x%02x", c);
1273 bc_vec_pushByte(vec, (char)c);
1277 static BcStatus bc_read_line(BcVec *vec)
1282 s = BC_STATUS_SUCCESS;
1287 bc_vec_pop_all(vec);
1291 #if ENABLE_FEATURE_BC_SIGNALS
1292 if (G_interrupt) { // ^C was pressed
1295 // GNU bc says "interrupted execution."
1296 // GNU dc says "Interrupt!"
1297 fputs("\ninterrupted execution\n", stderr);
1299 # if ENABLE_FEATURE_EDITING
1302 # define line_buf bb_common_bufsiz1
1303 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
1304 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1314 bad_chars |= push_input_byte(vec, c);
1321 IF_FEATURE_BC_SIGNALS(errno = 0;)
1324 #if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1325 // Both conditions appear simultaneously, check both just in case
1326 if (errno == EINTR || G_interrupt) {
1334 quit(); // this emits error message
1336 // Note: EOF does not append '\n', therefore:
1337 // printf 'print 123\n' | bc - works
1338 // printf 'print 123' | bc - fails (syntax error)
1341 bad_chars |= push_input_byte(vec, c);
1342 } while (c != '\n');
1344 } while (bad_chars);
1346 bc_vec_pushZeroByte(vec);
1351 static char* bc_read_file(const char *path)
1354 size_t size = ((size_t) -1);
1357 // Never returns NULL (dies on errors)
1358 buf = xmalloc_xopen_read_close(path, &size);
1360 for (i = 0; i < size; ++i) {
1362 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1374 static void bc_num_setToZero(BcNum *n, size_t scale)
1381 static void bc_num_zero(BcNum *n)
1383 bc_num_setToZero(n, 0);
1386 static void bc_num_one(BcNum *n)
1388 bc_num_setToZero(n, 0);
1393 static void bc_num_ten(BcNum *n)
1395 bc_num_setToZero(n, 0);
1401 // Note: this also sets BcNum to zero
1402 static void bc_num_init(BcNum *n, size_t req)
1404 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1405 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1406 n->num = xmalloc(req);
1413 static void bc_num_init_DEF_SIZE(BcNum *n)
1415 bc_num_init(n, BC_NUM_DEF_SIZE);
1418 static void bc_num_expand(BcNum *n, size_t req)
1420 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1422 n->num = xrealloc(n->num, req);
1427 static FAST_FUNC void bc_num_free(void *num)
1429 free(((BcNum *) num)->num);
1432 static void bc_num_copy(BcNum *d, BcNum *s)
1435 bc_num_expand(d, s->cap);
1439 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1443 static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
1446 unsigned long pow, result;
1448 if (n->neg) return bc_error("negative number");
1450 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1452 unsigned long prev = result, powprev = pow;
1454 result += ((unsigned long) n->num[i]) * pow;
1457 if (result < prev || pow < powprev)
1458 return bc_error("overflow");
1464 return BC_STATUS_SUCCESS;
1467 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1473 if (val == 0) return;
1475 if (ULONG_MAX == 0xffffffffUL)
1476 bc_num_expand(n, 10); // 10 digits: 4294967295
1477 if (ULONG_MAX == 0xffffffffffffffffULL)
1478 bc_num_expand(n, 20); // 20 digits: 18446744073709551615
1479 BUILD_BUG_ON(ULONG_MAX > 0xffffffffffffffffULL);
1486 if (val == 0) break;
1490 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
1494 for (i = 0; i < len; ++i) {
1495 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
1502 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1503 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1504 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1505 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1506 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1508 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1510 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1511 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1513 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1516 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1520 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
1521 return BC_NUM_NEG(i + 1, c < 0);
1524 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1526 size_t i, min, a_int, b_int, diff;
1527 BcDig *max_num, *min_num;
1528 bool a_max, neg = false;
1531 if (a == b) return 0;
1532 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1533 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1543 a_int = BC_NUM_INT(a);
1544 b_int = BC_NUM_INT(b);
1546 a_max = (a->rdx > b->rdx);
1548 if (a_int != 0) return (ssize_t) a_int;
1552 diff = a->rdx - b->rdx;
1553 max_num = a->num + diff;
1558 diff = b->rdx - a->rdx;
1559 max_num = b->num + diff;
1563 cmp = bc_num_compare(max_num, min_num, b_int + min);
1564 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1566 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1567 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1573 static void bc_num_truncate(BcNum *n, size_t places)
1575 if (places == 0) return;
1581 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1585 static void bc_num_extend(BcNum *n, size_t places)
1587 size_t len = n->len + places;
1591 if (n->cap < len) bc_num_expand(n, len);
1593 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1594 memset(n->num, 0, sizeof(BcDig) * places);
1601 static void bc_num_clean(BcNum *n)
1603 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1606 else if (n->len < n->rdx)
1610 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1613 bc_num_extend(n, scale - n->rdx);
1615 bc_num_truncate(n, n->rdx - scale);
1618 if (n->len != 0) n->neg = !neg1 != !neg2;
1621 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1626 b->len = n->len - idx;
1628 a->rdx = b->rdx = 0;
1630 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1631 memcpy(a->num, n->num, idx * sizeof(BcDig));
1642 static BcStatus bc_num_shift(BcNum *n, size_t places)
1644 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
1646 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1647 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1648 if (places + n->len > BC_MAX_NUM)
1649 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1652 if (n->rdx >= places)
1655 bc_num_extend(n, places - n->rdx);
1661 return BC_STATUS_SUCCESS;
1664 static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1673 return bc_num_div(&one, a, b, scale);
1676 static FAST_FUNC BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1678 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1679 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1682 // Because this function doesn't need to use scale (per the bc spec),
1683 // I am hijacking it to say whether it's doing an add or a subtract.
1687 if (sub && c->len) c->neg = !c->neg;
1688 return BC_STATUS_SUCCESS;
1690 else if (b->len == 0) {
1692 return BC_STATUS_SUCCESS;
1696 c->rdx = BC_MAX(a->rdx, b->rdx);
1697 min_rdx = BC_MIN(a->rdx, b->rdx);
1700 if (a->rdx > b->rdx) {
1701 diff = a->rdx - b->rdx;
1703 ptr_a = a->num + diff;
1707 diff = b->rdx - a->rdx;
1710 ptr_b = b->num + diff;
1713 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1716 a_int = BC_NUM_INT(a);
1717 b_int = BC_NUM_INT(b);
1719 if (a_int > b_int) {
1730 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
1731 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1733 ptr_c[i] = (BcDig)(in % 10);
1736 for (; i < max + min_rdx; ++i, ++c->len) {
1737 in = ((int) ptr[i]) + carry;
1739 ptr_c[i] = (BcDig)(in % 10);
1742 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1744 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1747 static FAST_FUNC BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1750 BcNum *minuend, *subtrahend;
1752 bool aneg, bneg, neg;
1754 // Because this function doesn't need to use scale (per the bc spec),
1755 // I am hijacking it to say whether it's doing an add or a subtract.
1759 if (sub && c->len) c->neg = !c->neg;
1760 return BC_STATUS_SUCCESS;
1762 else if (b->len == 0) {
1764 return BC_STATUS_SUCCESS;
1769 a->neg = b->neg = false;
1771 cmp = bc_num_cmp(a, b);
1777 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1778 return BC_STATUS_SUCCESS;
1787 if (sub) neg = !neg;
1792 bc_num_copy(c, minuend);
1795 if (c->rdx < subtrahend->rdx) {
1796 bc_num_extend(c, subtrahend->rdx - c->rdx);
1800 start = c->rdx - subtrahend->rdx;
1802 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1806 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1809 static FAST_FUNC BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1813 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1814 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1817 if (a->len == 0 || b->len == 0) {
1819 return BC_STATUS_SUCCESS;
1821 aone = BC_NUM_ONE(a);
1822 if (aone || BC_NUM_ONE(b)) {
1823 bc_num_copy(c, aone ? b : a);
1824 return BC_STATUS_SUCCESS;
1827 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1828 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1833 bc_num_expand(c, a->len + b->len + 1);
1835 memset(c->num, 0, sizeof(BcDig) * c->cap);
1838 for (i = 0; i < b->len; ++i) {
1841 for (j = 0; j < a->len; ++j) {
1842 unsigned in = c->num[i + j];
1843 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1844 // note: compilers prefer _unsigned_ div/const
1846 c->num[i + j] = (BcDig)(in % 10);
1849 c->num[i + j] += (BcDig) carry;
1850 len = BC_MAX(len, i + j + !!carry);
1853 // a*a <- without check below, this will not be interruptible
1854 if (G_interrupt) return BC_STATUS_FAILURE;
1859 return BC_STATUS_SUCCESS;
1862 bc_num_init(&l1, max);
1863 bc_num_init(&h1, max);
1864 bc_num_init(&l2, max);
1865 bc_num_init(&h2, max);
1866 bc_num_init(&m1, max);
1867 bc_num_init(&m2, max);
1868 bc_num_init(&z0, max);
1869 bc_num_init(&z1, max);
1870 bc_num_init(&z2, max);
1871 bc_num_init(&temp, max + max);
1873 bc_num_split(a, max2, &l1, &h1);
1874 bc_num_split(b, max2, &l2, &h2);
1876 s = bc_num_add(&h1, &l1, &m1, 0);
1878 s = bc_num_add(&h2, &l2, &m2, 0);
1881 s = bc_num_k(&h1, &h2, &z0);
1883 s = bc_num_k(&m1, &m2, &z1);
1885 s = bc_num_k(&l1, &l2, &z2);
1888 s = bc_num_sub(&z1, &z0, &temp, 0);
1890 s = bc_num_sub(&temp, &z2, &z1, 0);
1893 s = bc_num_shift(&z0, max2 * 2);
1895 s = bc_num_shift(&z1, max2);
1897 s = bc_num_add(&z0, &z1, &temp, 0);
1899 s = bc_num_add(&temp, &z2, c, 0);
1915 static FAST_FUNC BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1919 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1921 scale = BC_MAX(scale, a->rdx);
1922 scale = BC_MAX(scale, b->rdx);
1923 scale = BC_MIN(a->rdx + b->rdx, scale);
1924 maxrdx = BC_MAX(maxrdx, scale);
1926 bc_num_init(&cpa, a->len);
1927 bc_num_init(&cpb, b->len);
1929 bc_num_copy(&cpa, a);
1930 bc_num_copy(&cpb, b);
1931 cpa.neg = cpb.neg = false;
1933 s = bc_num_shift(&cpa, maxrdx);
1935 s = bc_num_shift(&cpb, maxrdx);
1937 s = bc_num_k(&cpa, &cpb, c);
1941 bc_num_expand(c, c->len + maxrdx);
1943 if (c->len < maxrdx) {
1944 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1949 bc_num_retireMul(c, scale, a->neg, b->neg);
1957 static FAST_FUNC BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1959 BcStatus s = BC_STATUS_SUCCESS;
1966 return bc_error("divide by zero");
1967 else if (a->len == 0) {
1968 bc_num_setToZero(c, scale);
1969 return BC_STATUS_SUCCESS;
1971 else if (BC_NUM_ONE(b)) {
1973 bc_num_retireMul(c, scale, a->neg, b->neg);
1974 return BC_STATUS_SUCCESS;
1977 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1978 bc_num_copy(&cp, a);
1982 bc_num_expand(&cp, len + 2);
1983 bc_num_extend(&cp, len - cp.len);
1986 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1988 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1990 if (b->rdx == b->len) {
1991 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1995 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1997 // We want an extra zero in front to make things simpler.
1998 cp.num[cp.len++] = 0;
2001 bc_num_expand(c, cp.len);
2004 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2009 for (i = end - 1; !s && i < end; --i) {
2011 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
2012 bc_num_subArrays(n, p, len);
2016 // 1/a <- without check below, this will not be interruptible
2018 s = BC_STATUS_FAILURE;
2023 bc_num_retireMul(c, scale, a->neg, b->neg);
2029 static FAST_FUNC BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2030 BcNum *restrict d, size_t scale, size_t ts)
2037 return bc_error("divide by zero");
2040 bc_num_setToZero(d, ts);
2041 return BC_STATUS_SUCCESS;
2044 bc_num_init(&temp, d->cap);
2045 s = bc_num_d(a, b, c, scale);
2048 if (scale != 0) scale = ts;
2050 s = bc_num_m(c, b, &temp, scale);
2052 s = bc_num_sub(a, &temp, d, scale);
2055 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2058 bc_num_retireMul(d, ts, a->neg, b->neg);
2066 static FAST_FUNC BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2070 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2072 bc_num_init(&c1, len);
2073 s = bc_num_r(a, b, &c1, c, scale, ts);
2079 static FAST_FUNC BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2081 BcStatus s = BC_STATUS_SUCCESS;
2084 size_t i, powrdx, resrdx;
2087 if (b->rdx) return bc_error("non integer number");
2091 return BC_STATUS_SUCCESS;
2093 else if (a->len == 0) {
2094 bc_num_setToZero(c, scale);
2095 return BC_STATUS_SUCCESS;
2097 else if (BC_NUM_ONE(b)) {
2101 s = bc_num_inv(a, c, scale);
2108 s = bc_num_ulong(b, &pow);
2111 bc_num_init(©, a->len);
2112 bc_num_copy(©, a);
2117 if (a->rdx * pow < scale)
2118 scale = a->rdx * pow;
2123 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2125 s = bc_num_mul(©, ©, ©, powrdx);
2127 // Not needed: bc_num_mul() has a check for ^C:
2128 //if (G_interrupt) {
2129 // s = BC_STATUS_FAILURE;
2134 bc_num_copy(c, ©);
2136 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2139 s = bc_num_mul(©, ©, ©, powrdx);
2144 s = bc_num_mul(c, ©, c, resrdx);
2147 // Not needed: bc_num_mul() has a check for ^C:
2148 //if (G_interrupt) {
2149 // s = BC_STATUS_FAILURE;
2155 s = bc_num_inv(c, c, scale);
2159 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2161 // We can't use bc_num_clean() here.
2162 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2163 if (zero) bc_num_setToZero(c, scale);
2170 static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2171 BcNumBinaryOp op, size_t req)
2174 BcNum num2, *ptr_a, *ptr_b;
2179 memcpy(ptr_a, c, sizeof(BcNum));
2188 memcpy(ptr_b, c, sizeof(BcNum));
2196 bc_num_init(c, req);
2198 bc_num_expand(c, req);
2200 s = op(ptr_a, ptr_b, c, scale);
2202 if (init) bc_num_free(&num2);
2207 static void bc_num_printNewline(void)
2209 if (G.prog.nchars == G.prog.len - 1) {
2217 static FAST_FUNC void bc_num_printChar(size_t num, size_t width, bool radix)
2220 bb_putchar((char) num);
2221 G.prog.nchars += width;
2225 static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
2229 bc_num_printNewline();
2230 bb_putchar(radix ? '.' : ' ');
2233 bc_num_printNewline();
2234 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2237 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
2239 bc_num_printNewline();
2242 bb_putchar(((char) dig) + '0');
2246 static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
2249 bc_num_printNewline();
2254 bc_num_printNewline();
2255 bb_putchar(bb_hexdigits_upcase[num]);
2256 G.prog.nchars += width;
2259 static void bc_num_printDecimal(BcNum *n)
2261 size_t i, rdx = n->rdx - 1;
2263 if (n->neg) bb_putchar('-');
2264 G.prog.nchars += n->neg;
2266 for (i = n->len - 1; i < n->len; --i)
2267 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
2270 static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width, BcNumDigitOp print)
2274 BcNum intp, fracp, digit, frac_len;
2275 unsigned long dig, *ptr;
2280 print(0, width, false);
2281 return BC_STATUS_SUCCESS;
2284 bc_vec_init(&stack, sizeof(long), NULL);
2285 bc_num_init(&intp, n->len);
2286 bc_num_init(&fracp, n->rdx);
2287 bc_num_init(&digit, width);
2288 bc_num_init(&frac_len, BC_NUM_INT(n));
2289 bc_num_copy(&intp, n);
2290 bc_num_one(&frac_len);
2292 bc_num_truncate(&intp, intp.rdx);
2293 s = bc_num_sub(n, &intp, &fracp, 0);
2296 while (intp.len != 0) {
2297 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2299 s = bc_num_ulong(&digit, &dig);
2301 bc_vec_push(&stack, &dig);
2304 for (i = 0; i < stack.len; ++i) {
2305 ptr = bc_vec_item_rev(&stack, i);
2306 print(*ptr, width, false);
2309 if (!n->rdx) goto err;
2311 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2312 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2314 s = bc_num_ulong(&fracp, &dig);
2316 bc_num_ulong2num(&intp, dig);
2317 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2319 print(dig, width, radix);
2320 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2325 bc_num_free(&frac_len);
2326 bc_num_free(&digit);
2327 bc_num_free(&fracp);
2329 bc_vec_free(&stack);
2333 static BcStatus bc_num_printBase(BcNum *n)
2347 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
2349 print = bc_num_printHex;
2352 for (i = G.prog.ob_t - 1, width = 0; i != 0; i /= 10, ++width)
2354 print = bc_num_printDigits;
2357 s = bc_num_printNum(n, &G.prog.ob, width, print);
2364 static BcStatus bc_num_stream(BcNum *n, BcNum *base)
2366 return bc_num_printNum(n, base, 1, bc_num_printChar);
2370 static bool bc_num_strValid(const char *val, size_t base)
2375 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2382 if (radix) return false;
2386 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2392 // Note: n is already "bc_num_zero()"ed,
2393 // leading zeroes in "val" are removed
2394 static void bc_num_parseDecimal(BcNum *n, const char *val)
2403 bc_num_expand(n, len);
2405 ptr = strchr(val, '.');
2409 n->rdx = (size_t)((val + len) - (ptr + 1));
2411 for (i = 0; val[i]; ++i) {
2412 if (val[i] != '0' && val[i] != '.') {
2413 // Not entirely zero value - convert it, and exit
2416 n->num[n->len] = val[i] - '0';
2419 if ((ssize_t)--i == (ssize_t)-1) break;
2420 if (val[i] == '.') goto skip_dot;
2425 // if this is reached, the value is entirely zero
2428 // Note: n is already "bc_num_zero()"ed,
2429 // leading zeroes in "val" are removed
2430 static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2433 BcNum temp, mult, result;
2438 for (i = 0; ; ++i) {
2441 if (val[i] != '.' && val[i] != '0')
2445 bc_num_init_DEF_SIZE(&temp);
2446 bc_num_init_DEF_SIZE(&mult);
2450 if (c == '\0') goto int_err;
2451 if (c == '.') break;
2453 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2455 s = bc_num_mul(n, base, &mult, 0);
2456 if (s) goto int_err;
2457 bc_num_ulong2num(&temp, v);
2458 s = bc_num_add(&mult, &temp, n, 0);
2459 if (s) goto int_err;
2462 bc_num_init(&result, base->len);
2463 //bc_num_zero(&result); - already is
2469 if (c == '\0') break;
2472 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2474 s = bc_num_mul(&result, base, &result, 0);
2476 bc_num_ulong2num(&temp, v);
2477 s = bc_num_add(&result, &temp, &result, 0);
2479 s = bc_num_mul(&mult, base, &mult, 0);
2483 s = bc_num_div(&result, &mult, &result, digits);
2485 s = bc_num_add(n, &result, n, digits);
2489 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2494 bc_num_free(&result);
2500 static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2503 if (!bc_num_strValid(val, base_t))
2504 return bc_error("bad number string");
2507 while (*val == '0') val++;
2510 bc_num_parseDecimal(n, val);
2512 bc_num_parseBase(n, val, base);
2514 return BC_STATUS_SUCCESS;
2517 static BcStatus bc_num_print(BcNum *n, bool newline)
2519 BcStatus s = BC_STATUS_SUCCESS;
2521 bc_num_printNewline();
2527 else if (G.prog.ob_t == 10)
2528 bc_num_printDecimal(n);
2530 s = bc_num_printBase(n);
2540 static FAST_FUNC BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2542 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2544 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2547 static FAST_FUNC BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2549 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2551 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2554 static FAST_FUNC BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2556 size_t req = BC_NUM_MREQ(a, b, scale);
2557 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2560 static FAST_FUNC BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2562 size_t req = BC_NUM_MREQ(a, b, scale);
2563 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2566 static FAST_FUNC BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2568 size_t req = BC_NUM_MREQ(a, b, scale);
2569 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2572 static FAST_FUNC BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2574 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2577 static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2580 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2581 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2582 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2584 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2585 bc_num_expand(b, req);
2588 bc_num_setToZero(b, scale);
2589 return BC_STATUS_SUCCESS;
2592 return bc_error("negative number");
2593 else if (BC_NUM_ONE(a)) {
2595 bc_num_extend(b, scale);
2596 return BC_STATUS_SUCCESS;
2599 scale = BC_MAX(scale, a->rdx) + 1;
2600 len = a->len + scale;
2602 bc_num_init(&num1, len);
2603 bc_num_init(&num2, len);
2604 bc_num_init_DEF_SIZE(&half);
2610 bc_num_init(&f, len);
2611 bc_num_init(&fprime, len);
2617 pow = BC_NUM_INT(a);
2626 pow -= 2 - (pow & 1);
2628 bc_num_extend(x0, pow);
2630 // Make sure to move the radix back.
2634 x0->rdx = digs = digs1 = 0;
2636 len = BC_NUM_INT(x0) + resrdx - 1;
2638 while (cmp != 0 || digs < len) {
2640 s = bc_num_div(a, x0, &f, resrdx);
2642 s = bc_num_add(x0, &f, &fprime, resrdx);
2644 s = bc_num_mul(&fprime, &half, x1, resrdx);
2647 cmp = bc_num_cmp(x1, x0);
2648 digs = x1->len - (unsigned long long) llabs(cmp);
2650 if (cmp == cmp2 && digs == digs1)
2655 resrdx += times > 4;
2668 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2671 bc_num_free(&fprime);
2679 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2685 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2688 memcpy(&num2, c, sizeof(BcNum));
2690 bc_num_init(c, len);
2695 bc_num_expand(c, len);
2698 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2700 if (init) bc_num_free(&num2);
2706 static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2709 BcNum base, exp, two, temp;
2712 return bc_error("divide by zero");
2713 if (a->rdx || b->rdx || c->rdx)
2714 return bc_error("non integer number");
2716 return bc_error("negative number");
2718 bc_num_expand(d, c->len);
2719 bc_num_init(&base, c->len);
2720 bc_num_init(&exp, b->len);
2721 bc_num_init_DEF_SIZE(&two);
2722 bc_num_init(&temp, b->len);
2728 s = bc_num_rem(a, c, &base, 0);
2730 bc_num_copy(&exp, b);
2732 while (exp.len != 0) {
2734 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2737 if (BC_NUM_ONE(&temp)) {
2738 s = bc_num_mul(d, &base, &temp, 0);
2740 s = bc_num_rem(&temp, c, d, 0);
2744 s = bc_num_mul(&base, &base, &temp, 0);
2746 s = bc_num_rem(&temp, c, &base, 0);
2760 static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2765 for (i = 0; i < f->autos.len; ++i) {
2766 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2767 return bc_error("function parameter or auto var has the same name as another");
2773 bc_vec_push(&f->autos, &a);
2775 return BC_STATUS_SUCCESS;
2779 static void bc_func_init(BcFunc *f)
2781 bc_char_vec_init(&f->code);
2782 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2783 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2787 static FAST_FUNC void bc_func_free(void *func)
2789 BcFunc *f = (BcFunc *) func;
2790 bc_vec_free(&f->code);
2791 bc_vec_free(&f->autos);
2792 bc_vec_free(&f->labels);
2795 static void bc_array_expand(BcVec *a, size_t len);
2797 static void bc_array_init(BcVec *a, bool nums)
2800 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2802 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2803 bc_array_expand(a, 1);
2806 static void bc_array_expand(BcVec *a, size_t len)
2810 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2811 while (len > a->len) {
2812 bc_num_init_DEF_SIZE(&data.n);
2813 bc_vec_push(a, &data.n);
2817 while (len > a->len) {
2818 bc_array_init(&data.v, true);
2819 bc_vec_push(a, &data.v);
2824 static void bc_array_copy(BcVec *d, const BcVec *s)
2829 bc_vec_expand(d, s->cap);
2832 for (i = 0; i < s->len; ++i) {
2833 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2834 bc_num_init(dnum, snum->len);
2835 bc_num_copy(dnum, snum);
2839 static FAST_FUNC void bc_string_free(void *string)
2841 free(*((char **) string));
2845 static void bc_result_copy(BcResult *d, BcResult *src)
2851 case BC_RESULT_TEMP:
2852 case BC_RESULT_IBASE:
2853 case BC_RESULT_SCALE:
2854 case BC_RESULT_OBASE:
2856 bc_num_init(&d->d.n, src->d.n.len);
2857 bc_num_copy(&d->d.n, &src->d.n);
2862 case BC_RESULT_ARRAY:
2863 case BC_RESULT_ARRAY_ELEM:
2865 d->d.id.name = xstrdup(src->d.id.name);
2869 case BC_RESULT_CONSTANT:
2870 case BC_RESULT_LAST:
2874 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2881 static FAST_FUNC void bc_result_free(void *result)
2883 BcResult *r = (BcResult *) result;
2887 case BC_RESULT_TEMP:
2888 case BC_RESULT_IBASE:
2889 case BC_RESULT_SCALE:
2890 case BC_RESULT_OBASE:
2892 bc_num_free(&r->d.n);
2897 case BC_RESULT_ARRAY:
2898 case BC_RESULT_ARRAY_ELEM:
2912 static void bc_lex_lineComment(BcLex *l)
2914 l->t.t = BC_LEX_WHITESPACE;
2915 while (l->i < l->len && l->buf[l->i++] != '\n');
2919 static void bc_lex_whitespace(BcLex *l)
2922 l->t.t = BC_LEX_WHITESPACE;
2923 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2926 static BcStatus bc_lex_number(BcLex *l, char start)
2928 const char *buf = l->buf + l->i;
2929 size_t len, hits = 0, bslashes = 0, i = 0, j;
2931 bool last_pt, pt = start == '.';
2934 l->t.t = BC_LEX_NUMBER;
2936 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2937 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2951 len = i + !last_pt - bslashes * 2;
2952 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2953 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2954 if (len > BC_MAX_NUM)
2955 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2958 bc_vec_pop_all(&l->t.v);
2959 bc_vec_expand(&l->t.v, len + 1);
2960 bc_vec_push(&l->t.v, &start);
2962 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2966 // If we have hit a backslash, skip it. We don't have
2967 // to check for a newline because it's guaranteed.
2968 if (hits < bslashes && c == '\\') {
2974 bc_vec_push(&l->t.v, &c);
2977 bc_vec_pushZeroByte(&l->t.v);
2980 return BC_STATUS_SUCCESS;
2983 static BcStatus bc_lex_name(BcLex *l)
2986 const char *buf = l->buf + l->i - 1;
2989 l->t.t = BC_LEX_NAME;
2991 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2993 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2994 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2995 if (i > BC_MAX_STRING)
2996 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2998 bc_vec_string(&l->t.v, i, buf);
3000 // Increment the index. We minus 1 because it has already been incremented.
3003 return BC_STATUS_SUCCESS;
3006 static void bc_lex_init(BcLex *l, BcLexNext next)
3009 bc_char_vec_init(&l->t.v);
3012 static void bc_lex_free(BcLex *l)
3014 bc_vec_free(&l->t.v);
3017 static void bc_lex_file(BcLex *l)
3019 G.err_line = l->line = 1;
3023 static BcStatus bc_lex_next(BcLex *l)
3028 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
3030 l->line += l->newline;
3031 G.err_line = l->line;
3032 l->t.t = BC_LEX_EOF;
3034 l->newline = (l->i == l->len);
3035 if (l->newline) return BC_STATUS_SUCCESS;
3037 // Loop until failure or we don't have whitespace. This
3038 // is so the parser doesn't get inundated with whitespace.
3041 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3046 static BcStatus bc_lex_text(BcLex *l, const char *text)
3050 l->len = strlen(text);
3051 l->t.t = l->t.last = BC_LEX_INVALID;
3052 return bc_lex_next(l);
3056 static BcStatus bc_lex_identifier(BcLex *l)
3060 const char *buf = l->buf + l->i - 1;
3062 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3063 const char *keyword8 = bc_lex_kws[i].name8;
3065 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3067 if (j == 8) goto match;
3069 if (keyword8[j] != '\0')
3072 // buf starts with keyword bc_lex_kws[i]
3073 l->t.t = BC_LEX_KEY_1st_keyword + i;
3074 if (!bc_lex_kws_POSIX(i)) {
3075 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3079 // We minus 1 because the index has already been incremented.
3081 return BC_STATUS_SUCCESS;
3087 if (l->t.v.len > 2) {
3090 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3092 unsigned len = strchrnul(buf, '\n') - buf;
3093 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3099 static BcStatus bc_lex_string(BcLex *l)
3101 size_t len, nls = 0, i = l->i;
3104 l->t.t = BC_LEX_STR;
3106 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3110 return bc_error("string end could not be found");
3114 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3115 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3116 if (len > BC_MAX_STRING)
3117 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3119 bc_vec_string(&l->t.v, len, l->buf + l->i);
3123 G.err_line = l->line;
3125 return BC_STATUS_SUCCESS;
3128 static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3130 if (l->buf[l->i] == '=') {
3138 static BcStatus bc_lex_comment(BcLex *l)
3141 const char *buf = l->buf;
3143 l->t.t = BC_LEX_WHITESPACE;
3156 return bc_error("comment end could not be found");
3164 G.err_line = l->line;
3166 return BC_STATUS_SUCCESS;
3169 static FAST_FUNC BcStatus bc_lex_token(BcLex *l)
3171 BcStatus s = BC_STATUS_SUCCESS;
3172 char c = l->buf[l->i++], c2;
3174 // This is the workhorse of the lexer.
3181 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3191 bc_lex_whitespace(l);
3197 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3199 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
3200 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3209 s = bc_lex_string(l);
3215 s = bc_POSIX_does_not_allow("'#' script comments");
3218 bc_lex_lineComment(l);
3225 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3234 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3238 l->t.t = BC_LEX_OP_BOOL_AND;
3241 l->t.t = BC_LEX_INVALID;
3242 s = bc_error_bad_character('&');
3251 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3257 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3266 l->t.t = BC_LEX_OP_INC;
3269 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3275 l->t.t = BC_LEX_COMMA;
3284 l->t.t = BC_LEX_OP_DEC;
3287 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3293 if (isdigit(l->buf[l->i]))
3294 s = bc_lex_number(l, c);
3296 l->t.t = BC_LEX_KEY_LAST;
3297 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3306 s = bc_lex_comment(l);
3308 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3329 s = bc_lex_number(l, c);
3335 l->t.t = BC_LEX_SCOLON;
3341 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3347 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3353 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3360 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3366 if (l->buf[l->i] == '\n') {
3367 l->t.t = BC_LEX_WHITESPACE;
3371 s = bc_error_bad_character(c);
3377 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3408 s = bc_lex_identifier(l);
3415 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3424 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3428 l->t.t = BC_LEX_OP_BOOL_OR;
3431 l->t.t = BC_LEX_INVALID;
3432 s = bc_error_bad_character(c);
3440 l->t.t = BC_LEX_INVALID;
3441 s = bc_error_bad_character(c);
3451 static BcStatus dc_lex_register(BcLex *l)
3453 BcStatus s = BC_STATUS_SUCCESS;
3455 if (isspace(l->buf[l->i - 1])) {
3456 bc_lex_whitespace(l);
3459 s = bc_error("extended register");
3464 bc_vec_pop_all(&l->t.v);
3465 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
3466 bc_vec_pushZeroByte(&l->t.v);
3467 l->t.t = BC_LEX_NAME;
3473 static BcStatus dc_lex_string(BcLex *l)
3475 size_t depth = 1, nls = 0, i = l->i;
3478 l->t.t = BC_LEX_STR;
3479 bc_vec_pop_all(&l->t.v);
3481 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3483 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3484 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3487 if (depth) bc_vec_push(&l->t.v, &c);
3492 return bc_error("string end could not be found");
3495 bc_vec_pushZeroByte(&l->t.v);
3496 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3497 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3498 if (i - l->i > BC_MAX_STRING)
3499 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3504 G.err_line = l->line;
3506 return BC_STATUS_SUCCESS;
3509 static FAST_FUNC BcStatus dc_lex_token(BcLex *l)
3511 BcStatus s = BC_STATUS_SUCCESS;
3512 char c = l->buf[l->i++], c2;
3515 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3516 if (l->t.last == dc_lex_regs[i])
3517 return dc_lex_register(l);
3520 if (c >= '%' && c <= '~' &&
3521 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3526 // This is the workhorse of the lexer.
3531 l->t.t = BC_LEX_EOF;
3542 l->newline = (c == '\n');
3543 bc_lex_whitespace(l);
3552 l->t.t = BC_LEX_OP_REL_NE;
3554 l->t.t = BC_LEX_OP_REL_LE;
3556 l->t.t = BC_LEX_OP_REL_GE;
3558 return bc_error_bad_character(c);
3566 bc_lex_lineComment(l);
3572 if (isdigit(l->buf[l->i]))
3573 s = bc_lex_number(l, c);
3575 s = bc_error_bad_character(c);
3596 s = bc_lex_number(l, c);
3602 s = dc_lex_string(l);
3608 l->t.t = BC_LEX_INVALID;
3609 s = bc_error_bad_character(c);
3618 static void bc_program_addFunc(char *name, size_t *idx);
3620 static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3622 bc_program_addFunc(name, idx);
3623 p->func = bc_program_func(p->fidx);
3626 #define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3628 static void bc_parse_pushName(BcParse *p, char *name)
3630 size_t i = 0, len = strlen(name);
3632 for (; i < len; ++i) bc_parse_push(p, name[i]);
3633 bc_parse_push(p, BC_PARSE_STREND);
3638 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3640 unsigned char amt, i, nums[sizeof(size_t)];
3642 for (amt = 0; idx; ++amt) {
3643 nums[amt] = (char) idx;
3644 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3647 bc_parse_push(p, amt);
3648 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3651 static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3653 char *num = xstrdup(p->l.t.v.v);
3654 size_t idx = G.prog.consts.len;
3656 bc_vec_push(&G.prog.consts, &num);
3658 bc_parse_push(p, BC_INST_NUM);
3659 bc_parse_pushIndex(p, idx);
3662 (*prev) = BC_INST_NUM;
3665 static BcStatus bc_parse_text(BcParse *p, const char *text)
3669 p->func = bc_program_func(p->fidx);
3671 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
3672 p->l.t.t = BC_LEX_INVALID;
3675 if (!BC_PARSE_CAN_EXEC(p))
3676 return bc_error("file is not executable");
3679 return bc_lex_text(&p->l, text);
3682 // Called when parsing or execution detects a failure,
3683 // resets execution structures.
3684 static void bc_program_reset(void)
3689 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3690 bc_vec_pop_all(&G.prog.results);
3692 f = bc_program_func(0);
3693 ip = bc_vec_top(&G.prog.stack);
3694 ip->idx = f->code.len;
3697 #define bc_parse_updateFunc(p, f) \
3698 ((p)->func = bc_program_func((p)->fidx = (f)))
3700 // Called when bc/dc_parse_parse() detects a failure,
3701 // resets parsing structures.
3702 static void bc_parse_reset(BcParse *p)
3704 if (p->fidx != BC_PROG_MAIN) {
3705 p->func->nparams = 0;
3706 bc_vec_pop_all(&p->func->code);
3707 bc_vec_pop_all(&p->func->autos);
3708 bc_vec_pop_all(&p->func->labels);
3710 bc_parse_updateFunc(p, BC_PROG_MAIN);
3714 p->l.t.t = BC_LEX_EOF;
3715 p->auto_part = (p->nbraces = 0);
3717 bc_vec_npop(&p->flags, p->flags.len - 1);
3718 bc_vec_pop_all(&p->exits);
3719 bc_vec_pop_all(&p->conds);
3720 bc_vec_pop_all(&p->ops);
3725 static void bc_parse_free(BcParse *p)
3727 bc_vec_free(&p->flags);
3728 bc_vec_free(&p->exits);
3729 bc_vec_free(&p->conds);
3730 bc_vec_free(&p->ops);
3734 static void bc_parse_create(BcParse *p, size_t func,
3735 BcParseParse parse, BcLexNext next)
3737 memset(p, 0, sizeof(BcParse));
3739 bc_lex_init(&p->l, next);
3740 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3741 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3742 bc_vec_init(&p->conds, sizeof(size_t), NULL);
3743 bc_vec_pushZeroByte(&p->flags);
3744 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3747 // p->auto_part = p->nbraces = 0; - already is
3748 bc_parse_updateFunc(p, func);
3753 #define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3754 #define BC_PARSE_LEAF(p, rparen) \
3755 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3756 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3758 // We can calculate the conversion between tokens and exprs by subtracting the
3759 // position of the first operator in the lex enum and adding the position of the
3760 // first in the expr enum. Note: This only works for binary operators.
3761 #define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3763 static BcStatus bc_parse_else(BcParse *p);
3764 static BcStatus bc_parse_stmt(BcParse *p);
3765 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
3766 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
3768 static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3769 size_t *nexprs, bool next)
3771 BcStatus s = BC_STATUS_SUCCESS;
3773 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3774 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
3776 while (p->ops.len > start) {
3778 t = BC_PARSE_TOP_OP(p);
3779 if (t == BC_LEX_LPAREN) break;
3781 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
3782 if (l >= r && (l != r || !left)) break;
3784 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3785 bc_vec_pop(&p->ops);
3786 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3789 bc_vec_push(&p->ops, &type);
3790 if (next) s = bc_lex_next(&p->l);
3795 static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3799 if (p->ops.len <= ops_bgn)
3800 return bc_error_bad_expression();
3801 top = BC_PARSE_TOP_OP(p);
3803 while (top != BC_LEX_LPAREN) {
3805 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3807 bc_vec_pop(&p->ops);
3808 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3810 if (p->ops.len <= ops_bgn)
3811 return bc_error_bad_expression();
3812 top = BC_PARSE_TOP_OP(p);
3815 bc_vec_pop(&p->ops);
3817 return bc_lex_next(&p->l);
3820 static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3826 s = bc_lex_next(&p->l);
3829 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3831 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3832 s = bc_parse_expr(p, flags, bc_parse_next_param);
3835 comma = p->l.t.t == BC_LEX_COMMA;
3837 s = bc_lex_next(&p->l);
3842 if (comma) return bc_error_bad_token();
3843 bc_parse_push(p, BC_INST_CALL);
3844 bc_parse_pushIndex(p, nparams);
3846 return BC_STATUS_SUCCESS;
3849 static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3852 BcId entry, *entry_ptr;
3857 s = bc_parse_params(p, flags);
3860 if (p->l.t.t != BC_LEX_RPAREN) {
3861 s = bc_error_bad_token();
3865 idx = bc_map_index(&G.prog.fn_map, &entry);
3867 if (idx == BC_VEC_INVALID_IDX) {
3868 name = xstrdup(entry.name);
3869 bc_parse_addFunc(p, name, &idx);
3870 idx = bc_map_index(&G.prog.fn_map, &entry);
3876 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3877 bc_parse_pushIndex(p, entry_ptr->idx);
3879 return bc_lex_next(&p->l);
3886 static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3891 name = xstrdup(p->l.t.v.v);
3892 s = bc_lex_next(&p->l);
3895 if (p->l.t.t == BC_LEX_LBRACKET) {
3897 s = bc_lex_next(&p->l);
3900 if (p->l.t.t == BC_LEX_RBRACKET) {
3902 if (!(flags & BC_PARSE_ARRAY)) {
3903 s = bc_error_bad_expression();
3907 *type = BC_INST_ARRAY;
3911 *type = BC_INST_ARRAY_ELEM;
3913 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3914 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3918 s = bc_lex_next(&p->l);
3920 bc_parse_push(p, *type);
3921 bc_parse_pushName(p, name);
3923 else if (p->l.t.t == BC_LEX_LPAREN) {
3925 if (flags & BC_PARSE_NOCALL) {
3926 s = bc_error_bad_token();
3930 *type = BC_INST_CALL;
3931 s = bc_parse_call(p, name, flags);
3934 *type = BC_INST_VAR;
3935 bc_parse_push(p, BC_INST_VAR);
3936 bc_parse_pushName(p, name);
3946 static BcStatus bc_parse_read(BcParse *p)
3950 s = bc_lex_next(&p->l);
3952 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3954 s = bc_lex_next(&p->l);
3956 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3958 bc_parse_push(p, BC_INST_READ);
3960 return bc_lex_next(&p->l);
3963 static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3968 s = bc_lex_next(&p->l);
3970 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3972 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3974 s = bc_lex_next(&p->l);
3977 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3980 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3982 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3983 bc_parse_push(p, *prev);
3985 return bc_lex_next(&p->l);
3988 static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3992 s = bc_lex_next(&p->l);
3995 if (p->l.t.t != BC_LEX_LPAREN) {
3996 *type = BC_INST_SCALE;
3997 bc_parse_push(p, BC_INST_SCALE);
3998 return BC_STATUS_SUCCESS;
4001 *type = BC_INST_SCALE_FUNC;
4002 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
4004 s = bc_lex_next(&p->l);
4007 s = bc_parse_expr(p, flags, bc_parse_next_rel);
4009 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4010 bc_parse_push(p, BC_INST_SCALE_FUNC);
4012 return bc_lex_next(&p->l);
4015 static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
4016 size_t *nexprs, uint8_t flags)
4021 BcInst etype = *prev;
4023 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4024 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4025 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4027 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4028 bc_parse_push(p, inst);
4029 s = bc_lex_next(&p->l);
4033 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4036 s = bc_lex_next(&p->l);
4040 // Because we parse the next part of the expression
4041 // right here, we need to increment this.
4042 *nexprs = *nexprs + 1;
4048 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4052 case BC_LEX_KEY_IBASE:
4053 case BC_LEX_KEY_LAST:
4054 case BC_LEX_KEY_OBASE:
4056 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4057 s = bc_lex_next(&p->l);
4061 case BC_LEX_KEY_SCALE:
4063 s = bc_lex_next(&p->l);
4065 if (p->l.t.t == BC_LEX_LPAREN)
4066 s = bc_error_bad_token();
4068 bc_parse_push(p, BC_INST_SCALE);
4074 s = bc_error_bad_token();
4079 if (!s) bc_parse_push(p, inst);
4085 static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4086 bool rparen, size_t *nexprs)
4090 BcInst etype = *prev;
4092 s = bc_lex_next(&p->l);
4095 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4096 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4099 *prev = BC_PARSE_TOKEN_INST(type);
4101 // We can just push onto the op stack because this is the largest
4102 // precedence operator that gets pushed. Inc/dec does not.
4103 if (type != BC_LEX_OP_MINUS)
4104 bc_vec_push(&p->ops, &type);
4106 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4111 static BcStatus bc_parse_string(BcParse *p, char inst)
4113 char *str = xstrdup(p->l.t.v.v);
4115 bc_parse_push(p, BC_INST_STR);
4116 bc_parse_pushIndex(p, G.prog.strs.len);
4117 bc_vec_push(&G.prog.strs, &str);
4118 bc_parse_push(p, inst);
4120 return bc_lex_next(&p->l);
4123 static BcStatus bc_parse_print(BcParse *p)
4129 s = bc_lex_next(&p->l);
4134 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
4135 return bc_error("bad print statement");
4138 while (type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4140 if (type == BC_LEX_STR) {
4141 s = bc_parse_string(p, BC_INST_PRINT_POP);
4144 s = bc_parse_expr(p, 0, bc_parse_next_print);
4146 bc_parse_push(p, BC_INST_PRINT_POP);
4149 comma = p->l.t.t == BC_LEX_COMMA;
4151 s = bc_lex_next(&p->l);
4157 if (comma) return bc_error_bad_token();
4159 return bc_lex_next(&p->l);
4162 static BcStatus bc_parse_return(BcParse *p)
4168 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
4170 s = bc_lex_next(&p->l);
4174 paren = t == BC_LEX_LPAREN;
4176 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4177 bc_parse_push(p, BC_INST_RET0);
4180 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
4181 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4182 bc_parse_push(p, BC_INST_RET0);
4183 s = bc_lex_next(&p->l);
4187 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
4188 s = bc_POSIX_requires("parentheses around return expressions");
4192 bc_parse_push(p, BC_INST_RET);
4198 static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4200 BcStatus s = BC_STATUS_SUCCESS;
4202 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
4203 return bc_error_bad_token();
4207 if (p->l.t.t == BC_LEX_RBRACE) {
4208 if (!p->nbraces) return bc_error_bad_token();
4210 s = bc_lex_next(&p->l);
4214 return bc_error_bad_token();
4217 if (BC_PARSE_IF(p)) {
4221 while (p->l.t.t == BC_LEX_NLINE) {
4222 s = bc_lex_next(&p->l);
4226 bc_vec_pop(&p->flags);
4228 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4229 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4231 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4233 else if (BC_PARSE_ELSE(p)) {
4238 bc_vec_pop(&p->flags);
4240 ip = bc_vec_top(&p->exits);
4241 label = bc_vec_item(&p->func->labels, ip->idx);
4242 *label = p->func->code.len;
4244 bc_vec_pop(&p->exits);
4246 else if (BC_PARSE_FUNC_INNER(p)) {
4247 bc_parse_push(p, BC_INST_RET0);
4248 bc_parse_updateFunc(p, BC_PROG_MAIN);
4249 bc_vec_pop(&p->flags);
4253 BcInstPtr *ip = bc_vec_top(&p->exits);
4254 size_t *label = bc_vec_top(&p->conds);
4256 bc_parse_push(p, BC_INST_JUMP);
4257 bc_parse_pushIndex(p, *label);
4259 label = bc_vec_item(&p->func->labels, ip->idx);
4260 *label = p->func->code.len;
4262 bc_vec_pop(&p->flags);
4263 bc_vec_pop(&p->exits);
4264 bc_vec_pop(&p->conds);
4270 static void bc_parse_startBody(BcParse *p, uint8_t flags)
4272 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4273 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4274 flags |= BC_PARSE_FLAG_BODY;
4275 bc_vec_push(&p->flags, &flags);
4278 static void bc_parse_noElse(BcParse *p)
4282 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4284 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4286 ip = bc_vec_top(&p->exits);
4287 label = bc_vec_item(&p->func->labels, ip->idx);
4288 *label = p->func->code.len;
4290 bc_vec_pop(&p->exits);
4293 static BcStatus bc_parse_if(BcParse *p)
4298 s = bc_lex_next(&p->l);
4300 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4302 s = bc_lex_next(&p->l);
4304 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4306 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4308 s = bc_lex_next(&p->l);
4310 bc_parse_push(p, BC_INST_JUMP_ZERO);
4312 ip.idx = p->func->labels.len;
4313 ip.func = ip.len = 0;
4315 bc_parse_pushIndex(p, ip.idx);
4316 bc_vec_push(&p->exits, &ip);
4317 bc_vec_push(&p->func->labels, &ip.idx);
4318 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4320 return BC_STATUS_SUCCESS;
4323 static BcStatus bc_parse_else(BcParse *p)
4327 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
4329 ip.idx = p->func->labels.len;
4330 ip.func = ip.len = 0;
4332 bc_parse_push(p, BC_INST_JUMP);
4333 bc_parse_pushIndex(p, ip.idx);
4337 bc_vec_push(&p->exits, &ip);
4338 bc_vec_push(&p->func->labels, &ip.idx);
4339 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4341 return bc_lex_next(&p->l);
4344 static BcStatus bc_parse_while(BcParse *p)
4349 s = bc_lex_next(&p->l);
4351 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4352 s = bc_lex_next(&p->l);
4355 ip.idx = p->func->labels.len;
4357 bc_vec_push(&p->func->labels, &p->func->code.len);
4358 bc_vec_push(&p->conds, &ip.idx);
4360 ip.idx = p->func->labels.len;
4364 bc_vec_push(&p->exits, &ip);
4365 bc_vec_push(&p->func->labels, &ip.idx);
4367 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4369 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4370 s = bc_lex_next(&p->l);
4373 bc_parse_push(p, BC_INST_JUMP_ZERO);
4374 bc_parse_pushIndex(p, ip.idx);
4375 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4377 return BC_STATUS_SUCCESS;
4380 static BcStatus bc_parse_for(BcParse *p)
4384 size_t cond_idx, exit_idx, body_idx, update_idx;
4386 s = bc_lex_next(&p->l);
4388 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4389 s = bc_lex_next(&p->l);
4392 if (p->l.t.t != BC_LEX_SCOLON)
4393 s = bc_parse_expr(p, 0, bc_parse_next_for);
4395 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4398 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4399 s = bc_lex_next(&p->l);
4402 cond_idx = p->func->labels.len;
4403 update_idx = cond_idx + 1;
4404 body_idx = update_idx + 1;
4405 exit_idx = body_idx + 1;
4407 bc_vec_push(&p->func->labels, &p->func->code.len);
4409 if (p->l.t.t != BC_LEX_SCOLON)
4410 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4412 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4415 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4417 s = bc_lex_next(&p->l);
4420 bc_parse_push(p, BC_INST_JUMP_ZERO);
4421 bc_parse_pushIndex(p, exit_idx);
4422 bc_parse_push(p, BC_INST_JUMP);
4423 bc_parse_pushIndex(p, body_idx);
4425 ip.idx = p->func->labels.len;
4427 bc_vec_push(&p->conds, &update_idx);
4428 bc_vec_push(&p->func->labels, &p->func->code.len);
4430 if (p->l.t.t != BC_LEX_RPAREN)
4431 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4433 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4437 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4438 bc_parse_push(p, BC_INST_JUMP);
4439 bc_parse_pushIndex(p, cond_idx);
4440 bc_vec_push(&p->func->labels, &p->func->code.len);
4446 bc_vec_push(&p->exits, &ip);
4447 bc_vec_push(&p->func->labels, &ip.idx);
4449 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4451 return BC_STATUS_SUCCESS;
4454 static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4460 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
4462 if (type == BC_LEX_KEY_BREAK) {
4464 if (p->exits.len == 0) return bc_error_bad_token();
4466 i = p->exits.len - 1;
4467 ip = bc_vec_item(&p->exits, i);
4469 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
4470 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
4475 i = *((size_t *) bc_vec_top(&p->conds));
4477 bc_parse_push(p, BC_INST_JUMP);
4478 bc_parse_pushIndex(p, i);
4480 s = bc_lex_next(&p->l);
4483 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
4484 return bc_error_bad_token();
4486 return bc_lex_next(&p->l);
4489 static BcStatus bc_parse_func(BcParse *p)
4492 bool var, comma = false;
4496 s = bc_lex_next(&p->l);
4498 if (p->l.t.t != BC_LEX_NAME)
4499 return bc_error("bad function definition");
4501 name = xstrdup(p->l.t.v.v);
4502 bc_parse_addFunc(p, name, &p->fidx);
4504 s = bc_lex_next(&p->l);
4506 if (p->l.t.t != BC_LEX_LPAREN)
4507 return bc_error("bad function definition");
4508 s = bc_lex_next(&p->l);
4511 while (p->l.t.t != BC_LEX_RPAREN) {
4513 if (p->l.t.t != BC_LEX_NAME)
4514 return bc_error("bad function definition");
4518 name = xstrdup(p->l.t.v.v);
4519 s = bc_lex_next(&p->l);
4522 var = p->l.t.t != BC_LEX_LBRACKET;
4526 s = bc_lex_next(&p->l);
4529 if (p->l.t.t != BC_LEX_RBRACKET) {
4530 s = bc_error("bad function definition");
4534 s = bc_lex_next(&p->l);
4538 comma = p->l.t.t == BC_LEX_COMMA;
4540 s = bc_lex_next(&p->l);
4544 s = bc_func_insert(p->func, name, var);
4548 if (comma) return bc_error("bad function definition");
4550 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4551 bc_parse_startBody(p, flags);
4553 s = bc_lex_next(&p->l);
4556 if (p->l.t.t != BC_LEX_LBRACE)
4557 s = bc_POSIX_requires("the left brace be on the same line as the function header");
4566 static BcStatus bc_parse_auto(BcParse *p)
4569 bool comma, var, one;
4572 if (!p->auto_part) return bc_error_bad_token();
4573 s = bc_lex_next(&p->l);
4576 p->auto_part = comma = false;
4577 one = p->l.t.t == BC_LEX_NAME;
4579 while (p->l.t.t == BC_LEX_NAME) {
4581 name = xstrdup(p->l.t.v.v);
4582 s = bc_lex_next(&p->l);
4585 var = p->l.t.t != BC_LEX_LBRACKET;
4588 s = bc_lex_next(&p->l);
4591 if (p->l.t.t != BC_LEX_RBRACKET) {
4592 s = bc_error("bad function definition");
4596 s = bc_lex_next(&p->l);
4600 comma = p->l.t.t == BC_LEX_COMMA;
4602 s = bc_lex_next(&p->l);
4606 s = bc_func_insert(p->func, name, var);
4610 if (comma) return bc_error("bad function definition");
4611 if (!one) return bc_error("no auto variable found");
4613 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
4614 return bc_error_bad_token();
4616 return bc_lex_next(&p->l);
4623 static BcStatus bc_parse_body(BcParse *p, bool brace)
4625 BcStatus s = BC_STATUS_SUCCESS;
4626 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4628 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4630 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4632 if (!brace) return bc_error_bad_token();
4633 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4635 if (!p->auto_part) {
4636 s = bc_parse_auto(p);
4640 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4643 s = bc_parse_stmt(p);
4644 if (!s && !brace) s = bc_parse_endBody(p, false);
4650 static BcStatus bc_parse_stmt(BcParse *p)
4652 BcStatus s = BC_STATUS_SUCCESS;
4658 return bc_lex_next(&p->l);
4661 case BC_LEX_KEY_ELSE:
4663 p->auto_part = false;
4669 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
4672 s = bc_lex_next(&p->l);
4675 return bc_parse_body(p, true);
4678 case BC_LEX_KEY_AUTO:
4680 return bc_parse_auto(p);
4685 p->auto_part = false;
4687 if (BC_PARSE_IF_END(p)) {
4689 return BC_STATUS_SUCCESS;
4691 else if (BC_PARSE_BODY(p))
4692 return bc_parse_body(p, false);
4702 case BC_LEX_OP_MINUS:
4703 case BC_LEX_OP_BOOL_NOT:
4707 case BC_LEX_KEY_IBASE:
4708 case BC_LEX_KEY_LAST:
4709 case BC_LEX_KEY_LENGTH:
4710 case BC_LEX_KEY_OBASE:
4711 case BC_LEX_KEY_READ:
4712 case BC_LEX_KEY_SCALE:
4713 case BC_LEX_KEY_SQRT:
4715 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4719 case BC_LEX_KEY_ELSE:
4721 s = bc_parse_else(p);
4727 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4733 s = bc_parse_endBody(p, true);
4739 s = bc_parse_string(p, BC_INST_PRINT_STR);
4743 case BC_LEX_KEY_BREAK:
4744 case BC_LEX_KEY_CONTINUE:
4746 s = bc_parse_loopExit(p, p->l.t.t);
4750 case BC_LEX_KEY_FOR:
4752 s = bc_parse_for(p);
4756 case BC_LEX_KEY_HALT:
4758 bc_parse_push(p, BC_INST_HALT);
4759 s = bc_lex_next(&p->l);
4769 case BC_LEX_KEY_LIMITS:
4771 // "limits" is a compile-time command,
4772 // the output is produced at _parse time_.
4773 s = bc_lex_next(&p->l);
4776 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4777 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4778 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4779 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4780 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4781 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4782 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4783 "Number of vars = "BC_MAX_VARS_STR "\n"
4788 case BC_LEX_KEY_PRINT:
4790 s = bc_parse_print(p);
4794 case BC_LEX_KEY_QUIT:
4796 // "quit" is a compile-time command. For example,
4797 // "if (0 == 1) quit" terminates when parsing the statement,
4798 // not when it is executed
4799 QUIT_OR_RETURN_TO_MAIN;
4802 case BC_LEX_KEY_RETURN:
4804 s = bc_parse_return(p);
4808 case BC_LEX_KEY_WHILE:
4810 s = bc_parse_while(p);
4816 s = bc_error_bad_token();
4824 static FAST_FUNC BcStatus bc_parse_parse(BcParse *p)
4828 if (p->l.t.t == BC_LEX_EOF)
4829 s = p->flags.len > 0 ? bc_error("block end could not be found") : bc_error("end of file");
4830 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
4831 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
4832 s = bc_parse_func(p);
4835 s = bc_parse_stmt(p);
4837 if (s || G_interrupt) {
4839 s = BC_STATUS_FAILURE;
4845 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
4847 BcStatus s = BC_STATUS_SUCCESS;
4848 BcInst prev = BC_INST_PRINT;
4849 BcLexType top, t = p->l.t.t;
4850 size_t nexprs = 0, ops_bgn = p->ops.len;
4851 unsigned nparens, nrelops;
4852 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4854 paren_first = p->l.t.t == BC_LEX_LPAREN;
4855 nparens = nrelops = 0;
4856 paren_expr = rprn = done = get_token = assign = false;
4859 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
4865 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4866 rprn = get_token = bin_last = false;
4870 case BC_LEX_OP_MINUS:
4872 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4873 rprn = get_token = false;
4874 bin_last = prev == BC_INST_MINUS;
4878 case BC_LEX_OP_ASSIGN_POWER:
4879 case BC_LEX_OP_ASSIGN_MULTIPLY:
4880 case BC_LEX_OP_ASSIGN_DIVIDE:
4881 case BC_LEX_OP_ASSIGN_MODULUS:
4882 case BC_LEX_OP_ASSIGN_PLUS:
4883 case BC_LEX_OP_ASSIGN_MINUS:
4884 case BC_LEX_OP_ASSIGN:
4886 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4887 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4888 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4890 s = bc_error("bad assignment:"
4891 " left side must be scale,"
4892 " ibase, obase, last, var,"
4899 case BC_LEX_OP_POWER:
4900 case BC_LEX_OP_MULTIPLY:
4901 case BC_LEX_OP_DIVIDE:
4902 case BC_LEX_OP_MODULUS:
4903 case BC_LEX_OP_PLUS:
4904 case BC_LEX_OP_REL_EQ:
4905 case BC_LEX_OP_REL_LE:
4906 case BC_LEX_OP_REL_GE:
4907 case BC_LEX_OP_REL_NE:
4908 case BC_LEX_OP_REL_LT:
4909 case BC_LEX_OP_REL_GT:
4910 case BC_LEX_OP_BOOL_NOT:
4911 case BC_LEX_OP_BOOL_OR:
4912 case BC_LEX_OP_BOOL_AND:
4914 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4915 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4917 return bc_error_bad_expression();
4920 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4921 prev = BC_PARSE_TOKEN_INST(t);
4922 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4923 rprn = get_token = false;
4924 bin_last = t != BC_LEX_OP_BOOL_NOT;
4931 if (BC_PARSE_LEAF(prev, rprn))
4932 return bc_error_bad_expression();
4934 paren_expr = rprn = bin_last = false;
4936 bc_vec_push(&p->ops, &t);
4943 if (bin_last || prev == BC_INST_BOOL_NOT)
4944 return bc_error_bad_expression();
4947 s = BC_STATUS_SUCCESS;
4952 else if (!paren_expr)
4953 return BC_STATUS_PARSE_EMPTY_EXP;
4956 paren_expr = rprn = true;
4957 get_token = bin_last = false;
4959 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4966 if (BC_PARSE_LEAF(prev, rprn))
4967 return bc_error_bad_expression();
4969 rprn = get_token = bin_last = false;
4970 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4978 if (BC_PARSE_LEAF(prev, rprn))
4979 return bc_error_bad_expression();
4980 bc_parse_number(p, &prev, &nexprs);
4981 paren_expr = get_token = true;
4982 rprn = bin_last = false;
4987 case BC_LEX_KEY_IBASE:
4988 case BC_LEX_KEY_LAST:
4989 case BC_LEX_KEY_OBASE:
4991 if (BC_PARSE_LEAF(prev, rprn))
4992 return bc_error_bad_expression();
4993 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4994 bc_parse_push(p, (char) prev);
4996 paren_expr = get_token = true;
4997 rprn = bin_last = false;
5003 case BC_LEX_KEY_LENGTH:
5004 case BC_LEX_KEY_SQRT:
5006 if (BC_PARSE_LEAF(prev, rprn))
5007 return bc_error_bad_expression();
5008 s = bc_parse_builtin(p, t, flags, &prev);
5010 rprn = get_token = bin_last = false;
5016 case BC_LEX_KEY_READ:
5018 if (BC_PARSE_LEAF(prev, rprn))
5019 return bc_error_bad_expression();
5020 else if (flags & BC_PARSE_NOREAD)
5021 s = bc_error_nested_read_call();
5023 s = bc_parse_read(p);
5026 rprn = get_token = bin_last = false;
5028 prev = BC_INST_READ;
5033 case BC_LEX_KEY_SCALE:
5035 if (BC_PARSE_LEAF(prev, rprn))
5036 return bc_error_bad_expression();
5037 s = bc_parse_scale(p, &prev, flags);
5039 rprn = get_token = bin_last = false;
5041 prev = BC_INST_SCALE;
5048 s = bc_error_bad_token();
5053 if (!s && get_token) s = bc_lex_next(&p->l);
5057 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
5059 while (p->ops.len > ops_bgn) {
5061 top = BC_PARSE_TOP_OP(p);
5062 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5064 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
5065 return bc_error_bad_expression();
5067 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5069 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5070 bc_vec_pop(&p->ops);
5073 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
5074 return bc_error_bad_expression();
5076 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5078 if (t == (next & 0x7f))
5080 if (next & 0x80) // last element?
5084 return bc_error_bad_expression();
5087 if (!(flags & BC_PARSE_REL) && nrelops) {
5088 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
5091 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
5092 s = bc_POSIX_requires("exactly one comparison operator per condition");
5096 if (flags & BC_PARSE_PRINT) {
5097 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5098 bc_parse_push(p, BC_INST_POP);
5104 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5108 s = bc_parse_expr_empty_ok(p, flags, next);
5109 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5110 return bc_error("empty expression");
5114 static void bc_parse_init(BcParse *p, size_t func)
5116 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
5119 static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5121 return bc_parse_expr(p, flags, bc_parse_next_read);
5128 #define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5130 static BcStatus dc_parse_register(BcParse *p)
5135 s = bc_lex_next(&p->l);
5137 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
5139 name = xstrdup(p->l.t.v.v);
5140 bc_parse_pushName(p, name);
5145 static BcStatus dc_parse_string(BcParse *p)
5147 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
5148 size_t idx, len = G.prog.strs.len;
5150 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5153 str = xstrdup(p->l.t.v.v);
5154 bc_parse_push(p, BC_INST_STR);
5155 bc_parse_pushIndex(p, len);
5156 bc_vec_push(&G.prog.strs, &str);
5157 bc_parse_addFunc(p, name, &idx);
5159 return bc_lex_next(&p->l);
5162 static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5166 bc_parse_push(p, inst);
5168 s = dc_parse_register(p);
5173 bc_parse_push(p, BC_INST_SWAP);
5174 bc_parse_push(p, BC_INST_ASSIGN);
5175 bc_parse_push(p, BC_INST_POP);
5178 return bc_lex_next(&p->l);
5181 static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5185 bc_parse_push(p, inst);
5186 bc_parse_push(p, BC_INST_EXEC_COND);
5188 s = dc_parse_register(p);
5191 s = bc_lex_next(&p->l);
5194 if (p->l.t.t == BC_LEX_ELSE) {
5195 s = dc_parse_register(p);
5197 s = bc_lex_next(&p->l);
5200 bc_parse_push(p, BC_PARSE_STREND);
5205 static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5207 BcStatus s = BC_STATUS_SUCCESS;
5210 bool assign, get_token = false;
5214 case BC_LEX_OP_REL_EQ:
5215 case BC_LEX_OP_REL_LE:
5216 case BC_LEX_OP_REL_GE:
5217 case BC_LEX_OP_REL_NE:
5218 case BC_LEX_OP_REL_LT:
5219 case BC_LEX_OP_REL_GT:
5221 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5228 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5234 s = dc_parse_string(p);
5241 if (t == BC_LEX_NEG) {
5242 s = bc_lex_next(&p->l);
5244 if (p->l.t.t != BC_LEX_NUMBER)
5245 return bc_error_bad_token();
5248 bc_parse_number(p, &prev, &p->nbraces);
5250 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5256 case BC_LEX_KEY_READ:
5258 if (flags & BC_PARSE_NOREAD)
5259 s = bc_error_nested_read_call();
5261 bc_parse_push(p, BC_INST_READ);
5266 case BC_LEX_OP_ASSIGN:
5267 case BC_LEX_STORE_PUSH:
5269 assign = t == BC_LEX_OP_ASSIGN;
5270 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5271 s = dc_parse_mem(p, inst, true, assign);
5276 case BC_LEX_LOAD_POP:
5278 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5279 s = dc_parse_mem(p, inst, true, false);
5283 case BC_LEX_STORE_IBASE:
5284 case BC_LEX_STORE_SCALE:
5285 case BC_LEX_STORE_OBASE:
5287 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5288 s = dc_parse_mem(p, inst, false, true);
5294 s = bc_error_bad_token();
5300 if (!s && get_token) s = bc_lex_next(&p->l);
5305 static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5307 BcStatus s = BC_STATUS_SUCCESS;
5311 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
5313 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5315 inst = dc_parse_insts[t];
5317 if (inst != BC_INST_INVALID) {
5318 bc_parse_push(p, inst);
5319 s = bc_lex_next(&p->l);
5322 s = dc_parse_token(p, t, flags);
5325 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5326 bc_parse_push(p, BC_INST_POP_EXEC);
5331 static FAST_FUNC BcStatus dc_parse_parse(BcParse *p)
5335 if (p->l.t.t == BC_LEX_EOF)
5336 s = bc_error("end of file");
5338 s = dc_parse_expr(p, 0);
5340 if (s || G_interrupt) {
5342 s = BC_STATUS_FAILURE;
5348 static void dc_parse_init(BcParse *p, size_t func)
5350 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
5355 static void common_parse_init(BcParse *p, size_t func)
5358 IF_BC(bc_parse_init(p, func);)
5360 IF_DC(dc_parse_init(p, func);)
5364 static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5367 IF_BC(return bc_parse_expression(p, flags);)
5369 IF_DC(return dc_parse_expr(p, flags);)
5373 static BcVec* bc_program_search(char *id, bool var)
5381 v = var ? &G.prog.vars : &G.prog.arrs;
5382 map = var ? &G.prog.var_map : &G.prog.arr_map;
5386 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5389 bc_array_init(&data.v, var);
5390 bc_vec_push(v, &data.v);
5393 ptr = bc_vec_item(map, i);
5394 if (new) ptr->name = xstrdup(e.name);
5395 return bc_vec_item(v, ptr->idx);
5398 static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
5400 BcStatus s = BC_STATUS_SUCCESS;
5405 case BC_RESULT_TEMP:
5406 case BC_RESULT_IBASE:
5407 case BC_RESULT_SCALE:
5408 case BC_RESULT_OBASE:
5414 case BC_RESULT_CONSTANT:
5416 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
5417 size_t base_t, len = strlen(*str);
5420 bc_num_init(&r->d.n, len);
5422 hex = hex && len == 1;
5423 base = hex ? &G.prog.hexb : &G.prog.ib;
5424 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
5425 s = bc_num_parse(&r->d.n, *str, base, base_t);
5428 bc_num_free(&r->d.n);
5433 r->t = BC_RESULT_TEMP;
5439 case BC_RESULT_ARRAY:
5440 case BC_RESULT_ARRAY_ELEM:
5444 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
5446 if (r->t == BC_RESULT_ARRAY_ELEM) {
5448 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5449 *num = bc_vec_item(v, r->d.id.idx);
5452 *num = bc_vec_top(v);
5457 case BC_RESULT_LAST:
5459 *num = &G.prog.last;
5473 static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
5474 BcResult **r, BcNum **rn, bool assign)
5478 BcResultType lt, rt;
5480 if (!BC_PROG_STACK(&G.prog.results, 2))
5481 return bc_error_stack_has_too_few_elements();
5483 *r = bc_vec_item_rev(&G.prog.results, 0);
5484 *l = bc_vec_item_rev(&G.prog.results, 1);
5488 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5490 s = bc_program_num(*l, ln, false);
5492 s = bc_program_num(*r, rn, hex);
5495 // We run this again under these conditions in case any vector has been
5496 // reallocated out from under the BcNums or arrays we had.
5497 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
5498 s = bc_program_num(*l, ln, false);
5502 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
5503 return bc_error_variable_is_wrong_type();
5504 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5505 return bc_error_variable_is_wrong_type();
5510 static void bc_program_binOpRetire(BcResult *r)
5512 r->t = BC_RESULT_TEMP;
5513 bc_vec_pop(&G.prog.results);
5514 bc_vec_pop(&G.prog.results);
5515 bc_vec_push(&G.prog.results, r);
5518 static BcStatus bc_program_prep(BcResult **r, BcNum **n)
5522 if (!BC_PROG_STACK(&G.prog.results, 1))
5523 return bc_error_stack_has_too_few_elements();
5524 *r = bc_vec_top(&G.prog.results);
5526 s = bc_program_num(*r, n, false);
5529 if (!BC_PROG_NUM((*r), (*n)))
5530 return bc_error_variable_is_wrong_type();
5535 static void bc_program_retire(BcResult *r, BcResultType t)
5538 bc_vec_pop(&G.prog.results);
5539 bc_vec_push(&G.prog.results, r);
5542 static BcStatus bc_program_op(char inst)
5545 BcResult *opd1, *opd2, res;
5546 BcNum *n1, *n2 = NULL;
5548 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5550 bc_num_init_DEF_SIZE(&res.d.n);
5552 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5554 bc_program_binOpRetire(&res);
5559 bc_num_free(&res.d.n);
5563 static BcStatus bc_program_read(void)
5565 const char *sv_file;
5571 BcFunc *f = bc_program_func(BC_PROG_READ);
5573 for (i = 0; i < G.prog.stack.len; ++i) {
5574 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
5575 if (ip_ptr->func == BC_PROG_READ)
5576 return bc_error_nested_read_call();
5579 bc_vec_pop_all(&f->code);
5580 bc_char_vec_init(&buf);
5582 sv_file = G.prog.file;
5585 s = bc_read_line(&buf);
5588 common_parse_init(&parse, BC_PROG_READ);
5589 bc_lex_file(&parse.l);
5591 s = bc_parse_text(&parse, buf.v);
5592 if (s) goto exec_err;
5593 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
5594 if (s) goto exec_err;
5596 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
5597 s = bc_error("bad read() expression");
5601 ip.func = BC_PROG_READ;
5603 ip.len = G.prog.results.len;
5605 // Update this pointer, just in case.
5606 f = bc_program_func(BC_PROG_READ);
5608 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
5609 bc_vec_push(&G.prog.stack, &ip);
5612 G.prog.file = sv_file;
5613 bc_parse_free(&parse);
5619 static size_t bc_program_index(char *code, size_t *bgn)
5621 char amt = code[(*bgn)++], i = 0;
5624 for (; i < amt; ++i, ++(*bgn))
5625 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5630 static char *bc_program_name(char *code, size_t *bgn)
5633 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5635 s = xmalloc(ptr - str + 1);
5638 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5646 static void bc_program_printString(const char *str)
5648 size_t i, len = strlen(str);
5657 for (i = 0; i < len; ++i, ++G.prog.nchars) {
5661 if (c != '\\' || i == len - 1)
5697 G.prog.nchars = SIZE_MAX;
5721 // Just print the backslash and following character.
5732 static BcStatus bc_program_print(char inst, size_t idx)
5734 BcStatus s = BC_STATUS_SUCCESS;
5737 bool pop = inst != BC_INST_PRINT;
5739 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
5740 return bc_error_stack_has_too_few_elements();
5742 r = bc_vec_item_rev(&G.prog.results, idx);
5743 num = NULL; // is this NULL necessary?
5744 s = bc_program_num(r, &num, false);
5747 if (BC_PROG_NUM(r, num)) {
5748 s = bc_num_print(num, !pop);
5749 if (!s) bc_num_copy(&G.prog.last, num);
5754 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
5755 str = *bc_program_str(idx);
5757 if (inst == BC_INST_PRINT_STR) {
5760 if (c == '\0') break;
5763 if (c == '\n') G.prog.nchars = 0;
5767 bc_program_printString(str);
5768 if (inst == BC_INST_PRINT) bb_putchar('\n');
5772 if (!s && pop) bc_vec_pop(&G.prog.results);
5777 static BcStatus bc_program_negate(void)
5783 s = bc_program_prep(&ptr, &num);
5786 bc_num_init(&res.d.n, num->len);
5787 bc_num_copy(&res.d.n, num);
5788 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5790 bc_program_retire(&res, BC_RESULT_TEMP);
5795 static BcStatus bc_program_logical(char inst)
5798 BcResult *opd1, *opd2, res;
5803 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5805 bc_num_init_DEF_SIZE(&res.d.n);
5807 if (inst == BC_INST_BOOL_AND)
5808 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5809 else if (inst == BC_INST_BOOL_OR)
5810 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5813 cmp = bc_num_cmp(n1, n2);
5817 case BC_INST_REL_EQ:
5823 case BC_INST_REL_LE:
5829 case BC_INST_REL_GE:
5835 case BC_INST_REL_NE:
5841 case BC_INST_REL_LT:
5847 case BC_INST_REL_GT:
5855 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5857 bc_program_binOpRetire(&res);
5863 static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
5869 memset(&n2, 0, sizeof(BcNum));
5870 n2.rdx = res.d.id.idx = r->d.id.idx;
5871 res.t = BC_RESULT_STR;
5874 if (!BC_PROG_STACK(&G.prog.results, 2))
5875 return bc_error_stack_has_too_few_elements();
5877 bc_vec_pop(&G.prog.results);
5880 bc_vec_pop(&G.prog.results);
5882 bc_vec_push(&G.prog.results, &res);
5883 bc_vec_push(v, &n2);
5885 return BC_STATUS_SUCCESS;
5889 static BcStatus bc_program_copyToVar(char *name, bool var)
5896 if (!BC_PROG_STACK(&G.prog.results, 1))
5897 return bc_error_stack_has_too_few_elements();
5899 ptr = bc_vec_top(&G.prog.results);
5900 if ((ptr->t == BC_RESULT_ARRAY) != !var)
5901 return bc_error_variable_is_wrong_type();
5902 v = bc_program_search(name, var);
5905 if (ptr->t == BC_RESULT_STR && !var)
5906 return bc_error_variable_is_wrong_type();
5907 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
5910 s = bc_program_num(ptr, &n, false);
5913 // Do this once more to make sure that pointers were not invalidated.
5914 v = bc_program_search(name, var);
5917 bc_num_init_DEF_SIZE(&r.d.n);
5918 bc_num_copy(&r.d.n, n);
5921 bc_array_init(&r.d.v, true);
5922 bc_array_copy(&r.d.v, (BcVec *) n);
5925 bc_vec_push(v, &r.d);
5926 bc_vec_pop(&G.prog.results);
5931 static BcStatus bc_program_assign(char inst)
5934 BcResult *left, *right, res;
5935 BcNum *l = NULL, *r = NULL;
5936 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5938 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
5941 ib = left->t == BC_RESULT_IBASE;
5942 sc = left->t == BC_RESULT_SCALE;
5946 if (right->t == BC_RESULT_STR) {
5950 if (left->t != BC_RESULT_VAR)
5951 return bc_error_variable_is_wrong_type();
5952 v = bc_program_search(left->d.id.name, true);
5954 return bc_program_assignStr(right, v, false);
5958 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
5959 return bc_error("bad assignment:"
5960 " left side must be scale,"
5961 " ibase, obase, last, var,"
5966 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5967 return bc_error("divide by zero");
5972 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5979 if (ib || sc || left->t == BC_RESULT_OBASE) {
5980 static const char *const msg[] = {
5981 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5982 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5983 NULL, //can't happen //BC_RESULT_LAST
5984 NULL, //can't happen //BC_RESULT_CONSTANT
5985 NULL, //can't happen //BC_RESULT_ONE
5986 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
5989 unsigned long val, max;
5991 s = bc_num_ulong(l, &val);
5994 s = left->t - BC_RESULT_IBASE;
5997 ptr = &G.prog.scale;
6000 if (val < BC_NUM_MIN_BASE)
6001 return bc_error(msg[s]);
6002 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
6003 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
6007 return bc_error(msg[s]);
6009 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
6011 *ptr = (size_t) val;
6012 s = BC_STATUS_SUCCESS;
6015 bc_num_init(&res.d.n, l->len);
6016 bc_num_copy(&res.d.n, l);
6017 bc_program_binOpRetire(&res);
6023 #define bc_program_pushVar(code, bgn, pop, copy) \
6024 bc_program_pushVar(code, bgn)
6025 // for bc, 'pop' and 'copy' are always false
6027 static BcStatus bc_program_pushVar(char *code, size_t *bgn,
6028 bool pop, bool copy)
6030 BcStatus s = BC_STATUS_SUCCESS;
6032 char *name = bc_program_name(code, bgn);
6034 r.t = BC_RESULT_VAR;
6039 BcVec *v = bc_program_search(name, true);
6040 BcNum *num = bc_vec_top(v);
6044 if (!BC_PROG_STACK(v, 2 - copy)) {
6046 return bc_error_stack_has_too_few_elements();
6052 if (!BC_PROG_STR(num)) {
6054 r.t = BC_RESULT_TEMP;
6056 bc_num_init_DEF_SIZE(&r.d.n);
6057 bc_num_copy(&r.d.n, num);
6060 r.t = BC_RESULT_STR;
6061 r.d.id.idx = num->rdx;
6064 if (!copy) bc_vec_pop(v);
6069 bc_vec_push(&G.prog.results, &r);
6074 static BcStatus bc_program_pushArray(char *code, size_t *bgn,
6077 BcStatus s = BC_STATUS_SUCCESS;
6081 r.d.id.name = bc_program_name(code, bgn);
6083 if (inst == BC_INST_ARRAY) {
6084 r.t = BC_RESULT_ARRAY;
6085 bc_vec_push(&G.prog.results, &r);
6092 s = bc_program_prep(&operand, &num);
6094 s = bc_num_ulong(num, &temp);
6097 if (temp > BC_MAX_DIM) {
6098 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
6102 r.d.id.idx = (size_t) temp;
6103 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
6107 if (s) free(r.d.id.name);
6112 static BcStatus bc_program_incdec(char inst)
6115 BcResult *ptr, res, copy;
6119 s = bc_program_prep(&ptr, &num);
6122 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6123 copy.t = BC_RESULT_TEMP;
6124 bc_num_init(©.d.n, num->len);
6125 bc_num_copy(©.d.n, num);
6128 res.t = BC_RESULT_ONE;
6129 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6130 BC_INST_ASSIGN_PLUS :
6131 BC_INST_ASSIGN_MINUS;
6133 bc_vec_push(&G.prog.results, &res);
6134 bc_program_assign(inst);
6136 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
6137 bc_vec_pop(&G.prog.results);
6138 bc_vec_push(&G.prog.results, ©);
6144 static BcStatus bc_program_call(char *code, size_t *idx)
6146 BcStatus s = BC_STATUS_SUCCESS;
6148 size_t i, nparams = bc_program_index(code, idx);
6155 ip.func = bc_program_index(code, idx);
6156 func = bc_program_func(ip.func);
6158 if (func->code.len == 0) {
6159 return bc_error("undefined function");
6161 if (nparams != func->nparams) {
6162 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
6164 ip.len = G.prog.results.len - nparams;
6166 for (i = 0; i < nparams; ++i) {
6168 a = bc_vec_item(&func->autos, nparams - 1 - i);
6169 arg = bc_vec_top(&G.prog.results);
6171 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
6172 return bc_error_variable_is_wrong_type();
6174 s = bc_program_copyToVar(a->name, a->idx);
6178 for (; i < func->autos.len; ++i) {
6181 a = bc_vec_item(&func->autos, i);
6182 v = bc_program_search(a->name, a->idx);
6185 bc_num_init_DEF_SIZE(¶m.n);
6186 bc_vec_push(v, ¶m.n);
6189 bc_array_init(¶m.v, true);
6190 bc_vec_push(v, ¶m.v);
6194 bc_vec_push(&G.prog.stack, &ip);
6196 return BC_STATUS_SUCCESS;
6199 static BcStatus bc_program_return(char inst)
6205 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6207 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
6208 return bc_error_stack_has_too_few_elements();
6210 f = bc_program_func(ip->func);
6211 res.t = BC_RESULT_TEMP;
6213 if (inst == BC_INST_RET) {
6216 BcResult *operand = bc_vec_top(&G.prog.results);
6218 s = bc_program_num(operand, &num, false);
6220 bc_num_init(&res.d.n, num->len);
6221 bc_num_copy(&res.d.n, num);
6224 bc_num_init_DEF_SIZE(&res.d.n);
6225 //bc_num_zero(&res.d.n); - already is
6228 // We need to pop arguments as well, so this takes that into account.
6229 for (i = 0; i < f->autos.len; ++i) {
6232 BcId *a = bc_vec_item(&f->autos, i);
6234 v = bc_program_search(a->name, a->idx);
6238 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6239 bc_vec_push(&G.prog.results, &res);
6240 bc_vec_pop(&G.prog.stack);
6242 return BC_STATUS_SUCCESS;
6246 static unsigned long bc_program_scale(BcNum *n)
6248 return (unsigned long) n->rdx;
6251 static unsigned long bc_program_len(BcNum *n)
6253 size_t len = n->len;
6255 if (n->rdx != len) return len;
6257 if (len == 0) break;
6259 if (n->num[len] != 0) break;
6264 static BcStatus bc_program_builtin(char inst)
6270 bool len = inst == BC_INST_LENGTH;
6272 if (!BC_PROG_STACK(&G.prog.results, 1))
6273 return bc_error_stack_has_too_few_elements();
6274 opnd = bc_vec_top(&G.prog.results);
6276 s = bc_program_num(opnd, &num, false);
6280 if (!BC_PROG_NUM(opnd, num) && !len)
6281 return bc_error_variable_is_wrong_type();
6284 bc_num_init_DEF_SIZE(&res.d.n);
6286 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
6288 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
6289 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6293 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6296 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6298 str = bc_program_str(idx);
6299 bc_num_ulong2num(&res.d.n, strlen(*str));
6303 bc_num_ulong2num(&res.d.n, len ? bc_program_len(num) : bc_program_scale(num));
6306 bc_program_retire(&res, BC_RESULT_TEMP);
6312 static BcStatus bc_program_divmod(void)
6315 BcResult *opd1, *opd2, res, res2;
6316 BcNum *n1, *n2 = NULL;
6318 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6321 bc_num_init_DEF_SIZE(&res.d.n);
6322 bc_num_init(&res2.d.n, n2->len);
6324 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6327 bc_program_binOpRetire(&res2);
6328 res.t = BC_RESULT_TEMP;
6329 bc_vec_push(&G.prog.results, &res);
6334 bc_num_free(&res2.d.n);
6335 bc_num_free(&res.d.n);
6339 static BcStatus bc_program_modexp(void)
6342 BcResult *r1, *r2, *r3, res;
6343 BcNum *n1, *n2, *n3;
6345 if (!BC_PROG_STACK(&G.prog.results, 3))
6346 return bc_error_stack_has_too_few_elements();
6347 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6350 r1 = bc_vec_item_rev(&G.prog.results, 2);
6351 s = bc_program_num(r1, &n1, false);
6353 if (!BC_PROG_NUM(r1, n1))
6354 return bc_error_variable_is_wrong_type();
6356 // Make sure that the values have their pointers updated, if necessary.
6357 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6359 if (r1->t == r2->t) {
6360 s = bc_program_num(r2, &n2, false);
6364 if (r1->t == r3->t) {
6365 s = bc_program_num(r3, &n3, false);
6370 bc_num_init(&res.d.n, n3->len);
6371 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6374 bc_vec_pop(&G.prog.results);
6375 bc_program_binOpRetire(&res);
6380 bc_num_free(&res.d.n);
6384 static void bc_program_stackLen(void)
6387 size_t len = G.prog.results.len;
6389 res.t = BC_RESULT_TEMP;
6391 bc_num_init_DEF_SIZE(&res.d.n);
6392 bc_num_ulong2num(&res.d.n, len);
6393 bc_vec_push(&G.prog.results, &res);
6396 static BcStatus bc_program_asciify(void)
6401 char *str, *str2, c;
6402 size_t len = G.prog.strs.len, idx;
6405 if (!BC_PROG_STACK(&G.prog.results, 1))
6406 return bc_error_stack_has_too_few_elements();
6407 r = bc_vec_top(&G.prog.results);
6409 num = NULL; // TODO: is this NULL needed?
6410 s = bc_program_num(r, &num, false);
6413 if (BC_PROG_NUM(r, num)) {
6415 bc_num_init_DEF_SIZE(&n);
6416 bc_num_copy(&n, num);
6417 bc_num_truncate(&n, n.rdx);
6419 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
6420 if (s) goto num_err;
6421 s = bc_num_ulong(&n, &val);
6422 if (s) goto num_err;
6429 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
6430 str2 = *bc_program_str(idx);
6438 str2 = xstrdup(str);
6439 bc_program_addFunc(str2, &idx);
6441 if (idx != len + BC_PROG_REQ_FUNCS) {
6443 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6444 if (strcmp(*bc_program_str(idx), str) == 0) {
6453 bc_vec_push(&G.prog.strs, &str);
6455 res.t = BC_RESULT_STR;
6457 bc_vec_pop(&G.prog.results);
6458 bc_vec_push(&G.prog.results, &res);
6460 return BC_STATUS_SUCCESS;
6467 static BcStatus bc_program_printStream(void)
6475 if (!BC_PROG_STACK(&G.prog.results, 1))
6476 return bc_error_stack_has_too_few_elements();
6477 r = bc_vec_top(&G.prog.results);
6479 s = bc_program_num(r, &n, false);
6482 if (BC_PROG_NUM(r, n))
6483 s = bc_num_stream(n, &G.prog.strmb);
6485 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
6486 str = *bc_program_str(idx);
6493 static BcStatus bc_program_nquit(void)
6500 s = bc_program_prep(&opnd, &num);
6502 s = bc_num_ulong(num, &val);
6505 bc_vec_pop(&G.prog.results);
6507 if (G.prog.stack.len < val)
6508 return bc_error_stack_has_too_few_elements();
6509 if (G.prog.stack.len == val) {
6510 QUIT_OR_RETURN_TO_MAIN;
6513 bc_vec_npop(&G.prog.stack, val);
6518 static BcStatus bc_program_execStr(char *code, size_t *bgn,
6521 BcStatus s = BC_STATUS_SUCCESS;
6529 if (!BC_PROG_STACK(&G.prog.results, 1))
6530 return bc_error_stack_has_too_few_elements();
6532 r = bc_vec_top(&G.prog.results);
6535 BcNum *n = n; // for compiler
6538 char *then_name = bc_program_name(code, bgn);
6539 char *else_name = NULL;
6541 if (code[*bgn] == BC_PARSE_STREND)
6544 else_name = bc_program_name(code, bgn);
6546 exec = r->d.n.len != 0;
6548 if (!exec && else_name != NULL) {
6555 v = bc_program_search(name, true);
6562 if (!exec) goto exit;
6563 if (!BC_PROG_STR(n)) {
6564 s = bc_error_variable_is_wrong_type();
6570 if (r->t == BC_RESULT_STR) {
6572 } else if (r->t == BC_RESULT_VAR) {
6574 s = bc_program_num(r, &n, false);
6575 if (s || !BC_PROG_STR(n)) goto exit;
6581 fidx = sidx + BC_PROG_REQ_FUNCS;
6583 str = bc_program_str(sidx);
6584 f = bc_program_func(fidx);
6586 if (f->code.len == 0) {
6587 common_parse_init(&prs, fidx);
6588 s = bc_parse_text(&prs, *str);
6590 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
6593 if (prs.l.t.t != BC_LEX_EOF) {
6594 s = bc_error_bad_expression();
6598 bc_parse_free(&prs);
6602 ip.len = G.prog.results.len;
6605 bc_vec_pop(&G.prog.results);
6606 bc_vec_push(&G.prog.stack, &ip);
6608 return BC_STATUS_SUCCESS;
6611 bc_parse_free(&prs);
6612 f = bc_program_func(fidx);
6613 bc_vec_pop_all(&f->code);
6615 bc_vec_pop(&G.prog.results);
6620 static void bc_program_pushGlobal(char inst)
6625 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6626 if (inst == BC_INST_IBASE)
6627 val = (unsigned long) G.prog.ib_t;
6628 else if (inst == BC_INST_SCALE)
6629 val = (unsigned long) G.prog.scale;
6631 val = (unsigned long) G.prog.ob_t;
6633 bc_num_init_DEF_SIZE(&res.d.n);
6634 bc_num_ulong2num(&res.d.n, val);
6635 bc_vec_push(&G.prog.results, &res);
6638 static void bc_program_addFunc(char *name, size_t *idx)
6640 BcId entry, *entry_ptr;
6645 entry.idx = G.prog.fns.len;
6647 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6648 if (!inserted) free(name);
6650 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
6651 *idx = entry_ptr->idx;
6655 BcFunc *func = bc_program_func(entry_ptr->idx);
6657 // We need to reset these, so the function can be repopulated.
6659 bc_vec_pop_all(&func->autos);
6660 bc_vec_pop_all(&func->code);
6661 bc_vec_pop_all(&func->labels);
6665 bc_vec_push(&G.prog.fns, &f);
6669 static BcStatus bc_program_exec(void)
6673 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6674 BcFunc *func = bc_program_func(ip->func);
6675 char *code = func->code.v;
6678 while (ip->idx < func->code.len) {
6680 char inst = code[(ip->idx)++];
6684 case BC_INST_JUMP_ZERO:
6685 s = bc_program_prep(&ptr, &num);
6687 cond = !bc_num_cmp(num, &G.prog.zero);
6688 bc_vec_pop(&G.prog.results);
6690 case BC_INST_JUMP: {
6692 size_t idx = bc_program_index(code, &ip->idx);
6693 addr = bc_vec_item(&func->labels, idx);
6694 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6698 s = bc_program_call(code, &ip->idx);
6700 case BC_INST_INC_PRE:
6701 case BC_INST_DEC_PRE:
6702 case BC_INST_INC_POST:
6703 case BC_INST_DEC_POST:
6704 s = bc_program_incdec(inst);
6707 QUIT_OR_RETURN_TO_MAIN;
6711 s = bc_program_return(inst);
6713 case BC_INST_BOOL_OR:
6714 case BC_INST_BOOL_AND:
6716 case BC_INST_REL_EQ:
6717 case BC_INST_REL_LE:
6718 case BC_INST_REL_GE:
6719 case BC_INST_REL_NE:
6720 case BC_INST_REL_LT:
6721 case BC_INST_REL_GT:
6722 s = bc_program_logical(inst);
6725 s = bc_program_read();
6728 s = bc_program_pushVar(code, &ip->idx, false, false);
6730 case BC_INST_ARRAY_ELEM:
6732 s = bc_program_pushArray(code, &ip->idx, inst);
6735 r.t = BC_RESULT_LAST;
6736 bc_vec_push(&G.prog.results, &r);
6741 bc_program_pushGlobal(inst);
6743 case BC_INST_SCALE_FUNC:
6744 case BC_INST_LENGTH:
6746 s = bc_program_builtin(inst);
6749 r.t = BC_RESULT_CONSTANT;
6750 r.d.id.idx = bc_program_index(code, &ip->idx);
6751 bc_vec_push(&G.prog.results, &r);
6754 if (!BC_PROG_STACK(&G.prog.results, 1))
6755 s = bc_error_stack_has_too_few_elements();
6757 bc_vec_pop(&G.prog.results);
6759 case BC_INST_POP_EXEC:
6760 bc_vec_pop(&G.prog.stack);
6763 case BC_INST_PRINT_POP:
6764 case BC_INST_PRINT_STR:
6765 s = bc_program_print(inst, 0);
6768 r.t = BC_RESULT_STR;
6769 r.d.id.idx = bc_program_index(code, &ip->idx);
6770 bc_vec_push(&G.prog.results, &r);
6773 case BC_INST_MULTIPLY:
6774 case BC_INST_DIVIDE:
6775 case BC_INST_MODULUS:
6778 s = bc_program_op(inst);
6780 case BC_INST_BOOL_NOT:
6781 s = bc_program_prep(&ptr, &num);
6783 bc_num_init_DEF_SIZE(&r.d.n);
6784 if (!bc_num_cmp(num, &G.prog.zero))
6786 //else bc_num_zero(&r.d.n); - already is
6787 bc_program_retire(&r, BC_RESULT_TEMP);
6790 s = bc_program_negate();
6793 case BC_INST_ASSIGN_POWER:
6794 case BC_INST_ASSIGN_MULTIPLY:
6795 case BC_INST_ASSIGN_DIVIDE:
6796 case BC_INST_ASSIGN_MODULUS:
6797 case BC_INST_ASSIGN_PLUS:
6798 case BC_INST_ASSIGN_MINUS:
6800 case BC_INST_ASSIGN:
6801 s = bc_program_assign(inst);
6804 case BC_INST_MODEXP:
6805 s = bc_program_modexp();
6807 case BC_INST_DIVMOD:
6808 s = bc_program_divmod();
6810 case BC_INST_EXECUTE:
6811 case BC_INST_EXEC_COND:
6812 cond = inst == BC_INST_EXEC_COND;
6813 s = bc_program_execStr(code, &ip->idx, cond);
6815 case BC_INST_PRINT_STACK: {
6817 for (idx = 0; idx < G.prog.results.len; ++idx) {
6818 s = bc_program_print(BC_INST_PRINT, idx);
6823 case BC_INST_CLEAR_STACK:
6824 bc_vec_pop_all(&G.prog.results);
6826 case BC_INST_STACK_LEN:
6827 bc_program_stackLen();
6829 case BC_INST_DUPLICATE:
6830 if (!BC_PROG_STACK(&G.prog.results, 1))
6831 return bc_error_stack_has_too_few_elements();
6832 ptr = bc_vec_top(&G.prog.results);
6833 bc_result_copy(&r, ptr);
6834 bc_vec_push(&G.prog.results, &r);
6836 case BC_INST_SWAP: {
6838 if (!BC_PROG_STACK(&G.prog.results, 2))
6839 return bc_error_stack_has_too_few_elements();
6840 ptr = bc_vec_item_rev(&G.prog.results, 0);
6841 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6842 memcpy(&r, ptr, sizeof(BcResult));
6843 memcpy(ptr, ptr2, sizeof(BcResult));
6844 memcpy(ptr2, &r, sizeof(BcResult));
6847 case BC_INST_ASCIIFY:
6848 s = bc_program_asciify();
6850 case BC_INST_PRINT_STREAM:
6851 s = bc_program_printStream();
6854 case BC_INST_PUSH_VAR: {
6855 bool copy = inst == BC_INST_LOAD;
6856 s = bc_program_pushVar(code, &ip->idx, true, copy);
6859 case BC_INST_PUSH_TO_VAR: {
6860 char *name = bc_program_name(code, &ip->idx);
6861 s = bc_program_copyToVar(name, true);
6866 if (G.prog.stack.len <= 2)
6867 QUIT_OR_RETURN_TO_MAIN;
6868 bc_vec_npop(&G.prog.stack, 2);
6871 s = bc_program_nquit();
6876 if (s || G_interrupt) {
6881 // If the stack has changed, pointers may be invalid.
6882 ip = bc_vec_top(&G.prog.stack);
6883 func = bc_program_func(ip->func);
6884 code = func->code.v;
6887 return BC_STATUS_SUCCESS;
6891 static void bc_vm_info(void)
6893 printf("%s "BB_VER"\n"
6894 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6898 static void bc_args(char **argv)
6904 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6905 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6906 "warn\0" No_argument "w"
6907 "version\0" No_argument "v"
6908 "standard\0" No_argument "s"
6909 "quiet\0" No_argument "q"
6910 "mathlib\0" No_argument "l"
6911 "interactive\0" No_argument "i"
6914 opts = option_mask32 |= getopt32(argv, "wvsqli");
6916 if (getenv("POSIXLY_CORRECT"))
6917 option_mask32 |= BC_FLAG_S;
6919 if (opts & BC_FLAG_V) {
6924 for (i = optind; argv[i]; ++i)
6925 bc_vec_push(&G.files, argv + i);
6928 static void bc_vm_envArgs(void)
6932 char *env_args = getenv("BC_ENV_ARGS");
6934 if (!env_args) return;
6936 G.env_args = xstrdup(env_args);
6939 bc_vec_init(&v, sizeof(char *), NULL);
6941 while (*(buf = skip_whitespace(buf)) != '\0') {
6942 bc_vec_push(&v, &buf);
6943 buf = skip_non_whitespace(buf);
6949 // NULL terminate, and pass argv[] so that first arg is argv[1]
6950 if (sizeof(int) == sizeof(char*)) {
6951 bc_vec_push(&v, &const_int_0);
6953 static char *const nullptr = NULL;
6954 bc_vec_push(&v, &nullptr);
6956 bc_args(((char **)v.v) - 1);
6962 static unsigned bc_vm_envLen(const char *var)
6968 len = BC_NUM_PRINT_WIDTH;
6969 if (!lenv) return len;
6971 len = bb_strtou(lenv, NULL, 10) - 1;
6972 if (errno || len < 2 || len >= INT_MAX)
6973 len = BC_NUM_PRINT_WIDTH;
6978 static BcStatus bc_vm_process(const char *text)
6980 BcStatus s = bc_parse_text(&G.prs, text);
6984 while (G.prs.l.t.t != BC_LEX_EOF) {
6985 s = G.prs.parse(&G.prs);
6989 if (BC_PARSE_CAN_EXEC(&G.prs)) {
6990 s = bc_program_exec();
6999 static BcStatus bc_vm_file(const char *file)
7001 const char *sv_file;
7007 data = bc_read_file(file);
7008 if (!data) return bc_error_fmt("file '%s' is not text", file);
7010 sv_file = G.prog.file;
7012 bc_lex_file(&G.prs.l);
7013 s = bc_vm_process(data);
7016 main_func = bc_program_func(BC_PROG_MAIN);
7017 ip = bc_vec_item(&G.prog.stack, 0);
7019 if (main_func->code.len < ip->idx)
7020 s = bc_error_fmt("file '%s' is not executable", file);
7023 G.prog.file = sv_file;
7028 static BcStatus bc_vm_stdin(void)
7032 size_t len, i, str = 0;
7033 bool comment = false;
7036 bc_lex_file(&G.prs.l);
7038 bc_char_vec_init(&buffer);
7039 bc_char_vec_init(&buf);
7040 bc_vec_pushZeroByte(&buffer);
7042 // This loop is complex because the vm tries not to send any lines that end
7043 // with a backslash to the parser. The reason for that is because the parser
7044 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7045 // case, and for strings and comments, the parser will expect more stuff.
7046 while ((s = bc_read_line(&buf)) == BC_STATUS_SUCCESS) {
7048 char *string = buf.v;
7053 if (str && buf.v[0] == G.send)
7055 else if (buf.v[0] == G.sbgn)
7058 else if (len > 1 || comment) {
7060 for (i = 0; i < len; ++i) {
7062 bool notend = len > i + 1;
7065 if (i - 1 > len || string[i - 1] != '\\') {
7066 if (G.sbgn == G.send)
7068 else if (c == G.send)
7070 else if (c == G.sbgn)
7074 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7078 else if (c == '*' && notend && comment && string[i + 1] == '/')
7082 if (str || comment || string[len - 2] == '\\') {
7083 bc_vec_concat(&buffer, buf.v);
7088 bc_vec_concat(&buffer, buf.v);
7089 s = bc_vm_process(buffer.v);
7091 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
7092 // Debug config, non-interactive mode:
7093 // return all the way back to main.
7094 // Non-debug builds do not come here, they exit.
7099 bc_vec_pop_all(&buffer);
7101 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7102 s = BC_STATUS_SUCCESS;
7105 s = bc_error("string end could not be found");
7108 s = bc_error("comment end could not be found");
7112 bc_vec_free(&buffer);
7117 static const char bc_lib[] = {
7120 "\n" "auto b,s,n,r,d,i,p,f,v"
7129 "\n" "scale=scale(x)+1"
7139 "\n" "for(i=2;v!=0;++i){"
7145 "\n" "while((d--)!=0)r*=r"
7148 "\n" "if(n!=0)return(1/r)"
7152 "\n" "auto b,s,r,p,a,q,i,v"
7156 "\n" "r=(1-10^scale)/1"
7167 "\n" "while(x<=0.5){"
7171 "\n" "r=a=(x-1)/(x+1)"
7174 "\n" "for(i=3;v!=0;i+=2){"
7185 "\n" "auto b,s,r,n,a,q,i"
7189 "\n" "scale=1.1*s+2"
7198 "\n" "if(q%2!=0)x=-x"
7202 "\n" "for(i=3;a!=0;i+=2){"
7203 "\n" "a*=q/(i*(i-1))"
7208 "\n" "if(n!=0)return(-r/1)"
7217 "\n" "x=s(2*a(1)+x)"
7223 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7232 "\n" "if(scale<65){"
7233 "\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7237 "\n" "if(scale<65){"
7238 "\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7249 "\n" "x=(x-.2)/(1+.2*x)"
7254 "\n" "for(i=3;t!=0;i+=2){"
7261 "\n" "return((m*a+r)/n)"
7263 "\n" "define j(n,x){"
7264 "\n" "auto b,s,o,a,i,v,f"
7272 "\n" "if(n%2==1)o=1"
7275 "\n" "for(i=2;i<=n;++i)a*=i"
7277 "\n" "a=(x^n)/2^n/a"
7280 "\n" "scale=scale+length(a)-scale(a)"
7281 "\n" "for(i=1;v!=0;++i){"
7282 "\n" "v=v*f/i/(n+i)"
7288 "\n" "return(a*r/1)"
7293 static BcStatus bc_vm_exec(void)
7299 if (option_mask32 & BC_FLAG_L) {
7301 // We know that internal library is not buggy,
7302 // thus error checking is normally disabled.
7303 # define DEBUG_LIB 0
7304 bc_lex_file(&G.prs.l);
7305 s = bc_parse_text(&G.prs, bc_lib);
7306 if (DEBUG_LIB && s) return s;
7308 while (G.prs.l.t.t != BC_LEX_EOF) {
7309 s = G.prs.parse(&G.prs);
7310 if (DEBUG_LIB && s) return s;
7312 s = bc_program_exec();
7313 if (DEBUG_LIB && s) return s;
7317 s = BC_STATUS_SUCCESS;
7318 for (i = 0; !s && i < G.files.len; ++i)
7319 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
7320 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7321 // Debug config, non-interactive mode:
7322 // return all the way back to main.
7323 // Non-debug builds do not come here, they exit.
7327 if (IS_BC || (option_mask32 & BC_FLAG_I))
7330 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7331 s = bc_vm_process("");
7336 #if ENABLE_FEATURE_CLEAN_UP
7337 static void bc_program_free(void)
7339 bc_num_free(&G.prog.ib);
7340 bc_num_free(&G.prog.ob);
7341 bc_num_free(&G.prog.hexb);
7343 bc_num_free(&G.prog.strmb);
7345 bc_vec_free(&G.prog.fns);
7346 bc_vec_free(&G.prog.fn_map);
7347 bc_vec_free(&G.prog.vars);
7348 bc_vec_free(&G.prog.var_map);
7349 bc_vec_free(&G.prog.arrs);
7350 bc_vec_free(&G.prog.arr_map);
7351 bc_vec_free(&G.prog.strs);
7352 bc_vec_free(&G.prog.consts);
7353 bc_vec_free(&G.prog.results);
7354 bc_vec_free(&G.prog.stack);
7355 bc_num_free(&G.prog.last);
7356 bc_num_free(&G.prog.zero);
7357 bc_num_free(&G.prog.one);
7360 static void bc_vm_free(void)
7362 bc_vec_free(&G.files);
7364 bc_parse_free(&G.prs);
7369 static void bc_program_init(void)
7374 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7375 memset(&ip, 0, sizeof(BcInstPtr));
7377 /* G.prog.nchars = G.prog.scale = 0; - already is */
7378 bc_num_init_DEF_SIZE(&G.prog.ib);
7379 bc_num_ten(&G.prog.ib);
7382 bc_num_init_DEF_SIZE(&G.prog.ob);
7383 bc_num_ten(&G.prog.ob);
7386 bc_num_init_DEF_SIZE(&G.prog.hexb);
7387 bc_num_ten(&G.prog.hexb);
7388 G.prog.hexb.num[0] = 6;
7391 bc_num_init_DEF_SIZE(&G.prog.strmb);
7392 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7395 bc_num_init_DEF_SIZE(&G.prog.last);
7396 //bc_num_zero(&G.prog.last); - already is
7398 bc_num_init_DEF_SIZE(&G.prog.zero);
7399 //bc_num_zero(&G.prog.zero); - already is
7401 bc_num_init_DEF_SIZE(&G.prog.one);
7402 bc_num_one(&G.prog.one);
7404 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7405 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
7407 bc_program_addFunc(xstrdup("(main)"), &idx);
7408 bc_program_addFunc(xstrdup("(read)"), &idx);
7410 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7411 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7413 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7414 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7416 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7417 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7418 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7419 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7420 bc_vec_push(&G.prog.stack, &ip);
7423 static int bc_vm_init(const char *env_len)
7425 #if ENABLE_FEATURE_EDITING
7426 G.line_input_state = new_line_input_t(DO_HISTORY);
7428 G.prog.len = bc_vm_envLen(env_len);
7430 bc_vec_init(&G.files, sizeof(char *), NULL);
7432 IF_BC(bc_vm_envArgs();)
7435 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
7437 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
7441 #if ENABLE_FEATURE_BC_SIGNALS
7443 // With SA_RESTART, most system calls will restart
7444 // (IOW: they won't fail with EINTR).
7445 // In particular, this means ^C won't cause
7446 // stdout to get into "error state" if SIGINT hits
7447 // within write() syscall.
7448 // The downside is that ^C while line input is taken
7449 // will only be handled after [Enter] since read()
7450 // from stdin is not interrupted by ^C either,
7451 // it restarts, thus fgetc() does not return on ^C.
7452 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7454 // Without SA_RESTART, this exhibits a bug:
7455 // "while (1) print 1" and try ^C-ing it.
7456 // Intermittently, instead of returning to input line,
7457 // you'll get "output error: Interrupted system call"
7459 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7463 return 0; // "not a tty"
7466 static BcStatus bc_vm_run(void)
7468 BcStatus st = bc_vm_exec();
7469 #if ENABLE_FEATURE_CLEAN_UP
7470 if (G_exiting) // it was actually "halt" or "quit"
7473 # if ENABLE_FEATURE_EDITING
7474 free_line_input_t(G.line_input_state);
7482 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7483 int bc_main(int argc UNUSED_PARAM, char **argv)
7488 G.sbgn = G.send = '"';
7490 is_tty = bc_vm_init("BC_LINE_LENGTH");
7494 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7502 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7503 int dc_main(int argc UNUSED_PARAM, char **argv)
7511 * TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7512 * 1 char wider than bc from the same package.
7513 * Both default width, and xC_LINE_LENGTH=N are wider:
7514 * "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7517 * "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7520 * Do the same, or it's a bug?
7522 bc_vm_init("DC_LINE_LENGTH");
7524 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7525 noscript = BC_FLAG_I;
7527 int n = getopt(argc, argv, "e:f:x");
7533 n = bc_vm_process(optarg);
7541 option_mask32 |= DC_FLAG_X;
7551 bc_vec_push(&G.files, argv++);
7554 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7560 #endif // not DC_SMALL