1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 * Copyright (c) 2018 Gavin D. Howard and contributors.
7 //config: bool "bc (45 kb; 49 kb when combined with dc)"
10 //config: bc is a command-line, arbitrary-precision calculator with a
11 //config: Turing-complete language. See the GNU bc manual
12 //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
13 //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
14 //config: for details.
16 //config: This bc has four differences to the GNU bc:
18 //config: 1) The period (.) can also be used as a shortcut for "last", as in
20 //config: 2) Arrays are copied before being passed as arguments to
21 //config: functions. This behavior is required by the bc spec.
22 //config: 3) Arrays can be passed to the builtin "length" function to get
23 //config: the number of elements currently in the array. The following
24 //config: example prints "1":
29 //config: 4) The precedence of the boolean "not" operator (!) is equal to
30 //config: that of the unary minus (-), or negation, operator. This still
31 //config: allows POSIX-compliant scripts to work while somewhat
32 //config: preserving expected behavior (versus C) and making parsing
37 //config: -i --interactive force interactive mode
38 //config: -l --mathlib use predefined math routines:
40 //config: s(expr) = sine of expr in radians
41 //config: c(expr) = cosine of expr in radians
42 //config: a(expr) = arctangent of expr, returning
44 //config: l(expr) = natural log of expr
45 //config: e(expr) = raises e to the power of expr
46 //config: j(n, x) = Bessel function of integer order
49 //config: -q --quiet don't print version and copyright.
50 //config: -s --standard error if any non-POSIX extensions are used.
51 //config: -w --warn warn if any non-POSIX extensions are used.
52 //config: -v --version print version and copyright and exit.
54 //config: Long options are only available if FEATURE_BC_LONG_OPTIONS is
58 //config: bool "dc (38 kb; 49 kb when combined with bc)"
61 //config: dc is a reverse-polish notation command-line calculator which
62 //config: supports unlimited precision arithmetic. See the FreeBSD man page
63 //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
64 //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
65 //config: for details.
67 //config: This dc has a few differences from the two above:
69 //config: 1) When printing a byte stream (command "P"), this bc follows what
70 //config: the FreeBSD dc does.
71 //config: 2) This dc implements the GNU extensions for divmod ("~") and
72 //config: modular exponentiation ("|").
73 //config: 3) This dc implements all FreeBSD extensions, except for "J" and
75 //config: 4) Like the FreeBSD dc, this dc supports extended registers.
76 //config: However, they are implemented differently. When it encounters
77 //config: whitespace where a register should be, it skips the whitespace.
78 //config: If the character following is not a lowercase letter, an error
79 //config: is issued. Otherwise, the register name is parsed by the
80 //config: following regex:
82 //config: [a-z][a-z0-9_]*
84 //config: This generally means that register names will be surrounded by
89 //config: l idx s temp L index S temp2 < do_thing
91 //config: Also note that, like the FreeBSD dc, extended registers are not
92 //config: allowed unless the "-x" option is given.
94 //config:config FEATURE_DC_SMALL
95 //config: bool "Minimal dc implementation (4.2 kb), not using bc code base"
96 //config: depends on DC && !BC
99 //config:config FEATURE_DC_LIBM
100 //config: bool "Enable power and exp functions (requires libm)"
102 //config: depends on FEATURE_DC_SMALL
104 //config: Enable power and exp functions.
105 //config: NOTE: This will require libm to be present for linking.
107 //config:config FEATURE_BC_SIGNALS
108 //config: bool "Enable bc/dc signal handling"
110 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
112 //config: Enable signal handling for bc and dc.
114 //config:config FEATURE_BC_LONG_OPTIONS
115 //config: bool "Enable bc/dc long options"
117 //config: depends on (BC || DC) && !FEATURE_DC_SMALL
119 //config: Enable long options for bc and dc.
121 //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
122 //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
124 //kbuild:lib-$(CONFIG_BC) += bc.o
125 //kbuild:lib-$(CONFIG_DC) += bc.o
127 //See www.gnu.org/software/bc/manual/bc.html
128 //usage:#define bc_trivial_usage
129 //usage: "[-sqliw] FILE..."
131 //usage:#define bc_full_usage "\n"
132 //usage: "\nArbitrary precision calculator"
134 ///////: "\n -i Interactive" - has no effect for now
135 //usage: "\n -q Quiet"
136 //usage: "\n -l Load standard math library"
137 //usage: "\n -s Be POSIX compatible"
138 //usage: "\n -w Warn if extensions are used"
139 ///////: "\n -v Version"
141 //usage: "\n$BC_LINE_LENGTH changes output width"
143 //usage:#define bc_example_usage
144 //usage: "3 + 4.129\n"
145 //usage: "1903 - 2893\n"
146 //usage: "-129 * 213.28935\n"
147 //usage: "12 / -1932\n"
149 //usage: "34 ^ 189\n"
150 //usage: "scale = 13\n"
151 //usage: "ibase = 2\n"
152 //usage: "obase = A\n"
154 //usage:#define dc_trivial_usage
155 //usage: IF_NOT_FEATURE_DC_SMALL("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
157 //usage:#define dc_full_usage "\n"
158 //usage: "\nTiny RPN calculator. Operations:"
159 //usage: "\n+, -, *, /, %, ~, ^," IF_NOT_FEATURE_DC_SMALL(" |,")
160 //usage: "\np - print top of the stack (without popping)"
161 //usage: "\nf - print entire stack"
162 //usage: "\nk - pop the value and set the precision"
163 //usage: "\ni - pop the value and set input radix"
164 //usage: "\no - pop the value and set output radix"
165 //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
167 //usage:#define dc_example_usage
168 //usage: "$ dc -e'2 2 + p'\n"
170 //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
172 //usage: "$ dc -e'0 1 & p'\n"
174 //usage: "$ dc -e'0 1 | p'\n"
176 //usage: "$ echo '72 9 / 8 * p' | dc\n"
180 #include "common_bufsiz.h"
182 #if ENABLE_FEATURE_DC_SMALL
186 typedef enum BcStatus {
187 BC_STATUS_SUCCESS = 0,
188 BC_STATUS_FAILURE = 1,
189 BC_STATUS_PARSE_EMPTY_EXP = 2, // bc_parse_expr() uses this
190 BC_STATUS_EOF = 3, // bc_vm_stdin() uses this
193 #define BC_VEC_INVALID_IDX ((size_t) -1)
194 #define BC_VEC_START_CAP (1 << 5)
196 typedef void (*BcVecFree)(void *);
198 typedef struct BcVec {
206 typedef signed char BcDig;
208 typedef struct BcNum {
216 #define BC_NUM_MIN_BASE ((unsigned long) 2)
217 #define BC_NUM_MAX_IBASE ((unsigned long) 16)
218 // larger value might speed up BIGNUM calculations a bit:
219 #define BC_NUM_DEF_SIZE (16)
220 #define BC_NUM_PRINT_WIDTH (69)
222 #define BC_NUM_KARATSUBA_LEN (32)
224 typedef void (*BcNumDigitOp)(size_t, size_t, bool);
226 typedef BcStatus (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t);
228 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
229 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
230 static BcStatus bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
231 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
232 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
233 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
234 static BcStatus bc_num_sqrt(BcNum *a, BcNum *b, size_t scale);
235 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
238 typedef enum BcInst {
268 BC_INST_ASSIGN_POWER,
269 BC_INST_ASSIGN_MULTIPLY,
270 BC_INST_ASSIGN_DIVIDE,
271 BC_INST_ASSIGN_MODULUS,
273 BC_INST_ASSIGN_MINUS,
319 BC_INST_PRINT_STREAM,
334 BC_INST_INVALID = -1,
339 typedef struct BcId {
344 typedef struct BcFunc {
351 typedef enum BcResultType {
356 BC_RESULT_ARRAY_ELEM,
365 // These are between to calculate ibase, obase, and last from instructions.
373 typedef union BcResultData {
379 typedef struct BcResult {
384 typedef struct BcInstPtr {
390 // BC_LEX_NEG is not used in lexing; it is only for parsing.
391 typedef enum BcLexType {
419 BC_LEX_OP_ASSIGN_POWER,
420 BC_LEX_OP_ASSIGN_MULTIPLY,
421 BC_LEX_OP_ASSIGN_DIVIDE,
422 BC_LEX_OP_ASSIGN_MODULUS,
423 BC_LEX_OP_ASSIGN_PLUS,
424 BC_LEX_OP_ASSIGN_MINUS,
445 BC_LEX_KEY_1st_keyword,
446 BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
453 // code uses "type - BC_LEX_KEY_IBASE + BC_INST_IBASE" construct,
454 BC_LEX_KEY_IBASE, // relative order should match for: BC_INST_IBASE
456 BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
459 BC_LEX_KEY_OBASE, // relative order should match for: BC_INST_OBASE
497 // must match order of BC_LEX_KEY_foo etc above
499 struct BcLexKeyword {
502 #define BC_LEX_KW_ENTRY(a, b) \
503 { .name8 = a /*, .posix = b */ }
504 static const struct BcLexKeyword bc_lex_kws[20] = {
505 BC_LEX_KW_ENTRY("auto" , 1), // 0
506 BC_LEX_KW_ENTRY("break" , 1), // 1
507 BC_LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
508 BC_LEX_KW_ENTRY("define" , 1), // 3
510 BC_LEX_KW_ENTRY("else" , 0), // 4
511 BC_LEX_KW_ENTRY("for" , 1), // 5
512 BC_LEX_KW_ENTRY("halt" , 0), // 6
513 BC_LEX_KW_ENTRY("ibase" , 1), // 7
515 BC_LEX_KW_ENTRY("if" , 1), // 8
516 BC_LEX_KW_ENTRY("last" , 0), // 9
517 BC_LEX_KW_ENTRY("length" , 1), // 10
518 BC_LEX_KW_ENTRY("limits" , 0), // 11
520 BC_LEX_KW_ENTRY("obase" , 1), // 12
521 BC_LEX_KW_ENTRY("print" , 0), // 13
522 BC_LEX_KW_ENTRY("quit" , 1), // 14
523 BC_LEX_KW_ENTRY("read" , 0), // 15
525 BC_LEX_KW_ENTRY("return" , 1), // 16
526 BC_LEX_KW_ENTRY("scale" , 1), // 17
527 BC_LEX_KW_ENTRY("sqrt" , 1), // 18
528 BC_LEX_KW_ENTRY("while" , 1), // 19
530 #undef BC_LEX_KW_ENTRY
558 #define bc_lex_kws_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
562 typedef BcStatus (*BcLexNext)(struct BcLex *);
564 typedef struct BcLex {
582 #define BC_PARSE_STREND ((char) UCHAR_MAX)
584 #define BC_PARSE_REL (1 << 0)
585 #define BC_PARSE_PRINT (1 << 1)
586 #define BC_PARSE_NOCALL (1 << 2)
587 #define BC_PARSE_NOREAD (1 << 3)
588 #define BC_PARSE_ARRAY (1 << 4)
590 #define BC_PARSE_TOP_FLAG_PTR(parse) ((uint8_t *) bc_vec_top(&(parse)->flags))
591 #define BC_PARSE_TOP_FLAG(parse) (*(BC_PARSE_TOP_FLAG_PTR(parse)))
593 #define BC_PARSE_FLAG_FUNC_INNER (1 << 0)
594 #define BC_PARSE_FUNC_INNER(parse) \
595 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC_INNER)
597 #define BC_PARSE_FLAG_FUNC (1 << 1)
598 #define BC_PARSE_FUNC(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_FUNC)
600 #define BC_PARSE_FLAG_BODY (1 << 2)
601 #define BC_PARSE_BODY(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_BODY)
603 #define BC_PARSE_FLAG_LOOP (1 << 3)
604 #define BC_PARSE_LOOP(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP)
606 #define BC_PARSE_FLAG_LOOP_INNER (1 << 4)
607 #define BC_PARSE_LOOP_INNER(parse) \
608 (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_LOOP_INNER)
610 #define BC_PARSE_FLAG_IF (1 << 5)
611 #define BC_PARSE_IF(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF)
613 #define BC_PARSE_FLAG_ELSE (1 << 6)
614 #define BC_PARSE_ELSE(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_ELSE)
616 #define BC_PARSE_FLAG_IF_END (1 << 7)
617 #define BC_PARSE_IF_END(parse) (BC_PARSE_TOP_FLAG(parse) & BC_PARSE_FLAG_IF_END)
619 #define BC_PARSE_CAN_EXEC(parse) \
620 (!(BC_PARSE_TOP_FLAG(parse) & \
621 (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_BODY | \
622 BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER | BC_PARSE_FLAG_IF | \
623 BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_IF_END)))
629 typedef BcStatus (*BcParseParse)(struct BcParse *);
631 typedef struct BcParse {
652 typedef struct BcProgram {
693 #define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) n))
695 #define BC_PROG_MAIN (0)
696 #define BC_PROG_READ (1)
698 #define BC_PROG_REQ_FUNCS (2)
701 #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
702 #define BC_PROG_NUM(r, n) \
703 ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
705 typedef unsigned long (*BcProgramBuiltIn)(BcNum *);
707 #define BC_FLAG_W (1 << 0)
708 #define BC_FLAG_V (1 << 1)
709 #define BC_FLAG_S (1 << 2)
710 #define BC_FLAG_Q (1 << 3)
711 #define BC_FLAG_L (1 << 4)
712 #define BC_FLAG_I (1 << 5)
713 #define DC_FLAG_X (1 << 6)
715 #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
716 #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
718 #define BC_MAX_OBASE ((unsigned) 999)
719 #define BC_MAX_DIM ((unsigned) INT_MAX)
720 #define BC_MAX_SCALE ((unsigned) UINT_MAX)
721 #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
722 #define BC_MAX_NUM BC_MAX_STRING
723 // Unused apart from "limits" message. Just show a "biggish number" there.
724 //#define BC_MAX_NAME BC_MAX_STRING
725 //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
726 //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
727 #define BC_MAX_NAME_STR "999999999"
728 #define BC_MAX_EXP_STR "999999999"
729 #define BC_MAX_VARS_STR "999999999"
731 #define BC_MAX_OBASE_STR "999"
733 #if INT_MAX == 2147483647
734 # define BC_MAX_DIM_STR "2147483647"
735 #elif INT_MAX == 9223372036854775807
736 # define BC_MAX_DIM_STR "9223372036854775807"
738 # error Strange INT_MAX
741 #if UINT_MAX == 4294967295
742 # define BC_MAX_SCALE_STR "4294967295"
743 # define BC_MAX_STRING_STR "4294967294"
744 #elif UINT_MAX == 18446744073709551615
745 # define BC_MAX_SCALE_STR "18446744073709551615"
746 # define BC_MAX_STRING_STR "18446744073709551614"
748 # error Strange UINT_MAX
750 #define BC_MAX_NUM_STR BC_MAX_STRING_STR
753 IF_FEATURE_BC_SIGNALS(smallint ttyin;)
754 IF_FEATURE_CLEAN_UP(smallint exiting;)
761 // For error messages. Can be set to current parsed line,
762 // or [TODO] to current executing line (can be before last parsed one)
769 #if ENABLE_FEATURE_EDITING
770 line_input_t *line_input_state;
773 #define G (*ptr_to_globals)
774 #define INIT_G() do { \
775 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
777 #define FREE_G() do { \
778 FREE_PTR_TO_GLOBALS(); \
780 #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
781 #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
782 #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
783 #if ENABLE_FEATURE_BC_SIGNALS
784 # define G_interrupt bb_got_signal
785 # define G_ttyin G.ttyin
787 # define G_interrupt 0
790 #if ENABLE_FEATURE_CLEAN_UP
791 # define G_exiting G.exiting
795 #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
799 // This is a bit array that corresponds to token types. An entry is
800 // true if the token is valid in an expression, false otherwise.
802 BC_PARSE_EXPRS_BITS = 0
803 + ((uint64_t)((0 << 0)+(0 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (0*8))
804 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (1*8))
805 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(1 << 5)+(1 << 6)+(1 << 7)) << (2*8))
806 + ((uint64_t)((1 << 0)+(1 << 1)+(1 << 2)+(0 << 3)+(0 << 4)+(1 << 5)+(1 << 6)+(0 << 7)) << (3*8))
807 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(1 << 6)+(1 << 7)) << (4*8))
808 + ((uint64_t)((0 << 0)+(0 << 1)+(0 << 2)+(0 << 3)+(0 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (5*8))
809 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)+(0 << 5)+(0 << 6)+(1 << 7)) << (6*8))
810 + ((uint64_t)((0 << 0)+(1 << 1)+(1 << 2)+(0 << 3) ) << (7*8))
812 static ALWAYS_INLINE long bc_parse_exprs(unsigned i)
814 #if ULONG_MAX > 0xffffffff
815 // 64-bit version (will not work correctly for 32-bit longs!)
816 return BC_PARSE_EXPRS_BITS & (1UL << i);
819 unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
821 m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
824 return m & (1UL << i);
828 // This is an array of data for operators that correspond to token types.
829 static const uint8_t bc_parse_ops[] = {
830 #define OP(p,l) ((int)(l) * 0x10 + (p))
831 OP(0, false), OP( 0, false ), // inc dec
834 OP(3, true ), OP( 3, true ), OP( 3, true ), // pow mul div
835 OP(4, true ), OP( 4, true ), // mod + -
836 OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
838 OP(7, true ), OP( 7, true ), // or and
839 OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
840 OP(5, false), OP( 5, false ), // -= =
843 #define bc_parse_op_PREC(i) (bc_parse_ops[i] & 0x0f)
844 #define bc_parse_op_LEFT(i) (bc_parse_ops[i] & 0x10)
846 // Byte array of up to 4 BC_LEX's, packed into 32-bit word
847 typedef uint32_t BcParseNext;
849 // These identify what tokens can come after expressions in certain cases.
851 #define BC_PARSE_NEXT4(a,b,c,d) ( (a) | ((b)<<8) | ((c)<<16) | ((((d)|0x80)<<24)) )
852 #define BC_PARSE_NEXT2(a,b) BC_PARSE_NEXT4(a,b,0xff,0xff)
853 #define BC_PARSE_NEXT1(a) BC_PARSE_NEXT4(a,0xff,0xff,0xff)
854 bc_parse_next_expr = BC_PARSE_NEXT4(BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF),
855 bc_parse_next_param = BC_PARSE_NEXT2(BC_LEX_RPAREN, BC_LEX_COMMA),
856 bc_parse_next_print = BC_PARSE_NEXT4(BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF),
857 bc_parse_next_rel = BC_PARSE_NEXT1(BC_LEX_RPAREN),
858 bc_parse_next_elem = BC_PARSE_NEXT1(BC_LEX_RBRACKET),
859 bc_parse_next_for = BC_PARSE_NEXT1(BC_LEX_SCOLON),
860 bc_parse_next_read = BC_PARSE_NEXT2(BC_LEX_NLINE, BC_LEX_EOF),
861 #undef BC_PARSE_NEXT4
862 #undef BC_PARSE_NEXT2
863 #undef BC_PARSE_NEXT1
868 static const //BcLexType - should be this type, but narrower type saves size:
871 BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
872 BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
873 BC_LEX_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
877 static const //BcLexType - should be this type
880 BC_LEX_OP_MODULUS, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_LPAREN,
881 BC_LEX_INVALID, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID,
882 BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
883 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
884 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
885 BC_LEX_INVALID, BC_LEX_INVALID,
886 BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
887 BC_LEX_OP_REL_LT, BC_LEX_KEY_READ, BC_LEX_INVALID,
888 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
889 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, BC_LEX_INVALID,
890 BC_LEX_KEY_IBASE, BC_LEX_INVALID, BC_LEX_KEY_SCALE, BC_LEX_LOAD_POP,
891 BC_LEX_INVALID, BC_LEX_OP_BOOL_NOT, BC_LEX_KEY_OBASE, BC_LEX_PRINT_STREAM,
892 BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_INVALID, BC_LEX_INVALID,
893 BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_SCALE_FACTOR, BC_LEX_INVALID,
894 BC_LEX_KEY_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
895 BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
896 BC_LEX_ASCIIFY, BC_LEX_INVALID, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
897 BC_LEX_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, BC_LEX_INVALID,
898 BC_LEX_STORE_IBASE, BC_LEX_INVALID, BC_LEX_STORE_SCALE, BC_LEX_LOAD,
899 BC_LEX_INVALID, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KEY_PRINT,
900 BC_LEX_KEY_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
901 BC_LEX_INVALID, BC_LEX_KEY_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
902 BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
903 BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_INVALID, BC_LEX_OP_DIVMOD,
907 static const //BcInst - should be this type. Using signed narrow type since BC_INST_INVALID is -1
910 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
911 BC_INST_INVALID, BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE,
912 BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS,
913 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
914 BC_INST_INVALID, BC_INST_INVALID,
915 BC_INST_BOOL_NOT, BC_INST_INVALID, BC_INST_INVALID,
916 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
917 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
918 BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_INVALID,
919 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
920 BC_INST_INVALID, BC_INST_INVALID,
921 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
922 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
923 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_IBASE,
924 BC_INST_INVALID, BC_INST_INVALID, BC_INST_LENGTH, BC_INST_INVALID,
925 BC_INST_OBASE, BC_INST_PRINT, BC_INST_QUIT, BC_INST_INVALID,
926 BC_INST_INVALID, BC_INST_SCALE, BC_INST_SQRT, BC_INST_INVALID,
927 BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
928 BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
929 BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
930 BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID,
931 BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
932 BC_INST_PRINT, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
936 static const BcNumBinaryOp bc_program_ops[] = {
937 bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
940 static void fflush_and_check(void)
943 if (ferror(stdout) || ferror(stderr))
944 bb_perror_msg_and_die("output error");
947 #if ENABLE_FEATURE_CLEAN_UP
948 #define QUIT_OR_RETURN_TO_MAIN \
950 IF_FEATURE_BC_SIGNALS(G_ttyin = 0;) /* do not loop in main loop anymore */ \
952 return BC_STATUS_FAILURE; \
955 #define QUIT_OR_RETURN_TO_MAIN quit()
958 static void quit(void) NORETURN;
959 static void quit(void)
962 bb_perror_msg_and_die("input error");
967 static void bc_verror_msg(const char *fmt, va_list p)
969 const char *sv = sv; /* for compiler */
972 applet_name = xasprintf("%s: %s:%u", applet_name, G.prog.file, G.err_line);
974 bb_verror_msg(fmt, p, NULL);
976 free((char*)applet_name);
981 static NOINLINE int bc_error_fmt(const char *fmt, ...)
986 bc_verror_msg(fmt, p);
989 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
991 return BC_STATUS_FAILURE;
995 static NOINLINE int bc_posix_error_fmt(const char *fmt, ...)
999 // Are non-POSIX constructs totally ok?
1000 if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
1001 return BC_STATUS_SUCCESS; // yes
1004 bc_verror_msg(fmt, p);
1007 // Do we treat non-POSIX constructs as errors?
1008 if (!(option_mask32 & BC_FLAG_S))
1009 return BC_STATUS_SUCCESS; // no, it's a warning
1010 if (!ENABLE_FEATURE_CLEAN_UP && !G_ttyin)
1012 return BC_STATUS_FAILURE;
1016 // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
1017 // This idiom begs for tail-call optimization, but for it to work,
1018 // function must not have caller-cleaned parameters on stack.
1019 // Unfortunately, vararg function API does exactly that on most arches.
1020 // Thus, use these shims for the cases when we have no vararg PARAMS:
1021 static int bc_error(const char *msg)
1023 return bc_error_fmt("%s", msg);
1026 static int bc_POSIX_requires(const char *msg)
1028 return bc_posix_error_fmt("POSIX requires %s", msg);
1030 static int bc_POSIX_does_not_allow(const char *msg)
1032 return bc_posix_error_fmt("%s%s", "POSIX does not allow ", msg);
1034 static int bc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
1036 return bc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; the following is bad:", msg);
1038 static int bc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
1040 return bc_posix_error_fmt("%san empty %s expression in a for loop", "POSIX does not allow ", msg);
1043 static int bc_error_bad_character(char c)
1045 return bc_error_fmt("bad character '%c'", c);
1047 static int bc_error_bad_expression(void)
1049 return bc_error("bad expression");
1051 static int bc_error_bad_token(void)
1053 return bc_error("bad token");
1055 static int bc_error_stack_has_too_few_elements(void)
1057 return bc_error("stack has too few elements");
1059 static int bc_error_variable_is_wrong_type(void)
1061 return bc_error("variable is wrong type");
1063 static int bc_error_nested_read_call(void)
1065 return bc_error("read() call inside of a read() call");
1068 static void bc_vec_grow(BcVec *v, size_t n)
1070 size_t cap = v->cap * 2;
1071 while (cap < v->len + n) cap *= 2;
1072 v->v = xrealloc(v->v, v->size * cap);
1076 static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
1079 v->cap = BC_VEC_START_CAP;
1082 v->v = xmalloc(esize * BC_VEC_START_CAP);
1085 static void bc_char_vec_init(BcVec *v)
1087 bc_vec_init(v, sizeof(char), NULL);
1090 static void bc_vec_expand(BcVec *v, size_t req)
1093 v->v = xrealloc(v->v, v->size * req);
1098 static void bc_vec_pop(BcVec *v)
1102 v->dtor(v->v + (v->size * v->len));
1105 static void bc_vec_npop(BcVec *v, size_t n)
1110 size_t len = v->len - n;
1111 while (v->len > len) v->dtor(v->v + (v->size * --v->len));
1115 static void bc_vec_pop_all(BcVec *v)
1117 bc_vec_npop(v, v->len);
1120 static void bc_vec_push(BcVec *v, const void *data)
1122 if (v->len + 1 > v->cap) bc_vec_grow(v, 1);
1123 memmove(v->v + (v->size * v->len), data, v->size);
1127 static void bc_vec_pushByte(BcVec *v, char data)
1129 bc_vec_push(v, &data);
1132 static void bc_vec_pushZeroByte(BcVec *v)
1134 //bc_vec_pushByte(v, '\0');
1136 bc_vec_push(v, &const_int_0);
1139 static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
1142 bc_vec_push(v, data);
1147 if (v->len == v->cap) bc_vec_grow(v, 1);
1149 ptr = v->v + v->size * idx;
1151 memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
1152 memmove(ptr, data, v->size);
1156 static void bc_vec_string(BcVec *v, size_t len, const char *str)
1159 bc_vec_expand(v, len + 1);
1160 memcpy(v->v, str, len);
1163 bc_vec_pushZeroByte(v);
1166 static void bc_vec_concat(BcVec *v, const char *str)
1170 if (v->len == 0) bc_vec_pushZeroByte(v);
1172 len = v->len + strlen(str);
1174 if (v->cap < len) bc_vec_grow(v, len - v->len);
1175 strcpy(v->v + v->len - 1, str);
1180 static void *bc_vec_item(const BcVec *v, size_t idx)
1182 return v->v + v->size * idx;
1185 static char** bc_program_str(size_t idx)
1187 return bc_vec_item(&G.prog.strs, idx);
1190 static BcFunc* bc_program_func(size_t idx)
1192 return bc_vec_item(&G.prog.fns, idx);
1195 static void *bc_vec_item_rev(const BcVec *v, size_t idx)
1197 return v->v + v->size * (v->len - idx - 1);
1200 static void *bc_vec_top(const BcVec *v)
1202 return v->v + v->size * (v->len - 1);
1205 static void bc_vec_free(void *vec)
1207 BcVec *v = (BcVec *) vec;
1212 static int bc_id_cmp(const void *e1, const void *e2)
1214 return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
1217 static void bc_id_free(void *id)
1219 free(((BcId *) id)->name);
1222 static size_t bc_map_find(const BcVec *v, const void *ptr)
1224 size_t low = 0, high = v->len;
1226 while (low < high) {
1228 size_t mid = (low + high) / 2;
1229 BcId *id = bc_vec_item(v, mid);
1230 int result = bc_id_cmp(ptr, id);
1234 else if (result < 0)
1243 static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
1245 size_t n = *i = bc_map_find(v, ptr);
1248 bc_vec_push(v, ptr);
1249 else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
1250 return 0; // "was not inserted"
1252 bc_vec_pushAt(v, ptr, n);
1253 return 1; // "was inserted"
1257 static size_t bc_map_index(const BcVec *v, const void *ptr)
1259 size_t i = bc_map_find(v, ptr);
1260 if (i >= v->len) return BC_VEC_INVALID_IDX;
1261 return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
1265 static int push_input_byte(BcVec *vec, char c)
1267 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1270 // Bad chars on this line, ignore entire line
1271 bc_error_fmt("illegal character 0x%02x", c);
1274 bc_vec_pushByte(vec, (char)c);
1278 static BcStatus bc_read_line(BcVec *vec)
1283 s = BC_STATUS_SUCCESS;
1288 bc_vec_pop_all(vec);
1292 #if ENABLE_FEATURE_BC_SIGNALS
1293 if (G_interrupt) { // ^C was pressed
1296 // GNU bc says "interrupted execution."
1297 // GNU dc says "Interrupt!"
1298 fputs("\ninterrupted execution\n", stderr);
1300 # if ENABLE_FEATURE_EDITING
1303 # define line_buf bb_common_bufsiz1
1304 n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
1305 if (n <= 0) { // read errors or EOF, or ^D, or ^C
1315 bad_chars |= push_input_byte(vec, c);
1322 IF_FEATURE_BC_SIGNALS(errno = 0;)
1325 #if ENABLE_FEATURE_BC_SIGNALS && !ENABLE_FEATURE_EDITING
1326 // Both conditions appear simultaneously, check both just in case
1327 if (errno == EINTR || G_interrupt) {
1335 quit(); // this emits error message
1337 // Note: EOF does not append '\n', therefore:
1338 // printf 'print 123\n' | bc - works
1339 // printf 'print 123' | bc - fails (syntax error)
1342 bad_chars |= push_input_byte(vec, c);
1343 } while (c != '\n');
1345 } while (bad_chars);
1347 bc_vec_pushZeroByte(vec);
1352 static char* bc_read_file(const char *path)
1355 size_t size = ((size_t) -1);
1358 // Never returns NULL (dies on errors)
1359 buf = xmalloc_xopen_read_close(path, &size);
1361 for (i = 0; i < size; ++i) {
1363 if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
1375 static void bc_num_setToZero(BcNum *n, size_t scale)
1382 static void bc_num_zero(BcNum *n)
1384 bc_num_setToZero(n, 0);
1387 static void bc_num_one(BcNum *n)
1389 bc_num_setToZero(n, 0);
1394 static void bc_num_ten(BcNum *n)
1396 bc_num_setToZero(n, 0);
1402 // Note: this also sets BcNum to zero
1403 static void bc_num_init(BcNum *n, size_t req)
1405 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1406 //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
1407 n->num = xmalloc(req);
1414 static void bc_num_init_DEF_SIZE(BcNum *n)
1416 bc_num_init(n, BC_NUM_DEF_SIZE);
1419 static void bc_num_expand(BcNum *n, size_t req)
1421 req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
1423 n->num = xrealloc(n->num, req);
1428 static void bc_num_free(void *num)
1430 free(((BcNum *) num)->num);
1433 static void bc_num_copy(BcNum *d, BcNum *s)
1436 bc_num_expand(d, s->cap);
1440 memcpy(d->num, s->num, sizeof(BcDig) * d->len);
1444 static BcStatus bc_num_ulong(BcNum *n, unsigned long *result_p)
1447 unsigned long pow, result;
1449 if (n->neg) return bc_error("negative number");
1451 for (result = 0, pow = 1, i = n->rdx; i < n->len; ++i) {
1453 unsigned long prev = result, powprev = pow;
1455 result += ((unsigned long) n->num[i]) * pow;
1458 if (result < prev || pow < powprev)
1459 return bc_error("overflow");
1465 return BC_STATUS_SUCCESS;
1468 static void bc_num_ulong2num(BcNum *n, unsigned long val)
1476 if (val == 0) return;
1478 for (len = 1, i = ULONG_MAX; i != 0; i /= 10, ++len) bc_num_expand(n, len);
1479 for (ptr = n->num, i = 0; val; ++i, ++n->len, val /= 10) ptr[i] = val % 10;
1482 static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b,
1486 for (i = 0; i < len; ++i) {
1487 for (a[i] -= b[i], j = 0; a[i + j] < 0;) {
1494 #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
1495 #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
1496 #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
1497 //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
1498 static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
1500 return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
1502 //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
1503 static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
1505 return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
1508 static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
1512 for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
1513 return BC_NUM_NEG(i + 1, c < 0);
1516 static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
1518 size_t i, min, a_int, b_int, diff;
1519 BcDig *max_num, *min_num;
1520 bool a_max, neg = false;
1523 if (a == b) return 0;
1524 if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
1525 if (b->len == 0) return BC_NUM_NEG(1, a->neg);
1535 a_int = BC_NUM_INT(a);
1536 b_int = BC_NUM_INT(b);
1538 a_max = (a->rdx > b->rdx);
1540 if (a_int != 0) return (ssize_t) a_int;
1544 diff = a->rdx - b->rdx;
1545 max_num = a->num + diff;
1550 diff = b->rdx - a->rdx;
1551 max_num = b->num + diff;
1555 cmp = bc_num_compare(max_num, min_num, b_int + min);
1556 if (cmp != 0) return BC_NUM_NEG(cmp, (!a_max) != neg);
1558 for (max_num -= diff, i = diff - 1; i < diff; --i) {
1559 if (max_num[i]) return BC_NUM_NEG(1, (!a_max) != neg);
1565 static void bc_num_truncate(BcNum *n, size_t places)
1567 if (places == 0) return;
1573 memmove(n->num, n->num + places, n->len * sizeof(BcDig));
1577 static void bc_num_extend(BcNum *n, size_t places)
1579 size_t len = n->len + places;
1583 if (n->cap < len) bc_num_expand(n, len);
1585 memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
1586 memset(n->num, 0, sizeof(BcDig) * places);
1593 static void bc_num_clean(BcNum *n)
1595 while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
1598 else if (n->len < n->rdx)
1602 static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
1605 bc_num_extend(n, scale - n->rdx);
1607 bc_num_truncate(n, n->rdx - scale);
1610 if (n->len != 0) n->neg = !neg1 != !neg2;
1613 static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
1618 b->len = n->len - idx;
1620 a->rdx = b->rdx = 0;
1622 memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
1623 memcpy(a->num, n->num, idx * sizeof(BcDig));
1634 static BcStatus bc_num_shift(BcNum *n, size_t places)
1636 if (places == 0 || n->len == 0) return BC_STATUS_SUCCESS;
1638 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
1639 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
1640 if (places + n->len > BC_MAX_NUM)
1641 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
1644 if (n->rdx >= places)
1647 bc_num_extend(n, places - n->rdx);
1653 return BC_STATUS_SUCCESS;
1656 static BcStatus bc_num_inv(BcNum *a, BcNum *b, size_t scale)
1665 return bc_num_div(&one, a, b, scale);
1668 static BcStatus bc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1670 BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
1671 size_t i, max, min_rdx, min_int, diff, a_int, b_int;
1674 // Because this function doesn't need to use scale (per the bc spec),
1675 // I am hijacking it to say whether it's doing an add or a subtract.
1679 if (sub && c->len) c->neg = !c->neg;
1680 return BC_STATUS_SUCCESS;
1682 else if (b->len == 0) {
1684 return BC_STATUS_SUCCESS;
1688 c->rdx = BC_MAX(a->rdx, b->rdx);
1689 min_rdx = BC_MIN(a->rdx, b->rdx);
1692 if (a->rdx > b->rdx) {
1693 diff = a->rdx - b->rdx;
1695 ptr_a = a->num + diff;
1699 diff = b->rdx - a->rdx;
1702 ptr_b = b->num + diff;
1705 for (ptr_c = c->num, i = 0; i < diff; ++i, ++c->len) ptr_c[i] = ptr[i];
1708 a_int = BC_NUM_INT(a);
1709 b_int = BC_NUM_INT(b);
1711 if (a_int > b_int) {
1722 for (carry = 0, i = 0; i < min_rdx + min_int; ++i, ++c->len) {
1723 in = ((int) ptr_a[i]) + ((int) ptr_b[i]) + carry;
1725 ptr_c[i] = (BcDig)(in % 10);
1728 for (; i < max + min_rdx; ++i, ++c->len) {
1729 in = ((int) ptr[i]) + carry;
1731 ptr_c[i] = (BcDig)(in % 10);
1734 if (carry != 0) c->num[c->len++] = (BcDig) carry;
1736 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1739 static BcStatus bc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
1742 BcNum *minuend, *subtrahend;
1744 bool aneg, bneg, neg;
1746 // Because this function doesn't need to use scale (per the bc spec),
1747 // I am hijacking it to say whether it's doing an add or a subtract.
1751 if (sub && c->len) c->neg = !c->neg;
1752 return BC_STATUS_SUCCESS;
1754 else if (b->len == 0) {
1756 return BC_STATUS_SUCCESS;
1761 a->neg = b->neg = false;
1763 cmp = bc_num_cmp(a, b);
1769 bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
1770 return BC_STATUS_SUCCESS;
1779 if (sub) neg = !neg;
1784 bc_num_copy(c, minuend);
1787 if (c->rdx < subtrahend->rdx) {
1788 bc_num_extend(c, subtrahend->rdx - c->rdx);
1792 start = c->rdx - subtrahend->rdx;
1794 bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
1798 return BC_STATUS_SUCCESS; // can't make void, see bc_num_binary()
1801 static BcStatus bc_num_k(BcNum *restrict a, BcNum *restrict b,
1805 size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
1806 BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
1809 if (a->len == 0 || b->len == 0) {
1811 return BC_STATUS_SUCCESS;
1813 aone = BC_NUM_ONE(a);
1814 if (aone || BC_NUM_ONE(b)) {
1815 bc_num_copy(c, aone ? b : a);
1816 return BC_STATUS_SUCCESS;
1819 if (a->len + b->len < BC_NUM_KARATSUBA_LEN ||
1820 a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN)
1825 bc_num_expand(c, a->len + b->len + 1);
1827 memset(c->num, 0, sizeof(BcDig) * c->cap);
1830 for (i = 0; i < b->len; ++i) {
1833 for (j = 0; j < a->len; ++j) {
1834 unsigned in = c->num[i + j];
1835 in += ((unsigned) a->num[j]) * ((unsigned) b->num[i]) + carry;
1836 // note: compilers prefer _unsigned_ div/const
1838 c->num[i + j] = (BcDig)(in % 10);
1841 c->num[i + j] += (BcDig) carry;
1842 len = BC_MAX(len, i + j + !!carry);
1845 // a*a <- without check below, this will not be interruptible
1846 if (G_interrupt) return BC_STATUS_FAILURE;
1851 return BC_STATUS_SUCCESS;
1854 bc_num_init(&l1, max);
1855 bc_num_init(&h1, max);
1856 bc_num_init(&l2, max);
1857 bc_num_init(&h2, max);
1858 bc_num_init(&m1, max);
1859 bc_num_init(&m2, max);
1860 bc_num_init(&z0, max);
1861 bc_num_init(&z1, max);
1862 bc_num_init(&z2, max);
1863 bc_num_init(&temp, max + max);
1865 bc_num_split(a, max2, &l1, &h1);
1866 bc_num_split(b, max2, &l2, &h2);
1868 s = bc_num_add(&h1, &l1, &m1, 0);
1870 s = bc_num_add(&h2, &l2, &m2, 0);
1873 s = bc_num_k(&h1, &h2, &z0);
1875 s = bc_num_k(&m1, &m2, &z1);
1877 s = bc_num_k(&l1, &l2, &z2);
1880 s = bc_num_sub(&z1, &z0, &temp, 0);
1882 s = bc_num_sub(&temp, &z2, &z1, 0);
1885 s = bc_num_shift(&z0, max2 * 2);
1887 s = bc_num_shift(&z1, max2);
1889 s = bc_num_add(&z0, &z1, &temp, 0);
1891 s = bc_num_add(&temp, &z2, c, 0);
1907 static BcStatus bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1911 size_t maxrdx = BC_MAX(a->rdx, b->rdx);
1913 scale = BC_MAX(scale, a->rdx);
1914 scale = BC_MAX(scale, b->rdx);
1915 scale = BC_MIN(a->rdx + b->rdx, scale);
1916 maxrdx = BC_MAX(maxrdx, scale);
1918 bc_num_init(&cpa, a->len);
1919 bc_num_init(&cpb, b->len);
1921 bc_num_copy(&cpa, a);
1922 bc_num_copy(&cpb, b);
1923 cpa.neg = cpb.neg = false;
1925 s = bc_num_shift(&cpa, maxrdx);
1927 s = bc_num_shift(&cpb, maxrdx);
1929 s = bc_num_k(&cpa, &cpb, c);
1933 bc_num_expand(c, c->len + maxrdx);
1935 if (c->len < maxrdx) {
1936 memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
1941 bc_num_retireMul(c, scale, a->neg, b->neg);
1949 static BcStatus bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
1951 BcStatus s = BC_STATUS_SUCCESS;
1958 return bc_error("divide by zero");
1959 else if (a->len == 0) {
1960 bc_num_setToZero(c, scale);
1961 return BC_STATUS_SUCCESS;
1963 else if (BC_NUM_ONE(b)) {
1965 bc_num_retireMul(c, scale, a->neg, b->neg);
1966 return BC_STATUS_SUCCESS;
1969 bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
1970 bc_num_copy(&cp, a);
1974 bc_num_expand(&cp, len + 2);
1975 bc_num_extend(&cp, len - cp.len);
1978 if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
1980 if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
1982 if (b->rdx == b->len) {
1983 for (i = 0; zero && i < len; ++i) zero = !b->num[len - i - 1];
1987 if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
1989 // We want an extra zero in front to make things simpler.
1990 cp.num[cp.len++] = 0;
1993 bc_num_expand(c, cp.len);
1996 memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
2001 for (i = end - 1; !s && i < end; --i) {
2003 for (q = 0; (!s && n[len] != 0) || bc_num_compare(n, p, len) >= 0; ++q)
2004 bc_num_subArrays(n, p, len);
2008 // 1/a <- without check below, this will not be interruptible
2010 s = BC_STATUS_FAILURE;
2015 bc_num_retireMul(c, scale, a->neg, b->neg);
2021 static BcStatus bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
2022 BcNum *restrict d, size_t scale, size_t ts)
2029 return bc_error("divide by zero");
2032 bc_num_setToZero(d, ts);
2033 return BC_STATUS_SUCCESS;
2036 bc_num_init(&temp, d->cap);
2037 s = bc_num_d(a, b, c, scale);
2040 if (scale != 0) scale = ts;
2042 s = bc_num_m(c, b, &temp, scale);
2044 s = bc_num_sub(a, &temp, d, scale);
2047 if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
2050 bc_num_retireMul(d, ts, a->neg, b->neg);
2058 static BcStatus bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2062 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2064 bc_num_init(&c1, len);
2065 s = bc_num_r(a, b, &c1, c, scale, ts);
2071 static BcStatus bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
2073 BcStatus s = BC_STATUS_SUCCESS;
2076 size_t i, powrdx, resrdx;
2079 if (b->rdx) return bc_error("non integer number");
2083 return BC_STATUS_SUCCESS;
2085 else if (a->len == 0) {
2086 bc_num_setToZero(c, scale);
2087 return BC_STATUS_SUCCESS;
2089 else if (BC_NUM_ONE(b)) {
2093 s = bc_num_inv(a, c, scale);
2100 s = bc_num_ulong(b, &pow);
2103 bc_num_init(©, a->len);
2104 bc_num_copy(©, a);
2109 if (a->rdx * pow < scale)
2110 scale = a->rdx * pow;
2115 for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
2117 s = bc_num_mul(©, ©, ©, powrdx);
2119 // Not needed: bc_num_mul() has a check for ^C:
2120 //if (G_interrupt) {
2121 // s = BC_STATUS_FAILURE;
2126 bc_num_copy(c, ©);
2128 for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
2131 s = bc_num_mul(©, ©, ©, powrdx);
2136 s = bc_num_mul(c, ©, c, resrdx);
2139 // Not needed: bc_num_mul() has a check for ^C:
2140 //if (G_interrupt) {
2141 // s = BC_STATUS_FAILURE;
2147 s = bc_num_inv(c, c, scale);
2151 if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
2153 // We can't use bc_num_clean() here.
2154 for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i];
2155 if (zero) bc_num_setToZero(c, scale);
2162 static BcStatus bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
2163 BcNumBinaryOp op, size_t req)
2166 BcNum num2, *ptr_a, *ptr_b;
2171 memcpy(ptr_a, c, sizeof(BcNum));
2180 memcpy(ptr_b, c, sizeof(BcNum));
2188 bc_num_init(c, req);
2190 bc_num_expand(c, req);
2192 s = op(ptr_a, ptr_b, c, scale);
2194 if (init) bc_num_free(&num2);
2199 static void bc_num_printNewline(void)
2201 if (G.prog.nchars == G.prog.len - 1) {
2209 static void bc_num_printChar(size_t num, size_t width, bool radix)
2212 bb_putchar((char) num);
2213 G.prog.nchars += width;
2217 static void bc_num_printDigits(size_t num, size_t width, bool radix)
2221 bc_num_printNewline();
2222 bb_putchar(radix ? '.' : ' ');
2225 bc_num_printNewline();
2226 for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
2229 for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
2231 bc_num_printNewline();
2234 bb_putchar(((char) dig) + '0');
2238 static void bc_num_printHex(size_t num, size_t width, bool radix)
2241 bc_num_printNewline();
2246 bc_num_printNewline();
2247 bb_putchar(bb_hexdigits_upcase[num]);
2248 G.prog.nchars += width;
2251 static void bc_num_printDecimal(BcNum *n)
2253 size_t i, rdx = n->rdx - 1;
2255 if (n->neg) bb_putchar('-');
2256 G.prog.nchars += n->neg;
2258 for (i = n->len - 1; i < n->len; --i)
2259 bc_num_printHex((size_t) n->num[i], 1, i == rdx);
2262 static BcStatus bc_num_printNum(BcNum *n, BcNum *base, size_t width, BcNumDigitOp print)
2266 BcNum intp, fracp, digit, frac_len;
2267 unsigned long dig, *ptr;
2272 print(0, width, false);
2273 return BC_STATUS_SUCCESS;
2276 bc_vec_init(&stack, sizeof(long), NULL);
2277 bc_num_init(&intp, n->len);
2278 bc_num_init(&fracp, n->rdx);
2279 bc_num_init(&digit, width);
2280 bc_num_init(&frac_len, BC_NUM_INT(n));
2281 bc_num_copy(&intp, n);
2282 bc_num_one(&frac_len);
2284 bc_num_truncate(&intp, intp.rdx);
2285 s = bc_num_sub(n, &intp, &fracp, 0);
2288 while (intp.len != 0) {
2289 s = bc_num_divmod(&intp, base, &intp, &digit, 0);
2291 s = bc_num_ulong(&digit, &dig);
2293 bc_vec_push(&stack, &dig);
2296 for (i = 0; i < stack.len; ++i) {
2297 ptr = bc_vec_item_rev(&stack, i);
2298 print(*ptr, width, false);
2301 if (!n->rdx) goto err;
2303 for (radix = true; frac_len.len <= n->rdx; radix = false) {
2304 s = bc_num_mul(&fracp, base, &fracp, n->rdx);
2306 s = bc_num_ulong(&fracp, &dig);
2308 bc_num_ulong2num(&intp, dig);
2309 s = bc_num_sub(&fracp, &intp, &fracp, 0);
2311 print(dig, width, radix);
2312 s = bc_num_mul(&frac_len, base, &frac_len, 0);
2317 bc_num_free(&frac_len);
2318 bc_num_free(&digit);
2319 bc_num_free(&fracp);
2321 bc_vec_free(&stack);
2325 static BcStatus bc_num_printBase(BcNum *n)
2339 if (G.prog.ob_t <= BC_NUM_MAX_IBASE) {
2341 print = bc_num_printHex;
2344 for (i = G.prog.ob_t - 1, width = 0; i != 0; i /= 10, ++width)
2346 print = bc_num_printDigits;
2349 s = bc_num_printNum(n, &G.prog.ob, width, print);
2356 static BcStatus bc_num_stream(BcNum *n, BcNum *base)
2358 return bc_num_printNum(n, base, 1, bc_num_printChar);
2362 static bool bc_num_strValid(const char *val, size_t base)
2367 b = (BcDig)(base <= 10 ? base + '0' : base - 10 + 'A');
2374 if (radix) return false;
2378 if (c < '0' || c >= b || (c > '9' && c < 'A'))
2384 // Note: n is already "bc_num_zero()"ed,
2385 // leading zeroes in "val" are removed
2386 static void bc_num_parseDecimal(BcNum *n, const char *val)
2397 for (i = 0; val[i]; ++i) {
2398 if (val[i] != '0' && val[i] != '.') {
2403 bc_num_expand(n, len);
2405 ptr = strchr(val, '.');
2409 n->rdx = (size_t)((val + len) - (ptr + 1));
2414 n->num[n->len] = val[i] - '0';
2417 if ((ssize_t)--i == (ssize_t)-1) break;
2418 if (val[i] == '.') goto skip_dot;
2423 // Note: n is already "bc_num_zero()"ed,
2424 // leading zeroes in "val" are removed
2425 static void bc_num_parseBase(BcNum *n, const char *val, BcNum *base)
2428 BcNum temp, mult, result;
2433 for (i = 0; ; ++i) {
2436 if (val[i] != '.' && val[i] != '0')
2440 bc_num_init_DEF_SIZE(&temp);
2441 bc_num_init_DEF_SIZE(&mult);
2445 if (c == '\0') goto int_err;
2446 if (c == '.') break;
2448 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2450 s = bc_num_mul(n, base, &mult, 0);
2451 if (s) goto int_err;
2452 bc_num_ulong2num(&temp, v);
2453 s = bc_num_add(&mult, &temp, n, 0);
2454 if (s) goto int_err;
2457 bc_num_init(&result, base->len);
2458 //bc_num_zero(&result); - already is
2464 if (c == '\0') break;
2467 v = (unsigned long) (c <= '9' ? c - '0' : c - 'A' + 10);
2469 s = bc_num_mul(&result, base, &result, 0);
2471 bc_num_ulong2num(&temp, v);
2472 s = bc_num_add(&result, &temp, &result, 0);
2474 s = bc_num_mul(&mult, base, &mult, 0);
2478 s = bc_num_div(&result, &mult, &result, digits);
2480 s = bc_num_add(n, &result, n, digits);
2484 if (n->rdx < digits) bc_num_extend(n, digits - n->rdx);
2489 bc_num_free(&result);
2495 static BcStatus bc_num_parse(BcNum *n, const char *val, BcNum *base,
2498 if (!bc_num_strValid(val, base_t))
2499 return bc_error("bad number string");
2502 while (*val == '0') val++;
2505 bc_num_parseDecimal(n, val);
2507 bc_num_parseBase(n, val, base);
2509 return BC_STATUS_SUCCESS;
2512 static BcStatus bc_num_print(BcNum *n, bool newline)
2514 BcStatus s = BC_STATUS_SUCCESS;
2516 bc_num_printNewline();
2522 else if (G.prog.ob_t == 10)
2523 bc_num_printDecimal(n);
2525 s = bc_num_printBase(n);
2535 static BcStatus bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2537 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_a : bc_num_s;
2539 return bc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b));
2542 static BcStatus bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2544 BcNumBinaryOp op = (!a->neg == !b->neg) ? bc_num_s : bc_num_a;
2546 return bc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b));
2549 static BcStatus bc_num_mul(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_m, req);
2555 static BcStatus bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2557 size_t req = BC_NUM_MREQ(a, b, scale);
2558 return bc_num_binary(a, b, c, scale, bc_num_d, req);
2561 static BcStatus bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2563 size_t req = BC_NUM_MREQ(a, b, scale);
2564 return bc_num_binary(a, b, c, scale, bc_num_rem, req);
2567 static BcStatus bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
2569 return bc_num_binary(a, b, c, scale, bc_num_p, a->len * b->len + 1);
2572 static BcStatus bc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
2575 BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
2576 size_t pow, len, digs, digs1, resrdx, req, times = 0;
2577 ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
2579 req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
2580 bc_num_expand(b, req);
2583 bc_num_setToZero(b, scale);
2584 return BC_STATUS_SUCCESS;
2587 return bc_error("negative number");
2588 else if (BC_NUM_ONE(a)) {
2590 bc_num_extend(b, scale);
2591 return BC_STATUS_SUCCESS;
2594 scale = BC_MAX(scale, a->rdx) + 1;
2595 len = a->len + scale;
2597 bc_num_init(&num1, len);
2598 bc_num_init(&num2, len);
2599 bc_num_init_DEF_SIZE(&half);
2605 bc_num_init(&f, len);
2606 bc_num_init(&fprime, len);
2612 pow = BC_NUM_INT(a);
2621 pow -= 2 - (pow & 1);
2623 bc_num_extend(x0, pow);
2625 // Make sure to move the radix back.
2629 x0->rdx = digs = digs1 = 0;
2631 len = BC_NUM_INT(x0) + resrdx - 1;
2633 while (cmp != 0 || digs < len) {
2635 s = bc_num_div(a, x0, &f, resrdx);
2637 s = bc_num_add(x0, &f, &fprime, resrdx);
2639 s = bc_num_mul(&fprime, &half, x1, resrdx);
2642 cmp = bc_num_cmp(x1, x0);
2643 digs = x1->len - (unsigned long long) llabs(cmp);
2645 if (cmp == cmp2 && digs == digs1)
2650 resrdx += times > 4;
2663 if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
2666 bc_num_free(&fprime);
2674 static BcStatus bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
2680 size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
2683 memcpy(&num2, c, sizeof(BcNum));
2685 bc_num_init(c, len);
2690 bc_num_expand(c, len);
2693 s = bc_num_r(ptr_a, b, c, d, scale, ts);
2695 if (init) bc_num_free(&num2);
2701 static BcStatus bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
2704 BcNum base, exp, two, temp;
2707 return bc_error("divide by zero");
2708 if (a->rdx || b->rdx || c->rdx)
2709 return bc_error("non integer number");
2711 return bc_error("negative number");
2713 bc_num_expand(d, c->len);
2714 bc_num_init(&base, c->len);
2715 bc_num_init(&exp, b->len);
2716 bc_num_init_DEF_SIZE(&two);
2717 bc_num_init(&temp, b->len);
2723 s = bc_num_rem(a, c, &base, 0);
2725 bc_num_copy(&exp, b);
2727 while (exp.len != 0) {
2729 s = bc_num_divmod(&exp, &two, &exp, &temp, 0);
2732 if (BC_NUM_ONE(&temp)) {
2733 s = bc_num_mul(d, &base, &temp, 0);
2735 s = bc_num_rem(&temp, c, d, 0);
2739 s = bc_num_mul(&base, &base, &temp, 0);
2741 s = bc_num_rem(&temp, c, &base, 0);
2755 static BcStatus bc_func_insert(BcFunc *f, char *name, bool var)
2760 for (i = 0; i < f->autos.len; ++i) {
2761 if (strcmp(name, ((BcId *) bc_vec_item(&f->autos, i))->name) == 0)
2762 return bc_error("function parameter or auto var has the same name as another");
2768 bc_vec_push(&f->autos, &a);
2770 return BC_STATUS_SUCCESS;
2774 static void bc_func_init(BcFunc *f)
2776 bc_char_vec_init(&f->code);
2777 bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);
2778 bc_vec_init(&f->labels, sizeof(size_t), NULL);
2782 static void bc_func_free(void *func)
2784 BcFunc *f = (BcFunc *) func;
2785 bc_vec_free(&f->code);
2786 bc_vec_free(&f->autos);
2787 bc_vec_free(&f->labels);
2790 static void bc_array_expand(BcVec *a, size_t len);
2792 static void bc_array_init(BcVec *a, bool nums)
2795 bc_vec_init(a, sizeof(BcNum), bc_num_free);
2797 bc_vec_init(a, sizeof(BcVec), bc_vec_free);
2798 bc_array_expand(a, 1);
2801 static void bc_array_expand(BcVec *a, size_t len)
2805 if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
2806 while (len > a->len) {
2807 bc_num_init_DEF_SIZE(&data.n);
2808 bc_vec_push(a, &data.n);
2812 while (len > a->len) {
2813 bc_array_init(&data.v, true);
2814 bc_vec_push(a, &data.v);
2819 static void bc_array_copy(BcVec *d, const BcVec *s)
2824 bc_vec_expand(d, s->cap);
2827 for (i = 0; i < s->len; ++i) {
2828 BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
2829 bc_num_init(dnum, snum->len);
2830 bc_num_copy(dnum, snum);
2834 static void bc_string_free(void *string)
2836 free(*((char **) string));
2840 static void bc_result_copy(BcResult *d, BcResult *src)
2846 case BC_RESULT_TEMP:
2847 case BC_RESULT_IBASE:
2848 case BC_RESULT_SCALE:
2849 case BC_RESULT_OBASE:
2851 bc_num_init(&d->d.n, src->d.n.len);
2852 bc_num_copy(&d->d.n, &src->d.n);
2857 case BC_RESULT_ARRAY:
2858 case BC_RESULT_ARRAY_ELEM:
2860 d->d.id.name = xstrdup(src->d.id.name);
2864 case BC_RESULT_CONSTANT:
2865 case BC_RESULT_LAST:
2869 memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
2876 static void bc_result_free(void *result)
2878 BcResult *r = (BcResult *) result;
2882 case BC_RESULT_TEMP:
2883 case BC_RESULT_IBASE:
2884 case BC_RESULT_SCALE:
2885 case BC_RESULT_OBASE:
2887 bc_num_free(&r->d.n);
2892 case BC_RESULT_ARRAY:
2893 case BC_RESULT_ARRAY_ELEM:
2907 static void bc_lex_lineComment(BcLex *l)
2909 l->t.t = BC_LEX_WHITESPACE;
2910 while (l->i < l->len && l->buf[l->i++] != '\n');
2914 static void bc_lex_whitespace(BcLex *l)
2917 l->t.t = BC_LEX_WHITESPACE;
2918 for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
2921 static BcStatus bc_lex_number(BcLex *l, char start)
2923 const char *buf = l->buf + l->i;
2924 size_t len, hits = 0, bslashes = 0, i = 0, j;
2926 bool last_pt, pt = start == '.';
2929 l->t.t = BC_LEX_NUMBER;
2931 while (c != 0 && (isdigit(c) || (c >= 'A' && c <= 'F') ||
2932 (c == '.' && !pt) || (c == '\\' && buf[i + 1] == '\n')))
2946 len = i + !last_pt - bslashes * 2;
2947 // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
2948 if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
2949 if (len > BC_MAX_NUM)
2950 return bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]");
2953 bc_vec_pop_all(&l->t.v);
2954 bc_vec_expand(&l->t.v, len + 1);
2955 bc_vec_push(&l->t.v, &start);
2957 for (buf -= 1, j = 1; j < len + hits * 2; ++j) {
2961 // If we have hit a backslash, skip it. We don't have
2962 // to check for a newline because it's guaranteed.
2963 if (hits < bslashes && c == '\\') {
2969 bc_vec_push(&l->t.v, &c);
2972 bc_vec_pushZeroByte(&l->t.v);
2975 return BC_STATUS_SUCCESS;
2978 static BcStatus bc_lex_name(BcLex *l)
2981 const char *buf = l->buf + l->i - 1;
2984 l->t.t = BC_LEX_NAME;
2986 while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
2988 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
2989 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
2990 if (i > BC_MAX_STRING)
2991 return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
2993 bc_vec_string(&l->t.v, i, buf);
2995 // Increment the index. We minus 1 because it has already been incremented.
2998 return BC_STATUS_SUCCESS;
3001 static void bc_lex_init(BcLex *l, BcLexNext next)
3004 bc_char_vec_init(&l->t.v);
3007 static void bc_lex_free(BcLex *l)
3009 bc_vec_free(&l->t.v);
3012 static void bc_lex_file(BcLex *l)
3014 G.err_line = l->line = 1;
3018 static BcStatus bc_lex_next(BcLex *l)
3023 if (l->t.last == BC_LEX_EOF) return bc_error("end of file");
3025 l->line += l->newline;
3026 G.err_line = l->line;
3027 l->t.t = BC_LEX_EOF;
3029 l->newline = (l->i == l->len);
3030 if (l->newline) return BC_STATUS_SUCCESS;
3032 // Loop until failure or we don't have whitespace. This
3033 // is so the parser doesn't get inundated with whitespace.
3036 } while (!s && l->t.t == BC_LEX_WHITESPACE);
3041 static BcStatus bc_lex_text(BcLex *l, const char *text)
3045 l->len = strlen(text);
3046 l->t.t = l->t.last = BC_LEX_INVALID;
3047 return bc_lex_next(l);
3051 static BcStatus bc_lex_identifier(BcLex *l)
3055 const char *buf = l->buf + l->i - 1;
3057 for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
3058 const char *keyword8 = bc_lex_kws[i].name8;
3060 while (buf[j] != '\0' && buf[j] == keyword8[j]) {
3062 if (j == 8) goto match;
3064 if (keyword8[j] != '\0')
3067 // buf starts with keyword bc_lex_kws[i]
3068 l->t.t = BC_LEX_KEY_1st_keyword + i;
3069 if (!bc_lex_kws_POSIX(i)) {
3070 s = bc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
3074 // We minus 1 because the index has already been incremented.
3076 return BC_STATUS_SUCCESS;
3082 if (l->t.v.len > 2) {
3085 // bc: POSIX only allows one character names; the following is bad: 'qwe=1
3087 unsigned len = strchrnul(buf, '\n') - buf;
3088 s = bc_posix_error_fmt("POSIX only allows one character names; the following is bad: '%.*s'", len, buf);
3094 static BcStatus bc_lex_string(BcLex *l)
3096 size_t len, nls = 0, i = l->i;
3099 l->t.t = BC_LEX_STR;
3101 for (c = l->buf[i]; c != 0 && c != '"'; c = l->buf[++i]) nls += (c == '\n');
3105 return bc_error("string end could not be found");
3109 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3110 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3111 if (len > BC_MAX_STRING)
3112 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3114 bc_vec_string(&l->t.v, len, l->buf + l->i);
3118 G.err_line = l->line;
3120 return BC_STATUS_SUCCESS;
3123 static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without)
3125 if (l->buf[l->i] == '=') {
3133 static BcStatus bc_lex_comment(BcLex *l)
3136 const char *buf = l->buf;
3138 l->t.t = BC_LEX_WHITESPACE;
3151 return bc_error("comment end could not be found");
3159 G.err_line = l->line;
3161 return BC_STATUS_SUCCESS;
3164 static BcStatus bc_lex_token(BcLex *l)
3166 BcStatus s = BC_STATUS_SUCCESS;
3167 char c = l->buf[l->i++], c2;
3169 // This is the workhorse of the lexer.
3176 l->t.t = !c ? BC_LEX_EOF : BC_LEX_NLINE;
3186 bc_lex_whitespace(l);
3192 bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
3194 if (l->t.t == BC_LEX_OP_BOOL_NOT) {
3195 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
3204 s = bc_lex_string(l);
3210 s = bc_POSIX_does_not_allow("'#' script comments");
3213 bc_lex_lineComment(l);
3220 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
3229 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
3233 l->t.t = BC_LEX_OP_BOOL_AND;
3236 l->t.t = BC_LEX_INVALID;
3237 s = bc_error_bad_character('&');
3246 l->t.t = (BcLexType)(c - '(' + BC_LEX_LPAREN);
3252 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
3261 l->t.t = BC_LEX_OP_INC;
3264 bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
3270 l->t.t = BC_LEX_COMMA;
3279 l->t.t = BC_LEX_OP_DEC;
3282 bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
3288 if (isdigit(l->buf[l->i]))
3289 s = bc_lex_number(l, c);
3291 l->t.t = BC_LEX_KEY_LAST;
3292 s = bc_POSIX_does_not_allow("a period ('.') as a shortcut for the last result");
3301 s = bc_lex_comment(l);
3303 bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
3324 s = bc_lex_number(l, c);
3330 l->t.t = BC_LEX_SCOLON;
3336 bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
3342 bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
3348 bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
3355 l->t.t = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
3361 if (l->buf[l->i] == '\n') {
3362 l->t.t = BC_LEX_WHITESPACE;
3366 s = bc_error_bad_character(c);
3372 bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
3403 s = bc_lex_identifier(l);
3410 l->t.t = (BcLexType)(c - '{' + BC_LEX_LBRACE);
3419 s = bc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
3423 l->t.t = BC_LEX_OP_BOOL_OR;
3426 l->t.t = BC_LEX_INVALID;
3427 s = bc_error_bad_character(c);
3435 l->t.t = BC_LEX_INVALID;
3436 s = bc_error_bad_character(c);
3446 static BcStatus dc_lex_register(BcLex *l)
3448 BcStatus s = BC_STATUS_SUCCESS;
3450 if (isspace(l->buf[l->i - 1])) {
3451 bc_lex_whitespace(l);
3454 s = bc_error("extended register");
3459 bc_vec_pop_all(&l->t.v);
3460 bc_vec_push(&l->t.v, &l->buf[l->i - 1]);
3461 bc_vec_pushZeroByte(&l->t.v);
3462 l->t.t = BC_LEX_NAME;
3468 static BcStatus dc_lex_string(BcLex *l)
3470 size_t depth = 1, nls = 0, i = l->i;
3473 l->t.t = BC_LEX_STR;
3474 bc_vec_pop_all(&l->t.v);
3476 for (c = l->buf[i]; c != 0 && depth; c = l->buf[++i]) {
3478 depth += (c == '[' && (i == l->i || l->buf[i - 1] != '\\'));
3479 depth -= (c == ']' && (i == l->i || l->buf[i - 1] != '\\'));
3482 if (depth) bc_vec_push(&l->t.v, &c);
3487 return bc_error("string end could not be found");
3490 bc_vec_pushZeroByte(&l->t.v);
3491 // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
3492 if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
3493 if (i - l->i > BC_MAX_STRING)
3494 return bc_error("string too long: must be [1,"BC_MAX_STRING_STR"]");
3499 G.err_line = l->line;
3501 return BC_STATUS_SUCCESS;
3504 static BcStatus dc_lex_token(BcLex *l)
3506 BcStatus s = BC_STATUS_SUCCESS;
3507 char c = l->buf[l->i++], c2;
3510 for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
3511 if (l->t.last == dc_lex_regs[i])
3512 return dc_lex_register(l);
3515 if (c >= '%' && c <= '~' &&
3516 (l->t.t = dc_lex_tokens[(c - '%')]) != BC_LEX_INVALID)
3521 // This is the workhorse of the lexer.
3526 l->t.t = BC_LEX_EOF;
3537 l->newline = (c == '\n');
3538 bc_lex_whitespace(l);
3547 l->t.t = BC_LEX_OP_REL_NE;
3549 l->t.t = BC_LEX_OP_REL_LE;
3551 l->t.t = BC_LEX_OP_REL_GE;
3553 return bc_error_bad_character(c);
3561 bc_lex_lineComment(l);
3567 if (isdigit(l->buf[l->i]))
3568 s = bc_lex_number(l, c);
3570 s = bc_error_bad_character(c);
3591 s = bc_lex_number(l, c);
3597 s = dc_lex_string(l);
3603 l->t.t = BC_LEX_INVALID;
3604 s = bc_error_bad_character(c);
3613 static void bc_program_addFunc(char *name, size_t *idx);
3615 static void bc_parse_addFunc(BcParse *p, char *name, size_t *idx)
3617 bc_program_addFunc(name, idx);
3618 p->func = bc_program_func(p->fidx);
3621 #define bc_parse_push(p, i) bc_vec_pushByte(&(p)->func->code, (char) (i))
3623 static void bc_parse_pushName(BcParse *p, char *name)
3625 size_t i = 0, len = strlen(name);
3627 for (; i < len; ++i) bc_parse_push(p, name[i]);
3628 bc_parse_push(p, BC_PARSE_STREND);
3633 static void bc_parse_pushIndex(BcParse *p, size_t idx)
3635 unsigned char amt, i, nums[sizeof(size_t)];
3637 for (amt = 0; idx; ++amt) {
3638 nums[amt] = (char) idx;
3639 idx = (idx & ((unsigned long) ~(UCHAR_MAX))) >> sizeof(char) * CHAR_BIT;
3642 bc_parse_push(p, amt);
3643 for (i = 0; i < amt; ++i) bc_parse_push(p, nums[i]);
3646 static void bc_parse_number(BcParse *p, BcInst *prev, size_t *nexs)
3648 char *num = xstrdup(p->l.t.v.v);
3649 size_t idx = G.prog.consts.len;
3651 bc_vec_push(&G.prog.consts, &num);
3653 bc_parse_push(p, BC_INST_NUM);
3654 bc_parse_pushIndex(p, idx);
3657 (*prev) = BC_INST_NUM;
3660 static BcStatus bc_parse_text(BcParse *p, const char *text)
3664 p->func = bc_program_func(p->fidx);
3666 if (!text[0] && !BC_PARSE_CAN_EXEC(p)) {
3667 p->l.t.t = BC_LEX_INVALID;
3670 if (!BC_PARSE_CAN_EXEC(p))
3671 return bc_error("file is not executable");
3674 return bc_lex_text(&p->l, text);
3677 // Called when parsing or execution detects a failure,
3678 // resets execution structures.
3679 static void bc_program_reset(void)
3684 bc_vec_npop(&G.prog.stack, G.prog.stack.len - 1);
3685 bc_vec_pop_all(&G.prog.results);
3687 f = bc_program_func(0);
3688 ip = bc_vec_top(&G.prog.stack);
3689 ip->idx = f->code.len;
3692 #define bc_parse_updateFunc(p, f) \
3693 ((p)->func = bc_program_func((p)->fidx = (f)))
3695 // Called when bc/dc_parse_parse() detects a failure,
3696 // resets parsing structures.
3697 static void bc_parse_reset(BcParse *p)
3699 if (p->fidx != BC_PROG_MAIN) {
3700 p->func->nparams = 0;
3701 bc_vec_pop_all(&p->func->code);
3702 bc_vec_pop_all(&p->func->autos);
3703 bc_vec_pop_all(&p->func->labels);
3705 bc_parse_updateFunc(p, BC_PROG_MAIN);
3709 p->l.t.t = BC_LEX_EOF;
3710 p->auto_part = (p->nbraces = 0);
3712 bc_vec_npop(&p->flags, p->flags.len - 1);
3713 bc_vec_pop_all(&p->exits);
3714 bc_vec_pop_all(&p->conds);
3715 bc_vec_pop_all(&p->ops);
3720 static void bc_parse_free(BcParse *p)
3722 bc_vec_free(&p->flags);
3723 bc_vec_free(&p->exits);
3724 bc_vec_free(&p->conds);
3725 bc_vec_free(&p->ops);
3729 static void bc_parse_create(BcParse *p, size_t func,
3730 BcParseParse parse, BcLexNext next)
3732 memset(p, 0, sizeof(BcParse));
3734 bc_lex_init(&p->l, next);
3735 bc_vec_init(&p->flags, sizeof(uint8_t), NULL);
3736 bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
3737 bc_vec_init(&p->conds, sizeof(size_t), NULL);
3738 bc_vec_pushZeroByte(&p->flags);
3739 bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
3742 // p->auto_part = p->nbraces = 0; - already is
3743 bc_parse_updateFunc(p, func);
3748 #define BC_PARSE_TOP_OP(p) (*((BcLexType *) bc_vec_top(&(p)->ops)))
3749 #define BC_PARSE_LEAF(p, rparen) \
3750 (((p) >= BC_INST_NUM && (p) <= BC_INST_SQRT) || (rparen) || \
3751 (p) == BC_INST_INC_POST || (p) == BC_INST_DEC_POST)
3753 // We can calculate the conversion between tokens and exprs by subtracting the
3754 // position of the first operator in the lex enum and adding the position of the
3755 // first in the expr enum. Note: This only works for binary operators.
3756 #define BC_PARSE_TOKEN_INST(t) ((char) ((t) -BC_LEX_NEG + BC_INST_NEG))
3758 static BcStatus bc_parse_else(BcParse *p);
3759 static BcStatus bc_parse_stmt(BcParse *p);
3760 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next);
3761 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next);
3763 static BcStatus bc_parse_operator(BcParse *p, BcLexType type, size_t start,
3764 size_t *nexprs, bool next)
3766 BcStatus s = BC_STATUS_SUCCESS;
3768 char l, r = bc_parse_op_PREC(type - BC_LEX_OP_INC);
3769 bool left = bc_parse_op_LEFT(type - BC_LEX_OP_INC);
3771 while (p->ops.len > start) {
3773 t = BC_PARSE_TOP_OP(p);
3774 if (t == BC_LEX_LPAREN) break;
3776 l = bc_parse_op_PREC(t - BC_LEX_OP_INC);
3777 if (l >= r && (l != r || !left)) break;
3779 bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
3780 bc_vec_pop(&p->ops);
3781 *nexprs -= t != BC_LEX_OP_BOOL_NOT && t != BC_LEX_NEG;
3784 bc_vec_push(&p->ops, &type);
3785 if (next) s = bc_lex_next(&p->l);
3790 static BcStatus bc_parse_rightParen(BcParse *p, size_t ops_bgn, size_t *nexs)
3794 if (p->ops.len <= ops_bgn)
3795 return bc_error_bad_expression();
3796 top = BC_PARSE_TOP_OP(p);
3798 while (top != BC_LEX_LPAREN) {
3800 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
3802 bc_vec_pop(&p->ops);
3803 *nexs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
3805 if (p->ops.len <= ops_bgn)
3806 return bc_error_bad_expression();
3807 top = BC_PARSE_TOP_OP(p);
3810 bc_vec_pop(&p->ops);
3812 return bc_lex_next(&p->l);
3815 static BcStatus bc_parse_params(BcParse *p, uint8_t flags)
3821 s = bc_lex_next(&p->l);
3824 for (nparams = 0; p->l.t.t != BC_LEX_RPAREN; ++nparams) {
3826 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3827 s = bc_parse_expr(p, flags, bc_parse_next_param);
3830 comma = p->l.t.t == BC_LEX_COMMA;
3832 s = bc_lex_next(&p->l);
3837 if (comma) return bc_error_bad_token();
3838 bc_parse_push(p, BC_INST_CALL);
3839 bc_parse_pushIndex(p, nparams);
3841 return BC_STATUS_SUCCESS;
3844 static BcStatus bc_parse_call(BcParse *p, char *name, uint8_t flags)
3847 BcId entry, *entry_ptr;
3852 s = bc_parse_params(p, flags);
3855 if (p->l.t.t != BC_LEX_RPAREN) {
3856 s = bc_error_bad_token();
3860 idx = bc_map_index(&G.prog.fn_map, &entry);
3862 if (idx == BC_VEC_INVALID_IDX) {
3863 name = xstrdup(entry.name);
3864 bc_parse_addFunc(p, name, &idx);
3865 idx = bc_map_index(&G.prog.fn_map, &entry);
3871 entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
3872 bc_parse_pushIndex(p, entry_ptr->idx);
3874 return bc_lex_next(&p->l);
3881 static BcStatus bc_parse_name(BcParse *p, BcInst *type, uint8_t flags)
3886 name = xstrdup(p->l.t.v.v);
3887 s = bc_lex_next(&p->l);
3890 if (p->l.t.t == BC_LEX_LBRACKET) {
3892 s = bc_lex_next(&p->l);
3895 if (p->l.t.t == BC_LEX_RBRACKET) {
3897 if (!(flags & BC_PARSE_ARRAY)) {
3898 s = bc_error_bad_expression();
3902 *type = BC_INST_ARRAY;
3906 *type = BC_INST_ARRAY_ELEM;
3908 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3909 s = bc_parse_expr(p, flags, bc_parse_next_elem);
3913 s = bc_lex_next(&p->l);
3915 bc_parse_push(p, *type);
3916 bc_parse_pushName(p, name);
3918 else if (p->l.t.t == BC_LEX_LPAREN) {
3920 if (flags & BC_PARSE_NOCALL) {
3921 s = bc_error_bad_token();
3925 *type = BC_INST_CALL;
3926 s = bc_parse_call(p, name, flags);
3929 *type = BC_INST_VAR;
3930 bc_parse_push(p, BC_INST_VAR);
3931 bc_parse_pushName(p, name);
3941 static BcStatus bc_parse_read(BcParse *p)
3945 s = bc_lex_next(&p->l);
3947 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3949 s = bc_lex_next(&p->l);
3951 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3953 bc_parse_push(p, BC_INST_READ);
3955 return bc_lex_next(&p->l);
3958 static BcStatus bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags,
3963 s = bc_lex_next(&p->l);
3965 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
3967 flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
3969 s = bc_lex_next(&p->l);
3972 s = bc_parse_expr(p, flags, bc_parse_next_rel);
3975 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
3977 *prev = (type == BC_LEX_KEY_LENGTH) ? BC_INST_LENGTH : BC_INST_SQRT;
3978 bc_parse_push(p, *prev);
3980 return bc_lex_next(&p->l);
3983 static BcStatus bc_parse_scale(BcParse *p, BcInst *type, uint8_t flags)
3987 s = bc_lex_next(&p->l);
3990 if (p->l.t.t != BC_LEX_LPAREN) {
3991 *type = BC_INST_SCALE;
3992 bc_parse_push(p, BC_INST_SCALE);
3993 return BC_STATUS_SUCCESS;
3996 *type = BC_INST_SCALE_FUNC;
3997 flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
3999 s = bc_lex_next(&p->l);
4002 s = bc_parse_expr(p, flags, bc_parse_next_rel);
4004 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4005 bc_parse_push(p, BC_INST_SCALE_FUNC);
4007 return bc_lex_next(&p->l);
4010 static BcStatus bc_parse_incdec(BcParse *p, BcInst *prev, bool *paren_expr,
4011 size_t *nexprs, uint8_t flags)
4016 BcInst etype = *prev;
4018 if (etype == BC_INST_VAR || etype == BC_INST_ARRAY_ELEM ||
4019 etype == BC_INST_SCALE || etype == BC_INST_LAST ||
4020 etype == BC_INST_IBASE || etype == BC_INST_OBASE)
4022 *prev = inst = BC_INST_INC_POST + (p->l.t.t != BC_LEX_OP_INC);
4023 bc_parse_push(p, inst);
4024 s = bc_lex_next(&p->l);
4028 *prev = inst = BC_INST_INC_PRE + (p->l.t.t != BC_LEX_OP_INC);
4031 s = bc_lex_next(&p->l);
4035 // Because we parse the next part of the expression
4036 // right here, we need to increment this.
4037 *nexprs = *nexprs + 1;
4043 s = bc_parse_name(p, prev, flags | BC_PARSE_NOCALL);
4047 case BC_LEX_KEY_IBASE:
4048 case BC_LEX_KEY_LAST:
4049 case BC_LEX_KEY_OBASE:
4051 bc_parse_push(p, type - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4052 s = bc_lex_next(&p->l);
4056 case BC_LEX_KEY_SCALE:
4058 s = bc_lex_next(&p->l);
4060 if (p->l.t.t == BC_LEX_LPAREN)
4061 s = bc_error_bad_token();
4063 bc_parse_push(p, BC_INST_SCALE);
4069 s = bc_error_bad_token();
4074 if (!s) bc_parse_push(p, inst);
4080 static BcStatus bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
4081 bool rparen, size_t *nexprs)
4085 BcInst etype = *prev;
4087 s = bc_lex_next(&p->l);
4090 type = rparen || etype == BC_INST_INC_POST || etype == BC_INST_DEC_POST ||
4091 (etype >= BC_INST_NUM && etype <= BC_INST_SQRT) ?
4094 *prev = BC_PARSE_TOKEN_INST(type);
4096 // We can just push onto the op stack because this is the largest
4097 // precedence operator that gets pushed. Inc/dec does not.
4098 if (type != BC_LEX_OP_MINUS)
4099 bc_vec_push(&p->ops, &type);
4101 s = bc_parse_operator(p, type, ops_bgn, nexprs, false);
4106 static BcStatus bc_parse_string(BcParse *p, char inst)
4108 char *str = xstrdup(p->l.t.v.v);
4110 bc_parse_push(p, BC_INST_STR);
4111 bc_parse_pushIndex(p, G.prog.strs.len);
4112 bc_vec_push(&G.prog.strs, &str);
4113 bc_parse_push(p, inst);
4115 return bc_lex_next(&p->l);
4118 static BcStatus bc_parse_print(BcParse *p)
4124 s = bc_lex_next(&p->l);
4129 if (type == BC_LEX_SCOLON || type == BC_LEX_NLINE)
4130 return bc_error("bad print statement");
4133 while (type != BC_LEX_SCOLON && type != BC_LEX_NLINE) {
4135 if (type == BC_LEX_STR) {
4136 s = bc_parse_string(p, BC_INST_PRINT_POP);
4139 s = bc_parse_expr(p, 0, bc_parse_next_print);
4141 bc_parse_push(p, BC_INST_PRINT_POP);
4144 comma = p->l.t.t == BC_LEX_COMMA;
4146 s = bc_lex_next(&p->l);
4152 if (comma) return bc_error_bad_token();
4154 return bc_lex_next(&p->l);
4157 static BcStatus bc_parse_return(BcParse *p)
4163 if (!BC_PARSE_FUNC(p)) return bc_error_bad_token();
4165 s = bc_lex_next(&p->l);
4169 paren = t == BC_LEX_LPAREN;
4171 if (t == BC_LEX_NLINE || t == BC_LEX_SCOLON)
4172 bc_parse_push(p, BC_INST_RET0);
4175 s = bc_parse_expr_empty_ok(p, 0, bc_parse_next_expr);
4176 if (s == BC_STATUS_PARSE_EMPTY_EXP) {
4177 bc_parse_push(p, BC_INST_RET0);
4178 s = bc_lex_next(&p->l);
4182 if (!paren || p->l.t.last != BC_LEX_RPAREN) {
4183 s = bc_POSIX_requires("parentheses around return expressions");
4187 bc_parse_push(p, BC_INST_RET);
4193 static BcStatus bc_parse_endBody(BcParse *p, bool brace)
4195 BcStatus s = BC_STATUS_SUCCESS;
4197 if (p->flags.len <= 1 || (brace && p->nbraces == 0))
4198 return bc_error_bad_token();
4202 if (p->l.t.t == BC_LEX_RBRACE) {
4203 if (!p->nbraces) return bc_error_bad_token();
4205 s = bc_lex_next(&p->l);
4209 return bc_error_bad_token();
4212 if (BC_PARSE_IF(p)) {
4216 while (p->l.t.t == BC_LEX_NLINE) {
4217 s = bc_lex_next(&p->l);
4221 bc_vec_pop(&p->flags);
4223 flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4224 *flag_ptr = (*flag_ptr | BC_PARSE_FLAG_IF_END);
4226 if (p->l.t.t == BC_LEX_KEY_ELSE) s = bc_parse_else(p);
4228 else if (BC_PARSE_ELSE(p)) {
4233 bc_vec_pop(&p->flags);
4235 ip = bc_vec_top(&p->exits);
4236 label = bc_vec_item(&p->func->labels, ip->idx);
4237 *label = p->func->code.len;
4239 bc_vec_pop(&p->exits);
4241 else if (BC_PARSE_FUNC_INNER(p)) {
4242 bc_parse_push(p, BC_INST_RET0);
4243 bc_parse_updateFunc(p, BC_PROG_MAIN);
4244 bc_vec_pop(&p->flags);
4248 BcInstPtr *ip = bc_vec_top(&p->exits);
4249 size_t *label = bc_vec_top(&p->conds);
4251 bc_parse_push(p, BC_INST_JUMP);
4252 bc_parse_pushIndex(p, *label);
4254 label = bc_vec_item(&p->func->labels, ip->idx);
4255 *label = p->func->code.len;
4257 bc_vec_pop(&p->flags);
4258 bc_vec_pop(&p->exits);
4259 bc_vec_pop(&p->conds);
4265 static void bc_parse_startBody(BcParse *p, uint8_t flags)
4267 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4268 flags |= (*flag_ptr & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
4269 flags |= BC_PARSE_FLAG_BODY;
4270 bc_vec_push(&p->flags, &flags);
4273 static void bc_parse_noElse(BcParse *p)
4277 uint8_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
4279 *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
4281 ip = bc_vec_top(&p->exits);
4282 label = bc_vec_item(&p->func->labels, ip->idx);
4283 *label = p->func->code.len;
4285 bc_vec_pop(&p->exits);
4288 static BcStatus bc_parse_if(BcParse *p)
4293 s = bc_lex_next(&p->l);
4295 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4297 s = bc_lex_next(&p->l);
4299 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4301 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4303 s = bc_lex_next(&p->l);
4305 bc_parse_push(p, BC_INST_JUMP_ZERO);
4307 ip.idx = p->func->labels.len;
4308 ip.func = ip.len = 0;
4310 bc_parse_pushIndex(p, ip.idx);
4311 bc_vec_push(&p->exits, &ip);
4312 bc_vec_push(&p->func->labels, &ip.idx);
4313 bc_parse_startBody(p, BC_PARSE_FLAG_IF);
4315 return BC_STATUS_SUCCESS;
4318 static BcStatus bc_parse_else(BcParse *p)
4322 if (!BC_PARSE_IF_END(p)) return bc_error_bad_token();
4324 ip.idx = p->func->labels.len;
4325 ip.func = ip.len = 0;
4327 bc_parse_push(p, BC_INST_JUMP);
4328 bc_parse_pushIndex(p, ip.idx);
4332 bc_vec_push(&p->exits, &ip);
4333 bc_vec_push(&p->func->labels, &ip.idx);
4334 bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
4336 return bc_lex_next(&p->l);
4339 static BcStatus bc_parse_while(BcParse *p)
4344 s = bc_lex_next(&p->l);
4346 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4347 s = bc_lex_next(&p->l);
4350 ip.idx = p->func->labels.len;
4352 bc_vec_push(&p->func->labels, &p->func->code.len);
4353 bc_vec_push(&p->conds, &ip.idx);
4355 ip.idx = p->func->labels.len;
4359 bc_vec_push(&p->exits, &ip);
4360 bc_vec_push(&p->func->labels, &ip.idx);
4362 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_rel);
4364 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4365 s = bc_lex_next(&p->l);
4368 bc_parse_push(p, BC_INST_JUMP_ZERO);
4369 bc_parse_pushIndex(p, ip.idx);
4370 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4372 return BC_STATUS_SUCCESS;
4375 static BcStatus bc_parse_for(BcParse *p)
4379 size_t cond_idx, exit_idx, body_idx, update_idx;
4381 s = bc_lex_next(&p->l);
4383 if (p->l.t.t != BC_LEX_LPAREN) return bc_error_bad_token();
4384 s = bc_lex_next(&p->l);
4387 if (p->l.t.t != BC_LEX_SCOLON)
4388 s = bc_parse_expr(p, 0, bc_parse_next_for);
4390 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("init");
4393 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4394 s = bc_lex_next(&p->l);
4397 cond_idx = p->func->labels.len;
4398 update_idx = cond_idx + 1;
4399 body_idx = update_idx + 1;
4400 exit_idx = body_idx + 1;
4402 bc_vec_push(&p->func->labels, &p->func->code.len);
4404 if (p->l.t.t != BC_LEX_SCOLON)
4405 s = bc_parse_expr(p, BC_PARSE_REL, bc_parse_next_for);
4407 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
4410 if (p->l.t.t != BC_LEX_SCOLON) return bc_error_bad_token();
4412 s = bc_lex_next(&p->l);
4415 bc_parse_push(p, BC_INST_JUMP_ZERO);
4416 bc_parse_pushIndex(p, exit_idx);
4417 bc_parse_push(p, BC_INST_JUMP);
4418 bc_parse_pushIndex(p, body_idx);
4420 ip.idx = p->func->labels.len;
4422 bc_vec_push(&p->conds, &update_idx);
4423 bc_vec_push(&p->func->labels, &p->func->code.len);
4425 if (p->l.t.t != BC_LEX_RPAREN)
4426 s = bc_parse_expr(p, 0, bc_parse_next_rel);
4428 s = bc_POSIX_does_not_allow_empty_X_expression_in_for("update");
4432 if (p->l.t.t != BC_LEX_RPAREN) return bc_error_bad_token();
4433 bc_parse_push(p, BC_INST_JUMP);
4434 bc_parse_pushIndex(p, cond_idx);
4435 bc_vec_push(&p->func->labels, &p->func->code.len);
4441 bc_vec_push(&p->exits, &ip);
4442 bc_vec_push(&p->func->labels, &ip.idx);
4444 bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
4446 return BC_STATUS_SUCCESS;
4449 static BcStatus bc_parse_loopExit(BcParse *p, BcLexType type)
4455 if (!BC_PARSE_LOOP(p)) return bc_error_bad_token();
4457 if (type == BC_LEX_KEY_BREAK) {
4459 if (p->exits.len == 0) return bc_error_bad_token();
4461 i = p->exits.len - 1;
4462 ip = bc_vec_item(&p->exits, i);
4464 while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
4465 if (i >= p->exits.len && !ip->func) return bc_error_bad_token();
4470 i = *((size_t *) bc_vec_top(&p->conds));
4472 bc_parse_push(p, BC_INST_JUMP);
4473 bc_parse_pushIndex(p, i);
4475 s = bc_lex_next(&p->l);
4478 if (p->l.t.t != BC_LEX_SCOLON && p->l.t.t != BC_LEX_NLINE)
4479 return bc_error_bad_token();
4481 return bc_lex_next(&p->l);
4484 static BcStatus bc_parse_func(BcParse *p)
4487 bool var, comma = false;
4491 s = bc_lex_next(&p->l);
4493 if (p->l.t.t != BC_LEX_NAME)
4494 return bc_error("bad function definition");
4496 name = xstrdup(p->l.t.v.v);
4497 bc_parse_addFunc(p, name, &p->fidx);
4499 s = bc_lex_next(&p->l);
4501 if (p->l.t.t != BC_LEX_LPAREN)
4502 return bc_error("bad function definition");
4503 s = bc_lex_next(&p->l);
4506 while (p->l.t.t != BC_LEX_RPAREN) {
4508 if (p->l.t.t != BC_LEX_NAME)
4509 return bc_error("bad function definition");
4513 name = xstrdup(p->l.t.v.v);
4514 s = bc_lex_next(&p->l);
4517 var = p->l.t.t != BC_LEX_LBRACKET;
4521 s = bc_lex_next(&p->l);
4524 if (p->l.t.t != BC_LEX_RBRACKET) {
4525 s = bc_error("bad function definition");
4529 s = bc_lex_next(&p->l);
4533 comma = p->l.t.t == BC_LEX_COMMA;
4535 s = bc_lex_next(&p->l);
4539 s = bc_func_insert(p->func, name, var);
4543 if (comma) return bc_error("bad function definition");
4545 flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_BODY;
4546 bc_parse_startBody(p, flags);
4548 s = bc_lex_next(&p->l);
4551 if (p->l.t.t != BC_LEX_LBRACE)
4552 s = bc_POSIX_requires("the left brace be on the same line as the function header");
4561 static BcStatus bc_parse_auto(BcParse *p)
4564 bool comma, var, one;
4567 if (!p->auto_part) return bc_error_bad_token();
4568 s = bc_lex_next(&p->l);
4571 p->auto_part = comma = false;
4572 one = p->l.t.t == BC_LEX_NAME;
4574 while (p->l.t.t == BC_LEX_NAME) {
4576 name = xstrdup(p->l.t.v.v);
4577 s = bc_lex_next(&p->l);
4580 var = p->l.t.t != BC_LEX_LBRACKET;
4583 s = bc_lex_next(&p->l);
4586 if (p->l.t.t != BC_LEX_RBRACKET) {
4587 s = bc_error("bad function definition");
4591 s = bc_lex_next(&p->l);
4595 comma = p->l.t.t == BC_LEX_COMMA;
4597 s = bc_lex_next(&p->l);
4601 s = bc_func_insert(p->func, name, var);
4605 if (comma) return bc_error("bad function definition");
4606 if (!one) return bc_error("no auto variable found");
4608 if (p->l.t.t != BC_LEX_NLINE && p->l.t.t != BC_LEX_SCOLON)
4609 return bc_error_bad_token();
4611 return bc_lex_next(&p->l);
4618 static BcStatus bc_parse_body(BcParse *p, bool brace)
4620 BcStatus s = BC_STATUS_SUCCESS;
4621 uint8_t *flag_ptr = bc_vec_top(&p->flags);
4623 *flag_ptr &= ~(BC_PARSE_FLAG_BODY);
4625 if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
4627 if (!brace) return bc_error_bad_token();
4628 p->auto_part = p->l.t.t != BC_LEX_KEY_AUTO;
4630 if (!p->auto_part) {
4631 s = bc_parse_auto(p);
4635 if (p->l.t.t == BC_LEX_NLINE) s = bc_lex_next(&p->l);
4638 s = bc_parse_stmt(p);
4639 if (!s && !brace) s = bc_parse_endBody(p, false);
4645 static BcStatus bc_parse_stmt(BcParse *p)
4647 BcStatus s = BC_STATUS_SUCCESS;
4653 return bc_lex_next(&p->l);
4656 case BC_LEX_KEY_ELSE:
4658 p->auto_part = false;
4664 if (!BC_PARSE_BODY(p)) return bc_error_bad_token();
4667 s = bc_lex_next(&p->l);
4670 return bc_parse_body(p, true);
4673 case BC_LEX_KEY_AUTO:
4675 return bc_parse_auto(p);
4680 p->auto_part = false;
4682 if (BC_PARSE_IF_END(p)) {
4684 return BC_STATUS_SUCCESS;
4686 else if (BC_PARSE_BODY(p))
4687 return bc_parse_body(p, false);
4697 case BC_LEX_OP_MINUS:
4698 case BC_LEX_OP_BOOL_NOT:
4702 case BC_LEX_KEY_IBASE:
4703 case BC_LEX_KEY_LAST:
4704 case BC_LEX_KEY_LENGTH:
4705 case BC_LEX_KEY_OBASE:
4706 case BC_LEX_KEY_READ:
4707 case BC_LEX_KEY_SCALE:
4708 case BC_LEX_KEY_SQRT:
4710 s = bc_parse_expr(p, BC_PARSE_PRINT, bc_parse_next_expr);
4714 case BC_LEX_KEY_ELSE:
4716 s = bc_parse_else(p);
4722 while (!s && p->l.t.t == BC_LEX_SCOLON) s = bc_lex_next(&p->l);
4728 s = bc_parse_endBody(p, true);
4734 s = bc_parse_string(p, BC_INST_PRINT_STR);
4738 case BC_LEX_KEY_BREAK:
4739 case BC_LEX_KEY_CONTINUE:
4741 s = bc_parse_loopExit(p, p->l.t.t);
4745 case BC_LEX_KEY_FOR:
4747 s = bc_parse_for(p);
4751 case BC_LEX_KEY_HALT:
4753 bc_parse_push(p, BC_INST_HALT);
4754 s = bc_lex_next(&p->l);
4764 case BC_LEX_KEY_LIMITS:
4766 // "limits" is a compile-time command,
4767 // the output is produced at _parse time_.
4768 s = bc_lex_next(&p->l);
4771 "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
4772 "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
4773 "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
4774 "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
4775 "BC_NAME_MAX = "BC_MAX_NAME_STR "\n"
4776 "BC_NUM_MAX = "BC_MAX_NUM_STR "\n"
4777 "MAX Exponent = "BC_MAX_EXP_STR "\n"
4778 "Number of vars = "BC_MAX_VARS_STR "\n"
4783 case BC_LEX_KEY_PRINT:
4785 s = bc_parse_print(p);
4789 case BC_LEX_KEY_QUIT:
4791 // "quit" is a compile-time command. For example,
4792 // "if (0 == 1) quit" terminates when parsing the statement,
4793 // not when it is executed
4794 QUIT_OR_RETURN_TO_MAIN;
4797 case BC_LEX_KEY_RETURN:
4799 s = bc_parse_return(p);
4803 case BC_LEX_KEY_WHILE:
4805 s = bc_parse_while(p);
4811 s = bc_error_bad_token();
4819 static BcStatus bc_parse_parse(BcParse *p)
4823 if (p->l.t.t == BC_LEX_EOF)
4824 s = p->flags.len > 0 ? bc_error("block end could not be found") : bc_error("end of file");
4825 else if (p->l.t.t == BC_LEX_KEY_DEFINE) {
4826 if (!BC_PARSE_CAN_EXEC(p)) return bc_error_bad_token();
4827 s = bc_parse_func(p);
4830 s = bc_parse_stmt(p);
4832 if (s || G_interrupt) {
4834 s = BC_STATUS_FAILURE;
4840 static BcStatus bc_parse_expr_empty_ok(BcParse *p, uint8_t flags, BcParseNext next)
4842 BcStatus s = BC_STATUS_SUCCESS;
4843 BcInst prev = BC_INST_PRINT;
4844 BcLexType top, t = p->l.t.t;
4845 size_t nexprs = 0, ops_bgn = p->ops.len;
4846 unsigned nparens, nrelops;
4847 bool paren_first, paren_expr, rprn, done, get_token, assign, bin_last;
4849 paren_first = p->l.t.t == BC_LEX_LPAREN;
4850 nparens = nrelops = 0;
4851 paren_expr = rprn = done = get_token = assign = false;
4854 for (; !G_interrupt && !s && !done && bc_parse_exprs(t); t = p->l.t.t) {
4860 s = bc_parse_incdec(p, &prev, &paren_expr, &nexprs, flags);
4861 rprn = get_token = bin_last = false;
4865 case BC_LEX_OP_MINUS:
4867 s = bc_parse_minus(p, &prev, ops_bgn, rprn, &nexprs);
4868 rprn = get_token = false;
4869 bin_last = prev == BC_INST_MINUS;
4873 case BC_LEX_OP_ASSIGN_POWER:
4874 case BC_LEX_OP_ASSIGN_MULTIPLY:
4875 case BC_LEX_OP_ASSIGN_DIVIDE:
4876 case BC_LEX_OP_ASSIGN_MODULUS:
4877 case BC_LEX_OP_ASSIGN_PLUS:
4878 case BC_LEX_OP_ASSIGN_MINUS:
4879 case BC_LEX_OP_ASSIGN:
4881 if (prev != BC_INST_VAR && prev != BC_INST_ARRAY_ELEM &&
4882 prev != BC_INST_SCALE && prev != BC_INST_IBASE &&
4883 prev != BC_INST_OBASE && prev != BC_INST_LAST)
4885 s = bc_error("bad assignment:"
4886 " left side must be scale,"
4887 " ibase, obase, last, var,"
4894 case BC_LEX_OP_POWER:
4895 case BC_LEX_OP_MULTIPLY:
4896 case BC_LEX_OP_DIVIDE:
4897 case BC_LEX_OP_MODULUS:
4898 case BC_LEX_OP_PLUS:
4899 case BC_LEX_OP_REL_EQ:
4900 case BC_LEX_OP_REL_LE:
4901 case BC_LEX_OP_REL_GE:
4902 case BC_LEX_OP_REL_NE:
4903 case BC_LEX_OP_REL_LT:
4904 case BC_LEX_OP_REL_GT:
4905 case BC_LEX_OP_BOOL_NOT:
4906 case BC_LEX_OP_BOOL_OR:
4907 case BC_LEX_OP_BOOL_AND:
4909 if (((t == BC_LEX_OP_BOOL_NOT) != bin_last)
4910 || (t != BC_LEX_OP_BOOL_NOT && prev == BC_INST_BOOL_NOT)
4912 return bc_error_bad_expression();
4915 nrelops += t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT;
4916 prev = BC_PARSE_TOKEN_INST(t);
4917 s = bc_parse_operator(p, t, ops_bgn, &nexprs, true);
4918 rprn = get_token = false;
4919 bin_last = t != BC_LEX_OP_BOOL_NOT;
4926 if (BC_PARSE_LEAF(prev, rprn))
4927 return bc_error_bad_expression();
4929 paren_expr = rprn = bin_last = false;
4931 bc_vec_push(&p->ops, &t);
4938 if (bin_last || prev == BC_INST_BOOL_NOT)
4939 return bc_error_bad_expression();
4942 s = BC_STATUS_SUCCESS;
4947 else if (!paren_expr)
4948 return BC_STATUS_PARSE_EMPTY_EXP;
4951 paren_expr = rprn = true;
4952 get_token = bin_last = false;
4954 s = bc_parse_rightParen(p, ops_bgn, &nexprs);
4961 if (BC_PARSE_LEAF(prev, rprn))
4962 return bc_error_bad_expression();
4964 rprn = get_token = bin_last = false;
4965 s = bc_parse_name(p, &prev, flags & ~BC_PARSE_NOCALL);
4973 if (BC_PARSE_LEAF(prev, rprn))
4974 return bc_error_bad_expression();
4975 bc_parse_number(p, &prev, &nexprs);
4976 paren_expr = get_token = true;
4977 rprn = bin_last = false;
4982 case BC_LEX_KEY_IBASE:
4983 case BC_LEX_KEY_LAST:
4984 case BC_LEX_KEY_OBASE:
4986 if (BC_PARSE_LEAF(prev, rprn))
4987 return bc_error_bad_expression();
4988 prev = (char) (t - BC_LEX_KEY_IBASE + BC_INST_IBASE);
4989 bc_parse_push(p, (char) prev);
4991 paren_expr = get_token = true;
4992 rprn = bin_last = false;
4998 case BC_LEX_KEY_LENGTH:
4999 case BC_LEX_KEY_SQRT:
5001 if (BC_PARSE_LEAF(prev, rprn))
5002 return bc_error_bad_expression();
5003 s = bc_parse_builtin(p, t, flags, &prev);
5005 rprn = get_token = bin_last = false;
5011 case BC_LEX_KEY_READ:
5013 if (BC_PARSE_LEAF(prev, rprn))
5014 return bc_error_bad_expression();
5015 else if (flags & BC_PARSE_NOREAD)
5016 s = bc_error_nested_read_call();
5018 s = bc_parse_read(p);
5021 rprn = get_token = bin_last = false;
5023 prev = BC_INST_READ;
5028 case BC_LEX_KEY_SCALE:
5030 if (BC_PARSE_LEAF(prev, rprn))
5031 return bc_error_bad_expression();
5032 s = bc_parse_scale(p, &prev, flags);
5034 rprn = get_token = bin_last = false;
5036 prev = BC_INST_SCALE;
5043 s = bc_error_bad_token();
5048 if (!s && get_token) s = bc_lex_next(&p->l);
5052 if (G_interrupt) return BC_STATUS_FAILURE; // ^C: stop parsing
5054 while (p->ops.len > ops_bgn) {
5056 top = BC_PARSE_TOP_OP(p);
5057 assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
5059 if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
5060 return bc_error_bad_expression();
5062 bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
5064 nexprs -= top != BC_LEX_OP_BOOL_NOT && top != BC_LEX_NEG;
5065 bc_vec_pop(&p->ops);
5068 if (prev == BC_INST_BOOL_NOT || nexprs != 1)
5069 return bc_error_bad_expression();
5071 // next is BcParseNext, byte array of up to 4 BC_LEX's, packed into 32-bit word
5073 if (t == (next & 0x7f))
5075 if (next & 0x80) // last element?
5079 return bc_error_bad_expression();
5082 if (!(flags & BC_PARSE_REL) && nrelops) {
5083 s = bc_POSIX_does_not_allow("comparison operators outside if or loops");
5086 else if ((flags & BC_PARSE_REL) && nrelops > 1) {
5087 s = bc_POSIX_requires("exactly one comparison operator per condition");
5091 if (flags & BC_PARSE_PRINT) {
5092 if (paren_first || !assign) bc_parse_push(p, BC_INST_PRINT);
5093 bc_parse_push(p, BC_INST_POP);
5099 static BcStatus bc_parse_expr(BcParse *p, uint8_t flags, BcParseNext next)
5103 s = bc_parse_expr_empty_ok(p, flags, next);
5104 if (s == BC_STATUS_PARSE_EMPTY_EXP)
5105 return bc_error("empty expression");
5109 static void bc_parse_init(BcParse *p, size_t func)
5111 bc_parse_create(p, func, bc_parse_parse, bc_lex_token);
5114 static BcStatus bc_parse_expression(BcParse *p, uint8_t flags)
5116 return bc_parse_expr(p, flags, bc_parse_next_read);
5123 #define DC_PARSE_BUF_LEN ((int) (sizeof(uint32_t) * CHAR_BIT))
5125 static BcStatus dc_parse_register(BcParse *p)
5130 s = bc_lex_next(&p->l);
5132 if (p->l.t.t != BC_LEX_NAME) return bc_error_bad_token();
5134 name = xstrdup(p->l.t.v.v);
5135 bc_parse_pushName(p, name);
5140 static BcStatus dc_parse_string(BcParse *p)
5142 char *str, *name, b[DC_PARSE_BUF_LEN + 1];
5143 size_t idx, len = G.prog.strs.len;
5145 sprintf(b, "%0*zu", DC_PARSE_BUF_LEN, len);
5148 str = xstrdup(p->l.t.v.v);
5149 bc_parse_push(p, BC_INST_STR);
5150 bc_parse_pushIndex(p, len);
5151 bc_vec_push(&G.prog.strs, &str);
5152 bc_parse_addFunc(p, name, &idx);
5154 return bc_lex_next(&p->l);
5157 static BcStatus dc_parse_mem(BcParse *p, uint8_t inst, bool name, bool store)
5161 bc_parse_push(p, inst);
5163 s = dc_parse_register(p);
5168 bc_parse_push(p, BC_INST_SWAP);
5169 bc_parse_push(p, BC_INST_ASSIGN);
5170 bc_parse_push(p, BC_INST_POP);
5173 return bc_lex_next(&p->l);
5176 static BcStatus dc_parse_cond(BcParse *p, uint8_t inst)
5180 bc_parse_push(p, inst);
5181 bc_parse_push(p, BC_INST_EXEC_COND);
5183 s = dc_parse_register(p);
5186 s = bc_lex_next(&p->l);
5189 if (p->l.t.t == BC_LEX_ELSE) {
5190 s = dc_parse_register(p);
5192 s = bc_lex_next(&p->l);
5195 bc_parse_push(p, BC_PARSE_STREND);
5200 static BcStatus dc_parse_token(BcParse *p, BcLexType t, uint8_t flags)
5202 BcStatus s = BC_STATUS_SUCCESS;
5205 bool assign, get_token = false;
5209 case BC_LEX_OP_REL_EQ:
5210 case BC_LEX_OP_REL_LE:
5211 case BC_LEX_OP_REL_GE:
5212 case BC_LEX_OP_REL_NE:
5213 case BC_LEX_OP_REL_LT:
5214 case BC_LEX_OP_REL_GT:
5216 s = dc_parse_cond(p, t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
5223 s = dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
5229 s = dc_parse_string(p);
5236 if (t == BC_LEX_NEG) {
5237 s = bc_lex_next(&p->l);
5239 if (p->l.t.t != BC_LEX_NUMBER)
5240 return bc_error_bad_token();
5243 bc_parse_number(p, &prev, &p->nbraces);
5245 if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
5251 case BC_LEX_KEY_READ:
5253 if (flags & BC_PARSE_NOREAD)
5254 s = bc_error_nested_read_call();
5256 bc_parse_push(p, BC_INST_READ);
5261 case BC_LEX_OP_ASSIGN:
5262 case BC_LEX_STORE_PUSH:
5264 assign = t == BC_LEX_OP_ASSIGN;
5265 inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
5266 s = dc_parse_mem(p, inst, true, assign);
5271 case BC_LEX_LOAD_POP:
5273 inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
5274 s = dc_parse_mem(p, inst, true, false);
5278 case BC_LEX_STORE_IBASE:
5279 case BC_LEX_STORE_SCALE:
5280 case BC_LEX_STORE_OBASE:
5282 inst = t - BC_LEX_STORE_IBASE + BC_INST_IBASE;
5283 s = dc_parse_mem(p, inst, false, true);
5289 s = bc_error_bad_token();
5295 if (!s && get_token) s = bc_lex_next(&p->l);
5300 static BcStatus dc_parse_expr(BcParse *p, uint8_t flags)
5302 BcStatus s = BC_STATUS_SUCCESS;
5306 if (flags & BC_PARSE_NOCALL) p->nbraces = G.prog.results.len;
5308 for (t = p->l.t.t; !s && t != BC_LEX_EOF; t = p->l.t.t) {
5310 inst = dc_parse_insts[t];
5312 if (inst != BC_INST_INVALID) {
5313 bc_parse_push(p, inst);
5314 s = bc_lex_next(&p->l);
5317 s = dc_parse_token(p, t, flags);
5320 if (!s && p->l.t.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
5321 bc_parse_push(p, BC_INST_POP_EXEC);
5326 static BcStatus dc_parse_parse(BcParse *p)
5330 if (p->l.t.t == BC_LEX_EOF)
5331 s = bc_error("end of file");
5333 s = dc_parse_expr(p, 0);
5335 if (s || G_interrupt) {
5337 s = BC_STATUS_FAILURE;
5343 static void dc_parse_init(BcParse *p, size_t func)
5345 bc_parse_create(p, func, dc_parse_parse, dc_lex_token);
5350 static void common_parse_init(BcParse *p, size_t func)
5353 IF_BC(bc_parse_init(p, func);)
5355 IF_DC(dc_parse_init(p, func);)
5359 static BcStatus common_parse_expr(BcParse *p, uint8_t flags)
5362 IF_BC(return bc_parse_expression(p, flags);)
5364 IF_DC(return dc_parse_expr(p, flags);)
5368 static BcVec* bc_program_search(char *id, bool var)
5376 v = var ? &G.prog.vars : &G.prog.arrs;
5377 map = var ? &G.prog.var_map : &G.prog.arr_map;
5381 new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
5384 bc_array_init(&data.v, var);
5385 bc_vec_push(v, &data.v);
5388 ptr = bc_vec_item(map, i);
5389 if (new) ptr->name = xstrdup(e.name);
5390 return bc_vec_item(v, ptr->idx);
5393 static BcStatus bc_program_num(BcResult *r, BcNum **num, bool hex)
5395 BcStatus s = BC_STATUS_SUCCESS;
5400 case BC_RESULT_TEMP:
5401 case BC_RESULT_IBASE:
5402 case BC_RESULT_SCALE:
5403 case BC_RESULT_OBASE:
5409 case BC_RESULT_CONSTANT:
5411 char **str = bc_vec_item(&G.prog.consts, r->d.id.idx);
5412 size_t base_t, len = strlen(*str);
5415 bc_num_init(&r->d.n, len);
5417 hex = hex && len == 1;
5418 base = hex ? &G.prog.hexb : &G.prog.ib;
5419 base_t = hex ? BC_NUM_MAX_IBASE : G.prog.ib_t;
5420 s = bc_num_parse(&r->d.n, *str, base, base_t);
5423 bc_num_free(&r->d.n);
5428 r->t = BC_RESULT_TEMP;
5434 case BC_RESULT_ARRAY:
5435 case BC_RESULT_ARRAY_ELEM:
5439 v = bc_program_search(r->d.id.name, r->t == BC_RESULT_VAR);
5441 if (r->t == BC_RESULT_ARRAY_ELEM) {
5443 if (v->len <= r->d.id.idx) bc_array_expand(v, r->d.id.idx + 1);
5444 *num = bc_vec_item(v, r->d.id.idx);
5447 *num = bc_vec_top(v);
5452 case BC_RESULT_LAST:
5454 *num = &G.prog.last;
5468 static BcStatus bc_program_binOpPrep(BcResult **l, BcNum **ln,
5469 BcResult **r, BcNum **rn, bool assign)
5473 BcResultType lt, rt;
5475 if (!BC_PROG_STACK(&G.prog.results, 2))
5476 return bc_error_stack_has_too_few_elements();
5478 *r = bc_vec_item_rev(&G.prog.results, 0);
5479 *l = bc_vec_item_rev(&G.prog.results, 1);
5483 hex = assign && (lt == BC_RESULT_IBASE || lt == BC_RESULT_OBASE);
5485 s = bc_program_num(*l, ln, false);
5487 s = bc_program_num(*r, rn, hex);
5490 // We run this again under these conditions in case any vector has been
5491 // reallocated out from under the BcNums or arrays we had.
5492 if (lt == rt && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) {
5493 s = bc_program_num(*l, ln, false);
5497 if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != BC_RESULT_VAR))
5498 return bc_error_variable_is_wrong_type();
5499 if (!assign && !BC_PROG_NUM((*r), (*ln)))
5500 return bc_error_variable_is_wrong_type();
5505 static void bc_program_binOpRetire(BcResult *r)
5507 r->t = BC_RESULT_TEMP;
5508 bc_vec_pop(&G.prog.results);
5509 bc_vec_pop(&G.prog.results);
5510 bc_vec_push(&G.prog.results, r);
5513 static BcStatus bc_program_prep(BcResult **r, BcNum **n)
5517 if (!BC_PROG_STACK(&G.prog.results, 1))
5518 return bc_error_stack_has_too_few_elements();
5519 *r = bc_vec_top(&G.prog.results);
5521 s = bc_program_num(*r, n, false);
5524 if (!BC_PROG_NUM((*r), (*n)))
5525 return bc_error_variable_is_wrong_type();
5530 static void bc_program_retire(BcResult *r, BcResultType t)
5533 bc_vec_pop(&G.prog.results);
5534 bc_vec_push(&G.prog.results, r);
5537 static BcStatus bc_program_op(char inst)
5540 BcResult *opd1, *opd2, res;
5541 BcNum *n1, *n2 = NULL;
5543 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5545 bc_num_init_DEF_SIZE(&res.d.n);
5547 s = bc_program_ops[inst - BC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
5549 bc_program_binOpRetire(&res);
5554 bc_num_free(&res.d.n);
5558 static BcStatus bc_program_read(void)
5560 const char *sv_file;
5566 BcFunc *f = bc_program_func(BC_PROG_READ);
5568 for (i = 0; i < G.prog.stack.len; ++i) {
5569 BcInstPtr *ip_ptr = bc_vec_item(&G.prog.stack, i);
5570 if (ip_ptr->func == BC_PROG_READ)
5571 return bc_error_nested_read_call();
5574 bc_vec_pop_all(&f->code);
5575 bc_char_vec_init(&buf);
5577 sv_file = G.prog.file;
5580 s = bc_read_line(&buf);
5583 common_parse_init(&parse, BC_PROG_READ);
5584 bc_lex_file(&parse.l);
5586 s = bc_parse_text(&parse, buf.v);
5587 if (s) goto exec_err;
5588 s = common_parse_expr(&parse, BC_PARSE_NOREAD);
5589 if (s) goto exec_err;
5591 if (parse.l.t.t != BC_LEX_NLINE && parse.l.t.t != BC_LEX_EOF) {
5592 s = bc_error("bad read() expression");
5596 ip.func = BC_PROG_READ;
5598 ip.len = G.prog.results.len;
5600 // Update this pointer, just in case.
5601 f = bc_program_func(BC_PROG_READ);
5603 bc_vec_pushByte(&f->code, BC_INST_POP_EXEC);
5604 bc_vec_push(&G.prog.stack, &ip);
5607 G.prog.file = sv_file;
5608 bc_parse_free(&parse);
5614 static size_t bc_program_index(char *code, size_t *bgn)
5616 char amt = code[(*bgn)++], i = 0;
5619 for (; i < amt; ++i, ++(*bgn))
5620 res |= (((size_t)((int) code[*bgn]) & UCHAR_MAX) << (i * CHAR_BIT));
5625 static char *bc_program_name(char *code, size_t *bgn)
5628 char c, *s, *str = code + *bgn, *ptr = strchr(str, BC_PARSE_STREND);
5630 s = xmalloc(ptr - str + 1);
5633 for (i = 0; c != 0 && c != BC_PARSE_STREND; c = code[(*bgn)++], ++i)
5641 static void bc_program_printString(const char *str)
5643 size_t i, len = strlen(str);
5652 for (i = 0; i < len; ++i, ++G.prog.nchars) {
5656 if (c != '\\' || i == len - 1)
5692 G.prog.nchars = SIZE_MAX;
5716 // Just print the backslash and following character.
5727 static BcStatus bc_program_print(char inst, size_t idx)
5729 BcStatus s = BC_STATUS_SUCCESS;
5734 bool pop = inst != BC_INST_PRINT;
5736 if (!BC_PROG_STACK(&G.prog.results, idx + 1))
5737 return bc_error_stack_has_too_few_elements();
5739 r = bc_vec_item_rev(&G.prog.results, idx);
5740 s = bc_program_num(r, &num, false);
5743 if (BC_PROG_NUM(r, num)) {
5744 s = bc_num_print(num, !pop);
5745 if (!s) bc_num_copy(&G.prog.last, num);
5749 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
5750 str = *bc_program_str(idx);
5752 if (inst == BC_INST_PRINT_STR) {
5753 for (i = 0, len = strlen(str); i < len; ++i) {
5756 if (c == '\n') G.prog.nchars = SIZE_MAX;
5761 bc_program_printString(str);
5762 if (inst == BC_INST_PRINT) bb_putchar('\n');
5766 if (!s && pop) bc_vec_pop(&G.prog.results);
5771 static BcStatus bc_program_negate(void)
5777 s = bc_program_prep(&ptr, &num);
5780 bc_num_init(&res.d.n, num->len);
5781 bc_num_copy(&res.d.n, num);
5782 if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
5784 bc_program_retire(&res, BC_RESULT_TEMP);
5789 static BcStatus bc_program_logical(char inst)
5792 BcResult *opd1, *opd2, res;
5797 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
5799 bc_num_init_DEF_SIZE(&res.d.n);
5801 if (inst == BC_INST_BOOL_AND)
5802 cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
5803 else if (inst == BC_INST_BOOL_OR)
5804 cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
5807 cmp = bc_num_cmp(n1, n2);
5811 case BC_INST_REL_EQ:
5817 case BC_INST_REL_LE:
5823 case BC_INST_REL_GE:
5829 case BC_INST_REL_NE:
5835 case BC_INST_REL_LT:
5841 case BC_INST_REL_GT:
5849 (cond ? bc_num_one : bc_num_zero)(&res.d.n);
5851 bc_program_binOpRetire(&res);
5857 static BcStatus bc_program_assignStr(BcResult *r, BcVec *v,
5863 memset(&n2, 0, sizeof(BcNum));
5864 n2.rdx = res.d.id.idx = r->d.id.idx;
5865 res.t = BC_RESULT_STR;
5868 if (!BC_PROG_STACK(&G.prog.results, 2))
5869 return bc_error_stack_has_too_few_elements();
5871 bc_vec_pop(&G.prog.results);
5874 bc_vec_pop(&G.prog.results);
5876 bc_vec_push(&G.prog.results, &res);
5877 bc_vec_push(v, &n2);
5879 return BC_STATUS_SUCCESS;
5883 static BcStatus bc_program_copyToVar(char *name, bool var)
5890 if (!BC_PROG_STACK(&G.prog.results, 1))
5891 return bc_error_stack_has_too_few_elements();
5893 ptr = bc_vec_top(&G.prog.results);
5894 if ((ptr->t == BC_RESULT_ARRAY) != !var)
5895 return bc_error_variable_is_wrong_type();
5896 v = bc_program_search(name, var);
5899 if (ptr->t == BC_RESULT_STR && !var)
5900 return bc_error_variable_is_wrong_type();
5901 if (ptr->t == BC_RESULT_STR) return bc_program_assignStr(ptr, v, true);
5904 s = bc_program_num(ptr, &n, false);
5907 // Do this once more to make sure that pointers were not invalidated.
5908 v = bc_program_search(name, var);
5911 bc_num_init_DEF_SIZE(&r.d.n);
5912 bc_num_copy(&r.d.n, n);
5915 bc_array_init(&r.d.v, true);
5916 bc_array_copy(&r.d.v, (BcVec *) n);
5919 bc_vec_push(v, &r.d);
5920 bc_vec_pop(&G.prog.results);
5925 static BcStatus bc_program_assign(char inst)
5928 BcResult *left, *right, res;
5929 BcNum *l = NULL, *r = NULL;
5930 bool assign = inst == BC_INST_ASSIGN, ib, sc;
5932 s = bc_program_binOpPrep(&left, &l, &right, &r, assign);
5935 ib = left->t == BC_RESULT_IBASE;
5936 sc = left->t == BC_RESULT_SCALE;
5940 if (right->t == BC_RESULT_STR) {
5944 if (left->t != BC_RESULT_VAR)
5945 return bc_error_variable_is_wrong_type();
5946 v = bc_program_search(left->d.id.name, true);
5948 return bc_program_assignStr(right, v, false);
5952 if (left->t == BC_RESULT_CONSTANT || left->t == BC_RESULT_TEMP)
5953 return bc_error("bad assignment:"
5954 " left side must be scale,"
5955 " ibase, obase, last, var,"
5960 if (inst == BC_INST_ASSIGN_DIVIDE && !bc_num_cmp(r, &G.prog.zero))
5961 return bc_error("divide by zero");
5966 s = bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
5973 if (ib || sc || left->t == BC_RESULT_OBASE) {
5974 static const char *const msg[] = {
5975 "bad ibase; must be [2,16]", //BC_RESULT_IBASE
5976 "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //BC_RESULT_SCALE
5977 NULL, //can't happen //BC_RESULT_LAST
5978 NULL, //can't happen //BC_RESULT_CONSTANT
5979 NULL, //can't happen //BC_RESULT_ONE
5980 "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //BC_RESULT_OBASE
5983 unsigned long val, max;
5985 s = bc_num_ulong(l, &val);
5988 s = left->t - BC_RESULT_IBASE;
5991 ptr = &G.prog.scale;
5994 if (val < BC_NUM_MIN_BASE)
5995 return bc_error(msg[s]);
5996 max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
5997 ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
6001 return bc_error(msg[s]);
6003 bc_num_copy(ib ? &G.prog.ib : &G.prog.ob, l);
6005 *ptr = (size_t) val;
6006 s = BC_STATUS_SUCCESS;
6009 bc_num_init(&res.d.n, l->len);
6010 bc_num_copy(&res.d.n, l);
6011 bc_program_binOpRetire(&res);
6017 #define bc_program_pushVar(code, bgn, pop, copy) \
6018 bc_program_pushVar(code, bgn)
6019 // for bc, 'pop' and 'copy' are always false
6021 static BcStatus bc_program_pushVar(char *code, size_t *bgn,
6022 bool pop, bool copy)
6024 BcStatus s = BC_STATUS_SUCCESS;
6026 char *name = bc_program_name(code, bgn);
6028 r.t = BC_RESULT_VAR;
6033 BcVec *v = bc_program_search(name, true);
6034 BcNum *num = bc_vec_top(v);
6038 if (!BC_PROG_STACK(v, 2 - copy)) {
6040 return bc_error_stack_has_too_few_elements();
6046 if (!BC_PROG_STR(num)) {
6048 r.t = BC_RESULT_TEMP;
6050 bc_num_init_DEF_SIZE(&r.d.n);
6051 bc_num_copy(&r.d.n, num);
6054 r.t = BC_RESULT_STR;
6055 r.d.id.idx = num->rdx;
6058 if (!copy) bc_vec_pop(v);
6063 bc_vec_push(&G.prog.results, &r);
6068 static BcStatus bc_program_pushArray(char *code, size_t *bgn,
6071 BcStatus s = BC_STATUS_SUCCESS;
6075 r.d.id.name = bc_program_name(code, bgn);
6077 if (inst == BC_INST_ARRAY) {
6078 r.t = BC_RESULT_ARRAY;
6079 bc_vec_push(&G.prog.results, &r);
6086 s = bc_program_prep(&operand, &num);
6088 s = bc_num_ulong(num, &temp);
6091 if (temp > BC_MAX_DIM) {
6092 s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
6096 r.d.id.idx = (size_t) temp;
6097 bc_program_retire(&r, BC_RESULT_ARRAY_ELEM);
6101 if (s) free(r.d.id.name);
6106 static BcStatus bc_program_incdec(char inst)
6109 BcResult *ptr, res, copy;
6113 s = bc_program_prep(&ptr, &num);
6116 if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
6117 copy.t = BC_RESULT_TEMP;
6118 bc_num_init(©.d.n, num->len);
6119 bc_num_copy(©.d.n, num);
6122 res.t = BC_RESULT_ONE;
6123 inst = inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST ?
6124 BC_INST_ASSIGN_PLUS :
6125 BC_INST_ASSIGN_MINUS;
6127 bc_vec_push(&G.prog.results, &res);
6128 bc_program_assign(inst);
6130 if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
6131 bc_vec_pop(&G.prog.results);
6132 bc_vec_push(&G.prog.results, ©);
6138 static BcStatus bc_program_call(char *code, size_t *idx)
6140 BcStatus s = BC_STATUS_SUCCESS;
6142 size_t i, nparams = bc_program_index(code, idx);
6149 ip.func = bc_program_index(code, idx);
6150 func = bc_program_func(ip.func);
6152 if (func->code.len == 0) {
6153 return bc_error("undefined function");
6155 if (nparams != func->nparams) {
6156 return bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams);
6158 ip.len = G.prog.results.len - nparams;
6160 for (i = 0; i < nparams; ++i) {
6162 a = bc_vec_item(&func->autos, nparams - 1 - i);
6163 arg = bc_vec_top(&G.prog.results);
6165 if ((!a->idx) != (arg->t == BC_RESULT_ARRAY) || arg->t == BC_RESULT_STR)
6166 return bc_error_variable_is_wrong_type();
6168 s = bc_program_copyToVar(a->name, a->idx);
6172 for (; i < func->autos.len; ++i) {
6175 a = bc_vec_item(&func->autos, i);
6176 v = bc_program_search(a->name, a->idx);
6179 bc_num_init_DEF_SIZE(¶m.n);
6180 bc_vec_push(v, ¶m.n);
6183 bc_array_init(¶m.v, true);
6184 bc_vec_push(v, ¶m.v);
6188 bc_vec_push(&G.prog.stack, &ip);
6190 return BC_STATUS_SUCCESS;
6193 static BcStatus bc_program_return(char inst)
6199 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6201 if (!BC_PROG_STACK(&G.prog.results, ip->len + inst == BC_INST_RET))
6202 return bc_error_stack_has_too_few_elements();
6204 f = bc_program_func(ip->func);
6205 res.t = BC_RESULT_TEMP;
6207 if (inst == BC_INST_RET) {
6210 BcResult *operand = bc_vec_top(&G.prog.results);
6212 s = bc_program_num(operand, &num, false);
6214 bc_num_init(&res.d.n, num->len);
6215 bc_num_copy(&res.d.n, num);
6218 bc_num_init_DEF_SIZE(&res.d.n);
6219 //bc_num_zero(&res.d.n); - already is
6222 // We need to pop arguments as well, so this takes that into account.
6223 for (i = 0; i < f->autos.len; ++i) {
6226 BcId *a = bc_vec_item(&f->autos, i);
6228 v = bc_program_search(a->name, a->idx);
6232 bc_vec_npop(&G.prog.results, G.prog.results.len - ip->len);
6233 bc_vec_push(&G.prog.results, &res);
6234 bc_vec_pop(&G.prog.stack);
6236 return BC_STATUS_SUCCESS;
6240 static unsigned long bc_program_scale(BcNum *n)
6242 return (unsigned long) n->rdx;
6245 static unsigned long bc_program_len(BcNum *n)
6247 unsigned long len = n->len;
6250 if (n->rdx != n->len) return len;
6251 for (i = n->len - 1; i < n->len && n->num[i] == 0; --len, --i);
6256 static BcStatus bc_program_builtin(char inst)
6262 bool len = inst == BC_INST_LENGTH;
6264 if (!BC_PROG_STACK(&G.prog.results, 1))
6265 return bc_error_stack_has_too_few_elements();
6266 opnd = bc_vec_top(&G.prog.results);
6268 s = bc_program_num(opnd, &num, false);
6272 if (!BC_PROG_NUM(opnd, num) && !len)
6273 return bc_error_variable_is_wrong_type();
6276 bc_num_init_DEF_SIZE(&res.d.n);
6278 if (inst == BC_INST_SQRT) s = bc_num_sqrt(num, &res.d.n, G.prog.scale);
6280 else if (len != 0 && opnd->t == BC_RESULT_ARRAY) {
6281 bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
6285 else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
6288 size_t idx = opnd->t == BC_RESULT_STR ? opnd->d.id.idx : num->rdx;
6290 str = bc_program_str(idx);
6291 bc_num_ulong2num(&res.d.n, strlen(*str));
6295 BcProgramBuiltIn f = len ? bc_program_len : bc_program_scale;
6296 bc_num_ulong2num(&res.d.n, f(num));
6299 bc_program_retire(&res, BC_RESULT_TEMP);
6305 static BcStatus bc_program_divmod(void)
6308 BcResult *opd1, *opd2, res, res2;
6309 BcNum *n1, *n2 = NULL;
6311 s = bc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
6314 bc_num_init_DEF_SIZE(&res.d.n);
6315 bc_num_init(&res2.d.n, n2->len);
6317 s = bc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
6320 bc_program_binOpRetire(&res2);
6321 res.t = BC_RESULT_TEMP;
6322 bc_vec_push(&G.prog.results, &res);
6327 bc_num_free(&res2.d.n);
6328 bc_num_free(&res.d.n);
6332 static BcStatus bc_program_modexp(void)
6335 BcResult *r1, *r2, *r3, res;
6336 BcNum *n1, *n2, *n3;
6338 if (!BC_PROG_STACK(&G.prog.results, 3))
6339 return bc_error_stack_has_too_few_elements();
6340 s = bc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
6343 r1 = bc_vec_item_rev(&G.prog.results, 2);
6344 s = bc_program_num(r1, &n1, false);
6346 if (!BC_PROG_NUM(r1, n1))
6347 return bc_error_variable_is_wrong_type();
6349 // Make sure that the values have their pointers updated, if necessary.
6350 if (r1->t == BC_RESULT_VAR || r1->t == BC_RESULT_ARRAY_ELEM) {
6352 if (r1->t == r2->t) {
6353 s = bc_program_num(r2, &n2, false);
6357 if (r1->t == r3->t) {
6358 s = bc_program_num(r3, &n3, false);
6363 bc_num_init(&res.d.n, n3->len);
6364 s = bc_num_modexp(n1, n2, n3, &res.d.n);
6367 bc_vec_pop(&G.prog.results);
6368 bc_program_binOpRetire(&res);
6373 bc_num_free(&res.d.n);
6377 static void bc_program_stackLen(void)
6380 size_t len = G.prog.results.len;
6382 res.t = BC_RESULT_TEMP;
6384 bc_num_init_DEF_SIZE(&res.d.n);
6385 bc_num_ulong2num(&res.d.n, len);
6386 bc_vec_push(&G.prog.results, &res);
6389 static BcStatus bc_program_asciify(void)
6394 char *str, *str2, c;
6395 size_t len = G.prog.strs.len, idx;
6398 if (!BC_PROG_STACK(&G.prog.results, 1))
6399 return bc_error_stack_has_too_few_elements();
6400 r = bc_vec_top(&G.prog.results);
6402 num = NULL; // TODO: is this NULL needed?
6403 s = bc_program_num(r, &num, false);
6406 if (BC_PROG_NUM(r, num)) {
6408 bc_num_init_DEF_SIZE(&n);
6409 bc_num_copy(&n, num);
6410 bc_num_truncate(&n, n.rdx);
6412 s = bc_num_mod(&n, &G.prog.strmb, &n, 0);
6413 if (s) goto num_err;
6414 s = bc_num_ulong(&n, &val);
6415 if (s) goto num_err;
6422 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : num->rdx;
6423 str2 = *bc_program_str(idx);
6431 str2 = xstrdup(str);
6432 bc_program_addFunc(str2, &idx);
6434 if (idx != len + BC_PROG_REQ_FUNCS) {
6436 for (idx = 0; idx < G.prog.strs.len; ++idx) {
6437 if (strcmp(*bc_program_str(idx), str) == 0) {
6446 bc_vec_push(&G.prog.strs, &str);
6448 res.t = BC_RESULT_STR;
6450 bc_vec_pop(&G.prog.results);
6451 bc_vec_push(&G.prog.results, &res);
6453 return BC_STATUS_SUCCESS;
6460 static BcStatus bc_program_printStream(void)
6468 if (!BC_PROG_STACK(&G.prog.results, 1))
6469 return bc_error_stack_has_too_few_elements();
6470 r = bc_vec_top(&G.prog.results);
6472 s = bc_program_num(r, &n, false);
6475 if (BC_PROG_NUM(r, n))
6476 s = bc_num_stream(n, &G.prog.strmb);
6478 idx = (r->t == BC_RESULT_STR) ? r->d.id.idx : n->rdx;
6479 str = *bc_program_str(idx);
6486 static BcStatus bc_program_nquit(void)
6493 s = bc_program_prep(&opnd, &num);
6495 s = bc_num_ulong(num, &val);
6498 bc_vec_pop(&G.prog.results);
6500 if (G.prog.stack.len < val)
6501 return bc_error_stack_has_too_few_elements();
6502 if (G.prog.stack.len == val) {
6503 QUIT_OR_RETURN_TO_MAIN;
6506 bc_vec_npop(&G.prog.stack, val);
6511 static BcStatus bc_program_execStr(char *code, size_t *bgn,
6514 BcStatus s = BC_STATUS_SUCCESS;
6522 if (!BC_PROG_STACK(&G.prog.results, 1))
6523 return bc_error_stack_has_too_few_elements();
6525 r = bc_vec_top(&G.prog.results);
6528 BcNum *n = n; // for compiler
6531 char *then_name = bc_program_name(code, bgn);
6532 char *else_name = NULL;
6534 if (code[*bgn] == BC_PARSE_STREND)
6537 else_name = bc_program_name(code, bgn);
6539 exec = r->d.n.len != 0;
6541 if (!exec && else_name != NULL) {
6548 v = bc_program_search(name, true);
6555 if (!exec) goto exit;
6556 if (!BC_PROG_STR(n)) {
6557 s = bc_error_variable_is_wrong_type();
6563 if (r->t == BC_RESULT_STR) {
6565 } else if (r->t == BC_RESULT_VAR) {
6567 s = bc_program_num(r, &n, false);
6568 if (s || !BC_PROG_STR(n)) goto exit;
6574 fidx = sidx + BC_PROG_REQ_FUNCS;
6576 str = bc_program_str(sidx);
6577 f = bc_program_func(fidx);
6579 if (f->code.len == 0) {
6580 common_parse_init(&prs, fidx);
6581 s = bc_parse_text(&prs, *str);
6583 s = common_parse_expr(&prs, BC_PARSE_NOCALL);
6586 if (prs.l.t.t != BC_LEX_EOF) {
6587 s = bc_error_bad_expression();
6591 bc_parse_free(&prs);
6595 ip.len = G.prog.results.len;
6598 bc_vec_pop(&G.prog.results);
6599 bc_vec_push(&G.prog.stack, &ip);
6601 return BC_STATUS_SUCCESS;
6604 bc_parse_free(&prs);
6605 f = bc_program_func(fidx);
6606 bc_vec_pop_all(&f->code);
6608 bc_vec_pop(&G.prog.results);
6613 static void bc_program_pushGlobal(char inst)
6618 res.t = inst - BC_INST_IBASE + BC_RESULT_IBASE;
6619 if (inst == BC_INST_IBASE)
6620 val = (unsigned long) G.prog.ib_t;
6621 else if (inst == BC_INST_SCALE)
6622 val = (unsigned long) G.prog.scale;
6624 val = (unsigned long) G.prog.ob_t;
6626 bc_num_init_DEF_SIZE(&res.d.n);
6627 bc_num_ulong2num(&res.d.n, val);
6628 bc_vec_push(&G.prog.results, &res);
6631 static void bc_program_addFunc(char *name, size_t *idx)
6633 BcId entry, *entry_ptr;
6638 entry.idx = G.prog.fns.len;
6640 inserted = bc_map_insert(&G.prog.fn_map, &entry, idx);
6641 if (!inserted) free(name);
6643 entry_ptr = bc_vec_item(&G.prog.fn_map, *idx);
6644 *idx = entry_ptr->idx;
6648 BcFunc *func = bc_program_func(entry_ptr->idx);
6650 // We need to reset these, so the function can be repopulated.
6652 bc_vec_pop_all(&func->autos);
6653 bc_vec_pop_all(&func->code);
6654 bc_vec_pop_all(&func->labels);
6658 bc_vec_push(&G.prog.fns, &f);
6662 static BcStatus bc_program_exec(void)
6666 BcInstPtr *ip = bc_vec_top(&G.prog.stack);
6667 BcFunc *func = bc_program_func(ip->func);
6668 char *code = func->code.v;
6671 while (ip->idx < func->code.len) {
6673 char inst = code[(ip->idx)++];
6677 case BC_INST_JUMP_ZERO:
6678 s = bc_program_prep(&ptr, &num);
6680 cond = !bc_num_cmp(num, &G.prog.zero);
6681 bc_vec_pop(&G.prog.results);
6683 case BC_INST_JUMP: {
6685 size_t idx = bc_program_index(code, &ip->idx);
6686 addr = bc_vec_item(&func->labels, idx);
6687 if (inst == BC_INST_JUMP || cond) ip->idx = *addr;
6691 s = bc_program_call(code, &ip->idx);
6693 case BC_INST_INC_PRE:
6694 case BC_INST_DEC_PRE:
6695 case BC_INST_INC_POST:
6696 case BC_INST_DEC_POST:
6697 s = bc_program_incdec(inst);
6700 QUIT_OR_RETURN_TO_MAIN;
6704 s = bc_program_return(inst);
6706 case BC_INST_BOOL_OR:
6707 case BC_INST_BOOL_AND:
6709 case BC_INST_REL_EQ:
6710 case BC_INST_REL_LE:
6711 case BC_INST_REL_GE:
6712 case BC_INST_REL_NE:
6713 case BC_INST_REL_LT:
6714 case BC_INST_REL_GT:
6715 s = bc_program_logical(inst);
6718 s = bc_program_read();
6721 s = bc_program_pushVar(code, &ip->idx, false, false);
6723 case BC_INST_ARRAY_ELEM:
6725 s = bc_program_pushArray(code, &ip->idx, inst);
6728 r.t = BC_RESULT_LAST;
6729 bc_vec_push(&G.prog.results, &r);
6734 bc_program_pushGlobal(inst);
6736 case BC_INST_SCALE_FUNC:
6737 case BC_INST_LENGTH:
6739 s = bc_program_builtin(inst);
6742 r.t = BC_RESULT_CONSTANT;
6743 r.d.id.idx = bc_program_index(code, &ip->idx);
6744 bc_vec_push(&G.prog.results, &r);
6747 if (!BC_PROG_STACK(&G.prog.results, 1))
6748 s = bc_error_stack_has_too_few_elements();
6750 bc_vec_pop(&G.prog.results);
6752 case BC_INST_POP_EXEC:
6753 bc_vec_pop(&G.prog.stack);
6756 case BC_INST_PRINT_POP:
6757 case BC_INST_PRINT_STR:
6758 s = bc_program_print(inst, 0);
6761 r.t = BC_RESULT_STR;
6762 r.d.id.idx = bc_program_index(code, &ip->idx);
6763 bc_vec_push(&G.prog.results, &r);
6766 case BC_INST_MULTIPLY:
6767 case BC_INST_DIVIDE:
6768 case BC_INST_MODULUS:
6771 s = bc_program_op(inst);
6773 case BC_INST_BOOL_NOT:
6774 s = bc_program_prep(&ptr, &num);
6776 bc_num_init_DEF_SIZE(&r.d.n);
6777 if (!bc_num_cmp(num, &G.prog.zero))
6779 //else bc_num_zero(&r.d.n); - already is
6780 bc_program_retire(&r, BC_RESULT_TEMP);
6783 s = bc_program_negate();
6786 case BC_INST_ASSIGN_POWER:
6787 case BC_INST_ASSIGN_MULTIPLY:
6788 case BC_INST_ASSIGN_DIVIDE:
6789 case BC_INST_ASSIGN_MODULUS:
6790 case BC_INST_ASSIGN_PLUS:
6791 case BC_INST_ASSIGN_MINUS:
6793 case BC_INST_ASSIGN:
6794 s = bc_program_assign(inst);
6797 case BC_INST_MODEXP:
6798 s = bc_program_modexp();
6800 case BC_INST_DIVMOD:
6801 s = bc_program_divmod();
6803 case BC_INST_EXECUTE:
6804 case BC_INST_EXEC_COND:
6805 cond = inst == BC_INST_EXEC_COND;
6806 s = bc_program_execStr(code, &ip->idx, cond);
6808 case BC_INST_PRINT_STACK: {
6810 for (idx = 0; idx < G.prog.results.len; ++idx) {
6811 s = bc_program_print(BC_INST_PRINT, idx);
6816 case BC_INST_CLEAR_STACK:
6817 bc_vec_pop_all(&G.prog.results);
6819 case BC_INST_STACK_LEN:
6820 bc_program_stackLen();
6822 case BC_INST_DUPLICATE:
6823 if (!BC_PROG_STACK(&G.prog.results, 1))
6824 return bc_error_stack_has_too_few_elements();
6825 ptr = bc_vec_top(&G.prog.results);
6826 bc_result_copy(&r, ptr);
6827 bc_vec_push(&G.prog.results, &r);
6829 case BC_INST_SWAP: {
6831 if (!BC_PROG_STACK(&G.prog.results, 2))
6832 return bc_error_stack_has_too_few_elements();
6833 ptr = bc_vec_item_rev(&G.prog.results, 0);
6834 ptr2 = bc_vec_item_rev(&G.prog.results, 1);
6835 memcpy(&r, ptr, sizeof(BcResult));
6836 memcpy(ptr, ptr2, sizeof(BcResult));
6837 memcpy(ptr2, &r, sizeof(BcResult));
6840 case BC_INST_ASCIIFY:
6841 s = bc_program_asciify();
6843 case BC_INST_PRINT_STREAM:
6844 s = bc_program_printStream();
6847 case BC_INST_PUSH_VAR: {
6848 bool copy = inst == BC_INST_LOAD;
6849 s = bc_program_pushVar(code, &ip->idx, true, copy);
6852 case BC_INST_PUSH_TO_VAR: {
6853 char *name = bc_program_name(code, &ip->idx);
6854 s = bc_program_copyToVar(name, true);
6859 if (G.prog.stack.len <= 2)
6860 QUIT_OR_RETURN_TO_MAIN;
6861 bc_vec_npop(&G.prog.stack, 2);
6864 s = bc_program_nquit();
6869 if (s || G_interrupt) {
6874 // If the stack has changed, pointers may be invalid.
6875 ip = bc_vec_top(&G.prog.stack);
6876 func = bc_program_func(ip->func);
6877 code = func->code.v;
6880 return BC_STATUS_SUCCESS;
6884 static void bc_vm_info(void)
6886 printf("%s "BB_VER"\n"
6887 "Copyright (c) 2018 Gavin D. Howard and contributors\n"
6891 static void bc_args(char **argv)
6897 #if ENABLE_FEATURE_BC_LONG_OPTIONS
6898 opts = option_mask32 |= getopt32long(argv, "wvsqli",
6899 "warn\0" No_argument "w"
6900 "version\0" No_argument "v"
6901 "standard\0" No_argument "s"
6902 "quiet\0" No_argument "q"
6903 "mathlib\0" No_argument "l"
6904 "interactive\0" No_argument "i"
6907 opts = option_mask32 |= getopt32(argv, "wvsqli");
6909 if (getenv("POSIXLY_CORRECT"))
6910 option_mask32 |= BC_FLAG_S;
6912 if (opts & BC_FLAG_V) {
6917 for (i = optind; argv[i]; ++i)
6918 bc_vec_push(&G.files, argv + i);
6921 static void bc_vm_envArgs(void)
6925 char *env_args = getenv("BC_ENV_ARGS");
6927 if (!env_args) return;
6929 G.env_args = xstrdup(env_args);
6932 bc_vec_init(&v, sizeof(char *), NULL);
6934 while (*(buf = skip_whitespace(buf)) != '\0') {
6935 bc_vec_push(&v, &buf);
6936 buf = skip_non_whitespace(buf);
6942 // NULL terminate, and pass argv[] so that first arg is argv[1]
6943 if (sizeof(int) == sizeof(char*)) {
6944 bc_vec_push(&v, &const_int_0);
6946 static char *const nullptr = NULL;
6947 bc_vec_push(&v, &nullptr);
6949 bc_args(((char **)v.v) - 1);
6955 static unsigned bc_vm_envLen(const char *var)
6961 len = BC_NUM_PRINT_WIDTH;
6962 if (!lenv) return len;
6964 len = bb_strtou(lenv, NULL, 10) - 1;
6965 if (errno || len < 2 || len >= INT_MAX)
6966 len = BC_NUM_PRINT_WIDTH;
6971 static BcStatus bc_vm_process(const char *text)
6973 BcStatus s = bc_parse_text(&G.prs, text);
6977 while (G.prs.l.t.t != BC_LEX_EOF) {
6978 s = G.prs.parse(&G.prs);
6982 if (BC_PARSE_CAN_EXEC(&G.prs)) {
6983 s = bc_program_exec();
6992 static BcStatus bc_vm_file(const char *file)
6994 const char *sv_file;
7000 data = bc_read_file(file);
7001 if (!data) return bc_error_fmt("file '%s' is not text", file);
7003 sv_file = G.prog.file;
7005 bc_lex_file(&G.prs.l);
7006 s = bc_vm_process(data);
7009 main_func = bc_program_func(BC_PROG_MAIN);
7010 ip = bc_vec_item(&G.prog.stack, 0);
7012 if (main_func->code.len < ip->idx)
7013 s = bc_error_fmt("file '%s' is not executable", file);
7016 G.prog.file = sv_file;
7021 static BcStatus bc_vm_stdin(void)
7025 size_t len, i, str = 0;
7026 bool comment = false;
7029 bc_lex_file(&G.prs.l);
7031 bc_char_vec_init(&buffer);
7032 bc_char_vec_init(&buf);
7033 bc_vec_pushZeroByte(&buffer);
7035 // This loop is complex because the vm tries not to send any lines that end
7036 // with a backslash to the parser. The reason for that is because the parser
7037 // treats a backslash+newline combo as whitespace, per the bc spec. In that
7038 // case, and for strings and comments, the parser will expect more stuff.
7039 while ((s = bc_read_line(&buf)) == BC_STATUS_SUCCESS) {
7041 char *string = buf.v;
7046 if (str && buf.v[0] == G.send)
7048 else if (buf.v[0] == G.sbgn)
7051 else if (len > 1 || comment) {
7053 for (i = 0; i < len; ++i) {
7055 bool notend = len > i + 1;
7058 if (i - 1 > len || string[i - 1] != '\\') {
7059 if (G.sbgn == G.send)
7061 else if (c == G.send)
7063 else if (c == G.sbgn)
7067 if (c == '/' && notend && !comment && string[i + 1] == '*') {
7071 else if (c == '*' && notend && comment && string[i + 1] == '/')
7075 if (str || comment || string[len - 2] == '\\') {
7076 bc_vec_concat(&buffer, buf.v);
7081 bc_vec_concat(&buffer, buf.v);
7082 s = bc_vm_process(buffer.v);
7084 if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin) {
7085 // Debug config, non-interactive mode:
7086 // return all the way back to main.
7087 // Non-debug builds do not come here, they exit.
7092 bc_vec_pop_all(&buffer);
7094 if (s == BC_STATUS_EOF) // input EOF (^D) is not an error
7095 s = BC_STATUS_SUCCESS;
7098 s = bc_error("string end could not be found");
7101 s = bc_error("comment end could not be found");
7105 bc_vec_free(&buffer);
7110 static const char bc_lib[] = {
7113 "\n" "auto b,s,n,r,d,i,p,f,v"
7122 "\n" "scale=scale(x)+1"
7132 "\n" "for(i=2;v!=0;++i){"
7138 "\n" "while((d--)!=0)r*=r"
7141 "\n" "if(n!=0)return(1/r)"
7145 "\n" "auto b,s,r,p,a,q,i,v"
7149 "\n" "r=(1-10^scale)/1"
7160 "\n" "while(x<=0.5){"
7164 "\n" "r=a=(x-1)/(x+1)"
7167 "\n" "for(i=3;v!=0;i+=2){"
7178 "\n" "auto b,s,r,n,a,q,i"
7182 "\n" "scale=1.1*s+2"
7191 "\n" "if(q%2!=0)x=-x"
7195 "\n" "for(i=3;a!=0;i+=2){"
7196 "\n" "a*=q/(i*(i-1))"
7201 "\n" "if(n!=0)return(-r/1)"
7210 "\n" "x=s(2*a(1)+x)"
7216 "\n" "auto b,s,r,n,a,m,t,f,i,u"
7225 "\n" "if(scale<65){"
7226 "\n" "return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
7230 "\n" "if(scale<65){"
7231 "\n" "return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
7242 "\n" "x=(x-.2)/(1+.2*x)"
7247 "\n" "for(i=3;t!=0;i+=2){"
7254 "\n" "return((m*a+r)/n)"
7256 "\n" "define j(n,x){"
7257 "\n" "auto b,s,o,a,i,v,f"
7265 "\n" "if(n%2==1)o=1"
7268 "\n" "for(i=2;i<=n;++i)a*=i"
7270 "\n" "a=(x^n)/2^n/a"
7273 "\n" "scale=scale+length(a)-scale(a)"
7274 "\n" "for(i=1;v!=0;++i){"
7275 "\n" "v=v*f/i/(n+i)"
7281 "\n" "return(a*r/1)"
7286 static BcStatus bc_vm_exec(void)
7292 if (option_mask32 & BC_FLAG_L) {
7294 // We know that internal library is not buggy,
7295 // thus error checking is normally disabled.
7296 # define DEBUG_LIB 0
7297 bc_lex_file(&G.prs.l);
7298 s = bc_parse_text(&G.prs, bc_lib);
7299 if (DEBUG_LIB && s) return s;
7301 while (G.prs.l.t.t != BC_LEX_EOF) {
7302 s = G.prs.parse(&G.prs);
7303 if (DEBUG_LIB && s) return s;
7305 s = bc_program_exec();
7306 if (DEBUG_LIB && s) return s;
7310 s = BC_STATUS_SUCCESS;
7311 for (i = 0; !s && i < G.files.len; ++i)
7312 s = bc_vm_file(*((char **) bc_vec_item(&G.files, i)));
7313 if (ENABLE_FEATURE_CLEAN_UP && s && !G_ttyin) {
7314 // Debug config, non-interactive mode:
7315 // return all the way back to main.
7316 // Non-debug builds do not come here, they exit.
7320 if (IS_BC || (option_mask32 & BC_FLAG_I))
7323 if (!s && !BC_PARSE_CAN_EXEC(&G.prs))
7324 s = bc_vm_process("");
7329 #if ENABLE_FEATURE_CLEAN_UP
7330 static void bc_program_free(void)
7332 bc_num_free(&G.prog.ib);
7333 bc_num_free(&G.prog.ob);
7334 bc_num_free(&G.prog.hexb);
7336 bc_num_free(&G.prog.strmb);
7338 bc_vec_free(&G.prog.fns);
7339 bc_vec_free(&G.prog.fn_map);
7340 bc_vec_free(&G.prog.vars);
7341 bc_vec_free(&G.prog.var_map);
7342 bc_vec_free(&G.prog.arrs);
7343 bc_vec_free(&G.prog.arr_map);
7344 bc_vec_free(&G.prog.strs);
7345 bc_vec_free(&G.prog.consts);
7346 bc_vec_free(&G.prog.results);
7347 bc_vec_free(&G.prog.stack);
7348 bc_num_free(&G.prog.last);
7349 bc_num_free(&G.prog.zero);
7350 bc_num_free(&G.prog.one);
7353 static void bc_vm_free(void)
7355 bc_vec_free(&G.files);
7357 bc_parse_free(&G.prs);
7362 static void bc_program_init(void)
7367 /* memset(&G.prog, 0, sizeof(G.prog)); - already is */
7368 memset(&ip, 0, sizeof(BcInstPtr));
7370 /* G.prog.nchars = G.prog.scale = 0; - already is */
7371 bc_num_init_DEF_SIZE(&G.prog.ib);
7372 bc_num_ten(&G.prog.ib);
7375 bc_num_init_DEF_SIZE(&G.prog.ob);
7376 bc_num_ten(&G.prog.ob);
7379 bc_num_init_DEF_SIZE(&G.prog.hexb);
7380 bc_num_ten(&G.prog.hexb);
7381 G.prog.hexb.num[0] = 6;
7384 bc_num_init_DEF_SIZE(&G.prog.strmb);
7385 bc_num_ulong2num(&G.prog.strmb, UCHAR_MAX + 1);
7388 bc_num_init_DEF_SIZE(&G.prog.last);
7389 //bc_num_zero(&G.prog.last); - already is
7391 bc_num_init_DEF_SIZE(&G.prog.zero);
7392 //bc_num_zero(&G.prog.zero); - already is
7394 bc_num_init_DEF_SIZE(&G.prog.one);
7395 bc_num_one(&G.prog.one);
7397 bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
7398 bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);
7400 bc_program_addFunc(xstrdup("(main)"), &idx);
7401 bc_program_addFunc(xstrdup("(read)"), &idx);
7403 bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
7404 bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
7406 bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
7407 bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
7409 bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);
7410 bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);
7411 bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
7412 bc_vec_init(&G.prog.stack, sizeof(BcInstPtr), NULL);
7413 bc_vec_push(&G.prog.stack, &ip);
7416 static int bc_vm_init(const char *env_len)
7418 #if ENABLE_FEATURE_EDITING
7419 G.line_input_state = new_line_input_t(DO_HISTORY);
7421 G.prog.len = bc_vm_envLen(env_len);
7423 bc_vec_init(&G.files, sizeof(char *), NULL);
7425 IF_BC(bc_vm_envArgs();)
7428 IF_BC(bc_parse_init(&G.prs, BC_PROG_MAIN);)
7430 IF_DC(dc_parse_init(&G.prs, BC_PROG_MAIN);)
7434 #if ENABLE_FEATURE_BC_SIGNALS
7436 // With SA_RESTART, most system calls will restart
7437 // (IOW: they won't fail with EINTR).
7438 // In particular, this means ^C won't cause
7439 // stdout to get into "error state" if SIGINT hits
7440 // within write() syscall.
7441 // The downside is that ^C while line input is taken
7442 // will only be handled after [Enter] since read()
7443 // from stdin is not interrupted by ^C either,
7444 // it restarts, thus fgetc() does not return on ^C.
7445 signal_SA_RESTART_empty_mask(SIGINT, record_signo);
7447 // Without SA_RESTART, this exhibits a bug:
7448 // "while (1) print 1" and try ^C-ing it.
7449 // Intermittently, instead of returning to input line,
7450 // you'll get "output error: Interrupted system call"
7452 //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
7456 return 0; // "not a tty"
7459 static BcStatus bc_vm_run(void)
7461 BcStatus st = bc_vm_exec();
7462 #if ENABLE_FEATURE_CLEAN_UP
7463 if (G_exiting) // it was actually "halt" or "quit"
7466 # if ENABLE_FEATURE_EDITING
7467 free_line_input_t(G.line_input_state);
7475 int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7476 int bc_main(int argc UNUSED_PARAM, char **argv)
7481 G.sbgn = G.send = '"';
7483 is_tty = bc_vm_init("BC_LINE_LENGTH");
7487 if (is_tty && !(option_mask32 & BC_FLAG_Q))
7495 int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7496 int dc_main(int argc UNUSED_PARAM, char **argv)
7504 * TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
7505 * 1 char wider than bc from the same package.
7506 * Both default width, and xC_LINE_LENGTH=N are wider:
7507 * "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
7510 * "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
7513 * Do the same, or it's a bug?
7515 bc_vm_init("DC_LINE_LENGTH");
7517 // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
7518 noscript = BC_FLAG_I;
7520 int n = getopt(argc, argv, "e:f:x");
7526 n = bc_vm_process(optarg);
7534 option_mask32 |= DC_FLAG_X;
7544 bc_vec_push(&G.files, argv++);
7547 option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
7553 #endif // not DC_SMALL