1 /* vi: set sw=4 ts=4: */
3 * Mini expr implementation for busybox
5 * based on GNU expr Mike Parker.
6 * Copyright (C) 86, 1991-1997, 1999 Free Software Foundation, Inc.
8 * Busybox modifications
9 * Copyright (c) 2000 Edward Betts <edward@debian.org>.
10 * Copyright (C) 2003-2005 Vladimir Oleynik <dzo@simtreas.ru>
11 * - reduced 464 bytes.
14 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
17 /* This program evaluates expressions. Each token (operator, operand,
18 * parenthesis) of the expression must be a separate argument. The
19 * parser used is a reasonably general one, though any incarnation of
20 * it is language-specific. It is especially nice for expressions.
22 * No parse tree is needed; a new node is evaluated immediately.
23 * One function can handle multiple operators all of equal precedence,
24 * provided they all associate ((x op x) op x). */
26 /* no getopt needed */
31 #if ENABLE_EXPR_MATH_SUPPORT_64
32 typedef int64_t arith_t;
35 #define PF_REZ_TYPE (long long)
36 #define STRTOL(s, e, b) strtoll(s, e, b)
41 #define PF_REZ_TYPE (long)
42 #define STRTOL(s, e, b) strtol(s, e, b)
45 /* TODO: use bb_strtol[l]? It's easier to check for errors... */
47 /* The kinds of value we can have. */
55 smallint type; /* Which kind. */
56 union { /* The value itself. */
61 typedef struct valinfo VALUE;
63 /* The arguments given to the program, minus the program name. */
67 #define G (*(struct globals*)&bb_common_bufsiz1)
69 /* forward declarations */
70 static VALUE *eval(void);
73 /* Return a VALUE for I. */
75 static VALUE *int_value(arith_t i)
79 v = xzalloc(sizeof(VALUE));
80 if (INTEGER) /* otherwise xzaaloc did it already */
86 /* Return a VALUE for S. */
88 static VALUE *str_value(const char *s)
92 v = xzalloc(sizeof(VALUE));
93 if (STRING) /* otherwise xzaaloc did it already */
99 /* Free VALUE V, including structure components. */
101 static void freev(VALUE *v)
103 if (v->type == STRING)
108 /* Return nonzero if V is a null-string or zero-number. */
110 static int null(VALUE *v)
112 if (v->type == INTEGER)
115 return v->u.s[0] == '\0' || LONE_CHAR(v->u.s, '0');
118 /* Coerce V to a STRING value (can't fail). */
120 static void tostring(VALUE *v)
122 if (v->type == INTEGER) {
123 v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
128 /* Coerce V to an INTEGER value. Return 1 on success, 0 on failure. */
130 static bool toarith(VALUE *v)
132 if (v->type == STRING) {
136 /* Don't interpret the empty string as an integer. */
137 /* Currently does not worry about overflow or int/long differences. */
138 i = STRTOL(v->u.s, &e, 10);
139 if ((v->u.s == e) || *e)
148 /* Return str[0]+str[1] if the next token matches STR exactly.
149 STR must not be NULL. */
151 static int nextarg(const char *str)
153 if (*G.args == NULL || strcmp(*G.args, str) != 0)
155 return (unsigned char)str[0] + (unsigned char)str[1];
158 /* The comparison operator handling functions. */
160 static int cmp_common(VALUE *l, VALUE *r, int op)
166 if (l->type == STRING || r->type == STRING) {
169 ll = strcmp(l->u.s, r->u.s);
172 /* calculating ll - rr and checking the result is prone to overflows.
173 * We'll do it differently: */
176 if (op == ('<' + '='))
178 if (op == '=' || (op == '=' + '='))
188 /* The arithmetic operator handling functions. */
190 static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
194 if (!toarith(l) || !toarith(r))
195 bb_error_msg_and_die("non-numeric argument");
205 bb_error_msg_and_die("division by zero");
211 /* Do the : operator.
212 SV is the VALUE for the lhs (the string),
213 PV is the VALUE for the rhs (the pattern). */
215 static VALUE *docolon(VALUE *sv, VALUE *pv)
220 regmatch_t re_regs[NMATCH];
225 if (pv->u.s[0] == '^') {
227 "warning: '%s': using '^' as the first character\n"
228 "of a basic regular expression is not portable; it is ignored", pv->u.s);
231 memset(&re_buffer, 0, sizeof(re_buffer));
232 memset(re_regs, 0, sizeof(re_regs));
233 xregcomp(&re_buffer, pv->u.s, 0);
235 /* expr uses an anchored pattern match, so check that there was a
236 * match and that the match starts at offset 0. */
237 if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
238 && re_regs[0].rm_so == 0
240 /* Were \(...\) used? */
241 if (re_buffer.re_nsub > 0 && re_regs[1].rm_so >= 0) {
242 sv->u.s[re_regs[1].rm_eo] = '\0';
243 v = str_value(sv->u.s + re_regs[1].rm_so);
245 v = int_value(re_regs[0].rm_eo);
248 /* Match failed -- return the right kind of null. */
249 if (re_buffer.re_nsub > 0)
258 /* Handle bare operands and ( expr ) syntax. */
260 static VALUE *eval7(void)
265 bb_error_msg_and_die("syntax error");
271 bb_error_msg_and_die("syntax error");
277 bb_error_msg_and_die("syntax error");
279 return str_value(*G.args++);
282 /* Handle match, substr, index, length, and quote keywords. */
284 static VALUE *eval6(void)
286 static const char keywords[] ALIGN1 =
287 "quote\0""length\0""match\0""index\0""substr\0";
290 VALUE *l = l; /* silence gcc */
291 VALUE *v = v; /* silence gcc */
292 int key = *G.args ? index_in_strings(keywords, *G.args) + 1 : 0;
294 if (key == 0) /* not a keyword */
296 G.args++; /* We have a valid token, so get the next argument. */
297 if (key == 1) { /* quote */
299 bb_error_msg_and_die("syntax error");
300 return str_value(*G.args++);
302 if (key == 2) { /* length */
305 v = int_value(strlen(r->u.s));
310 if (key == 3) { /* match */
316 if (key == 4) { /* index */
320 v = int_value(strcspn(l->u.s, r->u.s) + 1);
321 if (v->u.i == (arith_t) strlen(l->u.s) + 1)
326 if (key == 5) { /* substr */
330 if (!toarith(i1) || !toarith(i2)
331 || i1->u.i > (arith_t) strlen(l->u.s)
332 || i1->u.i <= 0 || i2->u.i <= 0)
335 v = xmalloc(sizeof(VALUE));
337 v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
347 /* Handle : operator (pattern matching).
348 Calls docolon to do the real work. */
350 static VALUE *eval5(void)
355 while (nextarg(":")) {
366 /* Handle *, /, % operators. */
368 static VALUE *eval4(void)
377 if (!op) { op = nextarg("/");
378 if (!op) { op = nextarg("%");
383 val = arithmetic_common(l, r, op);
390 /* Handle +, - operators. */
392 static VALUE *eval3(void)
407 val = arithmetic_common(l, r, op);
414 /* Handle comparisons. */
416 static VALUE *eval2(void)
425 if (!op) { op = nextarg("<=");
426 if (!op) { op = nextarg("=");
427 if (!op) { op = nextarg("==");
428 if (!op) { op = nextarg("!=");
429 if (!op) { op = nextarg(">=");
430 if (!op) { op = nextarg(">");
437 val = cmp_common(l, r, op);
446 static VALUE *eval1(void)
451 while (nextarg("&")) {
454 if (null(l) || null(r)) {
466 static VALUE *eval(void)
471 while (nextarg("|")) {
483 int expr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
484 int expr_main(int argc UNUSED_PARAM, char **argv)
488 xfunc_error_retval = 2; /* coreutils compat */
490 if (*G.args == NULL) {
491 bb_error_msg_and_die("too few arguments");
495 bb_error_msg_and_die("syntax error");
496 if (v->type == INTEGER)
497 printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
500 fflush_stdout_and_exit(null(v));