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 source tree.
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 */
28 //usage:#define expr_trivial_usage
30 //usage:#define expr_full_usage "\n\n"
31 //usage: "Print the value of EXPRESSION to stdout\n"
33 //usage: "EXPRESSION may be:\n"
34 //usage: " ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n"
35 //usage: " ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0\n"
36 //usage: " ARG1 < ARG2 1 if ARG1 is less than ARG2, else 0. Similarly:\n"
37 //usage: " ARG1 <= ARG2\n"
38 //usage: " ARG1 = ARG2\n"
39 //usage: " ARG1 != ARG2\n"
40 //usage: " ARG1 >= ARG2\n"
41 //usage: " ARG1 > ARG2\n"
42 //usage: " ARG1 + ARG2 Sum of ARG1 and ARG2. Similarly:\n"
43 //usage: " ARG1 - ARG2\n"
44 //usage: " ARG1 * ARG2\n"
45 //usage: " ARG1 / ARG2\n"
46 //usage: " ARG1 % ARG2\n"
47 //usage: " STRING : REGEXP Anchored pattern match of REGEXP in STRING\n"
48 //usage: " match STRING REGEXP Same as STRING : REGEXP\n"
49 //usage: " substr STRING POS LENGTH Substring of STRING, POS counted from 1\n"
50 //usage: " index STRING CHARS Index in STRING where any CHARS is found, or 0\n"
51 //usage: " length STRING Length of STRING\n"
52 //usage: " quote TOKEN Interpret TOKEN as a string, even if\n"
53 //usage: " it is a keyword like 'match' or an\n"
54 //usage: " operator like '/'\n"
55 //usage: " (EXPRESSION) Value of EXPRESSION\n"
57 //usage: "Beware that many operators need to be escaped or quoted for shells.\n"
58 //usage: "Comparisons are arithmetic if both ARGs are numbers, else\n"
59 //usage: "lexicographical. Pattern matches return the string matched between\n"
60 //usage: "\\( and \\) or null; if \\( and \\) are not used, they return the number\n"
61 //usage: "of characters matched or 0."
66 #if ENABLE_EXPR_MATH_SUPPORT_64
67 typedef int64_t arith_t;
70 #define PF_REZ_TYPE (long long)
71 #define STRTOL(s, e, b) strtoll(s, e, b)
76 #define PF_REZ_TYPE (long)
77 #define STRTOL(s, e, b) strtol(s, e, b)
80 /* TODO: use bb_strtol[l]? It's easier to check for errors... */
82 /* The kinds of value we can have. */
90 smallint type; /* Which kind. */
91 union { /* The value itself. */
96 typedef struct valinfo VALUE;
98 /* The arguments given to the program, minus the program name. */
102 #define G (*(struct globals*)&bb_common_bufsiz1)
103 #define INIT_G() do { } while (0)
105 /* forward declarations */
106 static VALUE *eval(void);
109 /* Return a VALUE for I. */
111 static VALUE *int_value(arith_t i)
115 v = xzalloc(sizeof(VALUE));
116 if (INTEGER) /* otherwise xzaaloc did it already */
122 /* Return a VALUE for S. */
124 static VALUE *str_value(const char *s)
128 v = xzalloc(sizeof(VALUE));
129 if (STRING) /* otherwise xzaaloc did it already */
135 /* Free VALUE V, including structure components. */
137 static void freev(VALUE *v)
139 if (v->type == STRING)
144 /* Return nonzero if V is a null-string or zero-number. */
146 static int null(VALUE *v)
148 if (v->type == INTEGER)
151 return v->u.s[0] == '\0' || LONE_CHAR(v->u.s, '0');
154 /* Coerce V to a STRING value (can't fail). */
156 static void tostring(VALUE *v)
158 if (v->type == INTEGER) {
159 v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
164 /* Coerce V to an INTEGER value. Return 1 on success, 0 on failure. */
166 static bool toarith(VALUE *v)
168 if (v->type == STRING) {
172 /* Don't interpret the empty string as an integer. */
173 /* Currently does not worry about overflow or int/long differences. */
174 i = STRTOL(v->u.s, &e, 10);
175 if ((v->u.s == e) || *e)
184 /* Return str[0]+str[1] if the next token matches STR exactly.
185 STR must not be NULL. */
187 static int nextarg(const char *str)
189 if (*G.args == NULL || strcmp(*G.args, str) != 0)
191 return (unsigned char)str[0] + (unsigned char)str[1];
194 /* The comparison operator handling functions. */
196 static int cmp_common(VALUE *l, VALUE *r, int op)
202 if (l->type == STRING || r->type == STRING) {
205 ll = strcmp(l->u.s, r->u.s);
208 /* calculating ll - rr and checking the result is prone to overflows.
209 * We'll do it differently: */
212 if (op == ('<' + '='))
214 if (op == '=' || (op == '=' + '='))
224 /* The arithmetic operator handling functions. */
226 static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
230 if (!toarith(l) || !toarith(r))
231 bb_error_msg_and_die("non-numeric argument");
241 bb_error_msg_and_die("division by zero");
247 /* Do the : operator.
248 SV is the VALUE for the lhs (the string),
249 PV is the VALUE for the rhs (the pattern). */
251 static VALUE *docolon(VALUE *sv, VALUE *pv)
256 regmatch_t re_regs[NMATCH];
261 if (pv->u.s[0] == '^') {
263 "warning: '%s': using '^' as the first character\n"
264 "of a basic regular expression is not portable; it is ignored", pv->u.s);
267 memset(&re_buffer, 0, sizeof(re_buffer));
268 memset(re_regs, 0, sizeof(re_regs));
269 xregcomp(&re_buffer, pv->u.s, 0);
271 /* expr uses an anchored pattern match, so check that there was a
272 * match and that the match starts at offset 0. */
273 if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
274 && re_regs[0].rm_so == 0
276 /* Were \(...\) used? */
277 if (re_buffer.re_nsub > 0 && re_regs[1].rm_so >= 0) {
278 sv->u.s[re_regs[1].rm_eo] = '\0';
279 v = str_value(sv->u.s + re_regs[1].rm_so);
281 v = int_value(re_regs[0].rm_eo);
284 /* Match failed -- return the right kind of null. */
285 if (re_buffer.re_nsub > 0)
294 /* Handle bare operands and ( expr ) syntax. */
296 static VALUE *eval7(void)
301 bb_error_msg_and_die("syntax error");
307 bb_error_msg_and_die("syntax error");
313 bb_error_msg_and_die("syntax error");
315 return str_value(*G.args++);
318 /* Handle match, substr, index, length, and quote keywords. */
320 static VALUE *eval6(void)
322 static const char keywords[] ALIGN1 =
323 "quote\0""length\0""match\0""index\0""substr\0";
326 VALUE *l = l; /* silence gcc */
327 VALUE *v = v; /* silence gcc */
328 int key = *G.args ? index_in_strings(keywords, *G.args) + 1 : 0;
330 if (key == 0) /* not a keyword */
332 G.args++; /* We have a valid token, so get the next argument. */
333 if (key == 1) { /* quote */
335 bb_error_msg_and_die("syntax error");
336 return str_value(*G.args++);
338 if (key == 2) { /* length */
341 v = int_value(strlen(r->u.s));
346 if (key == 3) { /* match */
352 if (key == 4) { /* index */
356 v = int_value(strcspn(l->u.s, r->u.s) + 1);
357 if (v->u.i == (arith_t) strlen(l->u.s) + 1)
362 if (key == 5) { /* substr */
366 if (!toarith(i1) || !toarith(i2)
367 || i1->u.i > (arith_t) strlen(l->u.s)
368 || i1->u.i <= 0 || i2->u.i <= 0)
371 v = xmalloc(sizeof(VALUE));
373 v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
382 /* Handle : operator (pattern matching).
383 Calls docolon to do the real work. */
385 static VALUE *eval5(void)
390 while (nextarg(":")) {
401 /* Handle *, /, % operators. */
403 static VALUE *eval4(void)
412 if (!op) { op = nextarg("/");
413 if (!op) { op = nextarg("%");
418 val = arithmetic_common(l, r, op);
425 /* Handle +, - operators. */
427 static VALUE *eval3(void)
442 val = arithmetic_common(l, r, op);
449 /* Handle comparisons. */
451 static VALUE *eval2(void)
460 if (!op) { op = nextarg("<=");
461 if (!op) { op = nextarg("=");
462 if (!op) { op = nextarg("==");
463 if (!op) { op = nextarg("!=");
464 if (!op) { op = nextarg(">=");
465 if (!op) { op = nextarg(">");
472 val = cmp_common(l, r, op);
481 static VALUE *eval1(void)
486 while (nextarg("&")) {
489 if (null(l) || null(r)) {
501 static VALUE *eval(void)
506 while (nextarg("|")) {
518 int expr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
519 int expr_main(int argc UNUSED_PARAM, char **argv)
525 xfunc_error_retval = 2; /* coreutils compat */
527 if (*G.args == NULL) {
528 bb_error_msg_and_die("too few arguments");
532 bb_error_msg_and_die("syntax error");
533 if (v->type == INTEGER)
534 printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
537 fflush_stdout_and_exit(null(v));