remove bb_printf and the like
[platform/upstream/busybox.git] / coreutils / expr.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini expr implementation for busybox
4  *
5  * based on GNU expr Mike Parker.
6  * Copyright (C) 86, 1991-1997, 1999 Free Software Foundation, Inc.
7  *
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.
12  *  - 64 math support
13  *
14  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
15  */
16
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.
21  *
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). */
25
26 /* no getopt needed */
27
28 #include "busybox.h"
29 #include "xregex.h"
30
31 /* The kinds of value we can have.  */
32 enum valtype {
33         integer,
34         string
35 };
36 typedef enum valtype TYPE;
37
38 #if ENABLE_EXPR_MATH_SUPPORT_64
39 typedef int64_t arith_t;
40
41 #define PF_REZ      "ll"
42 #define PF_REZ_TYPE (long long)
43 #define STRTOL(s, e, b) strtoll(s, e, b)
44 #else
45 typedef long arith_t;
46
47 #define PF_REZ      "l"
48 #define PF_REZ_TYPE (long)
49 #define STRTOL(s, e, b) strtol(s, e, b)
50 #endif
51
52 /* A value is.... */
53 struct valinfo {
54         TYPE type;                      /* Which kind. */
55         union {                         /* The value itself. */
56                 arith_t i;
57                 char *s;
58         } u;
59 };
60 typedef struct valinfo VALUE;
61
62 /* The arguments given to the program, minus the program name.  */
63 static char **args;
64
65 static VALUE *docolon(VALUE * sv, VALUE * pv);
66 static VALUE *eval(void);
67 static VALUE *int_value(arith_t i);
68 static VALUE *str_value(char *s);
69 static int nextarg(char *str);
70 static int null(VALUE * v);
71 static int toarith(VALUE * v);
72 static void freev(VALUE * v);
73 static void tostring(VALUE * v);
74
75 int expr_main(int argc, char **argv)
76 {
77         VALUE *v;
78
79         if (argc == 1) {
80                 bb_error_msg_and_die("too few arguments");
81         }
82
83         args = argv + 1;
84
85         v = eval();
86         if (*args)
87                 bb_error_msg_and_die("syntax error");
88
89         if (v->type == integer)
90                 printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
91         else
92                 puts(v->u.s);
93
94         fflush_stdout_and_exit(null(v));
95 }
96
97 /* Return a VALUE for I.  */
98
99 static VALUE *int_value(arith_t i)
100 {
101         VALUE *v;
102
103         v = xmalloc(sizeof(VALUE));
104         v->type = integer;
105         v->u.i = i;
106         return v;
107 }
108
109 /* Return a VALUE for S.  */
110
111 static VALUE *str_value(char *s)
112 {
113         VALUE *v;
114
115         v = xmalloc(sizeof(VALUE));
116         v->type = string;
117         v->u.s = xstrdup(s);
118         return v;
119 }
120
121 /* Free VALUE V, including structure components.  */
122
123 static void freev(VALUE * v)
124 {
125         if (v->type == string)
126                 free(v->u.s);
127         free(v);
128 }
129
130 /* Return nonzero if V is a null-string or zero-number.  */
131
132 static int null(VALUE * v)
133 {
134         if (v->type == integer)
135                 return v->u.i == 0;
136         else                            /* string: */
137                 return v->u.s[0] == '\0' || strcmp(v->u.s, "0") == 0;
138 }
139
140 /* Coerce V to a string value (can't fail).  */
141
142 static void tostring(VALUE * v)
143 {
144         if (v->type == integer) {
145                 v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
146                 v->type = string;
147         }
148 }
149
150 /* Coerce V to an integer value.  Return 1 on success, 0 on failure.  */
151
152 static int toarith(VALUE * v)
153 {
154         if (v->type == string) {
155                 arith_t i;
156                 char *e;
157
158                 /* Don't interpret the empty string as an integer.  */
159                 /* Currently does not worry about overflow or int/long differences. */
160                 i = STRTOL(v->u.s, &e, 10);
161                 if ((v->u.s == e) || *e)
162                         return 0;
163                 free(v->u.s);
164                 v->u.i = i;
165                 v->type = integer;
166         }
167         return 1;
168 }
169
170 /* Return nonzero if the next token matches STR exactly.
171    STR must not be NULL.  */
172
173 static int nextarg(char *str)
174 {
175         if (*args == NULL)
176                 return 0;
177         return strcmp(*args, str) == 0;
178 }
179
180 /* The comparison operator handling functions.  */
181
182 static int cmp_common(VALUE * l, VALUE * r, int op)
183 {
184         int cmpval;
185
186         if (l->type == string || r->type == string) {
187                 tostring(l);
188                 tostring(r);
189                 cmpval = strcmp(l->u.s, r->u.s);
190         } else
191                 cmpval = l->u.i - r->u.i;
192         if (op == '<')
193                 return cmpval < 0;
194         else if (op == ('L' + 'E'))
195                 return cmpval <= 0;
196         else if (op == '=')
197                 return cmpval == 0;
198         else if (op == '!')
199                 return cmpval != 0;
200         else if (op == '>')
201                 return cmpval > 0;
202         else                            /* >= */
203                 return cmpval >= 0;
204 }
205
206 /* The arithmetic operator handling functions.  */
207
208 static arith_t arithmetic_common(VALUE * l, VALUE * r, int op)
209 {
210         arith_t li, ri;
211
212         if (!toarith(l) || !toarith(r))
213                 bb_error_msg_and_die("non-numeric argument");
214         li = l->u.i;
215         ri = r->u.i;
216         if ((op == '/' || op == '%') && ri == 0)
217                 bb_error_msg_and_die("division by zero");
218         if (op == '+')
219                 return li + ri;
220         else if (op == '-')
221                 return li - ri;
222         else if (op == '*')
223                 return li * ri;
224         else if (op == '/')
225                 return li / ri;
226         else
227                 return li % ri;
228 }
229
230 /* Do the : operator.
231    SV is the VALUE for the lhs (the string),
232    PV is the VALUE for the rhs (the pattern).  */
233
234 static VALUE *docolon(VALUE * sv, VALUE * pv)
235 {
236         VALUE *v;
237         regex_t re_buffer;
238         const int NMATCH = 2;
239         regmatch_t re_regs[NMATCH];
240
241         tostring(sv);
242         tostring(pv);
243
244         if (pv->u.s[0] == '^') {
245                 fprintf(stderr, "\
246 warning: unportable BRE: `%s': using `^' as the first character\n\
247 of a basic regular expression is not portable; it is being ignored", pv->u.s);
248         }
249
250         memset(&re_buffer, 0, sizeof(re_buffer));
251         memset(re_regs, 0, sizeof(*re_regs));
252         if (regcomp(&re_buffer, pv->u.s, 0) != 0)
253                 bb_error_msg_and_die("invalid regular expression");
254
255         /* expr uses an anchored pattern match, so check that there was a
256          * match and that the match starts at offset 0. */
257         if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH &&
258                 re_regs[0].rm_so == 0) {
259                 /* Were \(...\) used? */
260                 if (re_buffer.re_nsub > 0) {
261                         sv->u.s[re_regs[1].rm_eo] = '\0';
262                         v = str_value(sv->u.s + re_regs[1].rm_so);
263                 } else
264                         v = int_value(re_regs[0].rm_eo);
265         } else {
266                 /* Match failed -- return the right kind of null.  */
267                 if (re_buffer.re_nsub > 0)
268                         v = str_value("");
269                 else
270                         v = int_value(0);
271         }
272         return v;
273 }
274
275 /* Handle bare operands and ( expr ) syntax.  */
276
277 static VALUE *eval7(void)
278 {
279         VALUE *v;
280
281         if (!*args)
282                 bb_error_msg_and_die("syntax error");
283
284         if (nextarg("(")) {
285                 args++;
286                 v = eval();
287                 if (!nextarg(")"))
288                         bb_error_msg_and_die("syntax error");
289                 args++;
290                 return v;
291         }
292
293         if (nextarg(")"))
294                 bb_error_msg_and_die("syntax error");
295
296         return str_value(*args++);
297 }
298
299 /* Handle match, substr, index, length, and quote keywords.  */
300
301 static VALUE *eval6(void)
302 {
303         VALUE *l, *r, *v, *i1, *i2;
304
305         if (nextarg("quote")) {
306                 args++;
307                 if (!*args)
308                         bb_error_msg_and_die("syntax error");
309                 return str_value(*args++);
310         } else if (nextarg("length")) {
311                 args++;
312                 r = eval6();
313                 tostring(r);
314                 v = int_value(strlen(r->u.s));
315                 freev(r);
316                 return v;
317         } else if (nextarg("match")) {
318                 args++;
319                 l = eval6();
320                 r = eval6();
321                 v = docolon(l, r);
322                 freev(l);
323                 freev(r);
324                 return v;
325         } else if (nextarg("index")) {
326                 args++;
327                 l = eval6();
328                 r = eval6();
329                 tostring(l);
330                 tostring(r);
331                 v = int_value(strcspn(l->u.s, r->u.s) + 1);
332                 if (v->u.i == (arith_t) strlen(l->u.s) + 1)
333                         v->u.i = 0;
334                 freev(l);
335                 freev(r);
336                 return v;
337         } else if (nextarg("substr")) {
338                 args++;
339                 l = eval6();
340                 i1 = eval6();
341                 i2 = eval6();
342                 tostring(l);
343                 if (!toarith(i1) || !toarith(i2)
344                         || i1->u.i > (arith_t) strlen(l->u.s)
345                         || i1->u.i <= 0 || i2->u.i <= 0)
346                         v = str_value("");
347                 else {
348                         v = xmalloc(sizeof(VALUE));
349                         v->type = string;
350                         v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
351                 }
352                 freev(l);
353                 freev(i1);
354                 freev(i2);
355                 return v;
356         } else
357                 return eval7();
358 }
359
360 /* Handle : operator (pattern matching).
361    Calls docolon to do the real work.  */
362
363 static VALUE *eval5(void)
364 {
365         VALUE *l, *r, *v;
366
367         l = eval6();
368         while (nextarg(":")) {
369                 args++;
370                 r = eval6();
371                 v = docolon(l, r);
372                 freev(l);
373                 freev(r);
374                 l = v;
375         }
376         return l;
377 }
378
379 /* Handle *, /, % operators.  */
380
381 static VALUE *eval4(void)
382 {
383         VALUE *l, *r;
384         int op;
385         arith_t val;
386
387         l = eval5();
388         while (1) {
389                 if (nextarg("*"))
390                         op = '*';
391                 else if (nextarg("/"))
392                         op = '/';
393                 else if (nextarg("%"))
394                         op = '%';
395                 else
396                         return l;
397                 args++;
398                 r = eval5();
399                 val = arithmetic_common(l, r, op);
400                 freev(l);
401                 freev(r);
402                 l = int_value(val);
403         }
404 }
405
406 /* Handle +, - operators.  */
407
408 static VALUE *eval3(void)
409 {
410         VALUE *l, *r;
411         int op;
412         arith_t val;
413
414         l = eval4();
415         while (1) {
416                 if (nextarg("+"))
417                         op = '+';
418                 else if (nextarg("-"))
419                         op = '-';
420                 else
421                         return l;
422                 args++;
423                 r = eval4();
424                 val = arithmetic_common(l, r, op);
425                 freev(l);
426                 freev(r);
427                 l = int_value(val);
428         }
429 }
430
431 /* Handle comparisons.  */
432
433 static VALUE *eval2(void)
434 {
435         VALUE *l, *r;
436         int op;
437         arith_t val;
438
439         l = eval3();
440         while (1) {
441                 if (nextarg("<"))
442                         op = '<';
443                 else if (nextarg("<="))
444                         op = 'L' + 'E';
445                 else if (nextarg("=") || nextarg("=="))
446                         op = '=';
447                 else if (nextarg("!="))
448                         op = '!';
449                 else if (nextarg(">="))
450                         op = 'G' + 'E';
451                 else if (nextarg(">"))
452                         op = '>';
453                 else
454                         return l;
455                 args++;
456                 r = eval3();
457                 toarith(l);
458                 toarith(r);
459                 val = cmp_common(l, r, op);
460                 freev(l);
461                 freev(r);
462                 l = int_value(val);
463         }
464 }
465
466 /* Handle &.  */
467
468 static VALUE *eval1(void)
469 {
470         VALUE *l, *r;
471
472         l = eval2();
473         while (nextarg("&")) {
474                 args++;
475                 r = eval2();
476                 if (null(l) || null(r)) {
477                         freev(l);
478                         freev(r);
479                         l = int_value(0);
480                 } else
481                         freev(r);
482         }
483         return l;
484 }
485
486 /* Handle |.  */
487
488 static VALUE *eval(void)
489 {
490         VALUE *l, *r;
491
492         l = eval1();
493         while (nextarg("|")) {
494                 args++;
495                 r = eval1();
496                 if (null(l)) {
497                         freev(l);
498                         l = r;
499                 } else
500                         freev(r);
501         }
502         return l;
503 }