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_DC_SMALL
98 //config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
99 //config: depends on DC && !BC
102 //config:config FEATURE_DC_LIBM
103 //config: bool "Enable power and exp functions (requires libm)"
105 //config: depends on FEATURE_DC_SMALL
107 //config: Enable power and exp functions.
108 //config: NOTE: This will require libm to be present for linking.
110 //config:config FEATURE_BC_SIGNALS
111 //config: bool "Enable bc/dc signal handling"
113 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
115 //config: Enable signal handling for bc and dc.
117 //config:config FEATURE_BC_LONG_OPTIONS
118 //config: bool "Enable bc/dc long options"
120 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
122 //config: Enable long options for bc and dc.
124 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
125 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
127 //kbuild:lib-$(CONFIG_BC) += bc.o
128 //kbuild:lib-$(CONFIG_DC) += bc.o
130 //See www.gnu.org/software/bc/manual/bc.html
131 //usage:#define bc_trivial_usage
132 //usage: "[-sqliw] FILE..."
134 //usage:#define bc_full_usage "\n"
135 //usage: "\nArbitrary precision calculator"
137 ///////: "\n -i Interactive" - has no effect for now
138 //usage: "\n -q Quiet"
139 //usage: "\n -l Load standard math library"
140 //usage: "\n -s Be POSIX compatible"
141 //usage: "\n -w Warn if extensions are used"
142 ///////: "\n -v Version"
144 //usage: "\n$BC_LINE_LENGTH changes output width"
146 //usage:#define bc_example_usage
147 //usage: "3 + 4.129\n"
148 //usage: "1903 - 2893\n"
149 //usage: "-129 * 213.28935\n"
150 //usage: "12 / -1932\n"
152 //usage: "34 ^ 189\n"
153 //usage: "scale = 13\n"
154 //usage: "ibase = 2\n"
155 //usage: "obase = A\n"
157 //usage:#define dc_trivial_usage
158 //usage: "[-eSCRIPT]... [-fFILE]... [FILE]..."
160 //usage:#define dc_full_usage "\n"
161 //usage: "\nTiny RPN calculator. Operations:"
162 //usage: "\n+, -, *, /, %, ~, ^, |,"
163 //usage: "\np - print top of the stack (without popping)"
164 //usage: "\nf - print entire stack"
165 //usage: "\nk - pop the value and set the precision"
166 //usage: "\ni - pop the value and set input radix"
167 //usage: "\no - pop the value and set output radix"
168 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
170 //usage:#define dc_example_usage
171 //usage: "$ dc -e'2 2 + p'\n"
173 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
175 //usage: "$ dc -e'0 1 & p'\n"
177 //usage: "$ dc -e'0 1 | p'\n"
179 //usage: "$ echo '72 9 / 8 * p' | dc\n"
183 #include "common_bufsiz.h"
185 #if ENABLE_FEATURE_DC_SMALL
189 typedef enum BcStatus {
190 BC_STATUS_SUCCESS = 0,
191 BC_STATUS_FAILURE = 1,
192 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
193 BC_STATUS_EOF = 3, // bc_vm_stdin() uses this
196 #define BC_VEC_INVALID_IDX ((size_t) -1)
197 #define BC_VEC_START_CAP (1 << 5)
199 typedef void (*BcVecFree)(void *);
201 typedef struct BcVec {
209 typedef signed char BcDig;
211 typedef struct BcNum {
219 #define BC_NUM_MIN_BASE ((unsigned long) 2)
220 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
221 // larger value might speed up BIGNUM calculations a bit:
222 #define BC_NUM_DEF_SIZE (16)
223 #define BC_NUM_PRINT_WIDTH (69)
225 #define BC_NUM_KARATSUBA_LEN (32)
227 typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
228 typedef void (*BcNumDigitOp)(size_t, size_t, bool, size_t *, size_t);
230 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
231 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
232 static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
233 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
234 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
235 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
236 static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
237 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
240 typedef enum BcInst {
270 BC_INST_ASSIGN_POWER,
271 BC_INST_ASSIGN_MULTIPLY,
272 BC_INST_ASSIGN_DIVIDE,
273 BC_INST_ASSIGN_MODULUS,
275 BC_INST_ASSIGN_MINUS,
321 BC_INST_PRINT_STREAM,
336 BC_INST_INVALID = -1,
341 typedef struct BcId {
346 typedef struct BcFunc {
353 typedef enum BcResultType {
358 BC_RESULT_ARRAY_ELEM,
367 // These are between to calculate ibase, obase, and last from instructions.
375 typedef union BcResultData {
381 typedef struct BcResult {
386 typedef struct BcInstPtr {
392 // BC_LEX_NEG is not used in lexing; it is only for parsing.
393 typedef enum BcLexType {
421 BC_LEX_OP_ASSIGN_POWER,
422 BC_LEX_OP_ASSIGN_MULTIPLY,
423 BC_LEX_OP_ASSIGN_DIVIDE,
424 BC_LEX_OP_ASSIGN_MODULUS,
425 BC_LEX_OP_ASSIGN_PLUS,
426 BC_LEX_OP_ASSIGN_MINUS,
447 BC_LEX_KEY_1st_keyword,
448 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
455 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
456 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
458 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
461 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
499 // must match order of BC_LEX_KEY_foo etc above
501 struct BcLexKeyword {
504 #define BC_LEX_KW_ENTRY(a, b) \
505 { .name8 = a /*, .posix = b */ }
506 static const struct BcLexKeyword bc_lex_kws[20] = {
507 BC_LEX_KW_ENTRY("auto" , 1), // 0
508 BC_LEX_KW_ENTRY("break" , 1), // 1
509 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
510 BC_LEX_KW_ENTRY("define" , 1), // 3
512 BC_LEX_KW_ENTRY("else" , 0), // 4
513 BC_LEX_KW_ENTRY("for" , 1), // 5
514 BC_LEX_KW_ENTRY("halt" , 0), // 6
515 BC_LEX_KW_ENTRY("ibase" , 1), // 7
517 BC_LEX_KW_ENTRY("if" , 1), // 8
518 BC_LEX_KW_ENTRY("last" , 0), // 9
519 BC_LEX_KW_ENTRY("length" , 1), // 10
520 BC_LEX_KW_ENTRY("limits" , 0), // 11
522 BC_LEX_KW_ENTRY("obase" , 1), // 12
523 BC_LEX_KW_ENTRY("print" , 0), // 13
524 BC_LEX_KW_ENTRY("quit" , 1), // 14
525 BC_LEX_KW_ENTRY("read" , 0), // 15
527 BC_LEX_KW_ENTRY("return" , 1), // 16
528 BC_LEX_KW_ENTRY("scale" , 1), // 17
529 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
530 BC_LEX_KW_ENTRY("while" , 1), // 19
532 #undef BC_LEX_KW_ENTRY
560 #define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
564 typedef BcStatus (*BcLexNext)(struct BcLex *);
566 typedef struct BcLex {
584 #define BC_PARSE_STREND ((char) UCHAR_MAX)
586 #define BC_PARSE_REL (1 << 0)
587 #define BC_PARSE_PRINT (1 << 1)
588 #define BC_PARSE_NOCALL (1 << 2)
589 #define BC_PARSE_NOREAD (1 << 3)
590 #define BC_PARSE_ARRAY (1 << 4)
592 #define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
593 #define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
595 #define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
596 #define BC_PARSE_FUNC_INNER(parse) \
597 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
599 #define BC_PARSE_FLAG_FUNC (1 << 1)
600 #define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
602 #define BC_PARSE_FLAG_BODY (1 << 2)
603 #define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
605 #define BC_PARSE_FLAG_LOOP (1 << 3)
606 #define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
608 #define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
609 #define BC_PARSE_LOOP_INNER(parse) \
610 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
612 #define BC_PARSE_FLAG_IF (1 << 5)
613 #define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
615 #define BC_PARSE_FLAG_ELSE (1 << 6)
616 #define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
618 #define BC_PARSE_FLAG_IF_END (1 << 7)
619 #define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
621 #define BC_PARSE_CAN_EXEC(parse) \
622 (!(BC_PARSE_TOP_FLAG(parse) & \
623 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
624 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
625 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
631 typedef BcStatus (*BcParseParse)(struct BcParse *);
633 typedef struct BcParse {
654 typedef struct BcProgram {
695 #define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
697 #define BC_PROG_MAIN (0)
698 #define BC_PROG_READ (1)
700 #define BC_PROG_REQ_FUNCS (2)
703 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
704 #define BC_PROG_NUM(r, n) \
705 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
707 typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
709 #define BC_FLAG_W (1 << 0)
710 #define BC_FLAG_V (1 << 1)
711 #define BC_FLAG_S (1 << 2)
712 #define BC_FLAG_Q (1 << 3)
713 #define BC_FLAG_L (1 << 4)
714 #define BC_FLAG_I (1 << 5)
715 #define DC_FLAG_X (1 << 6)
717 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
718 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
720 #define BC_MAX_OBASE ((unsigned) 999)
721 #define BC_MAX_DIM ((unsigned) INT_MAX)
722 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
723 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
724 #define BC_MAX_NUM BC_MAX_STRING
725 // Unused apart from "limits" message. Just show a "biggish number" there.
726 //#define BC_MAX_NAME BC_MAX_STRING
727 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
728 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
729 #define BC_MAX_NAME_STR "999999999"
730 #define BC_MAX_EXP_STR "999999999"
731 #define BC_MAX_VARS_STR "999999999"
733 #define BC_MAX_OBASE_STR "999"
735 #if INT_MAX == 2147483647
736 # define BC_MAX_DIM_STR "2147483647"
737 #elif INT_MAX == 9223372036854775807
738 # define BC_MAX_DIM_STR "9223372036854775807"
740 # error Strange INT_MAX
743 #if UINT_MAX == 4294967295
744 # define BC_MAX_SCALE_STR "4294967295"
745 # define BC_MAX_STRING_STR "4294967294"
746 #elif UINT_MAX == 18446744073709551615
747 # define BC_MAX_SCALE_STR "18446744073709551615"
748 # define BC_MAX_STRING_STR "18446744073709551614"
750 # error Strange UINT_MAX
752 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
755 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
756 IF_FEATURE_CLEAN_UP(smallint exiting;)
763 // For error messages. Can be set to current parsed line,
764 // or [TODO] to current executing line (can be before last parsed one)
771 #if ENABLE_FEATURE_EDITING
772 line_input_t *line_input_state;
775 #define G (*ptr_to_globals)
776 #define INIT_G() do { \
777 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
779 #define FREE_G() do { \
780 FREE_PTR_TO_GLOBALS(); \
782 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
783 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
784 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
785 #if ENABLE_FEATURE_BC_SIGNALS
786 # define G_interrupt bb_got_signal
787 # define G_ttyin G.ttyin
789 # define G_interrupt 0
792 #if ENABLE_FEATURE_CLEAN_UP
793 # define G_exiting G.exiting
797 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
801 // This is a bit array that corresponds to token types. An entry is
802 // true if the token is valid in an expression, false otherwise.
804 BC_PARSE_EXPRS_BITS = 0
805 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
806 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
807 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
808 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
809 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
810 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
811 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
812 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
814 static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
816 #if ULONG_MAX > 0xffffffff
817 // 64-bit version (will not work correctly for 32-bit longs!)
818 return BC_PARSE_EXPRS_BITS & (1UL << i);
821 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
823 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
826 return m & (1UL << i);
830 // This is an array of data for operators that correspond to token types.
831 static const uint8_t bc_parse_ops[] = {
832 #define OP(p,l) ((int)(l) * 0x10 + (p))
833 OP(0, false), OP( 0, false ), // inc dec
836 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
837 OP(4, true ), OP( 4, true ), // mod + -
838 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
840 OP(7, true ), OP( 7, true ), // or and
841 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
842 OP(5, false), OP( 5, false ), // -= =
845 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
846 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
848 // Byte array of up to 4 BC_LEX's, packed into 32-bit word
849 typedef uint32_t BcParseNext;
851 // These identify what tokens can come after expressions in certain cases.
853 #define BC_PARSE_NEXT4(a,b,c,d) ( (a) | ((b)<<8) | ((c)<<16) | ((((d)|0x80)<<24)) )
854 #define BC_PARSE_NEXT2(a,b) BC_PARSE_NEXT4(a,b,0xff,0xff)
855 #define BC_PARSE_NEXT1(a) BC_PARSE_NEXT4(a,0xff,0xff,0xff)
856 bc_parse_next_expr = BC_PARSE_NEXT4(BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF),
857 bc_parse_next_param = BC_PARSE_NEXT2(BC_LEX_RPAREN, BC_LEX_COMMA),
858 bc_parse_next_print = BC_PARSE_NEXT4(BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF),
859 bc_parse_next_rel = BC_PARSE_NEXT1(BC_LEX_RPAREN),
860 bc_parse_next_elem = BC_PARSE_NEXT1(BC_LEX_RBRACKET),
861 bc_parse_next_for = BC_PARSE_NEXT1(BC_LEX_SCOLON),
862 bc_parse_next_read = BC_PARSE_NEXT2(BC_LEX_NLINE, BC_LEX_EOF),
863 #undef BC_PARSE_NEXT4
864 #undef BC_PARSE_NEXT2
865 #undef BC_PARSE_NEXT1
870 static const //BcLexType - should be this type, but narrower type saves size:
873 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
874 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
875 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
879 static const //BcLexType - should be this type
882 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
883 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
884 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
885 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
886 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
887 BC_LEX_INVALID, BC_LEX_INVALID,
888 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
889 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
890 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
891 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
892 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
893 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
894 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
895 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
896 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
897 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
898 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
899 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
900 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
901 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
902 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
903 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
904 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
905 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
909 static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
912 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
913 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
914 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
915 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
916 BC_INST_INVALID, BC_INST_INVALID,
917 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
918 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
919 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
920 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
921 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
922 BC_INST_INVALID, BC_INST_INVALID,
923 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
924 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
925 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
926 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
927 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
928 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
929 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
930 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
931 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
932 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
933 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
934 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
938 static const BcNumBinaryOp bc_program_ops[] = {
939 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
942 static void fflush_and_check(void)
945 if (ferror(stdout) || ferror(stderr))
946 bb_perror_msg_and_die("output error");
949 #if ENABLE_FEATURE_CLEAN_UP
950 #define QUIT_OR_RETURN_TO_MAIN \
952 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
954 return BC_STATUS_FAILURE; \
957 #define QUIT_OR_RETURN_TO_MAIN quit()
960 static void quit(void) NORETURN;
961 static void quit(void)
964 bb_perror_msg_and_die("input error");
969 static void bc_verror_msg(const char *fmt, va_list p)
971 const char *sv = sv; /* for compiler */
974 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
976 bb_verror_msg(fmt, p, NULL);
978 free((char*)applet_name);
983 static NOINLINE int bc_error_fmt(const char *fmt, ...)
988 bc_verror_msg(fmt, p);
991 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
993 return BC_STATUS_FAILURE;
997 static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
1001 // Are non-POSIX constructs totally ok?
1002 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
1003 return BC_STATUS_SUCCESS; // yes
1006 bc_verror_msg(fmt, p);
1009 // Do we treat non-POSIX constructs as errors?
1010 if (!(option_mask32 & BC_FLAG_S))
1011 return BC_STATUS_SUCCESS; // no, it's a warning
1012 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
1014 return BC_STATUS_FAILURE;
1018 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
1019 // This idiom begs for tail-call optimization, but for it to work,
1020 // function must not have caller-cleaned parameters on stack.
1021 // Unfortunately, vararg function API does exactly that on most arches.
1022 // Thus, use these shims for the cases when we have no vararg PARAMS:
1023 static int bc_error(const char *msg)
1025 return bc_error_fmt("%s", msg);
1028 static int bc_POSIX_requires(const char *msg)
1030 return bc_posix_error_fmt("POSIX requires %s", msg);
1032 static int bc_POSIX_does_not_allow(const char *msg)
1034 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1036 static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1038 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1040 static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1042 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1045 static int bc_error_bad_character(char c)
1047 return bc_error_fmt("bad character '%c'", c);
1049 static int bc_error_bad_expression(void)
1051 return bc_error("bad expression");
1053 static int bc_error_bad_token(void)
1055 return bc_error("bad token");
1057 static int bc_error_stack_has_too_few_elements(void)
1059 return bc_error("stack has too few elements");
1061 static int bc_error_variable_is_wrong_type(void)
1063 return bc_error("variable is wrong type");
1065 static int bc_error_nested_read_call(void)
1067 return bc_error("read() call inside of a read() call");
1070 static void bc_vec_grow(BcVec *v, size_t n)
1072 size_t cap = v->cap * 2;
1073 while (cap < v->len + n) cap *= 2;
1074 v->v = xrealloc(v->v, v->size * cap);
1078 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1081 v->cap = BC_VEC_START_CAP;
1084 v->v = xmalloc(esize * BC_VEC_START_CAP);
1087 static void bc_char_vec_init(BcVec *v)
1089 bc_vec_init(v, sizeof(char), NULL);
1092 static void bc_vec_expand(BcVec *v, size_t req)
1095 v->v = xrealloc(v->v, v->size * req);
1100 static void bc_vec_pop(BcVec *v)
1104 v->dtor(v->v + (v->size * v->len));
1107 static void bc_vec_npop(BcVec *v, size_t n)
1112 size_t len = v->len - n;
1113 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1117 static void bc_vec_pop_all(BcVec *v)
1119 bc_vec_npop(v, v->len);
1122 static void bc_vec_push(BcVec *v, const void *data)
1124 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1125 memmove(v->v + (v->size * v->len), data, v->size);
1129 static void bc_vec_pushByte(BcVec *v, char data)
1131 bc_vec_push(v, &data);
1134 static void bc_vec_pushZeroByte(BcVec *v)
1136 //bc_vec_pushByte(v, '\0');
1138 bc_vec_push(v, &const_int_0);
1141 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1144 bc_vec_push(v, data);
1149 if (v->len == v->cap) bc_vec_grow(v, 1);
1151 ptr = v->v + v->size * idx;
1153 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1154 memmove(ptr, data, v->size);
1158 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1161 bc_vec_expand(v, len + 1);
1162 memcpy(v->v, str, len);
1165 bc_vec_pushZeroByte(v);
1168 static void bc_vec_concat(BcVec *v, const char *str)
1172 if (v->len == 0) bc_vec_pushZeroByte(v);
1174 len = v->len + strlen(str);
1176 if (v->cap < len) bc_vec_grow(v, len - v->len);
1177 strcpy(v->v + v->len - 1, str);
1182 static void *bc_vec_item(const BcVec *v, size_t idx)
1184 return v->v + v->size * idx;
1187 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1189 return v->v + v->size * (v->len - idx - 1);
1192 static void *bc_vec_top(const BcVec *v)
1194 return v->v + v->size * (v->len - 1);
1197 static void bc_vec_free(void *vec)
1199 BcVec *v = (BcVec *) vec;
1204 static int bc_id_cmp(const void *e1, const void *e2)
1206 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1209 static void bc_id_free(void *id)
1211 free(((BcId *) id)->name);
1214 static size_t bc_map_find(const BcVec *v, const void *ptr)
1216 size_t low = 0, high = v->len;
1218 while (low < high) {
1220 size_t mid = (low + high) / 2;
1221 BcId *id = bc_vec_item(v, mid);
1222 int result = bc_id_cmp(ptr, id);
1226 else if (result < 0)
1235 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1237 size_t n = *i = bc_map_find(v, ptr);
1240 bc_vec_push(v, ptr);
1241 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1242 return 0; // "was not inserted"
1244 bc_vec_pushAt(v, ptr, n);
1245 return 1; // "was inserted"
1249 static size_t bc_map_index(const BcVec *v, const void *ptr)
1251 size_t i = bc_map_find(v, ptr);
1252 if (i >= v->len) return BC_VEC_INVALID_IDX;
1253 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1257 static int push_input_byte(BcVec *vec, char c)
1259 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1262 // Bad chars on this line, ignore entire line
1263 bc_error_fmt("illegal character 0x%02x", c);
1266 bc_vec_pushByte(vec, (char)c);
1270 static BcStatus bc_read_line(BcVec *vec, const char *prompt)
1275 if (G_posix) prompt = "";
1277 s = BC_STATUS_SUCCESS;
1282 bc_vec_pop_all(vec);
1286 #if ENABLE_FEATURE_BC_SIGNALS
1287 if (G_interrupt) { // ^C was pressed
1291 ? "\ninterrupt (type \"quit\" to exit)\n"
1292 : "\ninterrupt (type \"q\" to exit)\n"
1295 # if ENABLE_FEATURE_EDITING
1298 # define line_buf bb_common_bufsiz1
1299 n = read_line_input(G.line_input_state, prompt, line_buf, COMMON_BUFSIZE);
1300 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1310 bad_chars |= push_input_byte(vec, c);
1318 fputs(prompt, stderr);
1319 IF_FEATURE_BC_SIGNALS(errno = 0;)
1322 #if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1323 // Both conditions appear simultaneously, check both just in case
1324 if (errno == EINTR || G_interrupt) {
1332 quit(); // this emits error message
1334 // Note: EOF does not append '\n', therefore:
1335 // printf 'print 123\n' | bc - works
1336 // printf 'print 123' | bc - fails (syntax error)
1339 bad_chars |= push_input_byte(vec, c);
1340 } while (c != '\n');
1342 } while (bad_chars);
1344 bc_vec_pushZeroByte(vec);
1349 static char* bc_read_file(const char *path)
1352 size_t size = ((size_t) -1);
1355 // Never returns NULL (dies on errors)
1356 buf = xmalloc_xopen_read_close(path, &size);
1358 for (i = 0; i < size; ++i) {
1360 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1372 static void bc_num_setToZero(BcNum *n, size_t scale)
1379 static void bc_num_zero(BcNum *n)
1381 bc_num_setToZero(n, 0);
1384 static void bc_num_one(BcNum *n)
1386 bc_num_setToZero(n, 0);
1391 static void bc_num_ten(BcNum *n)
1393 bc_num_setToZero(n, 0);
1399 static void bc_num_init(BcNum *n, size_t req)
1401 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1402 memset(n, 0, sizeof(BcNum));
1403 n->num = xmalloc(req);
1407 static void bc_num_expand(BcNum *n, size_t req)
1409 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1411 n->num = xrealloc(n->num, req);
1416 static void bc_num_free(void *num)
1418 free(((BcNum *) num)->num);
1421 static void bc_num_copy(BcNum *d, BcNum *s)
1424 bc_num_expand(d, s->cap);
1428 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1432 static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
1435 unsigned long pow, result;
1437 if (n->neg) return bc_error("negative number");
1439 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1441 unsigned long prev = result, powprev = pow;
1443 result += ((unsigned long) n->num[i]) * pow;
1446 if (result < prev || pow < powprev)
1447 return bc_error("overflow");
1453 return BC_STATUS_SUCCESS;
1456 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1464 if (val == 0) return;
1466 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1467 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1470 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
1474 for (i = 0; i < len; ++i) {
1475 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
1482 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1483 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1484 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1485 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1486 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1488 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1490 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1491 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1493 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1496 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1500 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
1501 return BC_NUM_NEG(i + 1, c < 0);
1504 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1506 size_t i, min, a_int, b_int, diff;
1507 BcDig *max_num, *min_num;
1508 bool a_max, neg = false;
1511 if (a == b) return 0;
1512 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1513 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1523 a_int = BC_NUM_INT(a);
1524 b_int = BC_NUM_INT(b);
1526 a_max = (a->rdx > b->rdx);
1528 if (a_int != 0) return (ssize_t) a_int;
1532 diff = a->rdx - b->rdx;
1533 max_num = a->num + diff;
1538 diff = b->rdx - a->rdx;
1539 max_num = b->num + diff;
1543 cmp = bc_num_compare(max_num, min_num, b_int + min);
1544 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1546 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1547 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1553 static void bc_num_truncate(BcNum *n, size_t places)
1555 if (places == 0) return;
1561 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1565 static void bc_num_extend(BcNum *n, size_t places)
1567 size_t len = n->len + places;
1571 if (n->cap < len) bc_num_expand(n, len);
1573 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1574 memset(n->num, 0, sizeof(BcDig) * places);
1581 static void bc_num_clean(BcNum *n)
1583 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1586 else if (n->len < n->rdx)
1590 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1593 bc_num_extend(n, scale - n->rdx);
1595 bc_num_truncate(n, n->rdx - scale);
1598 if (n->len != 0) n->neg = !neg1 != !neg2;
1601 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1606 b->len = n->len - idx;
1608 a->rdx = b->rdx = 0;
1610 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1611 memcpy(a->num, n->num, idx * sizeof(BcDig));
1622 static BcStatus bc_num_shift(BcNum *n, size_t places)
1624 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
1626 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1627 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1628 if (places + n->len > BC_MAX_NUM)
1629 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1632 if (n->rdx >= places)
1635 bc_num_extend(n, places - n->rdx);
1641 return BC_STATUS_SUCCESS;
1644 static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1653 return bc_num_div(&one, a, b, scale);
1656 static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1658 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1659 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1662 // Because this function doesn't need to use scale (per the bc spec),
1663 // I am hijacking it to say whether it's doing an add or a subtract.
1667 if (sub && c->len) c->neg = !c->neg;
1668 return BC_STATUS_SUCCESS;
1670 else if (b->len == 0) {
1672 return BC_STATUS_SUCCESS;
1676 c->rdx = BC_MAX(a->rdx, b->rdx);
1677 min_rdx = BC_MIN(a->rdx, b->rdx);
1680 if (a->rdx > b->rdx) {
1681 diff = a->rdx - b->rdx;
1683 ptr_a = a->num + diff;
1687 diff = b->rdx - a->rdx;
1690 ptr_b = b->num + diff;
1693 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1696 a_int = BC_NUM_INT(a);
1697 b_int = BC_NUM_INT(b);
1699 if (a_int > b_int) {
1710 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
1711 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1713 ptr_c[i] = (BcDig)(in % 10);
1716 for (; i < max + min_rdx; ++i, ++c->len) {
1717 in = ((int) ptr[i]) + carry;
1719 ptr_c[i] = (BcDig)(in % 10);
1722 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1724 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1727 static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1730 BcNum *minuend, *subtrahend;
1732 bool aneg, bneg, neg;
1734 // Because this function doesn't need to use scale (per the bc spec),
1735 // I am hijacking it to say whether it's doing an add or a subtract.
1739 if (sub && c->len) c->neg = !c->neg;
1740 return BC_STATUS_SUCCESS;
1742 else if (b->len == 0) {
1744 return BC_STATUS_SUCCESS;
1749 a->neg = b->neg = false;
1751 cmp = bc_num_cmp(a, b);
1757 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1758 return BC_STATUS_SUCCESS;
1767 if (sub) neg = !neg;
1772 bc_num_copy(c, minuend);
1775 if (c->rdx < subtrahend->rdx) {
1776 bc_num_extend(c, subtrahend->rdx - c->rdx);
1780 start = c->rdx - subtrahend->rdx;
1782 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1786 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1789 static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1793 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1794 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1797 if (a->len == 0 || b->len == 0) {
1799 return BC_STATUS_SUCCESS;
1801 aone = BC_NUM_ONE(a);
1802 if (aone || BC_NUM_ONE(b)) {
1803 bc_num_copy(c, aone ? b : a);
1804 return BC_STATUS_SUCCESS;
1807 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1808 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1813 bc_num_expand(c, a->len + b->len + 1);
1815 memset(c->num, 0, sizeof(BcDig) * c->cap);
1818 for (i = 0; i < b->len; ++i) {
1821 for (j = 0; j < a->len; ++j) {
1822 unsigned in = c->num[i + j];
1823 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1824 // note: compilers prefer _unsigned_ div/const
1826 c->num[i + j] = (BcDig)(in % 10);
1829 c->num[i + j] += (BcDig) carry;
1830 len = BC_MAX(len, i + j + !!carry);
1833 // a*a <- without check below, this will not be interruptible
1834 if (G_interrupt) return BC_STATUS_FAILURE;
1839 return BC_STATUS_SUCCESS;
1842 bc_num_init(&l1, max);
1843 bc_num_init(&h1, max);
1844 bc_num_init(&l2, max);
1845 bc_num_init(&h2, max);
1846 bc_num_init(&m1, max);
1847 bc_num_init(&m2, max);
1848 bc_num_init(&z0, max);
1849 bc_num_init(&z1, max);
1850 bc_num_init(&z2, max);
1851 bc_num_init(&temp, max + max);
1853 bc_num_split(a, max2, &l1, &h1);
1854 bc_num_split(b, max2, &l2, &h2);
1856 s = bc_num_add(&h1, &l1, &m1, 0);
1858 s = bc_num_add(&h2, &l2, &m2, 0);
1861 s = bc_num_k(&h1, &h2, &z0);
1863 s = bc_num_k(&m1, &m2, &z1);
1865 s = bc_num_k(&l1, &l2, &z2);
1868 s = bc_num_sub(&z1, &z0, &temp, 0);
1870 s = bc_num_sub(&temp, &z2, &z1, 0);
1873 s = bc_num_shift(&z0, max2 * 2);
1875 s = bc_num_shift(&z1, max2);
1877 s = bc_num_add(&z0, &z1, &temp, 0);
1879 s = bc_num_add(&temp, &z2, c, 0);
1895 static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1899 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1901 scale = BC_MAX(scale, a->rdx);
1902 scale = BC_MAX(scale, b->rdx);
1903 scale = BC_MIN(a->rdx + b->rdx, scale);
1904 maxrdx = BC_MAX(maxrdx, scale);
1906 bc_num_init(&cpa, a->len);
1907 bc_num_init(&cpb, b->len);
1909 bc_num_copy(&cpa, a);
1910 bc_num_copy(&cpb, b);
1911 cpa.neg = cpb.neg = false;
1913 s = bc_num_shift(&cpa, maxrdx);
1915 s = bc_num_shift(&cpb, maxrdx);
1917 s = bc_num_k(&cpa, &cpb, c);
1921 bc_num_expand(c, c->len + maxrdx);
1923 if (c->len < maxrdx) {
1924 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1929 bc_num_retireMul(c, scale, a->neg, b->neg);
1937 static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1939 BcStatus s = BC_STATUS_SUCCESS;
1946 return bc_error("divide by zero");
1947 else if (a->len == 0) {
1948 bc_num_setToZero(c, scale);
1949 return BC_STATUS_SUCCESS;
1951 else if (BC_NUM_ONE(b)) {
1953 bc_num_retireMul(c, scale, a->neg, b->neg);
1954 return BC_STATUS_SUCCESS;
1957 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1958 bc_num_copy(&cp, a);
1962 bc_num_expand(&cp, len + 2);
1963 bc_num_extend(&cp, len - cp.len);
1966 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1968 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1970 if (b->rdx == b->len) {
1971 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1975 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1977 // We want an extra zero in front to make things simpler.
1978 cp.num[cp.len++] = 0;
1981 bc_num_expand(c, cp.len);
1984 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
1989 for (i = end - 1; !s && i < end; --i) {
1991 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
1992 bc_num_subArrays(n, p, len);
1996 // 1/a <- without check below, this will not be interruptible
1998 s = BC_STATUS_FAILURE;
2003 bc_num_retireMul(c, scale, a->neg, b->neg);
2009 static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2010 BcNum *restrict d, size_t scale, size_t ts)
2017 return bc_error("divide by zero");
2020 bc_num_setToZero(d, ts);
2021 return BC_STATUS_SUCCESS;
2024 bc_num_init(&temp, d->cap);
2025 s = bc_num_d(a, b, c, scale);
2028 if (scale != 0) scale = ts;
2030 s = bc_num_m(c, b, &temp, scale);
2032 s = bc_num_sub(a, &temp, d, scale);
2035 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2038 bc_num_retireMul(d, ts, a->neg, b->neg);
2046 static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2050 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2052 bc_num_init(&c1, len);
2053 s = bc_num_r(a, b, &c1, c, scale, ts);
2059 static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2061 BcStatus s = BC_STATUS_SUCCESS;
2064 size_t i, powrdx, resrdx;
2067 if (b->rdx) return bc_error("non integer number");
2071 return BC_STATUS_SUCCESS;
2073 else if (a->len == 0) {
2074 bc_num_setToZero(c, scale);
2075 return BC_STATUS_SUCCESS;
2077 else if (BC_NUM_ONE(b)) {
2081 s = bc_num_inv(a, c, scale);
2088 s = bc_num_ulong(b, &pow);
2091 bc_num_init(©, a->len);
2092 bc_num_copy(©, a);
2097 if (a->rdx * pow < scale)
2098 scale = a->rdx * pow;
2103 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2105 s = bc_num_mul(©, ©, ©, powrdx);
2107 // Not needed: bc_num_mul() has a check for ^C:
2108 //if (G_interrupt) {
2109 // s = BC_STATUS_FAILURE;
2114 bc_num_copy(c, ©);
2116 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2119 s = bc_num_mul(©, ©, ©, powrdx);
2124 s = bc_num_mul(c, ©, c, resrdx);
2127 // Not needed: bc_num_mul() has a check for ^C:
2128 //if (G_interrupt) {
2129 // s = BC_STATUS_FAILURE;
2135 s = bc_num_inv(c, c, scale);
2139 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2141 // We can't use bc_num_clean() here.
2142 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2143 if (zero) bc_num_setToZero(c, scale);
2150 static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2151 BcNumBinaryOp op, size_t req)
2154 BcNum num2, *ptr_a, *ptr_b;
2159 memcpy(ptr_a, c, sizeof(BcNum));
2168 memcpy(ptr_b, c, sizeof(BcNum));
2176 bc_num_init(c, req);
2178 bc_num_expand(c, req);
2180 s = op(ptr_a, ptr_b, c, scale);
2182 if (init) bc_num_free(&num2);
2187 static bool bc_num_strValid(const char *val, size_t base)
2190 bool small, radix = false;
2191 size_t i, len = strlen(val);
2193 if (!len) return true;
2196 b = (BcDig)(small ? base + '0' : base - 10 + 'A');
2198 for (i = 0; i < len; ++i) {
2204 if (radix) return false;
2210 if (c < '0' || (small && c >= b) || (c > '9' && (c < 'A' || c >= b)))
2217 static void bc_num_parseDecimal(BcNum *n, const char *val)
2223 for (i = 0; val[i] == '0'; ++i);
2230 for (i = 0; zero && i < len; ++i) zero = val[i] == '0' || val[i] == '.';
2231 bc_num_expand(n, len);
2234 ptr = strchr(val, '.');
2238 n->rdx = (size_t)((val + len) - (ptr + 1));
2241 for (i = len - 1; i < len; ++n->len, i -= 1 + (i && val[i - 1] == '.'))
2242 n->num[n->len] = val[i] - '0';
2246 static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2249 BcNum temp, mult, result;
2253 size_t i, digits, len = strlen(val);
2257 for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
2260 bc_num_init(&temp, BC_NUM_DEF_SIZE);
2261 bc_num_init(&mult, BC_NUM_DEF_SIZE);
2263 for (i = 0; i < len; ++i) {
2266 if (c == '.') break;
2268 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2270 s = bc_num_mul(n, base, &mult, 0);
2271 if (s) goto int_err;
2272 bc_num_ulong2num(&temp, v);
2273 s = bc_num_add(&mult, &temp, n, 0);
2274 if (s) goto int_err;
2279 if (c == 0) goto int_err;
2282 bc_num_init(&result, base->len);
2283 bc_num_zero(&result);
2286 for (i += 1, digits = 0; i < len; ++i, ++digits) {
2291 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2293 s = bc_num_mul(&result, base, &result, 0);
2295 bc_num_ulong2num(&temp, v);
2296 s = bc_num_add(&result, &temp, &result, 0);
2298 s = bc_num_mul(&mult, base, &mult, 0);
2302 s = bc_num_div(&result, &mult, &result, digits);
2304 s = bc_num_add(n, &result, n, digits);
2308 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2314 bc_num_free(&result);
2320 static void bc_num_printNewline(size_t *nchars, size_t line_len)
2322 if (*nchars == line_len - 1) {
2330 static void bc_num_printChar(size_t num, size_t width, bool radix,
2331 size_t *nchars, size_t line_len)
2333 (void) radix, (void) line_len;
2334 bb_putchar((char) num);
2335 *nchars = *nchars + width;
2339 static void bc_num_printDigits(size_t num, size_t width, bool radix,
2340 size_t *nchars, size_t line_len)
2344 bc_num_printNewline(nchars, line_len);
2345 bb_putchar(radix ? '.' : ' ');
2348 bc_num_printNewline(nchars, line_len);
2349 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2352 for (exp = 0; exp < width; pow /= 10, ++(*nchars), ++exp) {
2354 bc_num_printNewline(nchars, line_len);
2357 bb_putchar(((char) dig) + '0');
2361 static void bc_num_printHex(size_t num, size_t width, bool radix,
2362 size_t *nchars, size_t line_len)
2365 bc_num_printNewline(nchars, line_len);
2370 bc_num_printNewline(nchars, line_len);
2371 bb_putchar(bb_hexdigits_upcase[num]);
2372 *nchars = *nchars + width;
2375 static void bc_num_printDecimal(BcNum *n, size_t *nchars, size_t len)
2377 size_t i, rdx = n->rdx - 1;
2379 if (n->neg) bb_putchar('-');
2380 (*nchars) += n->neg;
2382 for (i = n->len - 1; i < n->len; --i)
2383 bc_num_printHex((size_t) n->num[i], 1, i == rdx, nchars, len);
2386 static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width,
2387 size_t *nchars, size_t len, BcNumDigitOp print)
2391 BcNum intp, fracp, digit, frac_len;
2392 unsigned long dig, *ptr;
2397 print(0, width, false, nchars, len);
2398 return BC_STATUS_SUCCESS;
2401 bc_vec_init(&stack, sizeof(long), NULL);
2402 bc_num_init(&intp, n->len);
2403 bc_num_init(&fracp, n->rdx);
2404 bc_num_init(&digit, width);
2405 bc_num_init(&frac_len, BC_NUM_INT(n));
2406 bc_num_copy(&intp, n);
2407 bc_num_one(&frac_len);
2409 bc_num_truncate(&intp, intp.rdx);
2410 s = bc_num_sub(n, &intp, &fracp, 0);
2413 while (intp.len != 0) {
2414 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2416 s = bc_num_ulong(&digit, &dig);
2418 bc_vec_push(&stack, &dig);
2421 for (i = 0; i < stack.len; ++i) {
2422 ptr = bc_vec_item_rev(&stack, i);
2423 print(*ptr, width, false, nchars, len);
2426 if (!n->rdx) goto err;
2428 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2429 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2431 s = bc_num_ulong(&fracp, &dig);
2433 bc_num_ulong2num(&intp, dig);
2434 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2436 print(dig, width, radix, nchars, len);
2437 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2442 bc_num_free(&frac_len);
2443 bc_num_free(&digit);
2444 bc_num_free(&fracp);
2446 bc_vec_free(&stack);
2450 static BcStatus bc_num_printBase(BcNum *n, BcNum *base, size_t base_t,
2451 size_t *nchars, size_t line_len)
2458 if (neg) bb_putchar('-');
2463 if (base_t <= BC_NUM_MAX_IBASE) {
2465 print = bc_num_printHex;
2468 for (i = base_t - 1, width = 0; i != 0; i /= 10, ++width);
2469 print = bc_num_printDigits;
2472 s = bc_num_printNum(n, base, width, nchars, line_len, print);
2479 static BcStatus bc_num_stream(BcNum *n, BcNum *base, size_t *nchars, size_t len)
2481 return bc_num_printNum(n, base, 1, nchars, len, bc_num_printChar);
2485 static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2488 if (!bc_num_strValid(val, base_t))
2489 return bc_error("bad number string");
2492 bc_num_parseDecimal(n, val);
2494 bc_num_parseBase(n, val, base);
2496 return BC_STATUS_SUCCESS;
2499 static BcStatus bc_num_print(BcNum *n, BcNum *base, size_t base_t, bool newline,
2500 size_t *nchars, size_t line_len)
2502 BcStatus s = BC_STATUS_SUCCESS;
2504 bc_num_printNewline(nchars, line_len);
2510 else if (base_t == 10)
2511 bc_num_printDecimal(n, nchars, line_len);
2513 s = bc_num_printBase(n, base, base_t, nchars, line_len);
2523 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2525 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2527 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2530 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2532 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2534 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2537 static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2539 size_t req = BC_NUM_MREQ(a, b, scale);
2540 return bc_num_binary(a, b, c, scale, bc_num_m, req);
2543 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2545 size_t req = BC_NUM_MREQ(a, b, scale);
2546 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2549 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2551 size_t req = BC_NUM_MREQ(a, b, scale);
2552 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2555 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2557 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2560 static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2563 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2564 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2565 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2567 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2568 bc_num_expand(b, req);
2571 bc_num_setToZero(b, scale);
2572 return BC_STATUS_SUCCESS;
2575 return bc_error("negative number");
2576 else if (BC_NUM_ONE(a)) {
2578 bc_num_extend(b, scale);
2579 return BC_STATUS_SUCCESS;
2582 scale = BC_MAX(scale, a->rdx) + 1;
2583 len = a->len + scale;
2585 bc_num_init(&num1, len);
2586 bc_num_init(&num2, len);
2587 bc_num_init(&half, BC_NUM_DEF_SIZE);
2593 bc_num_init(&f, len);
2594 bc_num_init(&fprime, len);
2600 pow = BC_NUM_INT(a);
2609 pow -= 2 - (pow & 1);
2611 bc_num_extend(x0, pow);
2613 // Make sure to move the radix back.
2617 x0->rdx = digs = digs1 = 0;
2619 len = BC_NUM_INT(x0) + resrdx - 1;
2621 while (cmp != 0 || digs < len) {
2623 s = bc_num_div(a, x0, &f, resrdx);
2625 s = bc_num_add(x0, &f, &fprime, resrdx);
2627 s = bc_num_mul(&fprime, &half, x1, resrdx);
2630 cmp = bc_num_cmp(x1, x0);
2631 digs = x1->len - (unsigned long long) llabs(cmp);
2633 if (cmp == cmp2 && digs == digs1)
2638 resrdx += times > 4;
2651 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2654 bc_num_free(&fprime);
2662 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2668 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2671 memcpy(&num2, c, sizeof(BcNum));
2673 bc_num_init(c, len);
2678 bc_num_expand(c, len);
2681 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2683 if (init) bc_num_free(&num2);
2689 static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2692 BcNum base, exp, two, temp;
2695 return bc_error("divide by zero");
2696 if (a->rdx || b->rdx || c->rdx)
2697 return bc_error("non integer number");
2699 return bc_error("negative number");
2701 bc_num_expand(d, c->len);
2702 bc_num_init(&base, c->len);
2703 bc_num_init(&exp, b->len);
2704 bc_num_init(&two, BC_NUM_DEF_SIZE);
2705 bc_num_init(&temp, b->len);
2711 s = bc_num_rem(a, c, &base, 0);
2713 bc_num_copy(&exp, b);
2715 while (exp.len != 0) {
2717 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2720 if (BC_NUM_ONE(&temp)) {
2721 s = bc_num_mul(d, &base, &temp, 0);
2723 s = bc_num_rem(&temp, c, d, 0);
2727 s = bc_num_mul(&base, &base, &temp, 0);
2729 s = bc_num_rem(&temp, c, &base, 0);
2743 static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2748 for (i = 0; i < f->autos.len; ++i) {
2749 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2750 return bc_error("function parameter or auto var has the same name as another");
2756 bc_vec_push(&f->autos, &a);
2758 return BC_STATUS_SUCCESS;
2762 static void bc_func_init(BcFunc *f)
2764 bc_char_vec_init(&f->code);
2765 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2766 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2770 static void bc_func_free(void *func)
2772 BcFunc *f = (BcFunc *) func;
2773 bc_vec_free(&f->code);
2774 bc_vec_free(&f->autos);
2775 bc_vec_free(&f->labels);
2778 static void bc_array_expand(BcVec *a, size_t len);
2780 static void bc_array_init(BcVec *a, bool nums)
2783 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2785 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2786 bc_array_expand(a, 1);
2789 static void bc_array_expand(BcVec *a, size_t len)
2793 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2794 while (len > a->len) {
2795 bc_num_init(&data.n, BC_NUM_DEF_SIZE);
2796 bc_vec_push(a, &data.n);
2800 while (len > a->len) {
2801 bc_array_init(&data.v, true);
2802 bc_vec_push(a, &data.v);
2807 static void bc_array_copy(BcVec *d, const BcVec *s)
2812 bc_vec_expand(d, s->cap);
2815 for (i = 0; i < s->len; ++i) {
2816 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2817 bc_num_init(dnum, snum->len);
2818 bc_num_copy(dnum, snum);
2822 static void bc_string_free(void *string)
2824 free(*((char **) string));
2828 static void bc_result_copy(BcResult *d, BcResult *src)
2834 case BC_RESULT_TEMP:
2835 case BC_RESULT_IBASE:
2836 case BC_RESULT_SCALE:
2837 case BC_RESULT_OBASE:
2839 bc_num_init(&d->d.n, src->d.n.len);
2840 bc_num_copy(&d->d.n, &src->d.n);
2845 case BC_RESULT_ARRAY:
2846 case BC_RESULT_ARRAY_ELEM:
2848 d->d.id.name = xstrdup(src->d.id.name);
2852 case BC_RESULT_CONSTANT:
2853 case BC_RESULT_LAST:
2857 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2864 static void bc_result_free(void *result)
2866 BcResult *r = (BcResult *) result;
2870 case BC_RESULT_TEMP:
2871 case BC_RESULT_IBASE:
2872 case BC_RESULT_SCALE:
2873 case BC_RESULT_OBASE:
2875 bc_num_free(&r->d.n);
2880 case BC_RESULT_ARRAY:
2881 case BC_RESULT_ARRAY_ELEM:
2895 static void bc_lex_lineComment(BcLex *l)
2897 l->t.t = BC_LEX_WHITESPACE;
2898 while (l->i < l->len && l->buf[l->i++] != '\n');
2902 static void bc_lex_whitespace(BcLex *l)
2905 l->t.t = BC_LEX_WHITESPACE;
2906 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2909 static BcStatus bc_lex_number(BcLex *l, char start)
2911 const char *buf = l->buf + l->i;
2912 size_t len, hits = 0, bslashes = 0, i = 0, j;
2914 bool last_pt, pt = start == '.';
2917 l->t.t = BC_LEX_NUMBER;
2919 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2920 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2934 len = i + !last_pt - bslashes * 2;
2935 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2936 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2937 if (len > BC_MAX_NUM)
2938 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2941 bc_vec_pop_all(&l->t.v);
2942 bc_vec_expand(&l->t.v, len + 1);
2943 bc_vec_push(&l->t.v, &start);
2945 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2949 // If we have hit a backslash, skip it. We don't have
2950 // to check for a newline because it's guaranteed.
2951 if (hits < bslashes && c == '\\') {
2957 bc_vec_push(&l->t.v, &c);
2960 bc_vec_pushZeroByte(&l->t.v);
2963 return BC_STATUS_SUCCESS;
2966 static BcStatus bc_lex_name(BcLex *l)
2969 const char *buf = l->buf + l->i - 1;
2972 l->t.t = BC_LEX_NAME;
2974 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2976 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2977 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2978 if (i > BC_MAX_STRING)
2979 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2981 bc_vec_string(&l->t.v, i, buf);
2983 // Increment the index. We minus 1 because it has already been incremented.
2986 return BC_STATUS_SUCCESS;
2989 static void bc_lex_init(BcLex *l, BcLexNext next)
2992 bc_char_vec_init(&l->t.v);
2995 static void bc_lex_free(BcLex *l)
2997 bc_vec_free(&l->t.v);
3000 static void bc_lex_file(BcLex *l)
3002 G.err_line = l->line = 1;
3006 static BcStatus bc_lex_next(BcLex *l)
3011 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
3013 l->line += l->newline;
3014 G.err_line = l->line;
3015 l->t.t = BC_LEX_EOF;
3017 l->newline = (l->i == l->len);
3018 if (l->newline) return BC_STATUS_SUCCESS;
3020 // Loop until failure or we don't have whitespace. This
3021 // is so the parser doesn't get inundated with whitespace.
3024 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3029 static BcStatus bc_lex_text(BcLex *l, const char *text)
3033 l->len = strlen(text);
3034 l->t.t = l->t.last = BC_LEX_INVALID;
3035 return bc_lex_next(l);
3039 static BcStatus bc_lex_identifier(BcLex *l)
3043 const char *buf = l->buf + l->i - 1;
3045 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3046 const char *keyword8 = bc_lex_kws[i].name8;
3048 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3050 if (j == 8) goto match;
3052 if (keyword8[j] != '\0')
3055 // buf starts with keyword bc_lex_kws[i]
3056 l->t.t = BC_LEX_KEY_1st_keyword + i;
3057 if (!bc_lex_kws_POSIX(i)) {
3058 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3062 // We minus 1 because the index has already been incremented.
3064 return BC_STATUS_SUCCESS;
3070 if (l->t.v.len > 2) {
3073 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3075 unsigned len = strchrnul(buf, '\n') - buf;
3076 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3082 static BcStatus bc_lex_string(BcLex *l)
3084 size_t len, nls = 0, i = l->i;
3087 l->t.t = BC_LEX_STR;
3089 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3093 return bc_error("string end could not be found");
3097 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3098 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3099 if (len > BC_MAX_STRING)
3100 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3102 bc_vec_string(&l->t.v, len, l->buf + l->i);
3106 G.err_line = l->line;
3108 return BC_STATUS_SUCCESS;
3111 static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3113 if (l->buf[l->i] == '=') {
3121 static BcStatus bc_lex_comment(BcLex *l)
3124 const char *buf = l->buf;
3126 l->t.t = BC_LEX_WHITESPACE;
3139 return bc_error("comment end could not be found");
3147 G.err_line = l->line;
3149 return BC_STATUS_SUCCESS;
3152 static BcStatus bc_lex_token(BcLex *l)
3154 BcStatus s = BC_STATUS_SUCCESS;
3155 char c = l->buf[l->i++], c2;
3157 // This is the workhorse of the lexer.
3164 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3174 bc_lex_whitespace(l);
3180 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3182 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
3183 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3192 s = bc_lex_string(l);
3198 s = bc_POSIX_does_not_allow("'#' script comments");
3201 bc_lex_lineComment(l);
3208 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3217 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3221 l->t.t = BC_LEX_OP_BOOL_AND;
3224 l->t.t = BC_LEX_INVALID;
3225 s = bc_error_bad_character('&');
3234 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3240 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3249 l->t.t = BC_LEX_OP_INC;
3252 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3258 l->t.t = BC_LEX_COMMA;
3267 l->t.t = BC_LEX_OP_DEC;
3270 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3276 if (isdigit(l->buf[l->i]))
3277 s = bc_lex_number(l, c);
3279 l->t.t = BC_LEX_KEY_LAST;
3280 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3289 s = bc_lex_comment(l);
3291 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3312 s = bc_lex_number(l, c);
3318 l->t.t = BC_LEX_SCOLON;
3324 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3330 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3336 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3343 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3349 if (l->buf[l->i] == '\n') {
3350 l->t.t = BC_LEX_WHITESPACE;
3354 s = bc_error_bad_character(c);
3360 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3391 s = bc_lex_identifier(l);
3398 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3407 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3411 l->t.t = BC_LEX_OP_BOOL_OR;
3414 l->t.t = BC_LEX_INVALID;
3415 s = bc_error_bad_character(c);
3423 l->t.t = BC_LEX_INVALID;
3424 s = bc_error_bad_character(c);
3434 static BcStatus dc_lex_register(BcLex *l)
3436 BcStatus s = BC_STATUS_SUCCESS;
3438 if (isspace(l->buf[l->i - 1])) {
3439 bc_lex_whitespace(l);
3442 s = bc_error("extended register");
3447 bc_vec_pop_all(&l->t.v);
3448 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
3449 bc_vec_pushZeroByte(&l->t.v);
3450 l->t.t = BC_LEX_NAME;
3456 static BcStatus dc_lex_string(BcLex *l)
3458 size_t depth = 1, nls = 0, i = l->i;
3461 l->t.t = BC_LEX_STR;
3462 bc_vec_pop_all(&l->t.v);
3464 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3466 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3467 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3470 if (depth) bc_vec_push(&l->t.v, &c);
3475 return bc_error("string end could not be found");
3478 bc_vec_pushZeroByte(&l->t.v);
3479 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3480 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3481 if (i - l->i > BC_MAX_STRING)
3482 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3487 G.err_line = l->line;
3489 return BC_STATUS_SUCCESS;
3492 static BcStatus dc_lex_token(BcLex *l)
3494 BcStatus s = BC_STATUS_SUCCESS;
3495 char c = l->buf[l->i++], c2;
3498 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3499 if (l->t.last == dc_lex_regs[i])
3500 return dc_lex_register(l);
3503 if (c >= '%' && c <= '~' &&
3504 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3509 // This is the workhorse of the lexer.
3514 l->t.t = BC_LEX_EOF;
3525 l->newline = (c == '\n');
3526 bc_lex_whitespace(l);
3535 l->t.t = BC_LEX_OP_REL_NE;
3537 l->t.t = BC_LEX_OP_REL_LE;
3539 l->t.t = BC_LEX_OP_REL_GE;
3541 return bc_error_bad_character(c);
3549 bc_lex_lineComment(l);
3555 if (isdigit(l->buf[l->i]))
3556 s = bc_lex_number(l, c);
3558 s = bc_error_bad_character(c);
3579 s = bc_lex_number(l, c);
3585 s = dc_lex_string(l);
3591 l->t.t = BC_LEX_INVALID;
3592 s = bc_error_bad_character(c);
3601 static void bc_program_addFunc(char *name, size_t *idx);
3603 static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3605 bc_program_addFunc(name, idx);
3606 p->func = bc_vec_item(&G.prog.fns, p->fidx);
3609 #define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3611 static void bc_parse_pushName(BcParse *p, char *name)
3613 size_t i = 0, len = strlen(name);
3615 for (; i < len; ++i) bc_parse_push(p, name[i]);
3616 bc_parse_push(p, BC_PARSE_STREND);
3621 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3623 unsigned char amt, i, nums[sizeof(size_t)];
3625 for (amt = 0; idx; ++amt) {
3626 nums[amt] = (char) idx;
3627 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3630 bc_parse_push(p, amt);
3631 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3634 static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3636 char *num = xstrdup(p->l.t.v.v);
3637 size_t idx = G.prog.consts.len;
3639 bc_vec_push(&G.prog.consts, &num);
3641 bc_parse_push(p, BC_INST_NUM);
3642 bc_parse_pushIndex(p, idx);
3645 (*prev) = BC_INST_NUM;
3648 static BcStatus bc_parse_text(BcParse *p, const char *text)
3652 p->func = bc_vec_item(&G.prog.fns, p->fidx);
3654 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
3655 p->l.t.t = BC_LEX_INVALID;
3658 if (!BC_PARSE_CAN_EXEC(p))
3659 return bc_error("file is not executable");
3662 return bc_lex_text(&p->l, text);
3665 // Called when parsing or execution detects a failure,
3666 // resets execution structures.
3667 static void bc_program_reset(void)
3672 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3673 bc_vec_pop_all(&G.prog.results);
3675 f = bc_vec_item(&G.prog.fns, 0);
3676 ip = bc_vec_top(&G.prog.stack);
3677 ip->idx = f->code.len;
3680 #define bc_parse_updateFunc(p, f) \
3681 ((p)->func = bc_vec_item(&G.prog.fns, ((p)->fidx = (f))))
3683 // Called when bc/dc_parse_parse() detects a failure,
3684 // resets parsing structures.
3685 static void bc_parse_reset(BcParse *p)
3687 if (p->fidx != BC_PROG_MAIN) {
3688 p->func->nparams = 0;
3689 bc_vec_pop_all(&p->func->code);
3690 bc_vec_pop_all(&p->func->autos);
3691 bc_vec_pop_all(&p->func->labels);
3693 bc_parse_updateFunc(p, BC_PROG_MAIN);
3697 p->l.t.t = BC_LEX_EOF;
3698 p->auto_part = (p->nbraces = 0);
3700 bc_vec_npop(&p->flags, p->flags.len - 1);
3701 bc_vec_pop_all(&p->exits);
3702 bc_vec_pop_all(&p->conds);
3703 bc_vec_pop_all(&p->ops);
3708 static void bc_parse_free(BcParse *p)
3710 bc_vec_free(&p->flags);
3711 bc_vec_free(&p->exits);
3712 bc_vec_free(&p->conds);
3713 bc_vec_free(&p->ops);
3717 static void bc_parse_create(BcParse *p, size_t func,
3718 BcParseParse parse, BcLexNext next)
3720 memset(p, 0, sizeof(BcParse));
3722 bc_lex_init(&p->l, next);
3723 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3724 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3725 bc_vec_init(&p->conds, sizeof(size_t), NULL);
3726 bc_vec_pushZeroByte(&p->flags);
3727 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3730 // p->auto_part = p->nbraces = 0; - already is
3731 bc_parse_updateFunc(p, func);
3736 #define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3737 #define BC_PARSE_LEAF(p, rparen) \
3738 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3739 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3741 // We can calculate the conversion between tokens and exprs by subtracting the
3742 // position of the first operator in the lex enum and adding the position of the
3743 // first in the expr enum. Note: This only works for binary operators.
3744 #define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3746 static BcStatus bc_parse_else(BcParse *p);
3747 static BcStatus bc_parse_stmt(BcParse *p);
3748 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
3749 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
3751 static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3752 size_t *nexprs, bool next)
3754 BcStatus s = BC_STATUS_SUCCESS;
3756 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3757 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
3759 while (p->ops.len > start) {
3761 t = BC_PARSE_TOP_OP(p);
3762 if (t == BC_LEX_LPAREN) break;
3764 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
3765 if (l >= r && (l != r || !left)) break;
3767 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3768 bc_vec_pop(&p->ops);
3769 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3772 bc_vec_push(&p->ops, &type);
3773 if (next) s = bc_lex_next(&p->l);
3778 static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3782 if (p->ops.len <= ops_bgn)
3783 return bc_error_bad_expression();
3784 top = BC_PARSE_TOP_OP(p);
3786 while (top != BC_LEX_LPAREN) {
3788 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3790 bc_vec_pop(&p->ops);
3791 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3793 if (p->ops.len <= ops_bgn)
3794 return bc_error_bad_expression();
3795 top = BC_PARSE_TOP_OP(p);
3798 bc_vec_pop(&p->ops);
3800 return bc_lex_next(&p->l);
3803 static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3809 s = bc_lex_next(&p->l);
3812 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3814 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3815 s = bc_parse_expr(p, flags, bc_parse_next_param);
3818 comma = p->l.t.t == BC_LEX_COMMA;
3820 s = bc_lex_next(&p->l);
3825 if (comma) return bc_error_bad_token();
3826 bc_parse_push(p, BC_INST_CALL);
3827 bc_parse_pushIndex(p, nparams);
3829 return BC_STATUS_SUCCESS;
3832 static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3835 BcId entry, *entry_ptr;
3840 s = bc_parse_params(p, flags);
3843 if (p->l.t.t != BC_LEX_RPAREN) {
3844 s = bc_error_bad_token();
3848 idx = bc_map_index(&G.prog.fn_map, &entry);
3850 if (idx == BC_VEC_INVALID_IDX) {
3851 name = xstrdup(entry.name);
3852 bc_parse_addFunc(p, name, &idx);
3853 idx = bc_map_index(&G.prog.fn_map, &entry);
3859 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3860 bc_parse_pushIndex(p, entry_ptr->idx);
3862 return bc_lex_next(&p->l);
3869 static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3874 name = xstrdup(p->l.t.v.v);
3875 s = bc_lex_next(&p->l);
3878 if (p->l.t.t == BC_LEX_LBRACKET) {
3880 s = bc_lex_next(&p->l);
3883 if (p->l.t.t == BC_LEX_RBRACKET) {
3885 if (!(flags & BC_PARSE_ARRAY)) {
3886 s = bc_error_bad_expression();
3890 *type = BC_INST_ARRAY;
3894 *type = BC_INST_ARRAY_ELEM;
3896 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3897 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3901 s = bc_lex_next(&p->l);
3903 bc_parse_push(p, *type);
3904 bc_parse_pushName(p, name);
3906 else if (p->l.t.t == BC_LEX_LPAREN) {
3908 if (flags & BC_PARSE_NOCALL) {
3909 s = bc_error_bad_token();
3913 *type = BC_INST_CALL;
3914 s = bc_parse_call(p, name, flags);
3917 *type = BC_INST_VAR;
3918 bc_parse_push(p, BC_INST_VAR);
3919 bc_parse_pushName(p, name);
3929 static BcStatus bc_parse_read(BcParse *p)
3933 s = bc_lex_next(&p->l);
3935 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3937 s = bc_lex_next(&p->l);
3939 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3941 bc_parse_push(p, BC_INST_READ);
3943 return bc_lex_next(&p->l);
3946 static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3951 s = bc_lex_next(&p->l);
3953 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3955 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3957 s = bc_lex_next(&p->l);
3960 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3963 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3965 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3966 bc_parse_push(p, *prev);
3968 return bc_lex_next(&p->l);
3971 static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3975 s = bc_lex_next(&p->l);
3978 if (p->l.t.t != BC_LEX_LPAREN) {
3979 *type = BC_INST_SCALE;
3980 bc_parse_push(p, BC_INST_SCALE);
3981 return BC_STATUS_SUCCESS;
3984 *type = BC_INST_SCALE_FUNC;
3985 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3987 s = bc_lex_next(&p->l);
3990 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3992 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3993 bc_parse_push(p, BC_INST_SCALE_FUNC);
3995 return bc_lex_next(&p->l);
3998 static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
3999 size_t *nexprs, uint8_t flags)
4004 BcInst etype = *prev;
4006 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4007 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4008 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4010 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4011 bc_parse_push(p, inst);
4012 s = bc_lex_next(&p->l);
4016 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4019 s = bc_lex_next(&p->l);
4023 // Because we parse the next part of the expression
4024 // right here, we need to increment this.
4025 *nexprs = *nexprs + 1;
4031 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4035 case BC_LEX_KEY_IBASE:
4036 case BC_LEX_KEY_LAST:
4037 case BC_LEX_KEY_OBASE:
4039 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4040 s = bc_lex_next(&p->l);
4044 case BC_LEX_KEY_SCALE:
4046 s = bc_lex_next(&p->l);
4048 if (p->l.t.t == BC_LEX_LPAREN)
4049 s = bc_error_bad_token();
4051 bc_parse_push(p, BC_INST_SCALE);
4057 s = bc_error_bad_token();
4062 if (!s) bc_parse_push(p, inst);
4068 static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4069 bool rparen, size_t *nexprs)
4073 BcInst etype = *prev;
4075 s = bc_lex_next(&p->l);
4078 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4079 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4082 *prev = BC_PARSE_TOKEN_INST(type);
4084 // We can just push onto the op stack because this is the largest
4085 // precedence operator that gets pushed. Inc/dec does not.
4086 if (type != BC_LEX_OP_MINUS)
4087 bc_vec_push(&p->ops, &type);
4089 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4094 static BcStatus bc_parse_string(BcParse *p, char inst)
4096 char *str = xstrdup(p->l.t.v.v);
4098 bc_parse_push(p, BC_INST_STR);
4099 bc_parse_pushIndex(p, G.prog.strs.len);
4100 bc_vec_push(&G.prog.strs, &str);
4101 bc_parse_push(p, inst);
4103 return bc_lex_next(&p->l);
4106 static BcStatus bc_parse_print(BcParse *p)
4112 s = bc_lex_next(&p->l);
4117 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
4118 return bc_error("bad print statement");
4120 while (!s && type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4122 if (type == BC_LEX_STR)
4123 s = bc_parse_string(p, BC_INST_PRINT_POP);
4125 s = bc_parse_expr(p, 0, bc_parse_next_print);
4127 bc_parse_push(p, BC_INST_PRINT_POP);
4132 comma = p->l.t.t == BC_LEX_COMMA;
4133 if (comma) s = bc_lex_next(&p->l);
4138 if (comma) return bc_error_bad_token();
4140 return bc_lex_next(&p->l);
4143 static BcStatus bc_parse_return(BcParse *p)
4149 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
4151 s = bc_lex_next(&p->l);
4155 paren = t == BC_LEX_LPAREN;
4157 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4158 bc_parse_push(p, BC_INST_RET0);
4161 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
4162 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4163 bc_parse_push(p, BC_INST_RET0);
4164 s = bc_lex_next(&p->l);
4168 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
4169 s = bc_POSIX_requires("parentheses around return expressions");
4173 bc_parse_push(p, BC_INST_RET);
4179 static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4181 BcStatus s = BC_STATUS_SUCCESS;
4183 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
4184 return bc_error_bad_token();
4188 if (p->l.t.t == BC_LEX_RBRACE) {
4189 if (!p->nbraces) return bc_error_bad_token();
4191 s = bc_lex_next(&p->l);
4195 return bc_error_bad_token();
4198 if (BC_PARSE_IF(p)) {
4202 while (p->l.t.t == BC_LEX_NLINE) {
4203 s = bc_lex_next(&p->l);
4207 bc_vec_pop(&p->flags);
4209 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4210 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4212 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4214 else if (BC_PARSE_ELSE(p)) {
4219 bc_vec_pop(&p->flags);
4221 ip = bc_vec_top(&p->exits);
4222 label = bc_vec_item(&p->func->labels, ip->idx);
4223 *label = p->func->code.len;
4225 bc_vec_pop(&p->exits);
4227 else if (BC_PARSE_FUNC_INNER(p)) {
4228 bc_parse_push(p, BC_INST_RET0);
4229 bc_parse_updateFunc(p, BC_PROG_MAIN);
4230 bc_vec_pop(&p->flags);
4234 BcInstPtr *ip = bc_vec_top(&p->exits);
4235 size_t *label = bc_vec_top(&p->conds);
4237 bc_parse_push(p, BC_INST_JUMP);
4238 bc_parse_pushIndex(p, *label);
4240 label = bc_vec_item(&p->func->labels, ip->idx);
4241 *label = p->func->code.len;
4243 bc_vec_pop(&p->flags);
4244 bc_vec_pop(&p->exits);
4245 bc_vec_pop(&p->conds);
4251 static void bc_parse_startBody(BcParse *p, uint8_t flags)
4253 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4254 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4255 flags |= BC_PARSE_FLAG_BODY;
4256 bc_vec_push(&p->flags, &flags);
4259 static void bc_parse_noElse(BcParse *p)
4263 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4265 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4267 ip = bc_vec_top(&p->exits);
4268 label = bc_vec_item(&p->func->labels, ip->idx);
4269 *label = p->func->code.len;
4271 bc_vec_pop(&p->exits);
4274 static BcStatus bc_parse_if(BcParse *p)
4279 s = bc_lex_next(&p->l);
4281 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4283 s = bc_lex_next(&p->l);
4285 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4287 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4289 s = bc_lex_next(&p->l);
4291 bc_parse_push(p, BC_INST_JUMP_ZERO);
4293 ip.idx = p->func->labels.len;
4294 ip.func = ip.len = 0;
4296 bc_parse_pushIndex(p, ip.idx);
4297 bc_vec_push(&p->exits, &ip);
4298 bc_vec_push(&p->func->labels, &ip.idx);
4299 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4301 return BC_STATUS_SUCCESS;
4304 static BcStatus bc_parse_else(BcParse *p)
4308 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
4310 ip.idx = p->func->labels.len;
4311 ip.func = ip.len = 0;
4313 bc_parse_push(p, BC_INST_JUMP);
4314 bc_parse_pushIndex(p, ip.idx);
4318 bc_vec_push(&p->exits, &ip);
4319 bc_vec_push(&p->func->labels, &ip.idx);
4320 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4322 return bc_lex_next(&p->l);
4325 static BcStatus bc_parse_while(BcParse *p)
4330 s = bc_lex_next(&p->l);
4332 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4333 s = bc_lex_next(&p->l);
4336 ip.idx = p->func->labels.len;
4338 bc_vec_push(&p->func->labels, &p->func->code.len);
4339 bc_vec_push(&p->conds, &ip.idx);
4341 ip.idx = p->func->labels.len;
4345 bc_vec_push(&p->exits, &ip);
4346 bc_vec_push(&p->func->labels, &ip.idx);
4348 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4350 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4351 s = bc_lex_next(&p->l);
4354 bc_parse_push(p, BC_INST_JUMP_ZERO);
4355 bc_parse_pushIndex(p, ip.idx);
4356 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4358 return BC_STATUS_SUCCESS;
4361 static BcStatus bc_parse_for(BcParse *p)
4365 size_t cond_idx, exit_idx, body_idx, update_idx;
4367 s = bc_lex_next(&p->l);
4369 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4370 s = bc_lex_next(&p->l);
4373 if (p->l.t.t != BC_LEX_SCOLON)
4374 s = bc_parse_expr(p, 0, bc_parse_next_for);
4376 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4379 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4380 s = bc_lex_next(&p->l);
4383 cond_idx = p->func->labels.len;
4384 update_idx = cond_idx + 1;
4385 body_idx = update_idx + 1;
4386 exit_idx = body_idx + 1;
4388 bc_vec_push(&p->func->labels, &p->func->code.len);
4390 if (p->l.t.t != BC_LEX_SCOLON)
4391 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4393 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4396 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4398 s = bc_lex_next(&p->l);
4401 bc_parse_push(p, BC_INST_JUMP_ZERO);
4402 bc_parse_pushIndex(p, exit_idx);
4403 bc_parse_push(p, BC_INST_JUMP);
4404 bc_parse_pushIndex(p, body_idx);
4406 ip.idx = p->func->labels.len;
4408 bc_vec_push(&p->conds, &update_idx);
4409 bc_vec_push(&p->func->labels, &p->func->code.len);
4411 if (p->l.t.t != BC_LEX_RPAREN)
4412 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4414 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4418 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4419 bc_parse_push(p, BC_INST_JUMP);
4420 bc_parse_pushIndex(p, cond_idx);
4421 bc_vec_push(&p->func->labels, &p->func->code.len);
4427 bc_vec_push(&p->exits, &ip);
4428 bc_vec_push(&p->func->labels, &ip.idx);
4430 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4432 return BC_STATUS_SUCCESS;
4435 static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4441 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
4443 if (type == BC_LEX_KEY_BREAK) {
4445 if (p->exits.len == 0) return bc_error_bad_token();
4447 i = p->exits.len - 1;
4448 ip = bc_vec_item(&p->exits, i);
4450 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
4451 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
4456 i = *((size_t *) bc_vec_top(&p->conds));
4458 bc_parse_push(p, BC_INST_JUMP);
4459 bc_parse_pushIndex(p, i);
4461 s = bc_lex_next(&p->l);
4464 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
4465 return bc_error_bad_token();
4467 return bc_lex_next(&p->l);
4470 static BcStatus bc_parse_func(BcParse *p)
4473 bool var, comma = false;
4477 s = bc_lex_next(&p->l);
4479 if (p->l.t.t != BC_LEX_NAME)
4480 return bc_error("bad function definition");
4482 name = xstrdup(p->l.t.v.v);
4483 bc_parse_addFunc(p, name, &p->fidx);
4485 s = bc_lex_next(&p->l);
4487 if (p->l.t.t != BC_LEX_LPAREN)
4488 return bc_error("bad function definition");
4489 s = bc_lex_next(&p->l);
4492 while (p->l.t.t != BC_LEX_RPAREN) {
4494 if (p->l.t.t != BC_LEX_NAME)
4495 return bc_error("bad function definition");
4499 name = xstrdup(p->l.t.v.v);
4500 s = bc_lex_next(&p->l);
4503 var = p->l.t.t != BC_LEX_LBRACKET;
4507 s = bc_lex_next(&p->l);
4510 if (p->l.t.t != BC_LEX_RBRACKET) {
4511 s = bc_error("bad function definition");
4515 s = bc_lex_next(&p->l);
4519 comma = p->l.t.t == BC_LEX_COMMA;
4521 s = bc_lex_next(&p->l);
4525 s = bc_func_insert(p->func, name, var);
4529 if (comma) return bc_error("bad function definition");
4531 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4532 bc_parse_startBody(p, flags);
4534 s = bc_lex_next(&p->l);
4537 if (p->l.t.t != BC_LEX_LBRACE)
4538 s = bc_POSIX_requires("the left brace be on the same line as the function header");
4547 static BcStatus bc_parse_auto(BcParse *p)
4550 bool comma, var, one;
4553 if (!p->auto_part) return bc_error_bad_token();
4554 s = bc_lex_next(&p->l);
4557 p->auto_part = comma = false;
4558 one = p->l.t.t == BC_LEX_NAME;
4560 while (p->l.t.t == BC_LEX_NAME) {
4562 name = xstrdup(p->l.t.v.v);
4563 s = bc_lex_next(&p->l);
4566 var = p->l.t.t != BC_LEX_LBRACKET;
4569 s = bc_lex_next(&p->l);
4572 if (p->l.t.t != BC_LEX_RBRACKET) {
4573 s = bc_error("bad function definition");
4577 s = bc_lex_next(&p->l);
4581 comma = p->l.t.t == BC_LEX_COMMA;
4583 s = bc_lex_next(&p->l);
4587 s = bc_func_insert(p->func, name, var);
4591 if (comma) return bc_error("bad function definition");
4592 if (!one) return bc_error("no auto variable found");
4594 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
4595 return bc_error_bad_token();
4597 return bc_lex_next(&p->l);
4604 static BcStatus bc_parse_body(BcParse *p, bool brace)
4606 BcStatus s = BC_STATUS_SUCCESS;
4607 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4609 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4611 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4613 if (!brace) return bc_error_bad_token();
4614 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4616 if (!p->auto_part) {
4617 s = bc_parse_auto(p);
4621 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4624 s = bc_parse_stmt(p);
4625 if (!s && !brace) s = bc_parse_endBody(p, false);
4631 static BcStatus bc_parse_stmt(BcParse *p)
4633 BcStatus s = BC_STATUS_SUCCESS;
4639 return bc_lex_next(&p->l);
4642 case BC_LEX_KEY_ELSE:
4644 p->auto_part = false;
4650 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
4653 s = bc_lex_next(&p->l);
4656 return bc_parse_body(p, true);
4659 case BC_LEX_KEY_AUTO:
4661 return bc_parse_auto(p);
4666 p->auto_part = false;
4668 if (BC_PARSE_IF_END(p)) {
4670 return BC_STATUS_SUCCESS;
4672 else if (BC_PARSE_BODY(p))
4673 return bc_parse_body(p, false);
4683 case BC_LEX_OP_MINUS:
4684 case BC_LEX_OP_BOOL_NOT:
4688 case BC_LEX_KEY_IBASE:
4689 case BC_LEX_KEY_LAST:
4690 case BC_LEX_KEY_LENGTH:
4691 case BC_LEX_KEY_OBASE:
4692 case BC_LEX_KEY_READ:
4693 case BC_LEX_KEY_SCALE:
4694 case BC_LEX_KEY_SQRT:
4696 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4700 case BC_LEX_KEY_ELSE:
4702 s = bc_parse_else(p);
4708 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4714 s = bc_parse_endBody(p, true);
4720 s = bc_parse_string(p, BC_INST_PRINT_STR);
4724 case BC_LEX_KEY_BREAK:
4725 case BC_LEX_KEY_CONTINUE:
4727 s = bc_parse_loopExit(p, p->l.t.t);
4731 case BC_LEX_KEY_FOR:
4733 s = bc_parse_for(p);
4737 case BC_LEX_KEY_HALT:
4739 bc_parse_push(p, BC_INST_HALT);
4740 s = bc_lex_next(&p->l);
4750 case BC_LEX_KEY_LIMITS:
4752 // "limits" is a compile-time command,
4753 // the output is produced at _parse time_.
4754 s = bc_lex_next(&p->l);
4757 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4758 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4759 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4760 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4761 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4762 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4763 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4764 "Number of vars = "BC_MAX_VARS_STR "\n"
4769 case BC_LEX_KEY_PRINT:
4771 s = bc_parse_print(p);
4775 case BC_LEX_KEY_QUIT:
4777 // "quit" is a compile-time command. For example,
4778 // "if (0 == 1) quit" terminates when parsing the statement,
4779 // not when it is executed
4780 QUIT_OR_RETURN_TO_MAIN;
4783 case BC_LEX_KEY_RETURN:
4785 s = bc_parse_return(p);
4789 case BC_LEX_KEY_WHILE:
4791 s = bc_parse_while(p);
4797 s = bc_error_bad_token();
4805 static BcStatus bc_parse_parse(BcParse *p)
4809 if (p->l.t.t == BC_LEX_EOF)
4810 s = p->flags.len > 0 ? bc_error("block end could not be found") : bc_error("end of file");
4811 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
4812 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
4813 s = bc_parse_func(p);
4816 s = bc_parse_stmt(p);
4818 if (s || G_interrupt) {
4820 s = BC_STATUS_FAILURE;
4826 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
4828 BcStatus s = BC_STATUS_SUCCESS;
4829 BcInst prev = BC_INST_PRINT;
4830 BcLexType top, t = p->l.t.t;
4831 size_t nexprs = 0, ops_bgn = p->ops.len;
4832 unsigned nparens, nrelops;
4833 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4835 paren_first = p->l.t.t == BC_LEX_LPAREN;
4836 nparens = nrelops = 0;
4837 paren_expr = rprn = done = get_token = assign = false;
4840 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
4846 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4847 rprn = get_token = bin_last = false;
4851 case BC_LEX_OP_MINUS:
4853 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4854 rprn = get_token = false;
4855 bin_last = prev == BC_INST_MINUS;
4859 case BC_LEX_OP_ASSIGN_POWER:
4860 case BC_LEX_OP_ASSIGN_MULTIPLY:
4861 case BC_LEX_OP_ASSIGN_DIVIDE:
4862 case BC_LEX_OP_ASSIGN_MODULUS:
4863 case BC_LEX_OP_ASSIGN_PLUS:
4864 case BC_LEX_OP_ASSIGN_MINUS:
4865 case BC_LEX_OP_ASSIGN:
4867 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4868 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4869 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4871 s = bc_error("bad assignment:"
4872 " left side must be scale,"
4873 " ibase, obase, last, var,"
4880 case BC_LEX_OP_POWER:
4881 case BC_LEX_OP_MULTIPLY:
4882 case BC_LEX_OP_DIVIDE:
4883 case BC_LEX_OP_MODULUS:
4884 case BC_LEX_OP_PLUS:
4885 case BC_LEX_OP_REL_EQ:
4886 case BC_LEX_OP_REL_LE:
4887 case BC_LEX_OP_REL_GE:
4888 case BC_LEX_OP_REL_NE:
4889 case BC_LEX_OP_REL_LT:
4890 case BC_LEX_OP_REL_GT:
4891 case BC_LEX_OP_BOOL_NOT:
4892 case BC_LEX_OP_BOOL_OR:
4893 case BC_LEX_OP_BOOL_AND:
4895 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4896 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4898 return bc_error_bad_expression();
4901 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4902 prev = BC_PARSE_TOKEN_INST(t);
4903 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4904 rprn = get_token = false;
4905 bin_last = t != BC_LEX_OP_BOOL_NOT;
4912 if (BC_PARSE_LEAF(prev, rprn))
4913 return bc_error_bad_expression();
4915 paren_expr = rprn = bin_last = false;
4917 bc_vec_push(&p->ops, &t);
4924 if (bin_last || prev == BC_INST_BOOL_NOT)
4925 return bc_error_bad_expression();
4928 s = BC_STATUS_SUCCESS;
4933 else if (!paren_expr)
4934 return BC_STATUS_PARSE_EMPTY_EXP;
4937 paren_expr = rprn = true;
4938 get_token = bin_last = false;
4940 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4947 if (BC_PARSE_LEAF(prev, rprn))
4948 return bc_error_bad_expression();
4950 rprn = get_token = bin_last = false;
4951 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4959 if (BC_PARSE_LEAF(prev, rprn))
4960 return bc_error_bad_expression();
4961 bc_parse_number(p, &prev, &nexprs);
4962 paren_expr = get_token = true;
4963 rprn = bin_last = false;
4968 case BC_LEX_KEY_IBASE:
4969 case BC_LEX_KEY_LAST:
4970 case BC_LEX_KEY_OBASE:
4972 if (BC_PARSE_LEAF(prev, rprn))
4973 return bc_error_bad_expression();
4974 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4975 bc_parse_push(p, (char) prev);
4977 paren_expr = get_token = true;
4978 rprn = bin_last = false;
4984 case BC_LEX_KEY_LENGTH:
4985 case BC_LEX_KEY_SQRT:
4987 if (BC_PARSE_LEAF(prev, rprn))
4988 return bc_error_bad_expression();
4989 s = bc_parse_builtin(p, t, flags, &prev);
4991 rprn = get_token = bin_last = false;
4997 case BC_LEX_KEY_READ:
4999 if (BC_PARSE_LEAF(prev, rprn))
5000 return bc_error_bad_expression();
5001 else if (flags & BC_PARSE_NOREAD)
5002 s = bc_error_nested_read_call();
5004 s = bc_parse_read(p);
5007 rprn = get_token = bin_last = false;
5009 prev = BC_INST_READ;
5014 case BC_LEX_KEY_SCALE:
5016 if (BC_PARSE_LEAF(prev, rprn))
5017 return bc_error_bad_expression();
5018 s = bc_parse_scale(p, &prev, flags);
5020 rprn = get_token = bin_last = false;
5022 prev = BC_INST_SCALE;
5029 s = bc_error_bad_token();
5034 if (!s && get_token) s = bc_lex_next(&p->l);
5038 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
5040 while (p->ops.len > ops_bgn) {
5042 top = BC_PARSE_TOP_OP(p);
5043 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5045 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
5046 return bc_error_bad_expression();
5048 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5050 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5051 bc_vec_pop(&p->ops);
5054 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
5055 return bc_error_bad_expression();
5057 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5059 if (t == (next & 0x7f))
5061 if (next & 0x80) // last element?
5065 return bc_error_bad_expression();
5068 if (!(flags & BC_PARSE_REL) && nrelops) {
5069 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
5072 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
5073 s = bc_POSIX_requires("exactly one comparison operator per condition");
5077 if (flags & BC_PARSE_PRINT) {
5078 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5079 bc_parse_push(p, BC_INST_POP);
5085 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5089 s = bc_parse_expr_empty_ok(p, flags, next);
5090 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5091 return bc_error("empty expression");
5095 static void bc_parse_init(BcParse *p, size_t func)
5097 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
5100 static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5102 return bc_parse_expr(p, flags, bc_parse_next_read);
5109 #define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5111 static BcStatus dc_parse_register(BcParse *p)
5116 s = bc_lex_next(&p->l);
5118 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
5120 name = xstrdup(p->l.t.v.v);
5121 bc_parse_pushName(p, name);
5126 static BcStatus dc_parse_string(BcParse *p)
5128 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
5129 size_t idx, len = G.prog.strs.len;
5131 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5134 str = xstrdup(p->l.t.v.v);
5135 bc_parse_push(p, BC_INST_STR);
5136 bc_parse_pushIndex(p, len);
5137 bc_vec_push(&G.prog.strs, &str);
5138 bc_parse_addFunc(p, name, &idx);
5140 return bc_lex_next(&p->l);
5143 static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5147 bc_parse_push(p, inst);
5149 s = dc_parse_register(p);
5154 bc_parse_push(p, BC_INST_SWAP);
5155 bc_parse_push(p, BC_INST_ASSIGN);
5156 bc_parse_push(p, BC_INST_POP);
5159 return bc_lex_next(&p->l);
5162 static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5166 bc_parse_push(p, inst);
5167 bc_parse_push(p, BC_INST_EXEC_COND);
5169 s = dc_parse_register(p);
5172 s = bc_lex_next(&p->l);
5175 if (p->l.t.t == BC_LEX_ELSE) {
5176 s = dc_parse_register(p);
5178 s = bc_lex_next(&p->l);
5181 bc_parse_push(p, BC_PARSE_STREND);
5186 static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5188 BcStatus s = BC_STATUS_SUCCESS;
5191 bool assign, get_token = false;
5195 case BC_LEX_OP_REL_EQ:
5196 case BC_LEX_OP_REL_LE:
5197 case BC_LEX_OP_REL_GE:
5198 case BC_LEX_OP_REL_NE:
5199 case BC_LEX_OP_REL_LT:
5200 case BC_LEX_OP_REL_GT:
5202 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5209 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5215 s = dc_parse_string(p);
5222 if (t == BC_LEX_NEG) {
5223 s = bc_lex_next(&p->l);
5225 if (p->l.t.t != BC_LEX_NUMBER)
5226 return bc_error_bad_token();
5229 bc_parse_number(p, &prev, &p->nbraces);
5231 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5237 case BC_LEX_KEY_READ:
5239 if (flags & BC_PARSE_NOREAD)
5240 s = bc_error_nested_read_call();
5242 bc_parse_push(p, BC_INST_READ);
5247 case BC_LEX_OP_ASSIGN:
5248 case BC_LEX_STORE_PUSH:
5250 assign = t == BC_LEX_OP_ASSIGN;
5251 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5252 s = dc_parse_mem(p, inst, true, assign);
5257 case BC_LEX_LOAD_POP:
5259 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5260 s = dc_parse_mem(p, inst, true, false);
5264 case BC_LEX_STORE_IBASE:
5265 case BC_LEX_STORE_SCALE:
5266 case BC_LEX_STORE_OBASE:
5268 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5269 s = dc_parse_mem(p, inst, false, true);
5275 s = bc_error_bad_token();
5281 if (!s && get_token) s = bc_lex_next(&p->l);
5286 static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5288 BcStatus s = BC_STATUS_SUCCESS;
5292 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
5294 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5296 inst = dc_parse_insts[t];
5298 if (inst != BC_INST_INVALID) {
5299 bc_parse_push(p, inst);
5300 s = bc_lex_next(&p->l);
5303 s = dc_parse_token(p, t, flags);
5306 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5307 bc_parse_push(p, BC_INST_POP_EXEC);
5312 static BcStatus dc_parse_parse(BcParse *p)
5316 if (p->l.t.t == BC_LEX_EOF)
5317 s = bc_error("end of file");
5319 s = dc_parse_expr(p, 0);
5321 if (s || G_interrupt) {
5323 s = BC_STATUS_FAILURE;
5329 static void dc_parse_init(BcParse *p, size_t func)
5331 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
5336 static void common_parse_init(BcParse *p, size_t func)
5339 IF_BC(bc_parse_init(p, func);)
5341 IF_DC(dc_parse_init(p, func);)
5345 static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5348 IF_BC(return bc_parse_expression(p, flags);)
5350 IF_DC(return dc_parse_expr(p, flags);)
5354 static BcVec* bc_program_search(char *id, bool var)
5362 v = var ? &G.prog.vars : &G.prog.arrs;
5363 map = var ? &G.prog.var_map : &G.prog.arr_map;
5367 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5370 bc_array_init(&data.v, var);
5371 bc_vec_push(v, &data.v);
5374 ptr = bc_vec_item(map, i);
5375 if (new) ptr->name = xstrdup(e.name);
5376 return bc_vec_item(v, ptr->idx);
5379 static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
5381 BcStatus s = BC_STATUS_SUCCESS;
5386 case BC_RESULT_TEMP:
5387 case BC_RESULT_IBASE:
5388 case BC_RESULT_SCALE:
5389 case BC_RESULT_OBASE:
5395 case BC_RESULT_CONSTANT:
5397 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
5398 size_t base_t, len = strlen(*str);
5401 bc_num_init(&r->d.n, len);
5403 hex = hex && len == 1;
5404 base = hex ? &G.prog.hexb : &G.prog.ib;
5405 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
5406 s = bc_num_parse(&r->d.n, *str, base, base_t);
5409 bc_num_free(&r->d.n);
5414 r->t = BC_RESULT_TEMP;
5420 case BC_RESULT_ARRAY:
5421 case BC_RESULT_ARRAY_ELEM:
5425 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
5427 if (r->t == BC_RESULT_ARRAY_ELEM) {
5429 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5430 *num = bc_vec_item(v, r->d.id.idx);
5433 *num = bc_vec_top(v);
5438 case BC_RESULT_LAST:
5440 *num = &G.prog.last;
5454 static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
5455 BcResult **r, BcNum **rn, bool assign)
5459 BcResultType lt, rt;
5461 if (!BC_PROG_STACK(&G.prog.results, 2))
5462 return bc_error_stack_has_too_few_elements();
5464 *r = bc_vec_item_rev(&G.prog.results, 0);
5465 *l = bc_vec_item_rev(&G.prog.results, 1);
5469 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5471 s = bc_program_num(*l, ln, false);
5473 s = bc_program_num(*r, rn, hex);
5476 // We run this again under these conditions in case any vector has been
5477 // reallocated out from under the BcNums or arrays we had.
5478 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
5479 s = bc_program_num(*l, ln, false);
5483 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
5484 return bc_error_variable_is_wrong_type();
5485 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5486 return bc_error_variable_is_wrong_type();
5491 static void bc_program_binOpRetire(BcResult *r)
5493 r->t = BC_RESULT_TEMP;
5494 bc_vec_pop(&G.prog.results);
5495 bc_vec_pop(&G.prog.results);
5496 bc_vec_push(&G.prog.results, r);
5499 static BcStatus bc_program_prep(BcResult **r, BcNum **n)
5503 if (!BC_PROG_STACK(&G.prog.results, 1))
5504 return bc_error_stack_has_too_few_elements();
5505 *r = bc_vec_top(&G.prog.results);
5507 s = bc_program_num(*r, n, false);
5510 if (!BC_PROG_NUM((*r), (*n)))
5511 return bc_error_variable_is_wrong_type();
5516 static void bc_program_retire(BcResult *r, BcResultType t)
5519 bc_vec_pop(&G.prog.results);
5520 bc_vec_push(&G.prog.results, r);
5523 static BcStatus bc_program_op(char inst)
5526 BcResult *opd1, *opd2, res;
5527 BcNum *n1, *n2 = NULL;
5529 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5531 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5533 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5535 bc_program_binOpRetire(&res);
5540 bc_num_free(&res.d.n);
5544 static BcStatus bc_program_read(void)
5546 const char *sv_file;
5552 BcFunc *f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
5554 for (i = 0; i < G.prog.stack.len; ++i) {
5555 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
5556 if (ip_ptr->func == BC_PROG_READ)
5557 return bc_error_nested_read_call();
5560 bc_vec_pop_all(&f->code);
5561 bc_char_vec_init(&buf);
5563 sv_file = G.prog.file;
5566 s = bc_read_line(&buf, "read> ");
5569 common_parse_init(&parse, BC_PROG_READ);
5570 bc_lex_file(&parse.l);
5572 s = bc_parse_text(&parse, buf.v);
5573 if (s) goto exec_err;
5574 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
5575 if (s) goto exec_err;
5577 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
5578 s = bc_error("bad read() expression");
5582 ip.func = BC_PROG_READ;
5584 ip.len = G.prog.results.len;
5586 // Update this pointer, just in case.
5587 f = bc_vec_item(&G.prog.fns, BC_PROG_READ);
5589 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
5590 bc_vec_push(&G.prog.stack, &ip);
5593 G.prog.file = sv_file;
5594 bc_parse_free(&parse);
5600 static size_t bc_program_index(char *code, size_t *bgn)
5602 char amt = code[(*bgn)++], i = 0;
5605 for (; i < amt; ++i, ++(*bgn))
5606 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5611 static char *bc_program_name(char *code, size_t *bgn)
5614 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5616 s = xmalloc(ptr - str + 1);
5619 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5627 static void bc_program_printString(const char *str, size_t *nchars)
5629 size_t i, len = strlen(str);
5638 for (i = 0; i < len; ++i, ++(*nchars)) {
5642 if (c != '\\' || i == len - 1)
5702 // Just print the backslash and following character.
5713 static BcStatus bc_program_print(char inst, size_t idx)
5715 BcStatus s = BC_STATUS_SUCCESS;
5720 bool pop = inst != BC_INST_PRINT;
5722 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
5723 return bc_error_stack_has_too_few_elements();
5725 r = bc_vec_item_rev(&G.prog.results, idx);
5726 s = bc_program_num(r, &num, false);
5729 if (BC_PROG_NUM(r, num)) {
5730 s = bc_num_print(num, &G.prog.ob, G.prog.ob_t, !pop, &G.prog.nchars, G.prog.len);
5731 if (!s) bc_num_copy(&G.prog.last, num);
5735 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
5736 str = *((char **) bc_vec_item(&G.prog.strs, idx));
5738 if (inst == BC_INST_PRINT_STR) {
5739 for (i = 0, len = strlen(str); i < len; ++i) {
5742 if (c == '\n') G.prog.nchars = SIZE_MAX;
5747 bc_program_printString(str, &G.prog.nchars);
5748 if (inst == BC_INST_PRINT) bb_putchar('\n');
5752 if (!s && pop) bc_vec_pop(&G.prog.results);
5757 static BcStatus bc_program_negate(void)
5763 s = bc_program_prep(&ptr, &num);
5766 bc_num_init(&res.d.n, num->len);
5767 bc_num_copy(&res.d.n, num);
5768 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5770 bc_program_retire(&res, BC_RESULT_TEMP);
5775 static BcStatus bc_program_logical(char inst)
5778 BcResult *opd1, *opd2, res;
5783 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5785 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
5787 if (inst == BC_INST_BOOL_AND)
5788 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5789 else if (inst == BC_INST_BOOL_OR)
5790 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5793 cmp = bc_num_cmp(n1, n2);
5797 case BC_INST_REL_EQ:
5803 case BC_INST_REL_LE:
5809 case BC_INST_REL_GE:
5815 case BC_INST_REL_NE:
5821 case BC_INST_REL_LT:
5827 case BC_INST_REL_GT:
5835 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5837 bc_program_binOpRetire(&res);
5843 static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
5849 memset(&n2, 0, sizeof(BcNum));
5850 n2.rdx = res.d.id.idx = r->d.id.idx;
5851 res.t = BC_RESULT_STR;
5854 if (!BC_PROG_STACK(&G.prog.results, 2))
5855 return bc_error_stack_has_too_few_elements();
5857 bc_vec_pop(&G.prog.results);
5860 bc_vec_pop(&G.prog.results);
5862 bc_vec_push(&G.prog.results, &res);
5863 bc_vec_push(v, &n2);
5865 return BC_STATUS_SUCCESS;
5869 static BcStatus bc_program_copyToVar(char *name, bool var)
5876 if (!BC_PROG_STACK(&G.prog.results, 1))
5877 return bc_error_stack_has_too_few_elements();
5879 ptr = bc_vec_top(&G.prog.results);
5880 if ((ptr->t == BC_RESULT_ARRAY) != !var)
5881 return bc_error_variable_is_wrong_type();
5882 v = bc_program_search(name, var);
5885 if (ptr->t == BC_RESULT_STR && !var)
5886 return bc_error_variable_is_wrong_type();
5887 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
5890 s = bc_program_num(ptr, &n, false);
5893 // Do this once more to make sure that pointers were not invalidated.
5894 v = bc_program_search(name, var);
5897 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
5898 bc_num_copy(&r.d.n, n);
5901 bc_array_init(&r.d.v, true);
5902 bc_array_copy(&r.d.v, (BcVec *) n);
5905 bc_vec_push(v, &r.d);
5906 bc_vec_pop(&G.prog.results);
5911 static BcStatus bc_program_assign(char inst)
5914 BcResult *left, *right, res;
5915 BcNum *l = NULL, *r = NULL;
5916 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5918 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
5921 ib = left->t == BC_RESULT_IBASE;
5922 sc = left->t == BC_RESULT_SCALE;
5926 if (right->t == BC_RESULT_STR) {
5930 if (left->t != BC_RESULT_VAR)
5931 return bc_error_variable_is_wrong_type();
5932 v = bc_program_search(left->d.id.name, true);
5934 return bc_program_assignStr(right, v, false);
5938 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
5939 return bc_error("bad assignment:"
5940 " left side must be scale,"
5941 " ibase, obase, last, var,"
5946 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5947 return bc_error("divide by zero");
5952 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5959 if (ib || sc || left->t == BC_RESULT_OBASE) {
5960 static const char *const msg[] = {
5961 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5962 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5963 NULL, //can't happen //BC_RESULT_LAST
5964 NULL, //can't happen //BC_RESULT_CONSTANT
5965 NULL, //can't happen //BC_RESULT_ONE
5966 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
5969 unsigned long val, max;
5971 s = bc_num_ulong(l, &val);
5974 s = left->t - BC_RESULT_IBASE;
5977 ptr = &G.prog.scale;
5980 if (val < BC_NUM_MIN_BASE)
5981 return bc_error(msg[s]);
5982 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5983 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
5987 return bc_error(msg[s]);
5989 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
5991 *ptr = (size_t) val;
5992 s = BC_STATUS_SUCCESS;
5995 bc_num_init(&res.d.n, l->len);
5996 bc_num_copy(&res.d.n, l);
5997 bc_program_binOpRetire(&res);
6003 #define bc_program_pushVar(code, bgn, pop, copy) \
6004 bc_program_pushVar(code, bgn)
6005 // for bc, 'pop' and 'copy' are always false
6007 static BcStatus bc_program_pushVar(char *code, size_t *bgn,
6008 bool pop, bool copy)
6010 BcStatus s = BC_STATUS_SUCCESS;
6012 char *name = bc_program_name(code, bgn);
6014 r.t = BC_RESULT_VAR;
6019 BcVec *v = bc_program_search(name, true);
6020 BcNum *num = bc_vec_top(v);
6024 if (!BC_PROG_STACK(v, 2 - copy)) {
6026 return bc_error_stack_has_too_few_elements();
6032 if (!BC_PROG_STR(num)) {
6034 r.t = BC_RESULT_TEMP;
6036 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
6037 bc_num_copy(&r.d.n, num);
6040 r.t = BC_RESULT_STR;
6041 r.d.id.idx = num->rdx;
6044 if (!copy) bc_vec_pop(v);
6049 bc_vec_push(&G.prog.results, &r);
6054 static BcStatus bc_program_pushArray(char *code, size_t *bgn,
6057 BcStatus s = BC_STATUS_SUCCESS;
6061 r.d.id.name = bc_program_name(code, bgn);
6063 if (inst == BC_INST_ARRAY) {
6064 r.t = BC_RESULT_ARRAY;
6065 bc_vec_push(&G.prog.results, &r);
6072 s = bc_program_prep(&operand, &num);
6074 s = bc_num_ulong(num, &temp);
6077 if (temp > BC_MAX_DIM) {
6078 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
6082 r.d.id.idx = (size_t) temp;
6083 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
6087 if (s) free(r.d.id.name);
6092 static BcStatus bc_program_incdec(char inst)
6095 BcResult *ptr, res, copy;
6099 s = bc_program_prep(&ptr, &num);
6102 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6103 copy.t = BC_RESULT_TEMP;
6104 bc_num_init(©.d.n, num->len);
6105 bc_num_copy(©.d.n, num);
6108 res.t = BC_RESULT_ONE;
6109 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6110 BC_INST_ASSIGN_PLUS :
6111 BC_INST_ASSIGN_MINUS;
6113 bc_vec_push(&G.prog.results, &res);
6114 bc_program_assign(inst);
6116 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
6117 bc_vec_pop(&G.prog.results);
6118 bc_vec_push(&G.prog.results, ©);
6124 static BcStatus bc_program_call(char *code, size_t *idx)
6126 BcStatus s = BC_STATUS_SUCCESS;
6128 size_t i, nparams = bc_program_index(code, idx);
6135 ip.func = bc_program_index(code, idx);
6136 func = bc_vec_item(&G.prog.fns, ip.func);
6138 if (func->code.len == 0) {
6139 return bc_error("undefined function");
6141 if (nparams != func->nparams) {
6142 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
6144 ip.len = G.prog.results.len - nparams;
6146 for (i = 0; i < nparams; ++i) {
6148 a = bc_vec_item(&func->autos, nparams - 1 - i);
6149 arg = bc_vec_top(&G.prog.results);
6151 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
6152 return bc_error_variable_is_wrong_type();
6154 s = bc_program_copyToVar(a->name, a->idx);
6158 for (; i < func->autos.len; ++i) {
6161 a = bc_vec_item(&func->autos, i);
6162 v = bc_program_search(a->name, a->idx);
6165 bc_num_init(¶m.n, BC_NUM_DEF_SIZE);
6166 bc_vec_push(v, ¶m.n);
6169 bc_array_init(¶m.v, true);
6170 bc_vec_push(v, ¶m.v);
6174 bc_vec_push(&G.prog.stack, &ip);
6176 return BC_STATUS_SUCCESS;
6179 static BcStatus bc_program_return(char inst)
6185 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6187 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
6188 return bc_error_stack_has_too_few_elements();
6190 f = bc_vec_item(&G.prog.fns, ip->func);
6191 res.t = BC_RESULT_TEMP;
6193 if (inst == BC_INST_RET) {
6196 BcResult *operand = bc_vec_top(&G.prog.results);
6198 s = bc_program_num(operand, &num, false);
6200 bc_num_init(&res.d.n, num->len);
6201 bc_num_copy(&res.d.n, num);
6204 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6205 bc_num_zero(&res.d.n);
6208 // We need to pop arguments as well, so this takes that into account.
6209 for (i = 0; i < f->autos.len; ++i) {
6212 BcId *a = bc_vec_item(&f->autos, i);
6214 v = bc_program_search(a->name, a->idx);
6218 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6219 bc_vec_push(&G.prog.results, &res);
6220 bc_vec_pop(&G.prog.stack);
6222 return BC_STATUS_SUCCESS;
6226 static unsigned long bc_program_scale(BcNum *n)
6228 return (unsigned long) n->rdx;
6231 static unsigned long bc_program_len(BcNum *n)
6233 unsigned long len = n->len;
6236 if (n->rdx != n->len) return len;
6237 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6242 static BcStatus bc_program_builtin(char inst)
6248 bool len = inst == BC_INST_LENGTH;
6250 if (!BC_PROG_STACK(&G.prog.results, 1))
6251 return bc_error_stack_has_too_few_elements();
6252 opnd = bc_vec_top(&G.prog.results);
6254 s = bc_program_num(opnd, &num, false);
6258 if (!BC_PROG_NUM(opnd, num) && !len)
6259 return bc_error_variable_is_wrong_type();
6262 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6264 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
6266 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
6267 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6271 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6274 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6276 str = bc_vec_item(&G.prog.strs, idx);
6277 bc_num_ulong2num(&res.d.n, strlen(*str));
6281 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
6282 bc_num_ulong2num(&res.d.n, f(num));
6285 bc_program_retire(&res, BC_RESULT_TEMP);
6291 static BcStatus bc_program_divmod(void)
6294 BcResult *opd1, *opd2, res, res2;
6295 BcNum *n1, *n2 = NULL;
6297 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6300 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6301 bc_num_init(&res2.d.n, n2->len);
6303 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6306 bc_program_binOpRetire(&res2);
6307 res.t = BC_RESULT_TEMP;
6308 bc_vec_push(&G.prog.results, &res);
6313 bc_num_free(&res2.d.n);
6314 bc_num_free(&res.d.n);
6318 static BcStatus bc_program_modexp(void)
6321 BcResult *r1, *r2, *r3, res;
6322 BcNum *n1, *n2, *n3;
6324 if (!BC_PROG_STACK(&G.prog.results, 3))
6325 return bc_error_stack_has_too_few_elements();
6326 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6329 r1 = bc_vec_item_rev(&G.prog.results, 2);
6330 s = bc_program_num(r1, &n1, false);
6332 if (!BC_PROG_NUM(r1, n1))
6333 return bc_error_variable_is_wrong_type();
6335 // Make sure that the values have their pointers updated, if necessary.
6336 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6338 if (r1->t == r2->t) {
6339 s = bc_program_num(r2, &n2, false);
6343 if (r1->t == r3->t) {
6344 s = bc_program_num(r3, &n3, false);
6349 bc_num_init(&res.d.n, n3->len);
6350 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6353 bc_vec_pop(&G.prog.results);
6354 bc_program_binOpRetire(&res);
6359 bc_num_free(&res.d.n);
6363 static void bc_program_stackLen(void)
6366 size_t len = G.prog.results.len;
6368 res.t = BC_RESULT_TEMP;
6370 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6371 bc_num_ulong2num(&res.d.n, len);
6372 bc_vec_push(&G.prog.results, &res);
6375 static BcStatus bc_program_asciify(void)
6379 BcNum *num = NULL, n;
6380 char *str, *str2, c;
6381 size_t len = G.prog.strs.len, idx;
6384 if (!BC_PROG_STACK(&G.prog.results, 1))
6385 return bc_error_stack_has_too_few_elements();
6386 r = bc_vec_top(&G.prog.results);
6388 s = bc_program_num(r, &num, false);
6391 if (BC_PROG_NUM(r, num)) {
6393 bc_num_init(&n, BC_NUM_DEF_SIZE);
6394 bc_num_copy(&n, num);
6395 bc_num_truncate(&n, n.rdx);
6397 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
6398 if (s) goto num_err;
6399 s = bc_num_ulong(&n, &val);
6400 if (s) goto num_err;
6407 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
6408 str2 = *((char **) bc_vec_item(&G.prog.strs, idx));
6416 str2 = xstrdup(str);
6417 bc_program_addFunc(str2, &idx);
6419 if (idx != len + BC_PROG_REQ_FUNCS) {
6421 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6422 if (!strcmp(*((char **) bc_vec_item(&G.prog.strs, idx)), str)) {
6431 bc_vec_push(&G.prog.strs, &str);
6433 res.t = BC_RESULT_STR;
6435 bc_vec_pop(&G.prog.results);
6436 bc_vec_push(&G.prog.results, &res);
6438 return BC_STATUS_SUCCESS;
6445 static BcStatus bc_program_printStream(void)
6453 if (!BC_PROG_STACK(&G.prog.results, 1))
6454 return bc_error_stack_has_too_few_elements();
6455 r = bc_vec_top(&G.prog.results);
6457 s = bc_program_num(r, &n, false);
6460 if (BC_PROG_NUM(r, n))
6461 s = bc_num_stream(n, &G.prog.strmb, &G.prog.nchars, G.prog.len);
6463 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
6464 str = *((char **) bc_vec_item(&G.prog.strs, idx));
6471 static BcStatus bc_program_nquit(void)
6478 s = bc_program_prep(&opnd, &num);
6480 s = bc_num_ulong(num, &val);
6483 bc_vec_pop(&G.prog.results);
6485 if (G.prog.stack.len < val)
6486 return bc_error_stack_has_too_few_elements();
6487 if (G.prog.stack.len == val) {
6488 QUIT_OR_RETURN_TO_MAIN;
6491 bc_vec_npop(&G.prog.stack, val);
6496 static BcStatus bc_program_execStr(char *code, size_t *bgn,
6499 BcStatus s = BC_STATUS_SUCCESS;
6509 if (!BC_PROG_STACK(&G.prog.results, 1))
6510 return bc_error_stack_has_too_few_elements();
6512 r = bc_vec_top(&G.prog.results);
6516 char *name, *then_name = bc_program_name(code, bgn), *else_name = NULL;
6518 if (code[*bgn] == BC_PARSE_STREND)
6521 else_name = bc_program_name(code, bgn);
6523 exec = r->d.n.len != 0;
6527 else if (else_name != NULL) {
6534 v = bc_program_search(name, true);
6541 if (!exec) goto exit;
6542 if (!BC_PROG_STR(n)) {
6543 s = bc_error_variable_is_wrong_type();
6551 if (r->t == BC_RESULT_STR)
6553 else if (r->t == BC_RESULT_VAR) {
6554 s = bc_program_num(r, &n, false);
6555 if (s || !BC_PROG_STR(n)) goto exit;
6562 fidx = sidx + BC_PROG_REQ_FUNCS;
6564 str = bc_vec_item(&G.prog.strs, sidx);
6565 f = bc_vec_item(&G.prog.fns, fidx);
6567 if (f->code.len == 0) {
6568 common_parse_init(&prs, fidx);
6569 s = bc_parse_text(&prs, *str);
6571 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
6574 if (prs.l.t.t != BC_LEX_EOF) {
6575 s = bc_error_bad_expression();
6579 bc_parse_free(&prs);
6583 ip.len = G.prog.results.len;
6586 bc_vec_pop(&G.prog.results);
6587 bc_vec_push(&G.prog.stack, &ip);
6589 return BC_STATUS_SUCCESS;
6592 bc_parse_free(&prs);
6593 f = bc_vec_item(&G.prog.fns, fidx);
6594 bc_vec_pop_all(&f->code);
6596 bc_vec_pop(&G.prog.results);
6601 static void bc_program_pushGlobal(char inst)
6606 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6607 if (inst == BC_INST_IBASE)
6608 val = (unsigned long) G.prog.ib_t;
6609 else if (inst == BC_INST_SCALE)
6610 val = (unsigned long) G.prog.scale;
6612 val = (unsigned long) G.prog.ob_t;
6614 bc_num_init(&res.d.n, BC_NUM_DEF_SIZE);
6615 bc_num_ulong2num(&res.d.n, val);
6616 bc_vec_push(&G.prog.results, &res);
6619 static void bc_program_addFunc(char *name, size_t *idx)
6621 BcId entry, *entry_ptr;
6626 entry.idx = G.prog.fns.len;
6628 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6629 if (!inserted) free(name);
6631 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
6632 *idx = entry_ptr->idx;
6636 BcFunc *func = bc_vec_item(&G.prog.fns, entry_ptr->idx);
6638 // We need to reset these, so the function can be repopulated.
6640 bc_vec_pop_all(&func->autos);
6641 bc_vec_pop_all(&func->code);
6642 bc_vec_pop_all(&func->labels);
6646 bc_vec_push(&G.prog.fns, &f);
6650 static BcStatus bc_program_exec(void)
6652 BcStatus s = BC_STATUS_SUCCESS;
6656 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6657 BcFunc *func = bc_vec_item(&G.prog.fns, ip->func);
6658 char *code = func->code.v;
6661 while (!s && ip->idx < func->code.len) {
6663 char inst = code[(ip->idx)++];
6668 case BC_INST_JUMP_ZERO:
6670 s = bc_program_prep(&ptr, &num);
6672 cond = !bc_num_cmp(num, &G.prog.zero);
6673 bc_vec_pop(&G.prog.results);
6679 idx = bc_program_index(code, &ip->idx);
6680 addr = bc_vec_item(&func->labels, idx);
6681 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6687 s = bc_program_call(code, &ip->idx);
6691 case BC_INST_INC_PRE:
6692 case BC_INST_DEC_PRE:
6693 case BC_INST_INC_POST:
6694 case BC_INST_DEC_POST:
6696 s = bc_program_incdec(inst);
6702 QUIT_OR_RETURN_TO_MAIN;
6709 s = bc_program_return(inst);
6713 case BC_INST_BOOL_OR:
6714 case BC_INST_BOOL_AND:
6716 case BC_INST_REL_EQ:
6717 case BC_INST_REL_LE:
6718 case BC_INST_REL_GE:
6719 case BC_INST_REL_NE:
6720 case BC_INST_REL_LT:
6721 case BC_INST_REL_GT:
6723 s = bc_program_logical(inst);
6729 s = bc_program_read();
6735 s = bc_program_pushVar(code, &ip->idx, false, false);
6739 case BC_INST_ARRAY_ELEM:
6742 s = bc_program_pushArray(code, &ip->idx, inst);
6748 r.t = BC_RESULT_LAST;
6749 bc_vec_push(&G.prog.results, &r);
6757 bc_program_pushGlobal(inst);
6761 case BC_INST_SCALE_FUNC:
6762 case BC_INST_LENGTH:
6765 s = bc_program_builtin(inst);
6771 r.t = BC_RESULT_CONSTANT;
6772 r.d.id.idx = bc_program_index(code, &ip->idx);
6773 bc_vec_push(&G.prog.results, &r);
6779 if (!BC_PROG_STACK(&G.prog.results, 1))
6780 s = bc_error_stack_has_too_few_elements();
6782 bc_vec_pop(&G.prog.results);
6786 case BC_INST_POP_EXEC:
6788 bc_vec_pop(&G.prog.stack);
6793 case BC_INST_PRINT_POP:
6794 case BC_INST_PRINT_STR:
6796 s = bc_program_print(inst, 0);
6802 r.t = BC_RESULT_STR;
6803 r.d.id.idx = bc_program_index(code, &ip->idx);
6804 bc_vec_push(&G.prog.results, &r);
6809 case BC_INST_MULTIPLY:
6810 case BC_INST_DIVIDE:
6811 case BC_INST_MODULUS:
6815 s = bc_program_op(inst);
6819 case BC_INST_BOOL_NOT:
6821 s = bc_program_prep(&ptr, &num);
6824 bc_num_init(&r.d.n, BC_NUM_DEF_SIZE);
6825 (!bc_num_cmp(num, &G.prog.zero) ? bc_num_one : bc_num_zero)(&r.d.n);
6826 bc_program_retire(&r, BC_RESULT_TEMP);
6833 s = bc_program_negate();
6838 case BC_INST_ASSIGN_POWER:
6839 case BC_INST_ASSIGN_MULTIPLY:
6840 case BC_INST_ASSIGN_DIVIDE:
6841 case BC_INST_ASSIGN_MODULUS:
6842 case BC_INST_ASSIGN_PLUS:
6843 case BC_INST_ASSIGN_MINUS:
6845 case BC_INST_ASSIGN:
6847 s = bc_program_assign(inst);
6851 case BC_INST_MODEXP:
6853 s = bc_program_modexp();
6857 case BC_INST_DIVMOD:
6859 s = bc_program_divmod();
6863 case BC_INST_EXECUTE:
6864 case BC_INST_EXEC_COND:
6866 cond = inst == BC_INST_EXEC_COND;
6867 s = bc_program_execStr(code, &ip->idx, cond);
6871 case BC_INST_PRINT_STACK:
6873 for (idx = 0; !s && idx < G.prog.results.len; ++idx)
6874 s = bc_program_print(BC_INST_PRINT, idx);
6878 case BC_INST_CLEAR_STACK:
6880 bc_vec_pop_all(&G.prog.results);
6884 case BC_INST_STACK_LEN:
6886 bc_program_stackLen();
6890 case BC_INST_DUPLICATE:
6892 if (!BC_PROG_STACK(&G.prog.results, 1))
6893 return bc_error_stack_has_too_few_elements();
6894 ptr = bc_vec_top(&G.prog.results);
6895 bc_result_copy(&r, ptr);
6896 bc_vec_push(&G.prog.results, &r);
6904 if (!BC_PROG_STACK(&G.prog.results, 2))
6905 return bc_error_stack_has_too_few_elements();
6907 ptr = bc_vec_item_rev(&G.prog.results, 0);
6908 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6909 memcpy(&r, ptr, sizeof(BcResult));
6910 memcpy(ptr, ptr2, sizeof(BcResult));
6911 memcpy(ptr2, &r, sizeof(BcResult));
6916 case BC_INST_ASCIIFY:
6918 s = bc_program_asciify();
6922 case BC_INST_PRINT_STREAM:
6924 s = bc_program_printStream();
6929 case BC_INST_PUSH_VAR:
6931 bool copy = inst == BC_INST_LOAD;
6932 s = bc_program_pushVar(code, &ip->idx, true, copy);
6936 case BC_INST_PUSH_TO_VAR:
6938 char *name = bc_program_name(code, &ip->idx);
6939 s = bc_program_copyToVar(name, true);
6946 if (G.prog.stack.len <= 2)
6947 QUIT_OR_RETURN_TO_MAIN;
6948 bc_vec_npop(&G.prog.stack, 2);
6954 s = bc_program_nquit();
6960 if (s || G_interrupt) {
6965 // If the stack has changed, pointers may be invalid.
6966 ip = bc_vec_top(&G.prog.stack);
6967 func = bc_vec_item(&G.prog.fns, ip->func);
6968 code = func->code.v;
6975 static void bc_vm_info(void)
6977 printf("%s "BB_VER"\n"
6978 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6979 "Report bugs at: https://github.com/gavinhoward/bc\n"
6980 "This is free software with ABSOLUTELY NO WARRANTY\n"
6984 static void bc_args(char **argv)
6990 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6991 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6992 "warn\0" No_argument "w"
6993 "version\0" No_argument "v"
6994 "standard\0" No_argument "s"
6995 "quiet\0" No_argument "q"
6996 "mathlib\0" No_argument "l"
6997 "interactive\0" No_argument "i"
7000 opts = option_mask32 |= getopt32(argv, "wvsqli");
7002 if (getenv("POSIXLY_CORRECT"))
7003 option_mask32 |= BC_FLAG_S;
7005 ///should be in bc_vm_run() instead??
7006 if (opts & BC_FLAG_V) {
7011 for (i = optind; argv[i]; ++i)
7012 bc_vec_push(&G.files, argv + i);
7015 static void bc_vm_envArgs(void)
7019 char *env_args = getenv("BC_ENV_ARGS");
7021 if (!env_args) return;
7023 G.env_args = xstrdup(env_args);
7026 bc_vec_init(&v, sizeof(char *), NULL);
7028 while (*(buf = skip_whitespace(buf)) != '\0') {
7029 bc_vec_push(&v, &buf);
7030 buf = skip_non_whitespace(buf);
7036 // NULL terminate, and pass argv[] so that first arg is argv[1]
7037 if (sizeof(int) == sizeof(char*)) {
7038 bc_vec_push(&v, &const_int_0);
7040 static char *const nullptr = NULL;
7041 bc_vec_push(&v, &nullptr);
7043 bc_args(((char **)v.v) - 1);
7049 static unsigned bc_vm_envLen(const char *var)
7055 len = BC_NUM_PRINT_WIDTH;
7056 if (!lenv) return len;
7058 len = bb_strtou(lenv, NULL, 10) - 1;
7059 if (errno || len < 2 || len >= INT_MAX)
7060 len = BC_NUM_PRINT_WIDTH;
7065 static BcStatus bc_vm_process(const char *text)
7067 BcStatus s = bc_parse_text(&G.prs, text);
7071 while (G.prs.l.t.t != BC_LEX_EOF) {
7072 s = G.prs.parse(&G.prs);
7076 if (BC_PARSE_CAN_EXEC(&G.prs)) {
7077 s = bc_program_exec();
7086 static BcStatus bc_vm_file(const char *file)
7088 const char *sv_file;
7094 data = bc_read_file(file);
7095 if (!data) return bc_error_fmt("file '%s' is not text", file);
7097 sv_file = G.prog.file;
7099 bc_lex_file(&G.prs.l);
7100 s = bc_vm_process(data);
7103 main_func = bc_vec_item(&G.prog.fns, BC_PROG_MAIN);
7104 ip = bc_vec_item(&G.prog.stack, 0);
7106 if (main_func->code.len < ip->idx)
7107 s = bc_error_fmt("file '%s' is not executable", file);
7110 G.prog.file = sv_file;
7115 static BcStatus bc_vm_stdin(void)
7119 size_t len, i, str = 0;
7120 bool comment = false;
7123 bc_lex_file(&G.prs.l);
7125 bc_char_vec_init(&buffer);
7126 bc_char_vec_init(&buf);
7127 bc_vec_pushZeroByte(&buffer);
7129 // This loop is complex because the vm tries not to send any lines that end
7130 // with a backslash to the parser. The reason for that is because the parser
7131 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7132 // case, and for strings and comments, the parser will expect more stuff.
7133 while ((s = bc_read_line(&buf, ">>> ")) == BC_STATUS_SUCCESS) {
7135 char *string = buf.v;
7140 if (str && buf.v[0] == G.send)
7142 else if (buf.v[0] == G.sbgn)
7145 else if (len > 1 || comment) {
7147 for (i = 0; i < len; ++i) {
7149 bool notend = len > i + 1;
7152 if (i - 1 > len || string[i - 1] != '\\') {
7153 if (G.sbgn == G.send)
7155 else if (c == G.send)
7157 else if (c == G.sbgn)
7161 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7165 else if (c == '*' && notend && comment && string[i + 1] == '/')
7169 if (str || comment || string[len - 2] == '\\') {
7170 bc_vec_concat(&buffer, buf.v);
7175 bc_vec_concat(&buffer, buf.v);
7176 s = bc_vm_process(buffer.v);
7178 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
7179 // Debug config, non-interactive mode:
7180 // return all the way back to main.
7181 // Non-debug builds do not come here, they exit.
7185 fputs("ready for more input\n", stderr);
7188 bc_vec_pop_all(&buffer);
7190 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7191 s = BC_STATUS_SUCCESS;
7194 s = bc_error("string end could not be found");
7197 s = bc_error("comment end could not be found");
7201 bc_vec_free(&buffer);
7206 static const char bc_lib[] = {
7209 "\n" "auto b,s,n,r,d,i,p,f,v"
7218 "\n" "scale=scale(x)+1"
7228 "\n" "for(i=2;v!=0;++i){"
7234 "\n" "while((d--)!=0)r*=r"
7237 "\n" "if(n!=0)return(1/r)"
7241 "\n" "auto b,s,r,p,a,q,i,v"
7245 "\n" "r=(1-10^scale)/1"
7256 "\n" "while(x<=0.5){"
7260 "\n" "r=a=(x-1)/(x+1)"
7263 "\n" "for(i=3;v!=0;i+=2){"
7274 "\n" "auto b,s,r,n,a,q,i"
7278 "\n" "scale=1.1*s+2"
7287 "\n" "if(q%2!=0)x=-x"
7291 "\n" "for(i=3;a!=0;i+=2){"
7292 "\n" "a*=q/(i*(i-1))"
7297 "\n" "if(n!=0)return(-r/1)"
7306 "\n" "x=s(2*a(1)+x)"
7312 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7321 "\n" "if(scale<65){"
7322 "\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7326 "\n" "if(scale<65){"
7327 "\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7338 "\n" "x=(x-.2)/(1+.2*x)"
7343 "\n" "for(i=3;t!=0;i+=2){"
7350 "\n" "return((m*a+r)/n)"
7352 "\n" "define j(n,x){"
7353 "\n" "auto b,s,o,a,i,v,f"
7361 "\n" "if(n%2==1)o=1"
7364 "\n" "for(i=2;i<=n;++i)a*=i"
7366 "\n" "a=(x^n)/2^n/a"
7369 "\n" "scale=scale+length(a)-scale(a)"
7370 "\n" "for(i=1;v!=0;++i){"
7371 "\n" "v=v*f/i/(n+i)"
7377 "\n" "return(a*r/1)"
7382 static BcStatus bc_vm_exec(void)
7388 if (option_mask32 & BC_FLAG_L) {
7390 // We know that internal library is not buggy,
7391 // thus error checking is normally disabled.
7392 # define DEBUG_LIB 0
7393 bc_lex_file(&G.prs.l);
7394 s = bc_parse_text(&G.prs, bc_lib);
7395 if (DEBUG_LIB && s) return s;
7397 while (G.prs.l.t.t != BC_LEX_EOF) {
7398 s = G.prs.parse(&G.prs);
7399 if (DEBUG_LIB && s) return s;
7401 s = bc_program_exec();
7402 if (DEBUG_LIB && s) return s;
7406 s = BC_STATUS_SUCCESS;
7407 for (i = 0; !s && i < G.files.len; ++i)
7408 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
7409 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7410 // Debug config, non-interactive mode:
7411 // return all the way back to main.
7412 // Non-debug builds do not come here, they exit.
7416 if (IS_BC || (option_mask32 & BC_FLAG_I)) {
7419 fputs("ready for more input\n", stderr);
7424 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7425 s = bc_vm_process("");
7430 #if ENABLE_FEATURE_CLEAN_UP
7431 static void bc_program_free(void)
7433 bc_num_free(&G.prog.ib);
7434 bc_num_free(&G.prog.ob);
7435 bc_num_free(&G.prog.hexb);
7437 bc_num_free(&G.prog.strmb);
7439 bc_vec_free(&G.prog.fns);
7440 bc_vec_free(&G.prog.fn_map);
7441 bc_vec_free(&G.prog.vars);
7442 bc_vec_free(&G.prog.var_map);
7443 bc_vec_free(&G.prog.arrs);
7444 bc_vec_free(&G.prog.arr_map);
7445 bc_vec_free(&G.prog.strs);
7446 bc_vec_free(&G.prog.consts);
7447 bc_vec_free(&G.prog.results);
7448 bc_vec_free(&G.prog.stack);
7449 bc_num_free(&G.prog.last);
7450 bc_num_free(&G.prog.zero);
7451 bc_num_free(&G.prog.one);
7454 static void bc_vm_free(void)
7456 bc_vec_free(&G.files);
7458 bc_parse_free(&G.prs);
7463 static void bc_program_init(void)
7468 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7469 memset(&ip, 0, sizeof(BcInstPtr));
7471 /* G.prog.nchars = G.prog.scale = 0; - already is */
7473 bc_num_init(&G.prog.ib, BC_NUM_DEF_SIZE);
7474 bc_num_ten(&G.prog.ib);
7477 bc_num_init(&G.prog.ob, BC_NUM_DEF_SIZE);
7478 bc_num_ten(&G.prog.ob);
7481 bc_num_init(&G.prog.hexb, BC_NUM_DEF_SIZE);
7482 bc_num_ten(&G.prog.hexb);
7483 G.prog.hexb.num[0] = 6;
7486 bc_num_init(&G.prog.strmb, BC_NUM_DEF_SIZE);
7487 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7490 bc_num_init(&G.prog.last, BC_NUM_DEF_SIZE);
7491 bc_num_zero(&G.prog.last);
7493 bc_num_init(&G.prog.zero, BC_NUM_DEF_SIZE);
7494 bc_num_zero(&G.prog.zero);
7496 bc_num_init(&G.prog.one, BC_NUM_DEF_SIZE);
7497 bc_num_one(&G.prog.one);
7499 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7500 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
7502 bc_program_addFunc(xstrdup("(main)"), &idx);
7503 bc_program_addFunc(xstrdup("(read)"), &idx);
7505 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7506 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7508 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7509 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7511 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7512 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7513 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7514 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7515 bc_vec_push(&G.prog.stack, &ip);
7518 static int bc_vm_init(const char *env_len)
7520 #if ENABLE_FEATURE_EDITING
7521 G.line_input_state = new_line_input_t(DO_HISTORY);
7523 G.prog.len = bc_vm_envLen(env_len);
7525 bc_vec_init(&G.files, sizeof(char *), NULL);
7527 IF_BC(bc_vm_envArgs();)
7530 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
7532 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
7536 #if ENABLE_FEATURE_BC_SIGNALS
7538 // With SA_RESTART, most system calls will restart
7539 // (IOW: they won't fail with EINTR).
7540 // In particular, this means ^C won't cause
7541 // stdout to get into "error state" if SIGINT hits
7542 // within write() syscall.
7543 // The downside is that ^C while line input is taken
7544 // will only be handled after [Enter] since read()
7545 // from stdin is not interrupted by ^C either,
7546 // it restarts, thus fgetc() does not return on ^C.
7547 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7549 // Without SA_RESTART, this exhibits a bug:
7550 // "while (1) print 1" and try ^C-ing it.
7551 // Intermittently, instead of returning to input line,
7552 // you'll get "output error: Interrupted system call"
7554 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7558 return 0; // "not a tty"
7561 static BcStatus bc_vm_run(void)
7563 BcStatus st = bc_vm_exec();
7564 #if ENABLE_FEATURE_CLEAN_UP
7565 if (G_exiting) // it was actually "halt" or "quit"
7568 # if ENABLE_FEATURE_EDITING
7569 free_line_input_t(G.line_input_state);
7577 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7578 int bc_main(int argc UNUSED_PARAM, char **argv)
7583 G.sbgn = G.send = '"';
7585 is_tty = bc_vm_init("BC_LINE_LENGTH");
7589 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7597 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7598 int dc_main(int argc UNUSED_PARAM, char **argv)
7605 // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use default width
7606 // 1 char narrower than bc from the same package. Do the same?
7607 bc_vm_init("DC_LINE_LENGTH");
7609 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7610 noscript = BC_FLAG_I;
7612 int n = getopt(argc, argv, "e:f:x");
7618 n = bc_vm_process(optarg);
7626 option_mask32 |= DC_FLAG_X;
7636 bc_vec_push(&G.files, argv++);
7639 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7645 #endif // not DC_SMALL