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.
6 * ** Automatically generated from https://github.com/gavinhoward/bc **
7 * ** Do not edit unless you know what you are doing. **
10 //config: bool "bc (45 kb; 49 kb when combined with dc)"
13 //config: bc is a command-line, arbitrary-precision calculator with a
14 //config: Turing-complete language. See the GNU bc manual
15 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
16 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
17 //config: for details.
19 //config: This bc has four differences to the GNU bc:
21 //config: 1) The period (.) can also be used as a shortcut for "last", as in
23 //config: 2) Arrays are copied before being passed as arguments to
24 //config: functions. This behavior is required by the bc spec.
25 //config: 3) Arrays can be passed to the builtin "length" function to get
26 //config: the number of elements currently in the array. The following
27 //config: example prints "1":
32 //config: 4) The precedence of the boolean "not" operator (!) is equal to
33 //config: that of the unary minus (-), or negation, operator. This still
34 //config: allows POSIX-compliant scripts to work while somewhat
35 //config: preserving expected behavior (versus C) and making parsing
40 //config: -i --interactive force interactive mode
41 //config: -l --mathlib use predefined math routines:
43 //config: s(expr) = sine of expr in radians
44 //config: c(expr) = cosine of expr in radians
45 //config: a(expr) = arctangent of expr, returning
47 //config: l(expr) = natural log of expr
48 //config: e(expr) = raises e to the power of expr
49 //config: j(n, x) = Bessel function of integer order
52 //config: -q --quiet don't print version and copyright.
53 //config: -s --standard error if any non-POSIX extensions are used.
54 //config: -w --warn warn if any non-POSIX extensions are used.
55 //config: -v --version print version and copyright and exit.
57 //config: Long options are only available if FEATURE_BC_LONG_OPTIONS is
61 //config: bool "dc (38 kb; 49 kb when combined with bc)"
64 //config: dc is a reverse-polish notation command-line calculator which
65 //config: supports unlimited precision arithmetic. See the FreeBSD man page
66 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
67 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
68 //config: for details.
70 //config: This dc has a few differences from the two above:
72 //config: 1) When printing a byte stream (command "P"), this bc follows what
73 //config: the FreeBSD dc does.
74 //config: 2) This dc implements the GNU extensions for divmod ("~") and
75 //config: modular exponentiation ("|").
76 //config: 3) This dc implements all FreeBSD extensions, except for "J" and
78 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
79 //config: However, they are implemented differently. When it encounters
80 //config: whitespace where a register should be, it skips the whitespace.
81 //config: If the character following is not a lowercase letter, an error
82 //config: is issued. Otherwise, the register name is parsed by the
83 //config: following regex:
85 //config: [a-z][a-z0-9_]*
87 //config: This generally means that register names will be surrounded by
92 //config: l idx s temp L index S temp2 < do_thing
94 //config: Also note that, like the FreeBSD dc, extended registers are not
95 //config: allowed unless the "-x" option is given.
97 //config:config FEATURE_BC_SIGNALS
98 //config: bool "Enable bc/dc signal handling"
100 //config: depends on BC || DC
102 //config: Enable signal handling for bc and dc.
104 //config:config FEATURE_BC_LONG_OPTIONS
105 //config: bool "Enable bc/dc long options"
107 //config: depends on BC || DC
109 //config: Enable long options for bc and dc.
111 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
112 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
114 //kbuild:lib-$(CONFIG_BC) += bc.o
115 //kbuild:lib-$(CONFIG_DC) += bc.o
117 //See www.gnu.org/software/bc/manual/bc.html
118 //usage:#define bc_trivial_usage
119 //usage: "[-sqliw] FILE..."
121 //usage:#define bc_full_usage "\n"
122 //usage: "\nArbitrary precision calculator"
124 //usage: "\n -i Interactive"
125 //usage: "\n -l Load standard math library"
126 //usage: "\n -s Be POSIX compatible"
127 //usage: "\n -q Quiet"
128 //usage: "\n -w Warn if extensions are used"
129 ///////: "\n -v Version"
130 //usage: "\n$BC_LINE_LENGTH changes output width"
132 //usage:#define bc_example_usage
133 //usage: "3 + 4.129\n"
134 //usage: "1903 - 2893\n"
135 //usage: "-129 * 213.28935\n"
136 //usage: "12 / -1932\n"
138 //usage: "34 ^ 189\n"
139 //usage: "scale = 13\n"
140 //usage: "ibase = 2\n"
141 //usage: "obase = A\n"
143 //usage:#define dc_trivial_usage
144 //usage: "EXPRESSION..."
146 //usage:#define dc_full_usage "\n\n"
147 //usage: "Tiny RPN calculator. Operations:\n"
148 //usage: "+, add, -, sub, *, mul, /, div, %, mod, ^, exp, ~, divmod, |, "
149 //usage: "modular exponentiation,\n"
150 //usage: "p - print top of the stack (without popping),\n"
151 //usage: "f - print entire stack,\n"
152 //usage: "k - pop the value and set the precision.\n"
153 //usage: "i - pop the value and set input radix.\n"
154 //usage: "o - pop the value and set output radix.\n"
155 //usage: "Examples: 'dc 2 2 add p' -> 4, 'dc 8 8 mul 2 2 + / p' -> 16"
157 //usage:#define dc_example_usage
158 //usage: "$ dc 2 2 + p\n"
160 //usage: "$ dc 8 8 \\* 2 2 + / p\n"
162 //usage: "$ dc 0 1 and p\n"
164 //usage: "$ dc 0 1 or p\n"
166 //usage: "$ echo 72 9 div 8 mul p | dc\n"
170 #include "common_bufsiz.h"
172 typedef enum BcStatus {
173 BC_STATUS_SUCCESS = 0,
174 BC_STATUS_FAILURE = 1,
175 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
178 #define BC_VEC_INVALID_IDX ((size_t) -1)
179 #define BC_VEC_START_CAP (1 << 5)
181 typedef void (*BcVecFree)(void *);
183 typedef struct BcVec {
191 #define bc_vec_pop(v) (bc_vec_npop((v), 1))
192 #define bc_vec_top(v) (bc_vec_item_rev((v), 0))
194 typedef signed char BcDig;
196 typedef struct BcNum {
204 #define BC_NUM_MIN_BASE ((unsigned long) 2)
205 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
206 #define BC_NUM_DEF_SIZE (16)
207 #define BC_NUM_PRINT_WIDTH (69)
209 #define BC_NUM_KARATSUBA_LEN (32)
211 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
212 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
213 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
214 #define BC_NUM_AREQ(a, b) \
215 (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
216 #define BC_NUM_MREQ(a, b, scale) \
217 (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
219 typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
220 typedef void (*BcNumDigitOp)(size_t, size_t, bool, size_t *, size_t);
222 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
223 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
224 static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
225 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
226 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
227 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
228 static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
229 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
232 typedef enum BcInst {
262 BC_INST_ASSIGN_POWER,
263 BC_INST_ASSIGN_MULTIPLY,
264 BC_INST_ASSIGN_DIVIDE,
265 BC_INST_ASSIGN_MODULUS,
267 BC_INST_ASSIGN_MINUS,
313 BC_INST_PRINT_STREAM,
328 BC_INST_INVALID = -1,
333 typedef struct BcId {
338 typedef struct BcFunc {
345 typedef enum BcResultType {
350 BC_RESULT_ARRAY_ELEM,
359 // These are between to calculate ibase, obase, and last from instructions.
367 typedef union BcResultData {
373 typedef struct BcResult {
378 typedef struct BcInstPtr {
384 // BC_LEX_NEG is not used in lexing; it is only for parsing.
385 typedef enum BcLexType {
413 BC_LEX_OP_ASSIGN_POWER,
414 BC_LEX_OP_ASSIGN_MULTIPLY,
415 BC_LEX_OP_ASSIGN_DIVIDE,
416 BC_LEX_OP_ASSIGN_MODULUS,
417 BC_LEX_OP_ASSIGN_PLUS,
418 BC_LEX_OP_ASSIGN_MINUS,
439 BC_LEX_KEY_1st_keyword,
440 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
447 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
448 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
450 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
453 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
491 // must match order of BC_LEX_KEY_foo etc above
493 struct BcLexKeyword {
496 #define BC_LEX_KW_ENTRY(a, b, c) \
497 { .name8 = a /*, .len = b, .posix = c*/ }
498 static const struct BcLexKeyword bc_lex_kws[20] = {
499 BC_LEX_KW_ENTRY("auto" , 4, 1), // 0
500 BC_LEX_KW_ENTRY("break" , 5, 1), // 1
501 BC_LEX_KW_ENTRY("continue", 8, 0), // 2 note: this one has no terminating NUL
502 BC_LEX_KW_ENTRY("define" , 6, 1), // 3
504 BC_LEX_KW_ENTRY("else" , 4, 0), // 4
505 BC_LEX_KW_ENTRY("for" , 3, 1), // 5
506 BC_LEX_KW_ENTRY("halt" , 4, 0), // 6
507 BC_LEX_KW_ENTRY("ibase" , 5, 1), // 7
509 BC_LEX_KW_ENTRY("if" , 2, 1), // 8
510 BC_LEX_KW_ENTRY("last" , 4, 0), // 9
511 BC_LEX_KW_ENTRY("length" , 6, 1), // 10
512 BC_LEX_KW_ENTRY("limits" , 6, 0), // 11
514 BC_LEX_KW_ENTRY("obase" , 5, 1), // 12
515 BC_LEX_KW_ENTRY("print" , 5, 0), // 13
516 BC_LEX_KW_ENTRY("quit" , 4, 1), // 14
517 BC_LEX_KW_ENTRY("read" , 4, 0), // 15
519 BC_LEX_KW_ENTRY("return" , 6, 1), // 16
520 BC_LEX_KW_ENTRY("scale" , 5, 1), // 17
521 BC_LEX_KW_ENTRY("sqrt" , 4, 1), // 18
522 BC_LEX_KW_ENTRY("while" , 5, 1), // 19
554 typedef BcStatus (*BcLexNext)(struct BcLex *);
556 typedef struct BcLex {
574 #define BC_PARSE_STREND ((char) UCHAR_MAX)
576 #define bc_parse_push(p, i) (bc_vec_pushByte(&(p)->func->code, (char) (i)))
577 #define bc_parse_updateFunc(p, f) \
578 ((p)->func = bc_vec_item(&G.prog.fns, ((p)->fidx = (f))))
580 #define BC_PARSE_REL (1 << 0)
581 #define BC_PARSE_PRINT (1 << 1)
582 #define BC_PARSE_NOCALL (1 << 2)
583 #define BC_PARSE_NOREAD (1 << 3)
584 #define BC_PARSE_ARRAY (1 << 4)
586 #define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
587 #define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
589 #define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
590 #define BC_PARSE_FUNC_INNER(parse) \
591 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
593 #define BC_PARSE_FLAG_FUNC (1 << 1)
594 #define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
596 #define BC_PARSE_FLAG_BODY (1 << 2)
597 #define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
599 #define BC_PARSE_FLAG_LOOP (1 << 3)
600 #define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
602 #define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
603 #define BC_PARSE_LOOP_INNER(parse) \
604 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
606 #define BC_PARSE_FLAG_IF (1 << 5)
607 #define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
609 #define BC_PARSE_FLAG_ELSE (1 << 6)
610 #define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
612 #define BC_PARSE_FLAG_IF_END (1 << 7)
613 #define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
615 #define BC_PARSE_CAN_EXEC(parse) \
616 (!(BC_PARSE_TOP_FLAG(parse) & \
617 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
618 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
619 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
621 typedef struct BcParseNext {
626 #define BC_PARSE_NEXT_TOKENS(...) .tokens = { __VA_ARGS__ }
627 #define BC_PARSE_NEXT(a, ...) \
629 .len = (a), BC_PARSE_NEXT_TOKENS(__VA_ARGS__) \
636 typedef BcStatus (*BcParseParse)(struct BcParse *);
638 typedef struct BcParse {
659 typedef struct BcProgram {
700 #define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
702 #define BC_PROG_MAIN (0)
703 #define BC_PROG_READ (1)
706 #define BC_PROG_REQ_FUNCS (2)
709 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
710 #define BC_PROG_NUM(r, n) \
711 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
713 typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
715 static void bc_program_addFunc(char *name, size_t *idx);
716 static void bc_program_reset(void);
718 #define BC_FLAG_X (1 << 0)
719 #define BC_FLAG_W (1 << 1)
720 #define BC_FLAG_V (1 << 2)
721 #define BC_FLAG_S (1 << 3)
722 #define BC_FLAG_Q (1 << 4)
723 #define BC_FLAG_L (1 << 5)
724 #define BC_FLAG_I (1 << 6)
726 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
727 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
729 #define BC_MAX_OBASE ((unsigned) 999)
730 #define BC_MAX_DIM ((unsigned) INT_MAX)
731 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
732 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
733 #define BC_MAX_NAME BC_MAX_STRING
734 #define BC_MAX_NUM BC_MAX_STRING
735 #define BC_MAX_EXP ((unsigned long) LONG_MAX)
736 #define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
739 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
747 // For error messages. Can be set to current parsed line,
748 // or [TODO] to current executing line (can be before last parsed one)
755 #if ENABLE_FEATURE_EDITING
756 line_input_t *line_input_state;
759 #define G (*ptr_to_globals)
760 #define INIT_G() do { \
761 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
763 #define FREE_G() do { \
764 FREE_PTR_TO_GLOBALS(); \
766 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
767 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
768 #define G_exreg (ENABLE_DC && (option_mask32 & BC_FLAG_X))
769 #define G_interrupt (ENABLE_FEATURE_BC_SIGNALS ? bb_got_signal : 0)
770 #if ENABLE_FEATURE_BC_SIGNALS
771 # define G_ttyin G.ttyin
775 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
779 // This is a bit array that corresponds to token types. An entry is
780 // true if the token is valid in an expression, false otherwise.
782 BC_PARSE_EXPRS_BITS = 0
783 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
784 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
785 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
786 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
787 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
788 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
789 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
790 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
792 static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
794 #if ULONG_MAX > 0xffffffff
795 // 64-bit version (will not work correctly for 32-bit longs!)
796 return BC_PARSE_EXPRS_BITS & (1UL << i);
799 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
801 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
804 return m & (1UL << i);
808 // This is an array of data for operators that correspond to token types.
809 static const uint8_t bc_parse_ops[] = {
810 #define OP(p,l) ((int)(l) * 0x10 + (p))
811 OP(0, false), OP( 0, false ), // inc dec
814 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
815 OP(4, true ), OP( 4, true ), // mod + -
816 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
818 OP(7, true ), OP( 7, true ), // or and
819 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
820 OP(5, false), OP( 5, false ), // -= =
823 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
824 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
826 // These identify what tokens can come after expressions in certain cases.
827 static const BcParseNext bc_parse_next_expr =
828 BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF);
829 static const BcParseNext bc_parse_next_param =
830 BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA);
831 static const BcParseNext bc_parse_next_print =
832 BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF);
833 static const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN);
834 static const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET);
835 static const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON);
836 static const BcParseNext bc_parse_next_read =
837 BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF);
841 static const BcLexType dc_lex_regs[] = {
842 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
843 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
844 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
848 static const BcLexType dc_lex_tokens[] = {
849 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
850 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
851 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
852 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
853 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
854 BC_LEX_INVALID, BC_LEX_INVALID,
855 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
856 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
857 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
858 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
859 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
860 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
861 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
862 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
863 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
864 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
865 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
866 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
867 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
868 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
869 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
870 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
871 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
872 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
876 static const BcInst dc_parse_insts[] = {
877 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
878 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
879 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
880 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
881 BC_INST_INVALID, BC_INST_INVALID,
882 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
883 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
884 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
885 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
886 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
887 BC_INST_INVALID, BC_INST_INVALID,
888 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
889 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
890 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
891 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
892 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
893 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
894 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
895 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
896 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
897 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
898 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
899 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
903 static const BcNumBinaryOp bc_program_ops[] = {
904 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
907 static void fflush_and_check(void)
910 if (ferror(stdout) || ferror(stderr))
911 bb_perror_msg_and_die("output error");
914 #if ENABLE_FEATURE_CLEAN_UP
915 #define quit_or_return_for_exit() \
917 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
918 return BC_STATUS_FAILURE; \
921 #define quit_or_return_for_exit() quit()
924 static void quit(void) NORETURN;
925 static void quit(void)
928 bb_perror_msg_and_die("input error");
933 static void bc_verror_msg(const char *fmt, va_list p)
935 const char *sv = sv; /* for compiler */
938 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
940 bb_verror_msg(fmt, p, NULL);
942 free((char*)applet_name);
947 static NOINLINE int bc_error_fmt(const char *fmt, ...)
952 bc_verror_msg(fmt, p);
955 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
957 return BC_STATUS_FAILURE;
960 static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
964 // Are non-POSIX constructs totally ok?
965 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
966 return BC_STATUS_SUCCESS; // yes
969 bc_verror_msg(fmt, p);
972 // Do we treat non-POSIX constructs as errors?
973 if (!(option_mask32 & BC_FLAG_S))
974 return BC_STATUS_SUCCESS; // no, it's a warning
975 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
977 return BC_STATUS_FAILURE;
980 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
981 // This idiom begs for tail-call optimization, but for it to work,
982 // function must not have caller-cleaned parameters on stack.
983 // Unfortunately, vararg function API does exactly that on most arches.
984 // Thus, use these shims for the cases when we have no vararg PARAMS:
985 static int bc_error(const char *msg)
987 return bc_error_fmt("%s", msg);
989 static int bc_POSIX_requires(const char *msg)
991 return bc_posix_error_fmt("POSIX requires %s", msg);
993 static int bc_POSIX_does_not_allow(const char *msg)
995 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
997 static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
999 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1001 static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1003 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1005 static int bc_error_bad_character(char c)
1007 return bc_error_fmt("bad character '%c'", c);
1009 static int bc_error_bad_expression(void)
1011 return bc_error("bad expression");
1013 static int bc_error_bad_token(void)
1015 return bc_error("bad token");
1017 static int bc_error_stack_has_too_few_elements(void)
1019 return bc_error("stack has too few elements");
1021 static int bc_error_variable_is_wrong_type(void)
1023 return bc_error("variable is wrong type");
1025 static int bc_error_nested_read_call(void)
1027 return bc_error("read() call inside of a read() call");
1030 static void bc_vec_grow(BcVec *v, size_t n)
1032 size_t cap = v->cap * 2;
1033 while (cap < v->len + n) cap *= 2;
1034 v->v = xrealloc(v->v, v->size * cap);
1038 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1041 v->cap = BC_VEC_START_CAP;
1044 v->v = xmalloc(esize * BC_VEC_START_CAP);
1047 static void bc_char_vec_init(BcVec *v)
1049 bc_vec_init(v, sizeof(char), NULL);
1052 static void bc_vec_expand(BcVec *v, size_t req)
1055 v->v = xrealloc(v->v, v->size * req);
1060 static void bc_vec_npop(BcVec *v, size_t n)
1065 size_t len = v->len - n;
1066 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1070 static void bc_vec_pop_all(BcVec *v)
1072 bc_vec_npop(v, v->len);
1075 static void bc_vec_push(BcVec *v, const void *data)
1077 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1078 memmove(v->v + (v->size * v->len), data, v->size);
1082 static void bc_vec_pushByte(BcVec *v, char data)
1084 bc_vec_push(v, &data);
1087 static void bc_vec_pushZeroByte(BcVec *v)
1089 //bc_vec_pushByte(v, '\0');
1091 bc_vec_push(v, &const_int_0);
1094 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1097 bc_vec_push(v, data);
1102 if (v->len == v->cap) bc_vec_grow(v, 1);
1104 ptr = v->v + v->size * idx;
1106 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1107 memmove(ptr, data, v->size);
1111 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1114 bc_vec_expand(v, len + 1);
1115 memcpy(v->v, str, len);
1118 bc_vec_pushZeroByte(v);
1121 static void bc_vec_concat(BcVec *v, const char *str)
1125 if (v->len == 0) bc_vec_pushZeroByte(v);
1127 len = v->len + strlen(str);
1129 if (v->cap < len) bc_vec_grow(v, len - v->len);
1135 static void *bc_vec_item(const BcVec *v, size_t idx)
1137 return v->v + v->size * idx;
1140 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1142 return v->v + v->size * (v->len - idx - 1);
1145 static void bc_vec_free(void *vec)
1147 BcVec *v = (BcVec *) vec;
1152 static int bc_id_cmp(const void *e1, const void *e2)
1154 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1157 static void bc_id_free(void *id)
1159 free(((BcId *) id)->name);
1162 static size_t bc_map_find(const BcVec *v, const void *ptr)
1164 size_t low = 0, high = v->len;
1166 while (low < high) {
1168 size_t mid = (low + high) / 2;
1169 BcId *id = bc_vec_item(v, mid);
1170 int result = bc_id_cmp(ptr, id);
1174 else if (result < 0)
1183 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1185 size_t n = *i = bc_map_find(v, ptr);
1188 bc_vec_push(v, ptr);
1189 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1190 return 0; // "was not inserted"
1192 bc_vec_pushAt(v, ptr, n);
1193 return 1; // "was inserted"
1196 static size_t bc_map_index(const BcVec *v, const void *ptr)
1198 size_t i = bc_map_find(v, ptr);
1199 if (i >= v->len) return BC_VEC_INVALID_IDX;
1200 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1203 static int push_input_byte(BcVec *vec, char c)
1205 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1208 // Bad chars on this line, ignore entire line
1209 bc_error_fmt("illegal character 0x%02x", c);
1212 bc_vec_pushByte(vec, (char)c);
1216 static BcStatus bc_read_line(BcVec *vec, const char *prompt)
1220 if (G_posix) prompt = "";
1226 bc_vec_pop_all(vec);
1230 #if ENABLE_FEATURE_BC_SIGNALS
1231 if (bb_got_signal) { // ^C was pressed
1233 bb_got_signal = 0; // resets G_interrupt to zero
1235 ? "\ninterrupt (type \"quit\" to exit)\n"
1236 : "\ninterrupt (type \"q\" to exit)\n"
1239 # if ENABLE_FEATURE_EDITING
1242 # define line_buf bb_common_bufsiz1
1243 n = read_line_input(G.line_input_state, prompt, line_buf, COMMON_BUFSIZE);
1244 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1254 bad_chars |= push_input_byte(vec, c);
1262 fputs(prompt, stderr);
1263 IF_FEATURE_BC_SIGNALS(errno = 0;)
1266 #if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1267 // Both conditions appear simultaneously, check both just in case
1268 if (errno == EINTR || bb_got_signal) {
1276 quit(); // this emits error message
1278 // Note: EOF does not append '\n', therefore:
1279 // printf 'print 123\n' | bc - works
1280 // printf 'print 123' | bc - fails (syntax error)
1283 bad_chars |= push_input_byte(vec, c);
1284 } while (c != '\n');
1286 } while (bad_chars);
1288 bc_vec_pushZeroByte(vec);
1290 return BC_STATUS_SUCCESS;
1293 static char* bc_read_file(const char *path)
1296 size_t size = ((size_t) -1);
1299 buf = xmalloc_open_read_close(path, &size);
1301 for (i = 0; i < size; ++i) {
1303 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1315 static void bc_num_setToZero(BcNum *n, size_t scale)
1322 static void bc_num_zero(BcNum *n)
1324 bc_num_setToZero(n, 0);
1327 static void bc_num_one(BcNum *n)
1329 bc_num_setToZero(n, 0);
1334 static void bc_num_ten(BcNum *n)
1336 bc_num_setToZero(n, 0);
1342 static void bc_num_init(BcNum *n, size_t req)
1344 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1345 memset(n, 0, sizeof(BcNum));
1346 n->num = xmalloc(req);
1350 static void bc_num_expand(BcNum *n, size_t req)
1352 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1354 n->num = xrealloc(n->num, req);
1359 static void bc_num_free(void *num)
1361 free(((BcNum *) num)->num);
1364 static void bc_num_copy(BcNum *d, BcNum *s)
1367 bc_num_expand(d, s->cap);
1371 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1375 static BcStatus bc_num_ulong(BcNum *n, unsigned long *result)
1380 if (n->neg) return bc_error("negative number");
1382 for (*result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1384 unsigned long prev = *result, powprev = pow;
1386 *result += ((unsigned long) n->num[i]) * pow;
1389 if (*result < prev || pow < powprev)
1390 return bc_error("overflow");
1393 return BC_STATUS_SUCCESS;
1396 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1404 if (val == 0) return;
1406 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1407 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1410 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
1414 for (i = 0; i < len; ++i) {
1415 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
1422 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1426 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
1427 return BC_NUM_NEG(i + 1, c < 0);
1430 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1432 size_t i, min, a_int, b_int, diff;
1433 BcDig *max_num, *min_num;
1434 bool a_max, neg = false;
1437 if (a == b) return 0;
1438 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1439 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1449 a_int = BC_NUM_INT(a);
1450 b_int = BC_NUM_INT(b);
1452 a_max = (a->rdx > b->rdx);
1454 if (a_int != 0) return (ssize_t) a_int;
1458 diff = a->rdx - b->rdx;
1459 max_num = a->num + diff;
1464 diff = b->rdx - a->rdx;
1465 max_num = b->num + diff;
1469 cmp = bc_num_compare(max_num, min_num, b_int + min);
1470 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1472 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1473 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1479 static void bc_num_truncate(BcNum *n, size_t places)
1481 if (places == 0) return;
1487 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1491 static void bc_num_extend(BcNum *n, size_t places)
1493 size_t len = n->len + places;
1497 if (n->cap < len) bc_num_expand(n, len);
1499 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1500 memset(n->num, 0, sizeof(BcDig) * places);
1507 static void bc_num_clean(BcNum *n)
1509 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1512 else if (n->len < n->rdx)
1516 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1519 bc_num_extend(n, scale - n->rdx);
1521 bc_num_truncate(n, n->rdx - scale);
1524 if (n->len != 0) n->neg = !neg1 != !neg2;
1527 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1532 b->len = n->len - idx;
1534 a->rdx = b->rdx = 0;
1536 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1537 memcpy(a->num, n->num, idx * sizeof(BcDig));
1548 static BcStatus bc_num_shift(BcNum *n, size_t places)
1550 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
1551 if (places + n->len > BC_MAX_NUM)
1552 return bc_error("number too long: must be [1, BC_NUM_MAX]");
1554 if (n->rdx >= places)
1557 bc_num_extend(n, places - n->rdx);
1563 return BC_STATUS_SUCCESS;
1566 static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1575 return bc_num_div(&one, a, b, scale);
1578 static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1580 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1581 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1584 // Because this function doesn't need to use scale (per the bc spec),
1585 // I am hijacking it to say whether it's doing an add or a subtract.
1589 if (sub && c->len) c->neg = !c->neg;
1590 return BC_STATUS_SUCCESS;
1592 else if (b->len == 0) {
1594 return BC_STATUS_SUCCESS;
1598 c->rdx = BC_MAX(a->rdx, b->rdx);
1599 min_rdx = BC_MIN(a->rdx, b->rdx);
1602 if (a->rdx > b->rdx) {
1603 diff = a->rdx - b->rdx;
1605 ptr_a = a->num + diff;
1609 diff = b->rdx - a->rdx;
1612 ptr_b = b->num + diff;
1615 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1618 a_int = BC_NUM_INT(a);
1619 b_int = BC_NUM_INT(b);
1621 if (a_int > b_int) {
1632 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
1633 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1635 ptr_c[i] = (BcDig)(in % 10);
1638 for (; i < max + min_rdx; ++i, ++c->len) {
1639 in = ((int) ptr[i]) + carry;
1641 ptr_c[i] = (BcDig)(in % 10);
1644 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1646 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1649 static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1652 BcNum *minuend, *subtrahend;
1654 bool aneg, bneg, neg;
1656 // Because this function doesn't need to use scale (per the bc spec),
1657 // I am hijacking it to say whether it's doing an add or a subtract.
1661 if (sub && c->len) c->neg = !c->neg;
1662 return BC_STATUS_SUCCESS;
1664 else if (b->len == 0) {
1666 return BC_STATUS_SUCCESS;
1671 a->neg = b->neg = false;
1673 cmp = bc_num_cmp(a, b);
1679 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1680 return BC_STATUS_SUCCESS;
1689 if (sub) neg = !neg;
1694 bc_num_copy(c, minuend);
1697 if (c->rdx < subtrahend->rdx) {
1698 bc_num_extend(c, subtrahend->rdx - c->rdx);
1702 start = c->rdx - subtrahend->rdx;
1704 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1708 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1711 static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1715 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1716 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1719 if (a->len == 0 || b->len == 0) {
1721 return BC_STATUS_SUCCESS;
1723 aone = BC_NUM_ONE(a);
1724 if (aone || BC_NUM_ONE(b)) {
1725 bc_num_copy(c, aone ? b : a);
1726 return BC_STATUS_SUCCESS;
1729 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1730 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1735 bc_num_expand(c, a->len + b->len + 1);
1737 memset(c->num, 0, sizeof(BcDig) * c->cap);
1740 for (i = 0; i < b->len; ++i) {
1743 for (j = 0; j < a->len; ++j) {
1744 unsigned in = c->num[i + j];
1745 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1746 // note: compilers prefer _unsigned_ div/const
1748 c->num[i + j] = (BcDig)(in % 10);
1751 c->num[i + j] += (BcDig) carry;
1752 len = BC_MAX(len, i + j + !!carry);
1755 // a*a <- without check below, this will not be interruptible
1756 if (G_interrupt) return BC_STATUS_FAILURE;
1761 return BC_STATUS_SUCCESS;
1764 bc_num_init(&l1, max);
1765 bc_num_init(&h1, max);
1766 bc_num_init(&l2, max);
1767 bc_num_init(&h2, max);
1768 bc_num_init(&m1, max);
1769 bc_num_init(&m2, max);
1770 bc_num_init(&z0, max);
1771 bc_num_init(&z1, max);
1772 bc_num_init(&z2, max);
1773 bc_num_init(&temp, max + max);
1775 bc_num_split(a, max2, &l1, &h1);
1776 bc_num_split(b, max2, &l2, &h2);
1778 s = bc_num_add(&h1, &l1, &m1, 0);
1780 s = bc_num_add(&h2, &l2, &m2, 0);
1783 s = bc_num_k(&h1, &h2, &z0);
1785 s = bc_num_k(&m1, &m2, &z1);
1787 s = bc_num_k(&l1, &l2, &z2);
1790 s = bc_num_sub(&z1, &z0, &temp, 0);
1792 s = bc_num_sub(&temp, &z2, &z1, 0);
1795 s = bc_num_shift(&z0, max2 * 2);
1797 s = bc_num_shift(&z1, max2);
1799 s = bc_num_add(&z0, &z1, &temp, 0);
1801 s = bc_num_add(&temp, &z2, c, 0);
1817 static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1821 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1823 scale = BC_MAX(scale, a->rdx);
1824 scale = BC_MAX(scale, b->rdx);
1825 scale = BC_MIN(a->rdx + b->rdx, scale);
1826 maxrdx = BC_MAX(maxrdx, scale);
1828 bc_num_init(&cpa, a->len);
1829 bc_num_init(&cpb, b->len);
1831 bc_num_copy(&cpa, a);
1832 bc_num_copy(&cpb, b);
1833 cpa.neg = cpb.neg = false;
1835 s = bc_num_shift(&cpa, maxrdx);
1837 s = bc_num_shift(&cpb, maxrdx);
1839 s = bc_num_k(&cpa, &cpb, c);
1843 bc_num_expand(c, c->len + maxrdx);
1845 if (c->len < maxrdx) {
1846 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1851 bc_num_retireMul(c, scale, a->neg, b->neg);
1859 static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1861 BcStatus s = BC_STATUS_SUCCESS;
1868 return bc_error("divide by zero");
1869 else if (a->len == 0) {
1870 bc_num_setToZero(c, scale);
1871 return BC_STATUS_SUCCESS;
1873 else if (BC_NUM_ONE(b)) {
1875 bc_num_retireMul(c, scale, a->neg, b->neg);
1876 return BC_STATUS_SUCCESS;
1879 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1880 bc_num_copy(&cp, a);
1884 bc_num_expand(&cp, len + 2);
1885 bc_num_extend(&cp, len - cp.len);
1888 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1890 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1892 if (b->rdx == b->len) {
1893 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1897 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1899 // We want an extra zero in front to make things simpler.
1900 cp.num[cp.len++] = 0;
1903 bc_num_expand(c, cp.len);
1906 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1911 for (i = end - 1; !s && i < end; --i) {
1913 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
1914 bc_num_subArrays(n, p, len);
1918 // 1/a <- without check below, this will not be interruptible
1920 s = BC_STATUS_FAILURE;
1925 bc_num_retireMul(c, scale, a->neg, b->neg);
1931 static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
1932 BcNum *restrict d, size_t scale, size_t ts)
1939 return bc_error("divide by zero");
1942 bc_num_setToZero(d, ts);
1943 return BC_STATUS_SUCCESS;
1946 bc_num_init(&temp, d->cap);
1947 s = bc_num_d(a, b, c, scale);
1950 if (scale != 0) scale = ts;
1952 s = bc_num_m(c, b, &temp, scale);
1954 s = bc_num_sub(a, &temp, d, scale);
1957 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
1960 bc_num_retireMul(d, ts, a->neg, b->neg);
1968 static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1972 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
1974 bc_num_init(&c1, len);
1975 s = bc_num_r(a, b, &c1, c, scale, ts);
1981 static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1983 BcStatus s = BC_STATUS_SUCCESS;
1986 size_t i, powrdx, resrdx;
1989 if (b->rdx) return bc_error("non integer number");
1993 return BC_STATUS_SUCCESS;
1995 else if (a->len == 0) {
1996 bc_num_setToZero(c, scale);
1997 return BC_STATUS_SUCCESS;
1999 else if (BC_NUM_ONE(b)) {
2003 s = bc_num_inv(a, c, scale);
2010 s = bc_num_ulong(b, &pow);
2013 bc_num_init(©, a->len);
2014 bc_num_copy(©, a);
2016 if (!neg) scale = BC_MIN(a->rdx * pow, BC_MAX(scale, a->rdx));
2020 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2022 s = bc_num_mul(©, ©, ©, powrdx);
2024 // Not needed: bc_num_mul() has a check for ^C:
2025 //if (G_interrupt) {
2026 // s = BC_STATUS_FAILURE;
2031 bc_num_copy(c, ©);
2033 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2036 s = bc_num_mul(©, ©, ©, powrdx);
2041 s = bc_num_mul(c, ©, c, resrdx);
2044 // Not needed: bc_num_mul() has a check for ^C:
2045 //if (G_interrupt) {
2046 // s = BC_STATUS_FAILURE;
2052 s = bc_num_inv(c, c, scale);
2056 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2058 // We can't use bc_num_clean() here.
2059 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2060 if (zero) bc_num_setToZero(c, scale);
2067 static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2068 BcNumBinaryOp op, size_t req)
2071 BcNum num2, *ptr_a, *ptr_b;
2076 memcpy(ptr_a, c, sizeof(BcNum));
2085 memcpy(ptr_b, c, sizeof(BcNum));
2093 bc_num_init(c, req);
2095 bc_num_expand(c, req);
2097 s = op(ptr_a, ptr_b, c, scale);
2099 if (init) bc_num_free(&num2);
2104 static bool bc_num_strValid(const char *val, size_t base)
2107 bool small, radix = false;
2108 size_t i, len = strlen(val);
2110 if (!len) return true;
2113 b = (BcDig)(small ? base + '0' : base - 10 + 'A');
2115 for (i = 0; i < len; ++i) {
2121 if (radix) return false;
2127 if (c < '0' || (small && c >= b) || (c > '9' && (c < 'A' || c >= b)))
2134 static void bc_num_parseDecimal(BcNum *n, const char *val)
2140 for (i = 0; val[i] == '0'; ++i);
2147 for (i = 0; zero && i < len; ++i) zero = val[i] == '0' || val[i] == '.';
2148 bc_num_expand(n, len);
2151 ptr = strchr(val, '.');
2155 n->rdx = (size_t)((val + len) - (ptr + 1));
2158 for (i = len - 1; i < len; ++n->len, i -= 1 + (i && val[i - 1] == '.'))
2159 n->num[n->len] = val[i] - '0';
2163 static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2166 BcNum temp, mult, result;
2170 size_t i, digits, len = strlen(val);
2174 for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
2177 bc_num_init(&temp, BC_NUM_DEF_SIZE);
2178 bc_num_init(&mult, BC_NUM_DEF_SIZE);
2180 for (i = 0; i < len; ++i) {
2183 if (c == '.') break;
2185 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2187 s = bc_num_mul(n, base, &mult, 0);
2188 if (s) goto int_err;
2189 bc_num_ulong2num(&temp, v);
2190 s = bc_num_add(&mult, &temp, n, 0);
2191 if (s) goto int_err;
2196 if (c == 0) goto int_err;
2199 bc_num_init(&result, base->len);
2200 bc_num_zero(&result);
2203 for (i += 1, digits = 0; i < len; ++i, ++digits) {
2208 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2210 s = bc_num_mul(&result, base, &result, 0);
2212 bc_num_ulong2num(&temp, v);
2213 s = bc_num_add(&result, &temp, &result, 0);
2215 s = bc_num_mul(&mult, base, &mult, 0);
2219 s = bc_num_div(&result, &mult, &result, digits);
2221 s = bc_num_add(n, &result, n, digits);
2225 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2231 bc_num_free(&result);
2237 static void bc_num_printNewline(size_t *nchars, size_t line_len)
2239 if (*nchars == line_len - 1) {
2247 static void bc_num_printChar(size_t num, size_t width, bool radix,
2248 size_t *nchars, size_t line_len)
2250 (void) radix, (void) line_len;
2251 bb_putchar((char) num);
2252 *nchars = *nchars + width;
2256 static void bc_num_printDigits(size_t num, size_t width, bool radix,
2257 size_t *nchars, size_t line_len)
2261 bc_num_printNewline(nchars, line_len);
2262 bb_putchar(radix ? '.' : ' ');
2265 bc_num_printNewline(nchars, line_len);
2266 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2269 for (exp = 0; exp < width; pow /= 10, ++(*nchars), ++exp) {
2271 bc_num_printNewline(nchars, line_len);
2274 bb_putchar(((char) dig) + '0');
2278 static void bc_num_printHex(size_t num, size_t width, bool radix,
2279 size_t *nchars, size_t line_len)
2282 bc_num_printNewline(nchars, line_len);
2287 bc_num_printNewline(nchars, line_len);
2288 bb_putchar(bb_hexdigits_upcase[num]);
2289 *nchars = *nchars + width;
2292 static void bc_num_printDecimal(BcNum *n, size_t *nchars, size_t len)
2294 size_t i, rdx = n->rdx - 1;
2296 if (n->neg) bb_putchar('-');
2297 (*nchars) += n->neg;
2299 for (i = n->len - 1; i < n->len; --i)
2300 bc_num_printHex((size_t) n->num[i], 1, i == rdx, nchars, len);
2303 static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width,
2304 size_t *nchars, size_t len, BcNumDigitOp print)
2308 BcNum intp, fracp, digit, frac_len;
2309 unsigned long dig, *ptr;
2314 print(0, width, false, nchars, len);
2315 return BC_STATUS_SUCCESS;
2318 bc_vec_init(&stack, sizeof(long), NULL);
2319 bc_num_init(&intp, n->len);
2320 bc_num_init(&fracp, n->rdx);
2321 bc_num_init(&digit, width);
2322 bc_num_init(&frac_len, BC_NUM_INT(n));
2323 bc_num_copy(&intp, n);
2324 bc_num_one(&frac_len);
2326 bc_num_truncate(&intp, intp.rdx);
2327 s = bc_num_sub(n, &intp, &fracp, 0);
2330 while (intp.len != 0) {
2331 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2333 s = bc_num_ulong(&digit, &dig);
2335 bc_vec_push(&stack, &dig);
2338 for (i = 0; i < stack.len; ++i) {
2339 ptr = bc_vec_item_rev(&stack, i);
2340 print(*ptr, width, false, nchars, len);
2343 if (!n->rdx) goto err;
2345 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2346 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2348 s = bc_num_ulong(&fracp, &dig);
2350 bc_num_ulong2num(&intp, dig);
2351 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2353 print(dig, width, radix, nchars, len);
2354 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2359 bc_num_free(&frac_len);
2360 bc_num_free(&digit);
2361 bc_num_free(&fracp);
2363 bc_vec_free(&stack);
2367 static BcStatus bc_num_printBase(BcNum *n, BcNum *base, size_t base_t,
2368 size_t *nchars, size_t line_len)
2375 if (neg) bb_putchar('-');
2380 if (base_t <= BC_NUM_MAX_IBASE) {
2382 print = bc_num_printHex;
2385 for (i = base_t - 1, width = 0; i != 0; i /= 10, ++width);
2386 print = bc_num_printDigits;
2389 s = bc_num_printNum(n, base, width, nchars, line_len, print);
2396 static BcStatus bc_num_stream(BcNum *n, BcNum *base, size_t *nchars, size_t len)
2398 return bc_num_printNum(n, base, 1, nchars, len, bc_num_printChar);
2402 static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2405 if (!bc_num_strValid(val, base_t))
2406 return bc_error("bad number string");
2409 bc_num_parseDecimal(n, val);
2411 bc_num_parseBase(n, val, base);
2413 return BC_STATUS_SUCCESS;
2416 static BcStatus bc_num_print(BcNum *n, BcNum *base, size_t base_t, bool newline,
2417 size_t *nchars, size_t line_len)
2419 BcStatus s = BC_STATUS_SUCCESS;
2421 bc_num_printNewline(nchars, line_len);
2427 else if (base_t == 10)
2428 bc_num_printDecimal(n, nchars, line_len);
2430 s = bc_num_printBase(n, base, base_t, nchars, line_len);
2440 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2442 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2444 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2447 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2449 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2451 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2454 static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2456 size_t req = BC_NUM_MREQ(a, b, scale);
2457 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2460 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2462 size_t req = BC_NUM_MREQ(a, b, scale);
2463 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2466 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2468 size_t req = BC_NUM_MREQ(a, b, scale);
2469 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2472 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2474 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2477 static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2480 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2481 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2482 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2484 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2485 bc_num_expand(b, req);
2488 bc_num_setToZero(b, scale);
2489 return BC_STATUS_SUCCESS;
2492 return bc_error("negative number");
2493 else if (BC_NUM_ONE(a)) {
2495 bc_num_extend(b, scale);
2496 return BC_STATUS_SUCCESS;
2499 scale = BC_MAX(scale, a->rdx) + 1;
2500 len = a->len + scale;
2502 bc_num_init(&num1, len);
2503 bc_num_init(&num2, len);
2504 bc_num_init(&half, BC_NUM_DEF_SIZE);
2510 bc_num_init(&f, len);
2511 bc_num_init(&fprime, len);
2517 pow = BC_NUM_INT(a);
2526 pow -= 2 - (pow & 1);
2528 bc_num_extend(x0, pow);
2530 // Make sure to move the radix back.
2534 x0->rdx = digs = digs1 = 0;
2536 len = BC_NUM_INT(x0) + resrdx - 1;
2538 while (cmp != 0 || digs < len) {
2540 s = bc_num_div(a, x0, &f, resrdx);
2542 s = bc_num_add(x0, &f, &fprime, resrdx);
2544 s = bc_num_mul(&fprime, &half, x1, resrdx);
2547 cmp = bc_num_cmp(x1, x0);
2548 digs = x1->len - (unsigned long long) llabs(cmp);
2550 if (cmp == cmp2 && digs == digs1)
2555 resrdx += times > 4;
2568 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2571 bc_num_free(&fprime);
2579 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2585 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2588 memcpy(&num2, c, sizeof(BcNum));
2590 bc_num_init(c, len);
2595 bc_num_expand(c, len);
2598 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2600 if (init) bc_num_free(&num2);
2606 static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2609 BcNum base, exp, two, temp;
2612 return bc_error("divide by zero");
2613 if (a->rdx || b->rdx || c->rdx)
2614 return bc_error("non integer number");
2616 return bc_error("negative number");
2618 bc_num_expand(d, c->len);
2619 bc_num_init(&base, c->len);
2620 bc_num_init(&exp, b->len);
2621 bc_num_init(&two, BC_NUM_DEF_SIZE);
2622 bc_num_init(&temp, b->len);
2628 s = bc_num_rem(a, c, &base, 0);
2630 bc_num_copy(&exp, b);
2632 while (exp.len != 0) {
2634 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2637 if (BC_NUM_ONE(&temp)) {
2638 s = bc_num_mul(d, &base, &temp, 0);
2640 s = bc_num_rem(&temp, c, d, 0);
2644 s = bc_num_mul(&base, &base, &temp, 0);
2646 s = bc_num_rem(&temp, c, &base, 0);
2659 static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2664 for (i = 0; i < f->autos.len; ++i) {
2665 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2666 return bc_error("function parameter or auto var has the same name as another");
2672 bc_vec_push(&f->autos, &a);
2674 return BC_STATUS_SUCCESS;
2677 static void bc_func_init(BcFunc *f)
2679 bc_char_vec_init(&f->code);
2680 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2681 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2685 static void bc_func_free(void *func)
2687 BcFunc *f = (BcFunc *) func;
2688 bc_vec_free(&f->code);
2689 bc_vec_free(&f->autos);
2690 bc_vec_free(&f->labels);
2693 static void bc_array_expand(BcVec *a, size_t len);
2695 static void bc_array_init(BcVec *a, bool nums)
2698 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2700 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2701 bc_array_expand(a, 1);
2704 static void bc_array_expand(BcVec *a, size_t len)
2708 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2709 while (len > a->len) {
2710 bc_num_init(&data.n, BC_NUM_DEF_SIZE);
2711 bc_vec_push(a, &data.n);
2715 while (len > a->len) {
2716 bc_array_init(&data.v, true);
2717 bc_vec_push(a, &data.v);
2722 static void bc_array_copy(BcVec *d, const BcVec *s)
2727 bc_vec_expand(d, s->cap);
2730 for (i = 0; i < s->len; ++i) {
2731 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2732 bc_num_init(dnum, snum->len);
2733 bc_num_copy(dnum, snum);
2737 static void bc_string_free(void *string)
2739 free(*((char **) string));
2743 static void bc_result_copy(BcResult *d, BcResult *src)
2749 case BC_RESULT_TEMP:
2750 case BC_RESULT_IBASE:
2751 case BC_RESULT_SCALE:
2752 case BC_RESULT_OBASE:
2754 bc_num_init(&d->d.n, src->d.n.len);
2755 bc_num_copy(&d->d.n, &src->d.n);
2760 case BC_RESULT_ARRAY:
2761 case BC_RESULT_ARRAY_ELEM:
2763 d->d.id.name = xstrdup(src->d.id.name);
2767 case BC_RESULT_CONSTANT:
2768 case BC_RESULT_LAST:
2772 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2779 static void bc_result_free(void *result)
2781 BcResult *r = (BcResult *) result;
2785 case BC_RESULT_TEMP:
2786 case BC_RESULT_IBASE:
2787 case BC_RESULT_SCALE:
2788 case BC_RESULT_OBASE:
2790 bc_num_free(&r->d.n);
2795 case BC_RESULT_ARRAY:
2796 case BC_RESULT_ARRAY_ELEM:
2810 static void bc_lex_lineComment(BcLex *l)
2812 l->t.t = BC_LEX_WHITESPACE;
2813 while (l->i < l->len && l->buf[l->i++] != '\n');
2817 static void bc_lex_whitespace(BcLex *l)
2820 l->t.t = BC_LEX_WHITESPACE;
2821 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2824 static BcStatus bc_lex_number(BcLex *l, char start)
2826 const char *buf = l->buf + l->i;
2827 size_t len, hits = 0, bslashes = 0, i = 0, j;
2829 bool last_pt, pt = start == '.';
2832 l->t.t = BC_LEX_NUMBER;
2834 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2835 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2849 len = i + !last_pt - bslashes * 2;
2850 if (len > BC_MAX_NUM)
2851 return bc_error("number too long: must be [1, BC_NUM_MAX]");
2853 bc_vec_pop_all(&l->t.v);
2854 bc_vec_expand(&l->t.v, len + 1);
2855 bc_vec_push(&l->t.v, &start);
2857 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2861 // If we have hit a backslash, skip it. We don't have
2862 // to check for a newline because it's guaranteed.
2863 if (hits < bslashes && c == '\\') {
2869 bc_vec_push(&l->t.v, &c);
2872 bc_vec_pushZeroByte(&l->t.v);
2875 return BC_STATUS_SUCCESS;
2878 static BcStatus bc_lex_name(BcLex *l)
2881 const char *buf = l->buf + l->i - 1;
2884 l->t.t = BC_LEX_NAME;
2886 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2888 if (i > BC_MAX_STRING)
2889 return bc_error("name too long: must be [1, BC_NAME_MAX]");
2890 bc_vec_string(&l->t.v, i, buf);
2892 // Increment the index. We minus 1 because it has already been incremented.
2895 return BC_STATUS_SUCCESS;
2898 static void bc_lex_init(BcLex *l, BcLexNext next)
2901 bc_char_vec_init(&l->t.v);
2904 static void bc_lex_free(BcLex *l)
2906 bc_vec_free(&l->t.v);
2909 static void bc_lex_file(BcLex *l)
2911 G.err_line = l->line = 1;
2915 static BcStatus bc_lex_next(BcLex *l)
2920 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
2922 l->line += l->newline;
2923 G.err_line = l->line;
2924 l->t.t = BC_LEX_EOF;
2926 l->newline = (l->i == l->len);
2927 if (l->newline) return BC_STATUS_SUCCESS;
2929 // Loop until failure or we don't have whitespace. This
2930 // is so the parser doesn't get inundated with whitespace.
2933 } while (!s && l->t.t == BC_LEX_WHITESPACE);
2938 static BcStatus bc_lex_text(BcLex *l, const char *text)
2942 l->len = strlen(text);
2943 l->t.t = l->t.last = BC_LEX_INVALID;
2944 return bc_lex_next(l);
2948 static BcStatus bc_lex_identifier(BcLex *l)
2952 const char *buf = l->buf + l->i - 1;
2954 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
2955 const char *keyword8 = bc_lex_kws[i].name8;
2957 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
2959 if (j == 8) goto match;
2961 if (keyword8[j] != '\0')
2964 // buf starts with keyword bc_lex_kws[i]
2965 l->t.t = BC_LEX_KEY_1st_keyword + i;
2966 if (!((1 << i) & POSIX_KWORD_MASK)) {
2967 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
2971 // We minus 1 because the index has already been incremented.
2973 return BC_STATUS_SUCCESS;
2979 if (l->t.v.len > 2) {
2982 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
2984 unsigned len = strchrnul(buf, '\n') - buf;
2985 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
2991 static BcStatus bc_lex_string(BcLex *l)
2993 size_t len, nls = 0, i = l->i;
2996 l->t.t = BC_LEX_STR;
2998 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3002 return bc_error("string end could not be found");
3006 if (len > BC_MAX_STRING)
3007 return bc_error("string too long: must be [1, BC_STRING_MAX]");
3008 bc_vec_string(&l->t.v, len, l->buf + l->i);
3012 G.err_line = l->line;
3014 return BC_STATUS_SUCCESS;
3017 static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3019 if (l->buf[l->i] == '=') {
3027 static BcStatus bc_lex_comment(BcLex *l)
3030 const char *buf = l->buf;
3032 l->t.t = BC_LEX_WHITESPACE;
3045 return bc_error("comment end could not be found");
3053 G.err_line = l->line;
3055 return BC_STATUS_SUCCESS;
3058 static BcStatus bc_lex_token(BcLex *l)
3060 BcStatus s = BC_STATUS_SUCCESS;
3061 char c = l->buf[l->i++], c2;
3063 // This is the workhorse of the lexer.
3070 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3080 bc_lex_whitespace(l);
3086 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3088 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
3089 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3098 s = bc_lex_string(l);
3104 s = bc_POSIX_does_not_allow("'#' script comments");
3107 bc_lex_lineComment(l);
3114 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3123 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3127 l->t.t = BC_LEX_OP_BOOL_AND;
3130 l->t.t = BC_LEX_INVALID;
3131 s = bc_error_bad_character('&');
3140 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3146 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3155 l->t.t = BC_LEX_OP_INC;
3158 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3164 l->t.t = BC_LEX_COMMA;
3173 l->t.t = BC_LEX_OP_DEC;
3176 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3182 if (isdigit(l->buf[l->i]))
3183 s = bc_lex_number(l, c);
3185 l->t.t = BC_LEX_KEY_LAST;
3186 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3195 s = bc_lex_comment(l);
3197 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3218 s = bc_lex_number(l, c);
3224 l->t.t = BC_LEX_SCOLON;
3230 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3236 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3242 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3249 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3255 if (l->buf[l->i] == '\n') {
3256 l->t.t = BC_LEX_WHITESPACE;
3260 s = bc_error_bad_character(c);
3266 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3297 s = bc_lex_identifier(l);
3304 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3313 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3317 l->t.t = BC_LEX_OP_BOOL_OR;
3320 l->t.t = BC_LEX_INVALID;
3321 s = bc_error_bad_character(c);
3329 l->t.t = BC_LEX_INVALID;
3330 s = bc_error_bad_character(c);
3340 static BcStatus dc_lex_register(BcLex *l)
3342 BcStatus s = BC_STATUS_SUCCESS;
3344 if (isspace(l->buf[l->i - 1])) {
3345 bc_lex_whitespace(l);
3348 s = bc_error("extended register");
3353 bc_vec_pop_all(&l->t.v);
3354 bc_vec_pushByte(&l->t.v, l->buf[l->i - 1]);
3355 bc_vec_pushZeroByte(&l->t.v);
3356 l->t.t = BC_LEX_NAME;
3362 static BcStatus dc_lex_string(BcLex *l)
3364 size_t depth = 1, nls = 0, i = l->i;
3367 l->t.t = BC_LEX_STR;
3368 bc_vec_pop_all(&l->t.v);
3370 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3372 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3373 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3376 if (depth) bc_vec_push(&l->t.v, &c);
3381 return bc_error("string end could not be found");
3384 bc_vec_pushZeroByte(&l->t.v);
3385 if (i - l->i > BC_MAX_STRING)
3386 return bc_error("string too long: must be [1, BC_STRING_MAX]");
3390 G.err_line = l->line;
3392 return BC_STATUS_SUCCESS;
3395 static BcStatus dc_lex_token(BcLex *l)
3397 BcStatus s = BC_STATUS_SUCCESS;
3398 char c = l->buf[l->i++], c2;
3401 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3402 if (l->t.last == dc_lex_regs[i])
3403 return dc_lex_register(l);
3406 if (c >= '%' && c <= '~' &&
3407 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3412 // This is the workhorse of the lexer.
3417 l->t.t = BC_LEX_EOF;
3428 l->newline = (c == '\n');
3429 bc_lex_whitespace(l);
3438 l->t.t = BC_LEX_OP_REL_NE;
3440 l->t.t = BC_LEX_OP_REL_LE;
3442 l->t.t = BC_LEX_OP_REL_GE;
3444 return bc_error_bad_character(c);
3452 bc_lex_lineComment(l);
3458 if (isdigit(l->buf[l->i]))
3459 s = bc_lex_number(l, c);
3461 s = bc_error_bad_character(c);
3482 s = bc_lex_number(l, c);
3488 s = dc_lex_string(l);
3494 l->t.t = BC_LEX_INVALID;
3495 s = bc_error_bad_character(c);
3504 static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3506 bc_program_addFunc(name, idx);
3507 p->func = bc_vec_item(&G.prog.fns, p->fidx);
3510 static void bc_parse_pushName(BcParse *p, char *name)
3512 size_t i = 0, len = strlen(name);
3514 for (; i < len; ++i) bc_parse_push(p, name[i]);
3515 bc_parse_push(p, BC_PARSE_STREND);
3520 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3522 unsigned char amt, i, nums[sizeof(size_t)];
3524 for (amt = 0; idx; ++amt) {
3525 nums[amt] = (char) idx;
3526 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3529 bc_parse_push(p, amt);
3530 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3533 static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3535 char *num = xstrdup(p->l.t.v.v);
3536 size_t idx = G.prog.consts.len;
3538 bc_vec_push(&G.prog.consts, &num);
3540 bc_parse_push(p, BC_INST_NUM);
3541 bc_parse_pushIndex(p, idx);
3544 (*prev) = BC_INST_NUM;
3547 static BcStatus bc_parse_text(BcParse *p, const char *text)
3551 p->func = bc_vec_item(&G.prog.fns, p->fidx);
3553 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
3554 p->l.t.t = BC_LEX_INVALID;
3557 if (!BC_PARSE_CAN_EXEC(p))
3558 return bc_error("file is not executable");
3561 return bc_lex_text(&p->l, text);
3564 // Called when bc/dc_parse_parse() detects a failure,
3565 // resets parsing structures.
3566 static void bc_parse_reset(BcParse *p)
3568 if (p->fidx != BC_PROG_MAIN) {
3569 p->func->nparams = 0;
3570 bc_vec_pop_all(&p->func->code);
3571 bc_vec_pop_all(&p->func->autos);
3572 bc_vec_pop_all(&p->func->labels);
3574 bc_parse_updateFunc(p, BC_PROG_MAIN);
3578 p->l.t.t = BC_LEX_EOF;
3579 p->auto_part = (p->nbraces = 0);
3581 bc_vec_npop(&p->flags, p->flags.len - 1);
3582 bc_vec_pop_all(&p->exits);
3583 bc_vec_pop_all(&p->conds);
3584 bc_vec_pop_all(&p->ops);
3589 static void bc_parse_free(BcParse *p)
3591 bc_vec_free(&p->flags);
3592 bc_vec_free(&p->exits);
3593 bc_vec_free(&p->conds);
3594 bc_vec_free(&p->ops);
3598 static void bc_parse_create(BcParse *p, size_t func,
3599 BcParseParse parse, BcLexNext next)
3601 memset(p, 0, sizeof(BcParse));
3603 bc_lex_init(&p->l, next);
3604 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3605 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3606 bc_vec_init(&p->conds, sizeof(size_t), NULL);
3607 bc_vec_pushZeroByte(&p->flags);
3608 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3611 // p->auto_part = p->nbraces = 0; - already is
3612 bc_parse_updateFunc(p, func);
3617 #define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3618 #define BC_PARSE_LEAF(p, rparen) \
3619 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3620 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3622 // We can calculate the conversion between tokens and exprs by subtracting the
3623 // position of the first operator in the lex enum and adding the position of the
3624 // first in the expr enum. Note: This only works for binary operators.
3625 #define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3627 static BcStatus bc_parse_else(BcParse *p);
3628 static BcStatus bc_parse_stmt(BcParse *p);
3629 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
3630 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
3632 static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3633 size_t *nexprs, bool next)
3635 BcStatus s = BC_STATUS_SUCCESS;
3637 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3638 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
3640 while (p->ops.len > start) {
3642 t = BC_PARSE_TOP_OP(p);
3643 if (t == BC_LEX_LPAREN) break;
3645 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
3646 if (l >= r && (l != r || !left)) break;
3648 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3649 bc_vec_pop(&p->ops);
3650 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3653 bc_vec_push(&p->ops, &type);
3654 if (next) s = bc_lex_next(&p->l);
3659 static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3663 if (p->ops.len <= ops_bgn)
3664 return bc_error_bad_expression();
3665 top = BC_PARSE_TOP_OP(p);
3667 while (top != BC_LEX_LPAREN) {
3669 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3671 bc_vec_pop(&p->ops);
3672 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3674 if (p->ops.len <= ops_bgn)
3675 return bc_error_bad_expression();
3676 top = BC_PARSE_TOP_OP(p);
3679 bc_vec_pop(&p->ops);
3681 return bc_lex_next(&p->l);
3684 static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3690 s = bc_lex_next(&p->l);
3693 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3695 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3696 s = bc_parse_expr(p, flags, bc_parse_next_param);
3699 comma = p->l.t.t == BC_LEX_COMMA;
3701 s = bc_lex_next(&p->l);
3706 if (comma) return bc_error_bad_token();
3707 bc_parse_push(p, BC_INST_CALL);
3708 bc_parse_pushIndex(p, nparams);
3710 return BC_STATUS_SUCCESS;
3713 static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3716 BcId entry, *entry_ptr;
3721 s = bc_parse_params(p, flags);
3724 if (p->l.t.t != BC_LEX_RPAREN) {
3725 s = bc_error_bad_token();
3729 idx = bc_map_index(&G.prog.fn_map, &entry);
3731 if (idx == BC_VEC_INVALID_IDX) {
3732 name = xstrdup(entry.name);
3733 bc_parse_addFunc(p, name, &idx);
3734 idx = bc_map_index(&G.prog.fn_map, &entry);
3740 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3741 bc_parse_pushIndex(p, entry_ptr->idx);
3743 return bc_lex_next(&p->l);
3750 static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3755 name = xstrdup(p->l.t.v.v);
3756 s = bc_lex_next(&p->l);
3759 if (p->l.t.t == BC_LEX_LBRACKET) {
3761 s = bc_lex_next(&p->l);
3764 if (p->l.t.t == BC_LEX_RBRACKET) {
3766 if (!(flags & BC_PARSE_ARRAY)) {
3767 s = bc_error_bad_expression();
3771 *type = BC_INST_ARRAY;
3775 *type = BC_INST_ARRAY_ELEM;
3777 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3778 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3782 s = bc_lex_next(&p->l);
3784 bc_parse_push(p, *type);
3785 bc_parse_pushName(p, name);
3787 else if (p->l.t.t == BC_LEX_LPAREN) {
3789 if (flags & BC_PARSE_NOCALL) {
3790 s = bc_error_bad_token();
3794 *type = BC_INST_CALL;
3795 s = bc_parse_call(p, name, flags);
3798 *type = BC_INST_VAR;
3799 bc_parse_push(p, BC_INST_VAR);
3800 bc_parse_pushName(p, name);
3810 static BcStatus bc_parse_read(BcParse *p)
3814 s = bc_lex_next(&p->l);
3816 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3818 s = bc_lex_next(&p->l);
3820 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3822 bc_parse_push(p, BC_INST_READ);
3824 return bc_lex_next(&p->l);
3827 static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3832 s = bc_lex_next(&p->l);
3834 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3836 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3838 s = bc_lex_next(&p->l);
3841 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3844 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3846 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3847 bc_parse_push(p, *prev);
3849 return bc_lex_next(&p->l);
3852 static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3856 s = bc_lex_next(&p->l);
3859 if (p->l.t.t != BC_LEX_LPAREN) {
3860 *type = BC_INST_SCALE;
3861 bc_parse_push(p, BC_INST_SCALE);
3862 return BC_STATUS_SUCCESS;
3865 *type = BC_INST_SCALE_FUNC;
3866 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3868 s = bc_lex_next(&p->l);
3871 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3873 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3874 bc_parse_push(p, BC_INST_SCALE_FUNC);
3876 return bc_lex_next(&p->l);
3879 static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3880 size_t *nexprs, uint8_t flags)
3885 BcInst etype = *prev;
3887 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
3888 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
3889 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
3891 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
3892 bc_parse_push(p, inst);
3893 s = bc_lex_next(&p->l);
3897 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
3900 s = bc_lex_next(&p->l);
3904 // Because we parse the next part of the expression
3905 // right here, we need to increment this.
3906 *nexprs = *nexprs + 1;
3912 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
3916 case BC_LEX_KEY_IBASE:
3917 case BC_LEX_KEY_LAST:
3918 case BC_LEX_KEY_OBASE:
3920 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
3921 s = bc_lex_next(&p->l);
3925 case BC_LEX_KEY_SCALE:
3927 s = bc_lex_next(&p->l);
3929 if (p->l.t.t == BC_LEX_LPAREN)
3930 s = bc_error_bad_token();
3932 bc_parse_push(p, BC_INST_SCALE);
3938 s = bc_error_bad_token();
3943 if (!s) bc_parse_push(p, inst);
3949 static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
3950 bool rparen, size_t *nexprs)
3954 BcInst etype = *prev;
3956 s = bc_lex_next(&p->l);
3959 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
3960 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
3963 *prev = BC_PARSE_TOKEN_INST(type);
3965 // We can just push onto the op stack because this is the largest
3966 // precedence operator that gets pushed. Inc/dec does not.
3967 if (type != BC_LEX_OP_MINUS)
3968 bc_vec_push(&p->ops, &type);
3970 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
3975 static BcStatus bc_parse_string(BcParse *p, char inst)
3977 char *str = xstrdup(p->l.t.v.v);
3979 bc_parse_push(p, BC_INST_STR);
3980 bc_parse_pushIndex(p, G.prog.strs.len);
3981 bc_vec_push(&G.prog.strs, &str);
3982 bc_parse_push(p, inst);
3984 return bc_lex_next(&p->l);
3987 static BcStatus bc_parse_print(BcParse *p)
3993 s = bc_lex_next(&p->l);
3998 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
3999 return bc_error("bad print statement");
4001 while (!s && type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4003 if (type == BC_LEX_STR)
4004 s = bc_parse_string(p, BC_INST_PRINT_POP);
4006 s = bc_parse_expr(p, 0, bc_parse_next_print);
4008 bc_parse_push(p, BC_INST_PRINT_POP);
4013 comma = p->l.t.t == BC_LEX_COMMA;
4014 if (comma) s = bc_lex_next(&p->l);
4019 if (comma) return bc_error_bad_token();
4021 return bc_lex_next(&p->l);
4024 static BcStatus bc_parse_return(BcParse *p)
4030 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
4032 s = bc_lex_next(&p->l);
4036 paren = t == BC_LEX_LPAREN;
4038 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4039 bc_parse_push(p, BC_INST_RET0);
4042 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
4043 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4044 bc_parse_push(p, BC_INST_RET0);
4045 s = bc_lex_next(&p->l);
4049 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
4050 s = bc_POSIX_requires("parentheses around return expressions");
4054 bc_parse_push(p, BC_INST_RET);
4060 static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4062 BcStatus s = BC_STATUS_SUCCESS;
4064 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
4065 return bc_error_bad_token();
4069 if (p->l.t.t == BC_LEX_RBRACE) {
4070 if (!p->nbraces) return bc_error_bad_token();
4072 s = bc_lex_next(&p->l);
4076 return bc_error_bad_token();
4079 if (BC_PARSE_IF(p)) {
4083 while (p->l.t.t == BC_LEX_NLINE) {
4084 s = bc_lex_next(&p->l);
4088 bc_vec_pop(&p->flags);
4090 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4091 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4093 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4095 else if (BC_PARSE_ELSE(p)) {
4100 bc_vec_pop(&p->flags);
4102 ip = bc_vec_top(&p->exits);
4103 label = bc_vec_item(&p->func->labels, ip->idx);
4104 *label = p->func->code.len;
4106 bc_vec_pop(&p->exits);
4108 else if (BC_PARSE_FUNC_INNER(p)) {
4109 bc_parse_push(p, BC_INST_RET0);
4110 bc_parse_updateFunc(p, BC_PROG_MAIN);
4111 bc_vec_pop(&p->flags);
4115 BcInstPtr *ip = bc_vec_top(&p->exits);
4116 size_t *label = bc_vec_top(&p->conds);
4118 bc_parse_push(p, BC_INST_JUMP);
4119 bc_parse_pushIndex(p, *label);
4121 label = bc_vec_item(&p->func->labels, ip->idx);
4122 *label = p->func->code.len;
4124 bc_vec_pop(&p->flags);
4125 bc_vec_pop(&p->exits);
4126 bc_vec_pop(&p->conds);
4132 static void bc_parse_startBody(BcParse *p, uint8_t flags)
4134 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4135 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4136 flags |= BC_PARSE_FLAG_BODY;
4137 bc_vec_push(&p->flags, &flags);
4140 static void bc_parse_noElse(BcParse *p)
4144 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4146 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4148 ip = bc_vec_top(&p->exits);
4149 label = bc_vec_item(&p->func->labels, ip->idx);
4150 *label = p->func->code.len;
4152 bc_vec_pop(&p->exits);
4155 static BcStatus bc_parse_if(BcParse *p)
4160 s = bc_lex_next(&p->l);
4162 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4164 s = bc_lex_next(&p->l);
4166 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4168 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4170 s = bc_lex_next(&p->l);
4172 bc_parse_push(p, BC_INST_JUMP_ZERO);
4174 ip.idx = p->func->labels.len;
4175 ip.func = ip.len = 0;
4177 bc_parse_pushIndex(p, ip.idx);
4178 bc_vec_push(&p->exits, &ip);
4179 bc_vec_push(&p->func->labels, &ip.idx);
4180 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4182 return BC_STATUS_SUCCESS;
4185 static BcStatus bc_parse_else(BcParse *p)
4189 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
4191 ip.idx = p->func->labels.len;
4192 ip.func = ip.len = 0;
4194 bc_parse_push(p, BC_INST_JUMP);
4195 bc_parse_pushIndex(p, ip.idx);
4199 bc_vec_push(&p->exits, &ip);
4200 bc_vec_push(&p->func->labels, &ip.idx);
4201 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4203 return bc_lex_next(&p->l);
4206 static BcStatus bc_parse_while(BcParse *p)
4211 s = bc_lex_next(&p->l);
4213 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4214 s = bc_lex_next(&p->l);
4217 ip.idx = p->func->labels.len;
4219 bc_vec_push(&p->func->labels, &p->func->code.len);
4220 bc_vec_push(&p->conds, &ip.idx);
4222 ip.idx = p->func->labels.len;
4226 bc_vec_push(&p->exits, &ip);
4227 bc_vec_push(&p->func->labels, &ip.idx);
4229 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4231 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4232 s = bc_lex_next(&p->l);
4235 bc_parse_push(p, BC_INST_JUMP_ZERO);
4236 bc_parse_pushIndex(p, ip.idx);
4237 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4239 return BC_STATUS_SUCCESS;
4242 static BcStatus bc_parse_for(BcParse *p)
4246 size_t cond_idx, exit_idx, body_idx, update_idx;
4248 s = bc_lex_next(&p->l);
4250 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4251 s = bc_lex_next(&p->l);
4254 if (p->l.t.t != BC_LEX_SCOLON)
4255 s = bc_parse_expr(p, 0, bc_parse_next_for);
4257 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4260 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4261 s = bc_lex_next(&p->l);
4264 cond_idx = p->func->labels.len;
4265 update_idx = cond_idx + 1;
4266 body_idx = update_idx + 1;
4267 exit_idx = body_idx + 1;
4269 bc_vec_push(&p->func->labels, &p->func->code.len);
4271 if (p->l.t.t != BC_LEX_SCOLON)
4272 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4274 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4277 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4279 s = bc_lex_next(&p->l);
4282 bc_parse_push(p, BC_INST_JUMP_ZERO);
4283 bc_parse_pushIndex(p, exit_idx);
4284 bc_parse_push(p, BC_INST_JUMP);
4285 bc_parse_pushIndex(p, body_idx);
4287 ip.idx = p->func->labels.len;
4289 bc_vec_push(&p->conds, &update_idx);
4290 bc_vec_push(&p->func->labels, &p->func->code.len);
4292 if (p->l.t.t != BC_LEX_RPAREN)
4293 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4295 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4299 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4300 bc_parse_push(p, BC_INST_JUMP);
4301 bc_parse_pushIndex(p, cond_idx);
4302 bc_vec_push(&p->func->labels, &p->func->code.len);
4308 bc_vec_push(&p->exits, &ip);
4309 bc_vec_push(&p->func->labels, &ip.idx);
4311 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4313 return BC_STATUS_SUCCESS;
4316 static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4322 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
4324 if (type == BC_LEX_KEY_BREAK) {
4326 if (p->exits.len == 0) return bc_error_bad_token();
4328 i = p->exits.len - 1;
4329 ip = bc_vec_item(&p->exits, i);
4331 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
4332 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
4337 i = *((size_t *) bc_vec_top(&p->conds));
4339 bc_parse_push(p, BC_INST_JUMP);
4340 bc_parse_pushIndex(p, i);
4342 s = bc_lex_next(&p->l);
4345 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
4346 return bc_error_bad_token();
4348 return bc_lex_next(&p->l);
4351 static BcStatus bc_parse_func(BcParse *p)
4354 bool var, comma = false;
4358 s = bc_lex_next(&p->l);
4360 if (p->l.t.t != BC_LEX_NAME)
4361 return bc_error("bad function definition");
4363 name = xstrdup(p->l.t.v.v);
4364 bc_parse_addFunc(p, name, &p->fidx);
4366 s = bc_lex_next(&p->l);
4368 if (p->l.t.t != BC_LEX_LPAREN)
4369 return bc_error("bad function definition");
4370 s = bc_lex_next(&p->l);
4373 while (p->l.t.t != BC_LEX_RPAREN) {
4375 if (p->l.t.t != BC_LEX_NAME)
4376 return bc_error("bad function definition");
4380 name = xstrdup(p->l.t.v.v);
4381 s = bc_lex_next(&p->l);
4384 var = p->l.t.t != BC_LEX_LBRACKET;
4388 s = bc_lex_next(&p->l);
4391 if (p->l.t.t != BC_LEX_RBRACKET) {
4392 s = bc_error("bad function definition");
4396 s = bc_lex_next(&p->l);
4400 comma = p->l.t.t == BC_LEX_COMMA;
4402 s = bc_lex_next(&p->l);
4406 s = bc_func_insert(p->func, name, var);
4410 if (comma) return bc_error("bad function definition");
4412 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4413 bc_parse_startBody(p, flags);
4415 s = bc_lex_next(&p->l);
4418 if (p->l.t.t != BC_LEX_LBRACE)
4419 s = bc_POSIX_requires("the left brace be on the same line as the function header");
4428 static BcStatus bc_parse_auto(BcParse *p)
4431 bool comma, var, one;
4434 if (!p->auto_part) return bc_error_bad_token();
4435 s = bc_lex_next(&p->l);
4438 p->auto_part = comma = false;
4439 one = p->l.t.t == BC_LEX_NAME;
4441 while (p->l.t.t == BC_LEX_NAME) {
4443 name = xstrdup(p->l.t.v.v);
4444 s = bc_lex_next(&p->l);
4447 var = p->l.t.t != BC_LEX_LBRACKET;
4450 s = bc_lex_next(&p->l);
4453 if (p->l.t.t != BC_LEX_RBRACKET) {
4454 s = bc_error("bad function definition");
4458 s = bc_lex_next(&p->l);
4462 comma = p->l.t.t == BC_LEX_COMMA;
4464 s = bc_lex_next(&p->l);
4468 s = bc_func_insert(p->func, name, var);
4472 if (comma) return bc_error("bad function definition");
4473 if (!one) return bc_error("no auto variable found");
4475 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
4476 return bc_error_bad_token();
4478 return bc_lex_next(&p->l);
4485 static BcStatus bc_parse_body(BcParse *p, bool brace)
4487 BcStatus s = BC_STATUS_SUCCESS;
4488 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4490 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4492 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4494 if (!brace) return bc_error_bad_token();
4495 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4497 if (!p->auto_part) {
4498 s = bc_parse_auto(p);
4502 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4505 s = bc_parse_stmt(p);
4506 if (!s && !brace) s = bc_parse_endBody(p, false);
4512 static BcStatus bc_parse_stmt(BcParse *p)
4514 BcStatus s = BC_STATUS_SUCCESS;
4520 return bc_lex_next(&p->l);
4523 case BC_LEX_KEY_ELSE:
4525 p->auto_part = false;
4531 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
4534 s = bc_lex_next(&p->l);
4537 return bc_parse_body(p, true);
4540 case BC_LEX_KEY_AUTO:
4542 return bc_parse_auto(p);
4547 p->auto_part = false;
4549 if (BC_PARSE_IF_END(p)) {
4551 return BC_STATUS_SUCCESS;
4553 else if (BC_PARSE_BODY(p))
4554 return bc_parse_body(p, false);
4564 case BC_LEX_OP_MINUS:
4565 case BC_LEX_OP_BOOL_NOT:
4569 case BC_LEX_KEY_IBASE:
4570 case BC_LEX_KEY_LAST:
4571 case BC_LEX_KEY_LENGTH:
4572 case BC_LEX_KEY_OBASE:
4573 case BC_LEX_KEY_READ:
4574 case BC_LEX_KEY_SCALE:
4575 case BC_LEX_KEY_SQRT:
4577 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4581 case BC_LEX_KEY_ELSE:
4583 s = bc_parse_else(p);
4589 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4595 s = bc_parse_endBody(p, true);
4601 s = bc_parse_string(p, BC_INST_PRINT_STR);
4605 case BC_LEX_KEY_BREAK:
4606 case BC_LEX_KEY_CONTINUE:
4608 s = bc_parse_loopExit(p, p->l.t.t);
4612 case BC_LEX_KEY_FOR:
4614 s = bc_parse_for(p);
4618 case BC_LEX_KEY_HALT:
4620 bc_parse_push(p, BC_INST_HALT);
4621 s = bc_lex_next(&p->l);
4631 case BC_LEX_KEY_LIMITS:
4633 // "limits" is a compile-time command,
4634 // the output is produced at _parse time_.
4635 s = bc_lex_next(&p->l);
4637 printf("BC_BASE_MAX = %u\n", BC_MAX_OBASE);
4638 printf("BC_DIM_MAX = %u\n", BC_MAX_DIM);
4639 printf("BC_SCALE_MAX = %u\n", BC_MAX_SCALE);
4640 printf("BC_STRING_MAX = %u\n", BC_MAX_STRING);
4641 printf("BC_NAME_MAX = %u\n", BC_MAX_NAME);
4642 printf("BC_NUM_MAX = %u\n", BC_MAX_NUM);
4643 printf("MAX Exponent = %lu\n", BC_MAX_EXP);
4644 printf("Number of vars = %lu\n", BC_MAX_VARS);
4648 case BC_LEX_KEY_PRINT:
4650 s = bc_parse_print(p);
4654 case BC_LEX_KEY_QUIT:
4656 // "quit" is a compile-time command. For example,
4657 // "if (0 == 1) quit" terminates when parsing the statement,
4658 // not when it is executed
4659 quit_or_return_for_exit();
4662 case BC_LEX_KEY_RETURN:
4664 s = bc_parse_return(p);
4668 case BC_LEX_KEY_WHILE:
4670 s = bc_parse_while(p);
4676 s = bc_error_bad_token();
4684 static BcStatus bc_parse_parse(BcParse *p)
4688 if (p->l.t.t == BC_LEX_EOF)
4689 s = p->flags.len > 0 ? bc_error("block end could not be found") : bc_error("end of file");
4690 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
4691 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
4692 s = bc_parse_func(p);
4695 s = bc_parse_stmt(p);
4697 if (s || G_interrupt) {
4699 s = BC_STATUS_FAILURE;
4705 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
4707 BcStatus s = BC_STATUS_SUCCESS;
4708 BcInst prev = BC_INST_PRINT;
4709 BcLexType top, t = p->l.t.t;
4710 size_t nexprs = 0, ops_bgn = p->ops.len;
4711 uint32_t i, nparens, nrelops;
4712 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4714 paren_first = p->l.t.t == BC_LEX_LPAREN;
4715 nparens = nrelops = 0;
4716 paren_expr = rprn = done = get_token = assign = false;
4719 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
4725 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4726 rprn = get_token = bin_last = false;
4730 case BC_LEX_OP_MINUS:
4732 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4733 rprn = get_token = false;
4734 bin_last = prev == BC_INST_MINUS;
4738 case BC_LEX_OP_ASSIGN_POWER:
4739 case BC_LEX_OP_ASSIGN_MULTIPLY:
4740 case BC_LEX_OP_ASSIGN_DIVIDE:
4741 case BC_LEX_OP_ASSIGN_MODULUS:
4742 case BC_LEX_OP_ASSIGN_PLUS:
4743 case BC_LEX_OP_ASSIGN_MINUS:
4744 case BC_LEX_OP_ASSIGN:
4746 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4747 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4748 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4750 s = bc_error("bad assignment:"
4751 " left side must be scale,"
4752 " ibase, obase, last, var,"
4759 case BC_LEX_OP_POWER:
4760 case BC_LEX_OP_MULTIPLY:
4761 case BC_LEX_OP_DIVIDE:
4762 case BC_LEX_OP_MODULUS:
4763 case BC_LEX_OP_PLUS:
4764 case BC_LEX_OP_REL_EQ:
4765 case BC_LEX_OP_REL_LE:
4766 case BC_LEX_OP_REL_GE:
4767 case BC_LEX_OP_REL_NE:
4768 case BC_LEX_OP_REL_LT:
4769 case BC_LEX_OP_REL_GT:
4770 case BC_LEX_OP_BOOL_NOT:
4771 case BC_LEX_OP_BOOL_OR:
4772 case BC_LEX_OP_BOOL_AND:
4774 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4775 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4777 return bc_error_bad_expression();
4780 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4781 prev = BC_PARSE_TOKEN_INST(t);
4782 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4783 rprn = get_token = false;
4784 bin_last = t != BC_LEX_OP_BOOL_NOT;
4791 if (BC_PARSE_LEAF(prev, rprn))
4792 return bc_error_bad_expression();
4794 paren_expr = rprn = bin_last = false;
4796 bc_vec_push(&p->ops, &t);
4803 if (bin_last || prev == BC_INST_BOOL_NOT)
4804 return bc_error_bad_expression();
4807 s = BC_STATUS_SUCCESS;
4812 else if (!paren_expr)
4813 return BC_STATUS_PARSE_EMPTY_EXP;
4816 paren_expr = rprn = true;
4817 get_token = bin_last = false;
4819 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4826 if (BC_PARSE_LEAF(prev, rprn))
4827 return bc_error_bad_expression();
4829 rprn = get_token = bin_last = false;
4830 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4838 if (BC_PARSE_LEAF(prev, rprn))
4839 return bc_error_bad_expression();
4840 bc_parse_number(p, &prev, &nexprs);
4841 paren_expr = get_token = true;
4842 rprn = bin_last = false;
4847 case BC_LEX_KEY_IBASE:
4848 case BC_LEX_KEY_LAST:
4849 case BC_LEX_KEY_OBASE:
4851 if (BC_PARSE_LEAF(prev, rprn))
4852 return bc_error_bad_expression();
4853 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4854 bc_parse_push(p, (char) prev);
4856 paren_expr = get_token = true;
4857 rprn = bin_last = false;
4863 case BC_LEX_KEY_LENGTH:
4864 case BC_LEX_KEY_SQRT:
4866 if (BC_PARSE_LEAF(prev, rprn))
4867 return bc_error_bad_expression();
4868 s = bc_parse_builtin(p, t, flags, &prev);
4870 rprn = get_token = bin_last = false;
4876 case BC_LEX_KEY_READ:
4878 if (BC_PARSE_LEAF(prev, rprn))
4879 return bc_error_bad_expression();
4880 else if (flags & BC_PARSE_NOREAD)
4881 s = bc_error_nested_read_call();
4883 s = bc_parse_read(p);
4886 rprn = get_token = bin_last = false;
4888 prev = BC_INST_READ;
4893 case BC_LEX_KEY_SCALE:
4895 if (BC_PARSE_LEAF(prev, rprn))
4896 return bc_error_bad_expression();
4897 s = bc_parse_scale(p, &prev, flags);
4899 rprn = get_token = bin_last = false;
4901 prev = BC_INST_SCALE;
4908 s = bc_error_bad_token();
4913 if (!s && get_token) s = bc_lex_next(&p->l);
4917 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
4919 while (p->ops.len > ops_bgn) {
4921 top = BC_PARSE_TOP_OP(p);
4922 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
4924 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
4925 return bc_error_bad_expression();
4927 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
4929 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
4930 bc_vec_pop(&p->ops);
4933 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
4934 return bc_error_bad_expression();
4936 for (i = 0; i < next.len; ++i)
4937 if (t == next.tokens[i])
4939 return bc_error_bad_expression();
4942 if (!(flags & BC_PARSE_REL) && nrelops) {
4943 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
4946 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
4947 s = bc_POSIX_requires("exactly one comparison operator per condition");
4951 if (flags & BC_PARSE_PRINT) {
4952 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
4953 bc_parse_push(p, BC_INST_POP);
4959 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
4963 s = bc_parse_expr_empty_ok(p, flags, next);
4964 if (s == BC_STATUS_PARSE_EMPTY_EXP)
4965 return bc_error("empty expression");
4969 static void bc_parse_init(BcParse *p, size_t func)
4971 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
4974 static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
4976 return bc_parse_expr(p, flags, bc_parse_next_read);
4983 #define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
4985 static BcStatus dc_parse_register(BcParse *p)
4990 s = bc_lex_next(&p->l);
4992 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
4994 name = xstrdup(p->l.t.v.v);
4995 bc_parse_pushName(p, name);
5000 static BcStatus dc_parse_string(BcParse *p)
5002 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
5003 size_t idx, len = G.prog.strs.len;
5005 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5008 str = xstrdup(p->l.t.v.v);
5009 bc_parse_push(p, BC_INST_STR);
5010 bc_parse_pushIndex(p, len);
5011 bc_vec_push(&G.prog.strs, &str);
5012 bc_parse_addFunc(p, name, &idx);
5014 return bc_lex_next(&p->l);
5017 static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5021 bc_parse_push(p, inst);
5023 s = dc_parse_register(p);
5028 bc_parse_push(p, BC_INST_SWAP);
5029 bc_parse_push(p, BC_INST_ASSIGN);
5030 bc_parse_push(p, BC_INST_POP);
5033 return bc_lex_next(&p->l);
5036 static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5040 bc_parse_push(p, inst);
5041 bc_parse_push(p, BC_INST_EXEC_COND);
5043 s = dc_parse_register(p);
5046 s = bc_lex_next(&p->l);
5049 if (p->l.t.t == BC_LEX_ELSE) {
5050 s = dc_parse_register(p);
5052 s = bc_lex_next(&p->l);
5055 bc_parse_push(p, BC_PARSE_STREND);
5060 static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5062 BcStatus s = BC_STATUS_SUCCESS;
5065 bool assign, get_token = false;
5069 case BC_LEX_OP_REL_EQ:
5070 case BC_LEX_OP_REL_LE:
5071 case BC_LEX_OP_REL_GE:
5072 case BC_LEX_OP_REL_NE:
5073 case BC_LEX_OP_REL_LT:
5074 case BC_LEX_OP_REL_GT:
5076 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5083 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5089 s = dc_parse_string(p);
5096 if (t == BC_LEX_NEG) {
5097 s = bc_lex_next(&p->l);
5099 if (p->l.t.t != BC_LEX_NUMBER)
5100 return bc_error_bad_token();
5103 bc_parse_number(p, &prev, &p->nbraces);
5105 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5111 case BC_LEX_KEY_READ:
5113 if (flags & BC_PARSE_NOREAD)
5114 s = bc_error_nested_read_call();
5116 bc_parse_push(p, BC_INST_READ);
5121 case BC_LEX_OP_ASSIGN:
5122 case BC_LEX_STORE_PUSH:
5124 assign = t == BC_LEX_OP_ASSIGN;
5125 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5126 s = dc_parse_mem(p, inst, true, assign);
5131 case BC_LEX_LOAD_POP:
5133 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5134 s = dc_parse_mem(p, inst, true, false);
5138 case BC_LEX_STORE_IBASE:
5139 case BC_LEX_STORE_SCALE:
5140 case BC_LEX_STORE_OBASE:
5142 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5143 s = dc_parse_mem(p, inst, false, true);
5149 s = bc_error_bad_token();
5155 if (!s && get_token) s = bc_lex_next(&p->l);
5160 static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5162 BcStatus s = BC_STATUS_SUCCESS;
5166 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
5168 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5170 inst = dc_parse_insts[t];
5172 if (inst != BC_INST_INVALID) {
5173 bc_parse_push(p, inst);
5174 s = bc_lex_next(&p->l);
5177 s = dc_parse_token(p, t, flags);
5180 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5181 bc_parse_push(p, BC_INST_POP_EXEC);
5186 static BcStatus dc_parse_parse(BcParse *p)
5190 if (p->l.t.t == BC_LEX_EOF)
5191 s = bc_error("end of file");
5193 s = dc_parse_expr(p, 0);
5195 if (s || G_interrupt) {
5197 s = BC_STATUS_FAILURE;
5203 static void dc_parse_init(BcParse *p, size_t func)
5205 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
5210 static void common_parse_init(BcParse *p, size_t func)
5213 bc_parse_init(p, func);
5215 dc_parse_init(p, func);
5219 static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5222 return bc_parse_expression(p, flags);
5224 return dc_parse_expr(p, flags);
5228 static BcVec* bc_program_search(char *id, bool var)
5236 v = var ? &G.prog.vars : &G.prog.arrs;
5237 map = var ? &G.prog.var_map : &G.prog.arr_map;
5241 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5244 bc_array_init(&data.v, var);
5245 bc_vec_push(v, &data.v);
5248 ptr = bc_vec_item(map, i);
5249 if (new) ptr->name = xstrdup(e.name);
5250 return bc_vec_item(v, ptr->idx);
5253 static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
5255 BcStatus s = BC_STATUS_SUCCESS;
5260 case BC_RESULT_TEMP:
5261 case BC_RESULT_IBASE:
5262 case BC_RESULT_SCALE:
5263 case BC_RESULT_OBASE:
5269 case BC_RESULT_CONSTANT:
5271 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
5272 size_t base_t, len = strlen(*str);
5275 bc_num_init(&r->d.n, len);
5277 hex = hex && len == 1;
5278 base = hex ? &G.prog.hexb : &G.prog.ib;
5279 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
5280 s = bc_num_parse(&r->d.n, *str, base, base_t);
5283 bc_num_free(&r->d.n);
5288 r->t = BC_RESULT_TEMP;
5294 case BC_RESULT_ARRAY:
5295 case BC_RESULT_ARRAY_ELEM:
5299 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
5301 if (r->t == BC_RESULT_ARRAY_ELEM) {
5303 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5304 *num = bc_vec_item(v, r->d.id.idx);
5307 *num = bc_vec_top(v);
5312 case BC_RESULT_LAST:
5314 *num = &G.prog.last;
5328 static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
5329 BcResult **r, BcNum **rn, bool assign)
5333 BcResultType lt, rt;
5335 if (!BC_PROG_STACK(&G.prog.results, 2))
5336 return bc_error_stack_has_too_few_elements();
5338 *r = bc_vec_item_rev(&G.prog.results, 0);
5339 *l = bc_vec_item_rev(&G.prog.results, 1);
5343 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5345 s = bc_program_num(*l, ln, false);
5347 s = bc_program_num(*r, rn, hex);
5350 // We run this again under these conditions in case any vector has been
5351 // reallocated out from under the BcNums or arrays we had.
5352 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
5353 s = bc_program_num(*l, ln, false);
5357 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
5358 return bc_error_variable_is_wrong_type();
5359 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5360 return bc_error_variable_is_wrong_type();
5365 static void bc_program_binOpRetire(BcResult *r)
5367 r->t = BC_RESULT_TEMP;
5368 bc_vec_pop(&G.prog.results);
5369 bc_vec_pop(&G.prog.results);
5370 bc_vec_push(&G.prog.results, r);
5373 static BcStatus bc_program_prep(BcResult **r, BcNum **n)
5377 if (!BC_PROG_STACK(&G.prog.results, 1))
5378 return bc_error_stack_has_too_few_elements();
5379 *r = bc_vec_top(&G.prog.results);
5381 s = bc_program_num(*r, n, false);
5384 if (!BC_PROG_NUM((*r), (*n)))
5385 return bc_error_variable_is_wrong_type();
5390 static void bc_program_retire(BcResult *r, BcResultType t)
5393 bc_vec_pop(&G.prog.results);
5394 bc_vec_push(&G.prog.results, r);
5397 static BcStatus bc_program_op(char inst)
5400 BcResult *opd1, *opd2, res;
5401 BcNum *n1, *n2 = NULL;
5403 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5405 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5407 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5409 bc_program_binOpRetire(&res);
5414 bc_num_free(&res.d.n);
5418 static BcStatus bc_program_read(void)
5420 const char *sv_file;
5426 BcFunc *f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
5428 for (i = 0; i < G.prog.stack.len; ++i) {
5429 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
5430 if (ip_ptr->func == BC_PROG_READ)
5431 return bc_error_nested_read_call();
5434 bc_vec_pop_all(&f->code);
5435 bc_char_vec_init(&buf);
5437 sv_file = G.prog.file;
5440 s = bc_read_line(&buf, "read> ");
5443 common_parse_init(&parse, BC_PROG_READ);
5444 bc_lex_file(&parse.l);
5446 s = bc_parse_text(&parse, buf.v);
5447 if (s) goto exec_err;
5448 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
5449 if (s) goto exec_err;
5451 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
5452 s = bc_error("bad read() expression");
5456 ip.func = BC_PROG_READ;
5458 ip.len = G.prog.results.len;
5460 // Update this pointer, just in case.
5461 f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
5463 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
5464 bc_vec_push(&G.prog.stack, &ip);
5467 G.prog.file = sv_file;
5468 bc_parse_free(&parse);
5474 static size_t bc_program_index(char *code, size_t *bgn)
5476 char amt = code[(*bgn)++], i = 0;
5479 for (; i < amt; ++i, ++(*bgn))
5480 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5485 static char *bc_program_name(char *code, size_t *bgn)
5488 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5490 s = xmalloc(ptr - str + 1);
5493 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5501 static void bc_program_printString(const char *str, size_t *nchars)
5503 size_t i, len = strlen(str);
5512 for (i = 0; i < len; ++i, ++(*nchars)) {
5516 if (c != '\\' || i == len - 1)
5576 // Just print the backslash and following character.
5587 static BcStatus bc_program_print(char inst, size_t idx)
5589 BcStatus s = BC_STATUS_SUCCESS;
5594 bool pop = inst != BC_INST_PRINT;
5596 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
5597 return bc_error_stack_has_too_few_elements();
5599 r = bc_vec_item_rev(&G.prog.results, idx);
5600 s = bc_program_num(r, &num, false);
5603 if (BC_PROG_NUM(r, num)) {
5604 s = bc_num_print(num, &G.prog.ob, G.prog.ob_t, !pop, &G.prog.nchars, G.prog.len);
5605 if (!s) bc_num_copy(&G.prog.last, num);
5609 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
5610 str = *((char **) bc_vec_item(&G.prog.strs, idx));
5612 if (inst == BC_INST_PRINT_STR) {
5613 for (i = 0, len = strlen(str); i < len; ++i) {
5616 if (c == '\n') G.prog.nchars = SIZE_MAX;
5621 bc_program_printString(str, &G.prog.nchars);
5622 if (inst == BC_INST_PRINT) bb_putchar('\n');
5626 if (!s && pop) bc_vec_pop(&G.prog.results);
5631 static BcStatus bc_program_negate(void)
5637 s = bc_program_prep(&ptr, &num);
5640 bc_num_init(&res.d.n, num->len);
5641 bc_num_copy(&res.d.n, num);
5642 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5644 bc_program_retire(&res, BC_RESULT_TEMP);
5649 static BcStatus bc_program_logical(char inst)
5652 BcResult *opd1, *opd2, res;
5657 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5659 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5661 if (inst == BC_INST_BOOL_AND)
5662 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5663 else if (inst == BC_INST_BOOL_OR)
5664 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5667 cmp = bc_num_cmp(n1, n2);
5671 case BC_INST_REL_EQ:
5677 case BC_INST_REL_LE:
5683 case BC_INST_REL_GE:
5689 case BC_INST_REL_NE:
5695 case BC_INST_REL_LT:
5701 case BC_INST_REL_GT:
5709 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5711 bc_program_binOpRetire(&res);
5717 static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
5723 memset(&n2, 0, sizeof(BcNum));
5724 n2.rdx = res.d.id.idx = r->d.id.idx;
5725 res.t = BC_RESULT_STR;
5728 if (!BC_PROG_STACK(&G.prog.results, 2))
5729 return bc_error_stack_has_too_few_elements();
5731 bc_vec_pop(&G.prog.results);
5734 bc_vec_pop(&G.prog.results);
5736 bc_vec_push(&G.prog.results, &res);
5737 bc_vec_push(v, &n2);
5739 return BC_STATUS_SUCCESS;
5743 static BcStatus bc_program_copyToVar(char *name, bool var)
5750 if (!BC_PROG_STACK(&G.prog.results, 1))
5751 return bc_error_stack_has_too_few_elements();
5753 ptr = bc_vec_top(&G.prog.results);
5754 if ((ptr->t == BC_RESULT_ARRAY) != !var)
5755 return bc_error_variable_is_wrong_type();
5756 v = bc_program_search(name, var);
5759 if (ptr->t == BC_RESULT_STR && !var)
5760 return bc_error_variable_is_wrong_type();
5761 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
5764 s = bc_program_num(ptr, &n, false);
5767 // Do this once more to make sure that pointers were not invalidated.
5768 v = bc_program_search(name, var);
5771 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5772 bc_num_copy(&r.d.n, n);
5775 bc_array_init(&r.d.v, true);
5776 bc_array_copy(&r.d.v, (BcVec *) n);
5779 bc_vec_push(v, &r.d);
5780 bc_vec_pop(&G.prog.results);
5785 static BcStatus bc_program_assign(char inst)
5788 BcResult *left, *right, res;
5789 BcNum *l = NULL, *r = NULL;
5790 unsigned long val, max;
5791 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5793 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
5796 ib = left->t == BC_RESULT_IBASE;
5797 sc = left->t == BC_RESULT_SCALE;
5801 if (right->t == BC_RESULT_STR) {
5805 if (left->t != BC_RESULT_VAR)
5806 return bc_error_variable_is_wrong_type();
5807 v = bc_program_search(left->d.id.name, true);
5809 return bc_program_assignStr(right, v, false);
5813 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
5814 return bc_error("bad assignment:"
5815 " left side must be scale,"
5816 " ibase, obase, last, var,"
5821 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5822 return bc_error("divide by zero");
5827 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5834 if (ib || sc || left->t == BC_RESULT_OBASE) {
5835 static const char *const msg[] = {
5836 "bad ibase; must be [2, 16]", //BC_RESULT_IBASE
5837 "bad scale; must be [0, BC_SCALE_MAX]", //BC_RESULT_SCALE
5838 NULL, //can't happen //BC_RESULT_LAST
5839 NULL, //can't happen //BC_RESULT_CONSTANT
5840 NULL, //can't happen //BC_RESULT_ONE
5841 "bad obase; must be [2, BC_BASE_MAX]", //BC_RESULT_OBASE
5845 s = bc_num_ulong(l, &val);
5848 s = left->t - BC_RESULT_IBASE;
5851 ptr = &G.prog.scale;
5854 if (val < BC_NUM_MIN_BASE)
5855 return bc_error(msg[s]);
5856 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5857 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5861 return bc_error(msg[s]);
5863 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
5865 *ptr = (size_t) val;
5866 s = BC_STATUS_SUCCESS;
5869 bc_num_init(&res.d.n, l->len);
5870 bc_num_copy(&res.d.n, l);
5871 bc_program_binOpRetire(&res);
5877 #define bc_program_pushVar(code, bgn, pop, copy) \
5878 bc_program_pushVar(code, bgn)
5879 // for bc, 'pop' and 'copy' are always false
5881 static BcStatus bc_program_pushVar(char *code, size_t *bgn,
5882 bool pop, bool copy)
5884 BcStatus s = BC_STATUS_SUCCESS;
5886 char *name = bc_program_name(code, bgn);
5888 r.t = BC_RESULT_VAR;
5893 BcVec *v = bc_program_search(name, true);
5894 BcNum *num = bc_vec_top(v);
5898 if (!BC_PROG_STACK(v, 2 - copy)) {
5900 return bc_error_stack_has_too_few_elements();
5906 if (!BC_PROG_STR(num)) {
5908 r.t = BC_RESULT_TEMP;
5910 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5911 bc_num_copy(&r.d.n, num);
5914 r.t = BC_RESULT_STR;
5915 r.d.id.idx = num->rdx;
5918 if (!copy) bc_vec_pop(v);
5923 bc_vec_push(&G.prog.results, &r);
5928 static BcStatus bc_program_pushArray(char *code, size_t *bgn,
5931 BcStatus s = BC_STATUS_SUCCESS;
5935 r.d.id.name = bc_program_name(code, bgn);
5937 if (inst == BC_INST_ARRAY) {
5938 r.t = BC_RESULT_ARRAY;
5939 bc_vec_push(&G.prog.results, &r);
5946 s = bc_program_prep(&operand, &num);
5948 s = bc_num_ulong(num, &temp);
5951 if (temp > BC_MAX_DIM) {
5952 s = bc_error("array too long; must be [1, BC_DIM_MAX]");
5956 r.d.id.idx = (size_t) temp;
5957 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
5961 if (s) free(r.d.id.name);
5966 static BcStatus bc_program_incdec(char inst)
5969 BcResult *ptr, res, copy;
5973 s = bc_program_prep(&ptr, &num);
5976 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
5977 copy.t = BC_RESULT_TEMP;
5978 bc_num_init(©.d.n, num->len);
5979 bc_num_copy(©.d.n, num);
5982 res.t = BC_RESULT_ONE;
5983 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
5984 BC_INST_ASSIGN_PLUS :
5985 BC_INST_ASSIGN_MINUS;
5987 bc_vec_push(&G.prog.results, &res);
5988 bc_program_assign(inst);
5990 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
5991 bc_vec_pop(&G.prog.results);
5992 bc_vec_push(&G.prog.results, ©);
5998 static BcStatus bc_program_call(char *code, size_t *idx)
6000 BcStatus s = BC_STATUS_SUCCESS;
6002 size_t i, nparams = bc_program_index(code, idx);
6009 ip.func = bc_program_index(code, idx);
6010 func = bc_vec_item(&G.prog.fns, ip.func);
6012 if (func->code.len == 0) {
6013 return bc_error("undefined function");
6015 if (nparams != func->nparams) {
6016 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
6018 ip.len = G.prog.results.len - nparams;
6020 for (i = 0; i < nparams; ++i) {
6022 a = bc_vec_item(&func->autos, nparams - 1 - i);
6023 arg = bc_vec_top(&G.prog.results);
6025 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
6026 return bc_error_variable_is_wrong_type();
6028 s = bc_program_copyToVar(a->name, a->idx);
6032 for (; i < func->autos.len; ++i) {
6035 a = bc_vec_item(&func->autos, i);
6036 v = bc_program_search(a->name, a->idx);
6039 bc_num_init(¶m.n, BC_NUM_DEF_SIZE);
6040 bc_vec_push(v, ¶m.n);
6043 bc_array_init(¶m.v, true);
6044 bc_vec_push(v, ¶m.v);
6048 bc_vec_push(&G.prog.stack, &ip);
6050 return BC_STATUS_SUCCESS;
6053 static BcStatus bc_program_return(char inst)
6059 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6061 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
6062 return bc_error_stack_has_too_few_elements();
6064 f = bc_vec_item(&G.prog.fns, ip->func);
6065 res.t = BC_RESULT_TEMP;
6067 if (inst == BC_INST_RET) {
6070 BcResult *operand = bc_vec_top(&G.prog.results);
6072 s = bc_program_num(operand, &num, false);
6074 bc_num_init(&res.d.n, num->len);
6075 bc_num_copy(&res.d.n, num);
6078 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6079 bc_num_zero(&res.d.n);
6082 // We need to pop arguments as well, so this takes that into account.
6083 for (i = 0; i < f->autos.len; ++i) {
6086 BcId *a = bc_vec_item(&f->autos, i);
6088 v = bc_program_search(a->name, a->idx);
6092 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6093 bc_vec_push(&G.prog.results, &res);
6094 bc_vec_pop(&G.prog.stack);
6096 return BC_STATUS_SUCCESS;
6100 static unsigned long bc_program_scale(BcNum *n)
6102 return (unsigned long) n->rdx;
6105 static unsigned long bc_program_len(BcNum *n)
6107 unsigned long len = n->len;
6110 if (n->rdx != n->len) return len;
6111 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6116 static BcStatus bc_program_builtin(char inst)
6122 bool len = inst == BC_INST_LENGTH;
6124 if (!BC_PROG_STACK(&G.prog.results, 1))
6125 return bc_error_stack_has_too_few_elements();
6126 opnd = bc_vec_top(&G.prog.results);
6128 s = bc_program_num(opnd, &num, false);
6132 if (!BC_PROG_NUM(opnd, num) && !len)
6133 return bc_error_variable_is_wrong_type();
6136 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6138 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
6140 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
6141 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6145 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6148 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6150 str = bc_vec_item(&G.prog.strs, idx);
6151 bc_num_ulong2num(&res.d.n, strlen(*str));
6155 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
6156 bc_num_ulong2num(&res.d.n, f(num));
6159 bc_program_retire(&res, BC_RESULT_TEMP);
6165 static BcStatus bc_program_divmod(void)
6168 BcResult *opd1, *opd2, res, res2;
6169 BcNum *n1, *n2 = NULL;
6171 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6174 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6175 bc_num_init(&res2.d.n, n2->len);
6177 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6180 bc_program_binOpRetire(&res2);
6181 res.t = BC_RESULT_TEMP;
6182 bc_vec_push(&G.prog.results, &res);
6187 bc_num_free(&res2.d.n);
6188 bc_num_free(&res.d.n);
6192 static BcStatus bc_program_modexp(void)
6195 BcResult *r1, *r2, *r3, res;
6196 BcNum *n1, *n2, *n3;
6198 if (!BC_PROG_STACK(&G.prog.results, 3))
6199 return bc_error_stack_has_too_few_elements();
6200 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6203 r1 = bc_vec_item_rev(&G.prog.results, 2);
6204 s = bc_program_num(r1, &n1, false);
6206 if (!BC_PROG_NUM(r1, n1))
6207 return bc_error_variable_is_wrong_type();
6209 // Make sure that the values have their pointers updated, if necessary.
6210 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6212 if (r1->t == r2->t) {
6213 s = bc_program_num(r2, &n2, false);
6217 if (r1->t == r3->t) {
6218 s = bc_program_num(r3, &n3, false);
6223 bc_num_init(&res.d.n, n3->len);
6224 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6227 bc_vec_pop(&G.prog.results);
6228 bc_program_binOpRetire(&res);
6233 bc_num_free(&res.d.n);
6237 static void bc_program_stackLen(void)
6240 size_t len = G.prog.results.len;
6242 res.t = BC_RESULT_TEMP;
6244 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6245 bc_num_ulong2num(&res.d.n, len);
6246 bc_vec_push(&G.prog.results, &res);
6249 static BcStatus bc_program_asciify(void)
6253 BcNum *num = NULL, n;
6254 char *str, *str2, c;
6255 size_t len = G.prog.strs.len, idx;
6258 if (!BC_PROG_STACK(&G.prog.results, 1))
6259 return bc_error_stack_has_too_few_elements();
6260 r = bc_vec_top(&G.prog.results);
6262 s = bc_program_num(r, &num, false);
6265 if (BC_PROG_NUM(r, num)) {
6267 bc_num_init(&n, BC_NUM_DEF_SIZE);
6268 bc_num_copy(&n, num);
6269 bc_num_truncate(&n, n.rdx);
6271 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
6272 if (s) goto num_err;
6273 s = bc_num_ulong(&n, &val);
6274 if (s) goto num_err;
6281 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
6282 str2 = *((char **) bc_vec_item(&G.prog.strs, idx));
6290 str2 = xstrdup(str);
6291 bc_program_addFunc(str2, &idx);
6293 if (idx != len + BC_PROG_REQ_FUNCS) {
6295 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6296 if (!strcmp(*((char **) bc_vec_item(&G.prog.strs, idx)), str)) {
6305 bc_vec_push(&G.prog.strs, &str);
6307 res.t = BC_RESULT_STR;
6309 bc_vec_pop(&G.prog.results);
6310 bc_vec_push(&G.prog.results, &res);
6312 return BC_STATUS_SUCCESS;
6319 static BcStatus bc_program_printStream(void)
6327 if (!BC_PROG_STACK(&G.prog.results, 1))
6328 return bc_error_stack_has_too_few_elements();
6329 r = bc_vec_top(&G.prog.results);
6331 s = bc_program_num(r, &n, false);
6334 if (BC_PROG_NUM(r, n))
6335 s = bc_num_stream(n, &G.prog.strmb, &G.prog.nchars, G.prog.len);
6337 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
6338 str = *((char **) bc_vec_item(&G.prog.strs, idx));
6345 static BcStatus bc_program_nquit(void)
6352 s = bc_program_prep(&opnd, &num);
6354 s = bc_num_ulong(num, &val);
6357 bc_vec_pop(&G.prog.results);
6359 if (G.prog.stack.len < val)
6360 return bc_error_stack_has_too_few_elements();
6361 if (G.prog.stack.len == val) {
6362 if (ENABLE_FEATURE_CLEAN_UP)
6363 return BC_STATUS_FAILURE;
6367 bc_vec_npop(&G.prog.stack, val);
6372 static BcStatus bc_program_execStr(char *code, size_t *bgn,
6375 BcStatus s = BC_STATUS_SUCCESS;
6385 if (!BC_PROG_STACK(&G.prog.results, 1))
6386 return bc_error_stack_has_too_few_elements();
6388 r = bc_vec_top(&G.prog.results);
6392 char *name, *then_name = bc_program_name(code, bgn), *else_name = NULL;
6394 if (code[*bgn] == BC_PARSE_STREND)
6397 else_name = bc_program_name(code, bgn);
6399 exec = r->d.n.len != 0;
6403 else if (else_name != NULL) {
6410 v = bc_program_search(name, true);
6417 if (!exec) goto exit;
6418 if (!BC_PROG_STR(n)) {
6419 s = bc_error_variable_is_wrong_type();
6427 if (r->t == BC_RESULT_STR)
6429 else if (r->t == BC_RESULT_VAR) {
6430 s = bc_program_num(r, &n, false);
6431 if (s || !BC_PROG_STR(n)) goto exit;
6438 fidx = sidx + BC_PROG_REQ_FUNCS;
6440 str = bc_vec_item(&G.prog.strs, sidx);
6441 f = bc_vec_item(&G.prog.fns, fidx);
6443 if (f->code.len == 0) {
6444 common_parse_init(&prs, fidx);
6445 s = bc_parse_text(&prs, *str);
6447 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
6450 if (prs.l.t.t != BC_LEX_EOF) {
6451 s = bc_error_bad_expression();
6455 bc_parse_free(&prs);
6459 ip.len = G.prog.results.len;
6462 bc_vec_pop(&G.prog.results);
6463 bc_vec_push(&G.prog.stack, &ip);
6465 return BC_STATUS_SUCCESS;
6468 bc_parse_free(&prs);
6469 f = bc_vec_item(&G.prog.fns, fidx);
6470 bc_vec_pop_all(&f->code);
6472 bc_vec_pop(&G.prog.results);
6477 static void bc_program_pushGlobal(char inst)
6482 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6483 if (inst == BC_INST_IBASE)
6484 val = (unsigned long) G.prog.ib_t;
6485 else if (inst == BC_INST_SCALE)
6486 val = (unsigned long) G.prog.scale;
6488 val = (unsigned long) G.prog.ob_t;
6490 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6491 bc_num_ulong2num(&res.d.n, val);
6492 bc_vec_push(&G.prog.results, &res);
6495 static void bc_program_addFunc(char *name, size_t *idx)
6497 BcId entry, *entry_ptr;
6502 entry.idx = G.prog.fns.len;
6504 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6505 if (!inserted) free(name);
6507 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
6508 *idx = entry_ptr->idx;
6512 BcFunc *func = bc_vec_item(&G.prog.fns, entry_ptr->idx);
6514 // We need to reset these, so the function can be repopulated.
6516 bc_vec_pop_all(&func->autos);
6517 bc_vec_pop_all(&func->code);
6518 bc_vec_pop_all(&func->labels);
6522 bc_vec_push(&G.prog.fns, &f);
6526 // Called when parsing or execution detects a failure,
6527 // resets execution structures.
6528 static void bc_program_reset(void)
6533 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
6534 bc_vec_pop_all(&G.prog.results);
6536 f = bc_vec_item(&G.prog.fns, 0);
6537 ip = bc_vec_top(&G.prog.stack);
6538 ip->idx = f->code.len;
6540 // If !tty, no need to check for ^C: we don't have ^C handler,
6541 // we would be killed by a signal and won't reach this place
6544 static BcStatus bc_program_exec(void)
6546 BcStatus s = BC_STATUS_SUCCESS;
6550 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6551 BcFunc *func = bc_vec_item(&G.prog.fns, ip->func);
6552 char *code = func->code.v;
6555 while (!s && ip->idx < func->code.len) {
6557 char inst = code[(ip->idx)++];
6562 case BC_INST_JUMP_ZERO:
6564 s = bc_program_prep(&ptr, &num);
6566 cond = !bc_num_cmp(num, &G.prog.zero);
6567 bc_vec_pop(&G.prog.results);
6573 idx = bc_program_index(code, &ip->idx);
6574 addr = bc_vec_item(&func->labels, idx);
6575 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6581 s = bc_program_call(code, &ip->idx);
6585 case BC_INST_INC_PRE:
6586 case BC_INST_DEC_PRE:
6587 case BC_INST_INC_POST:
6588 case BC_INST_DEC_POST:
6590 s = bc_program_incdec(inst);
6596 quit_or_return_for_exit();
6603 s = bc_program_return(inst);
6607 case BC_INST_BOOL_OR:
6608 case BC_INST_BOOL_AND:
6610 case BC_INST_REL_EQ:
6611 case BC_INST_REL_LE:
6612 case BC_INST_REL_GE:
6613 case BC_INST_REL_NE:
6614 case BC_INST_REL_LT:
6615 case BC_INST_REL_GT:
6617 s = bc_program_logical(inst);
6623 s = bc_program_read();
6629 s = bc_program_pushVar(code, &ip->idx, false, false);
6633 case BC_INST_ARRAY_ELEM:
6636 s = bc_program_pushArray(code, &ip->idx, inst);
6642 r.t = BC_RESULT_LAST;
6643 bc_vec_push(&G.prog.results, &r);
6651 bc_program_pushGlobal(inst);
6655 case BC_INST_SCALE_FUNC:
6656 case BC_INST_LENGTH:
6659 s = bc_program_builtin(inst);
6665 r.t = BC_RESULT_CONSTANT;
6666 r.d.id.idx = bc_program_index(code, &ip->idx);
6667 bc_vec_push(&G.prog.results, &r);
6673 if (!BC_PROG_STACK(&G.prog.results, 1))
6674 s = bc_error_stack_has_too_few_elements();
6676 bc_vec_pop(&G.prog.results);
6680 case BC_INST_POP_EXEC:
6682 bc_vec_pop(&G.prog.stack);
6687 case BC_INST_PRINT_POP:
6688 case BC_INST_PRINT_STR:
6690 s = bc_program_print(inst, 0);
6696 r.t = BC_RESULT_STR;
6697 r.d.id.idx = bc_program_index(code, &ip->idx);
6698 bc_vec_push(&G.prog.results, &r);
6703 case BC_INST_MULTIPLY:
6704 case BC_INST_DIVIDE:
6705 case BC_INST_MODULUS:
6709 s = bc_program_op(inst);
6713 case BC_INST_BOOL_NOT:
6715 s = bc_program_prep(&ptr, &num);
6718 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
6719 (!bc_num_cmp(num, &G.prog.zero) ? bc_num_one : bc_num_zero)(&r.d.n);
6720 bc_program_retire(&r, BC_RESULT_TEMP);
6727 s = bc_program_negate();
6732 case BC_INST_ASSIGN_POWER:
6733 case BC_INST_ASSIGN_MULTIPLY:
6734 case BC_INST_ASSIGN_DIVIDE:
6735 case BC_INST_ASSIGN_MODULUS:
6736 case BC_INST_ASSIGN_PLUS:
6737 case BC_INST_ASSIGN_MINUS:
6739 case BC_INST_ASSIGN:
6741 s = bc_program_assign(inst);
6745 case BC_INST_MODEXP:
6747 s = bc_program_modexp();
6751 case BC_INST_DIVMOD:
6753 s = bc_program_divmod();
6757 case BC_INST_EXECUTE:
6758 case BC_INST_EXEC_COND:
6760 cond = inst == BC_INST_EXEC_COND;
6761 s = bc_program_execStr(code, &ip->idx, cond);
6765 case BC_INST_PRINT_STACK:
6767 for (idx = 0; !s && idx < G.prog.results.len; ++idx)
6768 s = bc_program_print(BC_INST_PRINT, idx);
6772 case BC_INST_CLEAR_STACK:
6774 bc_vec_pop_all(&G.prog.results);
6778 case BC_INST_STACK_LEN:
6780 bc_program_stackLen();
6784 case BC_INST_DUPLICATE:
6786 if (!BC_PROG_STACK(&G.prog.results, 1))
6787 return bc_error_stack_has_too_few_elements();
6788 ptr = bc_vec_top(&G.prog.results);
6789 bc_result_copy(&r, ptr);
6790 bc_vec_push(&G.prog.results, &r);
6798 if (!BC_PROG_STACK(&G.prog.results, 2))
6799 return bc_error_stack_has_too_few_elements();
6801 ptr = bc_vec_item_rev(&G.prog.results, 0);
6802 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6803 memcpy(&r, ptr, sizeof(BcResult));
6804 memcpy(ptr, ptr2, sizeof(BcResult));
6805 memcpy(ptr2, &r, sizeof(BcResult));
6810 case BC_INST_ASCIIFY:
6812 s = bc_program_asciify();
6816 case BC_INST_PRINT_STREAM:
6818 s = bc_program_printStream();
6823 case BC_INST_PUSH_VAR:
6825 bool copy = inst == BC_INST_LOAD;
6826 s = bc_program_pushVar(code, &ip->idx, true, copy);
6830 case BC_INST_PUSH_TO_VAR:
6832 char *name = bc_program_name(code, &ip->idx);
6833 s = bc_program_copyToVar(name, true);
6840 if (G.prog.stack.len <= 2)
6841 quit_or_return_for_exit();
6842 bc_vec_npop(&G.prog.stack, 2);
6848 s = bc_program_nquit();
6854 if (s || G_interrupt) {
6859 // If the stack has changed, pointers may be invalid.
6860 ip = bc_vec_top(&G.prog.stack);
6861 func = bc_vec_item(&G.prog.fns, ip->func);
6862 code = func->code.v;
6868 static void bc_vm_info(void)
6870 printf("%s "BB_VER"\n"
6871 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6872 "Report bugs at: https://github.com/gavinhoward/bc\n"
6873 "This is free software with ABSOLUTELY NO WARRANTY\n"
6877 static void bc_args(char **argv)
6883 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6884 opts = option_mask32 |= getopt32long(argv, "xwvsqli",
6885 "extended-register\0" No_argument "x"
6886 "warn\0" No_argument "w"
6887 "version\0" No_argument "v"
6888 "standard\0" No_argument "s"
6889 "quiet\0" No_argument "q"
6890 "mathlib\0" No_argument "l"
6891 "interactive\0" No_argument "i"
6894 opts = option_mask32 |= getopt32(argv, "xwvsqli");
6896 if (getenv("POSIXLY_CORRECT"))
6897 option_mask32 |= BC_FLAG_S;
6899 ///should be in bc_vm_run() instead??
6900 if (opts & BC_FLAG_V) {
6905 for (i = optind; argv[i]; ++i)
6906 bc_vec_push(&G.files, argv + i);
6910 static void bc_vm_envArgs(void)
6914 char *env_args = getenv("BC_ENV_ARGS");
6916 if (!env_args) return;
6918 G.env_args = xstrdup(env_args);
6921 bc_vec_init(&v, sizeof(char *), NULL);
6923 while (*(buf = skip_whitespace(buf)) != '\0') {
6924 bc_vec_push(&v, &buf);
6925 buf = skip_non_whitespace(buf);
6931 // NULL terminate, and pass argv[] so that first arg is argv[1]
6932 if (sizeof(int) == sizeof(char*)) {
6933 bc_vec_push(&v, &const_int_0);
6935 static char *const nullptr = NULL;
6936 bc_vec_push(&v, &nullptr);
6938 bc_args(((char **)v.v) - 1);
6944 static unsigned bc_vm_envLen(const char *var)
6950 len = BC_NUM_PRINT_WIDTH;
6951 if (!lenv) return len;
6953 len = bb_strtou(lenv, NULL, 10) - 1;
6954 if (errno || len < 2 || len >= INT_MAX)
6955 len = BC_NUM_PRINT_WIDTH;
6960 static BcStatus bc_vm_process(const char *text)
6962 BcStatus s = bc_parse_text(&G.prs, text);
6966 while (G.prs.l.t.t != BC_LEX_EOF) {
6967 s = G.prs.parse(&G.prs);
6971 if (BC_PARSE_CAN_EXEC(&G.prs)) {
6972 s = bc_program_exec();
6981 static BcStatus bc_vm_file(const char *file)
6983 const char *sv_file;
6989 data = bc_read_file(file);
6990 if (!data) return bc_error_fmt("file '%s' is not text", file);
6992 sv_file = G.prog.file;
6994 bc_lex_file(&G.prs.l);
6995 s = bc_vm_process(data);
6998 main_func = bc_vec_item(&G.prog.fns, BC_PROG_MAIN);
6999 ip = bc_vec_item(&G.prog.stack, 0);
7001 if (main_func->code.len < ip->idx)
7002 s = bc_error_fmt("file '%s' is not executable", file);
7005 G.prog.file = sv_file;
7010 static BcStatus bc_vm_stdin(void)
7014 size_t len, i, str = 0;
7015 bool comment = false;
7018 bc_lex_file(&G.prs.l);
7020 bc_char_vec_init(&buffer);
7021 bc_char_vec_init(&buf);
7022 bc_vec_pushZeroByte(&buffer);
7024 // This loop is complex because the vm tries not to send any lines that end
7025 // with a backslash to the parser. The reason for that is because the parser
7026 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7027 // case, and for strings and comments, the parser will expect more stuff.
7028 s = BC_STATUS_SUCCESS;
7029 while (!G.eof && (s = bc_read_line(&buf, ">>> ")) == BC_STATUS_SUCCESS) {
7031 char *string = buf.v;
7036 if (str && buf.v[0] == G.send)
7038 else if (buf.v[0] == G.sbgn)
7041 else if (len > 1 || comment) {
7043 for (i = 0; i < len; ++i) {
7045 bool notend = len > i + 1;
7048 if (i - 1 > len || string[i - 1] != '\\') {
7049 if (G.sbgn == G.send)
7051 else if (c == G.send)
7053 else if (c == G.sbgn)
7057 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7061 else if (c == '*' && notend && comment && string[i + 1] == '/')
7065 if (str || comment || string[len - 2] == '\\') {
7066 bc_vec_concat(&buffer, buf.v);
7071 bc_vec_concat(&buffer, buf.v);
7072 s = bc_vm_process(buffer.v);
7074 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
7075 // Debug config, non-interactive mode:
7076 // return all the way back to main.
7077 // Non-debug builds do not come here, they exit.
7081 fputs("ready for more input\n", stderr);
7084 bc_vec_pop_all(&buffer);
7088 s = bc_error("string end could not be found");
7091 s = bc_error("comment end could not be found");
7095 bc_vec_free(&buffer);
7100 static const char bc_lib[] = {
7103 "\n" "auto b,s,n,r,d,i,p,f,v"
7112 "\n" "scale=scale(x)+1"
7122 "\n" "for(i=2;v!=0;++i){"
7128 "\n" "while((d--)!=0)r*=r"
7131 "\n" "if(n!=0)return(1/r)"
7135 "\n" "auto b,s,r,p,a,q,i,v"
7139 "\n" "r=(1-10^scale)/1"
7150 "\n" "while(x<=0.5){"
7154 "\n" "r=a=(x-1)/(x+1)"
7157 "\n" "for(i=3;v!=0;i+=2){"
7168 "\n" "auto b,s,r,n,a,q,i"
7172 "\n" "scale=1.1*s+2"
7181 "\n" "if(q%2!=0)x=-x"
7185 "\n" "for(i=3;a!=0;i+=2){"
7186 "\n" "a*=q/(i*(i-1))"
7191 "\n" "if(n!=0)return(-r/1)"
7200 "\n" "x=s(2*a(1)+x)"
7206 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7215 "\n" "if(scale<65){"
7216 "\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7220 "\n" "if(scale<65){"
7221 "\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7232 "\n" "x=(x-.2)/(1+.2*x)"
7237 "\n" "for(i=3;t!=0;i+=2){"
7244 "\n" "return((m*a+r)/n)"
7246 "\n" "define j(n,x){"
7247 "\n" "auto b,s,o,a,i,v,f"
7255 "\n" "if(n%2==1)o=1"
7258 "\n" "for(i=2;i<=n;++i)a*=i"
7260 "\n" "a=(x^n)/2^n/a"
7263 "\n" "scale=scale+length(a)-scale(a)"
7264 "\n" "for(i=1;v!=0;++i){"
7265 "\n" "v=v*f/i/(n+i)"
7271 "\n" "return(a*r/1)"
7276 static BcStatus bc_vm_exec(void)
7278 BcStatus s = BC_STATUS_SUCCESS;
7282 if (option_mask32 & BC_FLAG_L) {
7284 // We know that internal library is not buggy,
7285 // thus error checking is normally disabled.
7286 # define DEBUG_LIB 0
7287 bc_lex_file(&G.prs.l);
7288 s = bc_parse_text(&G.prs, bc_lib);
7289 if (DEBUG_LIB && s) return s;
7291 while (G.prs.l.t.t != BC_LEX_EOF) {
7292 s = G.prs.parse(&G.prs);
7293 if (DEBUG_LIB && s) return s;
7295 s = bc_program_exec();
7296 if (DEBUG_LIB && s) return s;
7300 for (i = 0; !s && i < G.files.len; ++i)
7301 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
7303 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
7304 // Debug config, non-interactive mode:
7305 // return all the way back to main.
7306 // Non-debug builds do not come here, they exit.
7310 fputs("ready for more input\n", stderr);
7313 if (IS_BC || !G.files.len)
7315 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7316 s = bc_vm_process("");
7321 #if ENABLE_FEATURE_CLEAN_UP
7322 static void bc_program_free(void)
7324 bc_num_free(&G.prog.ib);
7325 bc_num_free(&G.prog.ob);
7326 bc_num_free(&G.prog.hexb);
7328 bc_num_free(&G.prog.strmb);
7330 bc_vec_free(&G.prog.fns);
7331 bc_vec_free(&G.prog.fn_map);
7332 bc_vec_free(&G.prog.vars);
7333 bc_vec_free(&G.prog.var_map);
7334 bc_vec_free(&G.prog.arrs);
7335 bc_vec_free(&G.prog.arr_map);
7336 bc_vec_free(&G.prog.strs);
7337 bc_vec_free(&G.prog.consts);
7338 bc_vec_free(&G.prog.results);
7339 bc_vec_free(&G.prog.stack);
7340 bc_num_free(&G.prog.last);
7341 bc_num_free(&G.prog.zero);
7342 bc_num_free(&G.prog.one);
7345 static void bc_vm_free(void)
7347 bc_vec_free(&G.files);
7349 bc_parse_free(&G.prs);
7354 static void bc_program_init(void)
7359 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7360 memset(&ip, 0, sizeof(BcInstPtr));
7362 /* G.prog.nchars = G.prog.scale = 0; - already is */
7364 bc_num_init(&G.prog.ib, BC_NUM_DEF_SIZE);
7365 bc_num_ten(&G.prog.ib);
7368 bc_num_init(&G.prog.ob, BC_NUM_DEF_SIZE);
7369 bc_num_ten(&G.prog.ob);
7372 bc_num_init(&G.prog.hexb, BC_NUM_DEF_SIZE);
7373 bc_num_ten(&G.prog.hexb);
7374 G.prog.hexb.num[0] = 6;
7377 bc_num_init(&G.prog.strmb, BC_NUM_DEF_SIZE);
7378 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7381 bc_num_init(&G.prog.last, BC_NUM_DEF_SIZE);
7382 bc_num_zero(&G.prog.last);
7384 bc_num_init(&G.prog.zero, BC_NUM_DEF_SIZE);
7385 bc_num_zero(&G.prog.zero);
7387 bc_num_init(&G.prog.one, BC_NUM_DEF_SIZE);
7388 bc_num_one(&G.prog.one);
7390 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7391 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
7393 bc_program_addFunc(xstrdup("(main)"), &idx);
7394 bc_program_addFunc(xstrdup("(read)"), &idx);
7396 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7397 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7399 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7400 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7402 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7403 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7404 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7405 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7406 bc_vec_push(&G.prog.stack, &ip);
7409 static void bc_vm_init(void)
7411 bc_vec_init(&G.files, sizeof(char *), NULL);
7416 bc_parse_init(&G.prs, BC_PROG_MAIN);
7418 dc_parse_init(&G.prs, BC_PROG_MAIN);
7422 static BcStatus bc_vm_run(char **argv, const char *env_len)
7426 #if ENABLE_FEATURE_EDITING
7427 G.line_input_state = new_line_input_t(DO_HISTORY);
7429 G.prog.len = bc_vm_envLen(env_len);
7435 #if ENABLE_FEATURE_BC_SIGNALS
7437 // With SA_RESTART, most system calls will restart
7438 // (IOW: they won't fail with EINTR).
7439 // In particular, this means ^C won't cause
7440 // stdout to get into "error state" if SIGINT hits
7441 // within write() syscall.
7442 // The downside is that ^C while line input is taken
7443 // will only be handled after [Enter] since read()
7444 // from stdin is not interrupted by ^C either,
7445 // it restarts, thus fgetc() does not return on ^C.
7446 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7448 // Without SA_RESTART, this exhibits a bug:
7449 // "while (1) print 1" and try ^C-ing it.
7450 // Intermittently, instead of returning to input line,
7451 // you'll get "output error: Interrupted system call"
7453 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7455 if (!(option_mask32 & BC_FLAG_Q))
7461 #if ENABLE_FEATURE_CLEAN_UP
7463 # if ENABLE_FEATURE_EDITING
7464 free_line_input_t(G.line_input_state);
7472 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7473 int bc_main(int argc UNUSED_PARAM, char **argv)
7476 G.sbgn = G.send = '"';
7478 return bc_vm_run(argv, "BC_LINE_LENGTH");
7483 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7484 int dc_main(int argc UNUSED_PARAM, char **argv)
7490 return bc_vm_run(argv, "DC_LINE_LENGTH");