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)
104 /* forward declarations */
105 static VALUE *eval(void);
108 /* Return a VALUE for I. */
110 static VALUE *int_value(arith_t i)
114 v = xzalloc(sizeof(VALUE));
115 if (INTEGER) /* otherwise xzaaloc did it already */
121 /* Return a VALUE for S. */
123 static VALUE *str_value(const char *s)
127 v = xzalloc(sizeof(VALUE));
128 if (STRING) /* otherwise xzaaloc did it already */
134 /* Free VALUE V, including structure components. */
136 static void freev(VALUE *v)
138 if (v->type == STRING)
143 /* Return nonzero if V is a null-string or zero-number. */
145 static int null(VALUE *v)
147 if (v->type == INTEGER)
150 return v->u.s[0] == '\0' || LONE_CHAR(v->u.s, '0');
153 /* Coerce V to a STRING value (can't fail). */
155 static void tostring(VALUE *v)
157 if (v->type == INTEGER) {
158 v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
163 /* Coerce V to an INTEGER value. Return 1 on success, 0 on failure. */
165 static bool toarith(VALUE *v)
167 if (v->type == STRING) {
171 /* Don't interpret the empty string as an integer. */
172 /* Currently does not worry about overflow or int/long differences. */
173 i = STRTOL(v->u.s, &e, 10);
174 if ((v->u.s == e) || *e)
183 /* Return str[0]+str[1] if the next token matches STR exactly.
184 STR must not be NULL. */
186 static int nextarg(const char *str)
188 if (*G.args == NULL || strcmp(*G.args, str) != 0)
190 return (unsigned char)str[0] + (unsigned char)str[1];
193 /* The comparison operator handling functions. */
195 static int cmp_common(VALUE *l, VALUE *r, int op)
201 if (l->type == STRING || r->type == STRING) {
204 ll = strcmp(l->u.s, r->u.s);
207 /* calculating ll - rr and checking the result is prone to overflows.
208 * We'll do it differently: */
211 if (op == ('<' + '='))
213 if (op == '=' || (op == '=' + '='))
223 /* The arithmetic operator handling functions. */
225 static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
229 if (!toarith(l) || !toarith(r))
230 bb_error_msg_and_die("non-numeric argument");
240 bb_error_msg_and_die("division by zero");
246 /* Do the : operator.
247 SV is the VALUE for the lhs (the string),
248 PV is the VALUE for the rhs (the pattern). */
250 static VALUE *docolon(VALUE *sv, VALUE *pv)
255 regmatch_t re_regs[NMATCH];
260 if (pv->u.s[0] == '^') {
262 "warning: '%s': using '^' as the first character\n"
263 "of a basic regular expression is not portable; it is ignored", pv->u.s);
266 memset(&re_buffer, 0, sizeof(re_buffer));
267 memset(re_regs, 0, sizeof(re_regs));
268 xregcomp(&re_buffer, pv->u.s, 0);
270 /* expr uses an anchored pattern match, so check that there was a
271 * match and that the match starts at offset 0. */
272 if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
273 && re_regs[0].rm_so == 0
275 /* Were \(...\) used? */
276 if (re_buffer.re_nsub > 0 && re_regs[1].rm_so >= 0) {
277 sv->u.s[re_regs[1].rm_eo] = '\0';
278 v = str_value(sv->u.s + re_regs[1].rm_so);
280 v = int_value(re_regs[0].rm_eo);
283 /* Match failed -- return the right kind of null. */
284 if (re_buffer.re_nsub > 0)
293 /* Handle bare operands and ( expr ) syntax. */
295 static VALUE *eval7(void)
300 bb_error_msg_and_die("syntax error");
306 bb_error_msg_and_die("syntax error");
312 bb_error_msg_and_die("syntax error");
314 return str_value(*G.args++);
317 /* Handle match, substr, index, length, and quote keywords. */
319 static VALUE *eval6(void)
321 static const char keywords[] ALIGN1 =
322 "quote\0""length\0""match\0""index\0""substr\0";
325 VALUE *l = l; /* silence gcc */
326 VALUE *v = v; /* silence gcc */
327 int key = *G.args ? index_in_strings(keywords, *G.args) + 1 : 0;
329 if (key == 0) /* not a keyword */
331 G.args++; /* We have a valid token, so get the next argument. */
332 if (key == 1) { /* quote */
334 bb_error_msg_and_die("syntax error");
335 return str_value(*G.args++);
337 if (key == 2) { /* length */
340 v = int_value(strlen(r->u.s));
345 if (key == 3) { /* match */
351 if (key == 4) { /* index */
355 v = int_value(strcspn(l->u.s, r->u.s) + 1);
356 if (v->u.i == (arith_t) strlen(l->u.s) + 1)
361 if (key == 5) { /* substr */
365 if (!toarith(i1) || !toarith(i2)
366 || i1->u.i > (arith_t) strlen(l->u.s)
367 || i1->u.i <= 0 || i2->u.i <= 0)
370 v = xmalloc(sizeof(VALUE));
372 v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
381 /* Handle : operator (pattern matching).
382 Calls docolon to do the real work. */
384 static VALUE *eval5(void)
389 while (nextarg(":")) {
400 /* Handle *, /, % operators. */
402 static VALUE *eval4(void)
411 if (!op) { op = nextarg("/");
412 if (!op) { op = nextarg("%");
417 val = arithmetic_common(l, r, op);
424 /* Handle +, - operators. */
426 static VALUE *eval3(void)
441 val = arithmetic_common(l, r, op);
448 /* Handle comparisons. */
450 static VALUE *eval2(void)
459 if (!op) { op = nextarg("<=");
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(">");
471 val = cmp_common(l, r, op);
480 static VALUE *eval1(void)
485 while (nextarg("&")) {
488 if (null(l) || null(r)) {
500 static VALUE *eval(void)
505 while (nextarg("|")) {
517 int expr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
518 int expr_main(int argc UNUSED_PARAM, char **argv)
522 xfunc_error_retval = 2; /* coreutils compat */
524 if (*G.args == NULL) {
525 bb_error_msg_and_die("too few arguments");
529 bb_error_msg_and_die("syntax error");
530 if (v->type == INTEGER)
531 printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
534 fflush_stdout_and_exit(null(v));