/** * @file arith.c * @brief Arithmetic evaluation for `$(( ))`, `(( ))` and `let`. * * A precedence-climbing evaluator over `intmax_t` with the C operators * POSIX requires, plus `++`, `--` and the comma operator. Signed overflow * wraps (the arithmetic is done unsigned), so no expression has undefined * behaviour. * * This is on the hot path of every loop counter, so the scanner avoids the * locale-aware calls and string comparisons: operators are * recognised by switching on their first character. */ #include #include #include #include #include #include #include "expand.h" #include "var.h" /** * @brief State of one evaluation. */ typedef struct arith { const char *p; const char *expr; int noeval; /**< >0 while skipping the untaken side of ?: && || */ } arith; static intmax_t parse_assign(arith *a); /** * @brief Abort the evaluation with an error message that quotes the expression. * @param a Evaluation state. * @param msg What is wrong. */ [[noreturn]] static void arith_error(const arith *a, const char *msg) { sh_error("arithmetic: %s: \"%s\"", msg, a->expr); } /** * @brief Advance past blanks and newlines. */ static void skip_space(arith *a) { while (*a->p == ' ' || *a->p == '\t' || *a->p == '\n') a->p++; } /** * @brief Consume the one-character token `c` if it is next. * @param a Evaluation state. * @param c The character. * @return true if it was there. */ static bool eat(arith *a, char c) { skip_space(a); if (*a->p != c) return false; a->p++; return true; } /** * @brief The slow path of var_value(): a value that is not a number is * evaluated as an expression, as ksh and bash do, so that after * `r=x; x=7` `$((r))` is 7. * * Kept out of var_value() because the setjmp() here would otherwise * stop the compiler optimising the common, numeric case (measured: 12M * more instructions in bench/loop.sh). A cycle such as `a=b; b=a` is * stopped by the depth limit. * * @param a Evaluation state, for error reports. * @param s The variable's value. * @param range strtoimax() reported overflow. * @return The value of the expression. */ static NOINLINE intmax_t var_value_expr(const arith *a, const char *s, bool range) { static int depth; if (range || depth >= 16) arith_error(a, range ? "number out of range" : "expression recursion too deep"); if (a->noeval) return 0; depth++; jmploc jl; jmploc *prev = exc_handler; if (setjmp(jl.buf)) { exc_handler = prev; depth = 0; exc_raise(exc_code); } exc_catch(&jl); intmax_t v = arith_eval(s); exc_handler = prev; depth--; return v; } /** * @brief Numeric value of a variable used in an expression. * * An unset or empty variable is 0. A short run of decimal digits, the * usual case, is converted here. Anything else (hex, octal, a sign) goes * through strtoimax(). * * @param a Evaluation state, for error reports. * @param name Variable name (not NUL-terminated). * @param nlen Its length. * @return The value. */ static intmax_t var_value(const arith *a, const char *name, size_t nlen) { const char *s = var_get_n(name, nlen); if (!s || !*s) return 0; /* The usual case: a short run of decimal digits. */ if (s[0] != '0' || !s[1]) { intmax_t v = 0; int n = 0; while (is_digit(s[n]) && n < 18) v = v * 10 + (s[n++] - '0'); if (n && !s[n]) return v; } char *end; errno = 0; intmax_t v = strtoimax(s, &end, 0); while (isspace((unsigned char)*end)) end++; if (*end || errno) v = var_value_expr(a, s, errno != 0); return v; } /** * @brief Store a result in a variable, unless evaluation is switched off. * @param a Evaluation state. * @param name Variable name. * @param nlen Its length. * @param v The value. */ static void assign(const arith *a, const char *name, size_t nlen, intmax_t v) { if (a->noeval) return; char buf[INT_BUFSZ]; var_set_n(name, nlen, fmt_int(v, buf), 0); } /** * @brief Add with two's-complement wrap-around instead of undefined overflow. */ static intmax_t wrap_add(intmax_t x, intmax_t y) { return (intmax_t)((uintmax_t)x + (uintmax_t)y); } /** * @brief Subtract with wrap-around. */ static intmax_t wrap_sub(intmax_t x, intmax_t y) { return (intmax_t)((uintmax_t)x - (uintmax_t)y); } /** * @brief Multiply with wrap-around. */ static intmax_t wrap_mul(intmax_t x, intmax_t y) { return (intmax_t)((uintmax_t)x * (uintmax_t)y); } /** * @brief The binary operators, in no particular order (precedence comes from * scan_binop()). */ typedef enum binop { OP_MUL, OP_DIV, OP_MOD, OP_ADD, OP_SUB, OP_SHL, OP_SHR, OP_LT, OP_LE, OP_GT, OP_GE, OP_EQ, OP_NE, OP_BAND, OP_BXOR, OP_BOR, OP_LAND, OP_LOR, } binop; /** * @brief Apply a binary operator to two values. * * Division by zero is an error, except in a branch that is not being * evaluated. `INTMAX_MIN / -1`, which would trap, is given its wrapped * result. * * @param a Evaluation state. * @param op The operator. * @param x Left operand. * @param y Right operand. * @return The result. */ static intmax_t apply(const arith *a, binop op, intmax_t x, intmax_t y) { switch (op) { case OP_MUL: return wrap_mul(x, y); case OP_DIV: case OP_MOD: if (y == 0) { if (a->noeval) return 0; arith_error(a, "division by zero"); } if (y == -1) /* INTMAX_MIN / -1 would trap */ return op == OP_DIV ? wrap_sub(0, x) : 0; return op == OP_DIV ? x / y : x % y; case OP_ADD: return wrap_add(x, y); case OP_SUB: return wrap_sub(x, y); case OP_SHL: return (intmax_t)((uintmax_t)x << (y & 63)); case OP_SHR: return x >> (y & 63); case OP_LT: return x < y; case OP_LE: return x <= y; case OP_GT: return x > y; case OP_GE: return x >= y; case OP_EQ: return x == y; case OP_NE: return x != y; case OP_BAND: return x & y; case OP_BXOR: return x ^ y; case OP_BOR: return x | y; case OP_LAND: return x && y; case OP_LOR: return x || y; } UNREACHABLE(); } /** * @brief Parse `base#digits`, the way ksh and bash write a number in a base. * @param a The arithmetic state. * @param p Start of the base digits. * @param hash The `#` that ends them. * @return The value. */ static intmax_t parse_based(arith *a, const char *p, const char *hash) { int base = 0; for (const char *q = p; q < hash; q++) { base = base * 10 + (*q - '0'); if (base > 64) arith_error(a, "bad number base"); } if (base < 2) arith_error(a, "bad number base"); /* * The digit set of ksh and bash. Spelling it out beats arithmetic on * character codes: the letters are not contiguous in EBCDIC. */ static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ@_"; uintmax_t v = 0; const char *q = hash + 1; for (; *q; q++) { int ch = (unsigned char)*q; if (base <= 36) ch = tolower(ch); const char *d = strchr(digits, ch); if (!d) break; uintmax_t dv = (uintmax_t)(d - digits); if (dv >= (uintmax_t)base) break; if (v > (UINTMAX_MAX - dv) / (uintmax_t)base) arith_error(a, "bad number"); v = v * base + dv; } /* No digits, or a digit the base does not have (16#0x10, 16# f). */ if (q == hash + 1 || (*q && strchr(digits, *q))) arith_error(a, "bad number"); a->p = q; return (intmax_t)v; } /** * @brief Parse a number, a variable, or a parenthesised expression. * @return Its value. */ static intmax_t parse_primary(arith *a) { skip_space(a); const char *p = a->p; if (*p == '(') { a->p++; intmax_t v = parse_assign(a); while (eat(a, ',')) v = parse_assign(a); if (!eat(a, ')')) arith_error(a, "missing ')'"); return v; } if (is_digit(*p)) { const char *hash = p; while (is_digit(*hash)) hash++; if (*hash == '#') return parse_based(a, p, hash); if (*p != '0') { /* decimal: no need for strtoumax() */ intmax_t v = 0; int n = 0; while (is_digit(p[n]) && n < 18) v = v * 10 + (p[n++] - '0'); if (!is_digit(p[n]) && !isalpha((unsigned char)p[n]) && p[n] != '_') { a->p = p + n; return v; } } char *end; errno = 0; intmax_t v = (intmax_t)strtoumax(p, &end, 0); if (errno || isalnum((unsigned char)*end) || *end == '_') arith_error(a, "bad number"); a->p = end; return v; } size_t nlen = name_len(p); if (!nlen) arith_error(a, "syntax error"); a->p += nlen; intmax_t v = var_value(a, p, nlen); skip_space(a); if ((a->p[0] == '+' || a->p[0] == '-') && a->p[1] == a->p[0]) { assign(a, p, nlen, a->p[0] == '+' ? wrap_add(v, 1) : wrap_sub(v, 1)); a->p += 2; } return v; } /** * @brief Parse unary `+ - ! ~`, prefix and postfix `++` and `--`, then a * primary. * @return Its value. */ static intmax_t parse_unary(arith *a) { /* Every recursion in the grammar passes through here. */ if (stack_low()) arith_error(a, "expression nested too deeply"); skip_space(a); const char *p = a->p; if ((p[0] == '+' || p[0] == '-') && p[1] == p[0] && name_len(p + 2 + strspn(p + 2, " \t\n"))) { a->p += 2; skip_space(a); size_t nlen = name_len(a->p); if (!nlen) arith_error(a, "++ or -- needs a variable"); const char *name = a->p; a->p += nlen; intmax_t v = var_value(a, name, nlen); v = p[0] == '+' ? wrap_add(v, 1) : wrap_sub(v, 1); assign(a, name, nlen, v); return v; } switch (*p) { case '+': a->p++; return parse_unary(a); case '-': a->p++; return wrap_sub(0, parse_unary(a)); case '!': a->p++; return !parse_unary(a); case '~': a->p++; return ~parse_unary(a); default: return parse_primary(a); } } /** * @brief Recognise the binary operator at `p`. * @param p Text. * @param op Receives the operator. * @param prec Receives its precedence. A higher value binds tighter. * @return The operator's length in characters, or 0 if there is none. */ static int scan_binop(const char *p, binop *op, int *prec) { if (!p[0]) return 0; /* at the end: p[1] is past the string */ char c1 = p[1]; switch (p[0]) { case '|': if (c1 == '|') return *op = OP_LOR, *prec = 1, 2; return *op = OP_BOR, *prec = 3, 1; case '&': if (c1 == '&') return *op = OP_LAND, *prec = 2, 2; return *op = OP_BAND, *prec = 5, 1; case '^': return *op = OP_BXOR, *prec = 4, 1; case '=': if (c1 == '=') return *op = OP_EQ, *prec = 6, 2; return 0; case '!': if (c1 == '=') return *op = OP_NE, *prec = 6, 2; return 0; case '<': if (c1 == '<') return *op = OP_SHL, *prec = 8, 2; if (c1 == '=') return *op = OP_LE, *prec = 7, 2; return *op = OP_LT, *prec = 7, 1; case '>': if (c1 == '>') return *op = OP_SHR, *prec = 8, 2; if (c1 == '=') return *op = OP_GE, *prec = 7, 2; return *op = OP_GT, *prec = 7, 1; case '+': return *op = OP_ADD, *prec = 9, 1; case '-': return *op = OP_SUB, *prec = 9, 1; case '*': return *op = OP_MUL, *prec = 10, 1; case '/': return *op = OP_DIV, *prec = 10, 1; case '%': return *op = OP_MOD, *prec = 10, 1; default: return 0; } } /** * @brief Parse a chain of binary operators by precedence climbing. * * `&&` and `||` do not evaluate their right-hand side when the left * decides the result (`noeval` is raised while it is parsed). * * @param a Evaluation state. * @param min_prec Only operators at least this strong are consumed. * @return The value. */ static intmax_t parse_binary(arith *a, int min_prec) { intmax_t lhs = parse_unary(a); for (;;) { skip_space(a); binop op; int prec; int len = scan_binop(a->p, &op, &prec); if (!len || prec < min_prec) return lhs; /* Leave "x op= y" for the assignment level to report. */ if (a->p[len] == '=' && prec != 6 && prec != 7) return lhs; a->p += len; bool skip = (op == OP_LAND && !lhs) || (op == OP_LOR && lhs); a->noeval += skip; intmax_t rhs = parse_binary(a, prec + 1); a->noeval -= skip; lhs = apply(a, op, lhs, rhs); } } /** * @brief Parse `cond ? a : b`. Only the chosen branch is evaluated. * @return The value. */ static intmax_t parse_ternary(arith *a) { intmax_t test = parse_binary(a, 1); if (!eat(a, '?')) return test; a->noeval += !test; intmax_t yes = parse_assign(a); a->noeval -= !test; if (!eat(a, ':')) arith_error(a, "missing ':'"); a->noeval += test != 0; intmax_t no = parse_ternary(a); a->noeval -= test != 0; return test ? yes : no; } /** * @brief Parse an assignment (`=` or `op=`) or fall through to the ternary * level. * @return The value assigned or computed. */ static intmax_t parse_assign(arith *a) { skip_space(a); const char *name = a->p; size_t nlen = name_len(name); if (nlen) { const char *save = a->p; a->p += nlen; skip_space(a); if (a->p[0] == '=' && a->p[1] != '=') { a->p++; intmax_t v = parse_assign(a); assign(a, name, nlen, v); return v; } /* "op=": any binary operator but the comparisons and && ||. */ binop op; int prec; int len = scan_binop(a->p, &op, &prec); if (len && a->p[len] == '=' && prec != 6 && prec != 7 && op != OP_LAND && op != OP_LOR) { a->p += len + 1; intmax_t rhs = parse_assign(a); intmax_t v = apply(a, op, var_value(a, name, nlen), rhs); assign(a, name, nlen, v); return v; } a->p = save; } return parse_ternary(a); } /** * @brief Evaluate an arithmetic expression. * * @param expr The expression text, already expanded. * @return Its value. A syntax error or division by zero raises EXC_ERROR. */ intmax_t arith_eval(const char *expr) { arith a = {.p = expr, .expr = expr}; skip_space(&a); if (!*a.p) return 0; intmax_t v = parse_assign(&a); while (eat(&a, ',')) v = parse_assign(&a); skip_space(&a); if (*a.p) arith_error(&a, "syntax error"); return v; }