summaryrefslogtreecommitdiffhomepage
path: root/src/arith.c
blob: 2a00d62de32c966be4c424a0cc92db66f829bd3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/**
 * @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 <ctype.h> calls and string comparisons: operators are
 * recognised by switching on their first character.
 */
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#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.
 */
static _Noreturn 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_handler = &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 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)) {
        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) {
    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;
}