1 /* expr -- evaluate expressions.
2 Copyright (C) 86, 1991-1997, 1999 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Author: Mike Parker.
20 This program evaluates expressions. Each token (operator, operand,
21 parenthesis) of the expression must be a seperate argument. The
22 parser used is a reasonably general one, though any incarnation of
23 it is language-specific. It is especially nice for expressions.
25 No parse tree is needed; a new node is evaluated immediately.
26 One function can handle multiple operators all of equal precedence,
27 provided they all associate ((x op x) op x).
29 Define EVAL_TRACE to print an evaluation trace. */
33 #include <sys/types.h>
37 #include "long-options.h"
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "expr"
44 #define AUTHORS "Mike Parker"
47 #define NEW(Type) XMALLOC (Type, 1)
48 #define OLD(x) free ((char *) x)
50 /* The kinds of value we can have. */
56 typedef enum valtype TYPE;
61 TYPE type; /* Which kind. */
63 { /* The value itself. */
68 typedef struct valinfo VALUE;
70 /* Non-zero if the POSIXLY_CORRECT environment variable is set.
71 The unary operator `quote' is disabled when this variable is zero. */
72 static int posixly_correct;
74 /* The arguments given to the program, minus the program name. */
77 /* The name this program was run with. */
80 static VALUE *docolon PARAMS ((VALUE *sv, VALUE *pv));
81 static VALUE *eval PARAMS ((void));
82 static VALUE *int_value PARAMS ((int i));
83 static VALUE *str_value PARAMS ((char *s));
84 static int isstring PARAMS ((VALUE *v));
85 static int nextarg PARAMS ((char *str));
86 static int nomoreargs PARAMS ((void));
87 static int null PARAMS ((VALUE *v));
88 static int toarith PARAMS ((VALUE *v));
89 static void freev PARAMS ((VALUE *v));
90 static void printv PARAMS ((VALUE *v));
91 static void tostring PARAMS ((VALUE *v));
101 fprintf (stderr, _("Try `%s --help' for more information.\n"),
106 Usage: %s EXPRESSION\n\
109 program_name, program_name);
112 --help display this help and exit\n\
113 --version output version information and exit\n\
117 Print the value of EXPRESSION to standard output. A blank line below\n\
118 separates increasing precedence groups. EXPRESSION may be:\n\
120 ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n\
122 ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0\n\
124 ARG1 < ARG2 ARG1 is less than ARG2\n\
125 ARG1 <= ARG2 ARG1 is less than or equal to ARG2\n\
126 ARG1 = ARG2 ARG1 is equal to ARG2\n\
127 ARG1 != ARG2 ARG1 is unequal to ARG2\n\
128 ARG1 >= ARG2 ARG1 is greater than or equal to ARG2\n\
129 ARG1 > ARG2 ARG1 is greater than ARG2\n\
131 ARG1 + ARG2 arithmetic sum of ARG1 and ARG2\n\
132 ARG1 - ARG2 arithmetic difference of ARG1 and ARG2\n\
134 ARG1 * ARG2 arithmetic product of ARG1 and ARG2\n\
135 ARG1 / ARG2 arithmetic quotient of ARG1 divided by ARG2\n\
136 ARG1 %% ARG2 arithmetic remainder of ARG1 divided by ARG2\n\
138 STRING : REGEXP anchored pattern match of REGEXP in STRING\n\
140 match STRING REGEXP same as STRING : REGEXP\n\
141 substr STRING POS LENGTH substring of STRING, POS counted from 1\n\
142 index STRING CHARS index in STRING where any CHARS is found, or 0\n\
143 length STRING length of STRING\n\
144 quote TOKEN interpret TOKEN as a string, even if it is a\n\
145 keyword like `match' or an operator like `/'\n\
147 ( EXPRESSION ) value of EXPRESSION\n\
151 Beware that many operators need to be escaped or quoted for shells.\n\
152 Comparisons are arithmetic if both ARGs are numbers, else lexicographical.\n\
153 Pattern matches return the string matched between \\( and \\) or null; if\n\
154 \\( and \\) are not used, they return the number of characters matched or 0.\n\
156 puts (_("\nReport bugs to <bug-sh-utils@gnu.org>."));
162 main (int argc, char **argv)
166 program_name = argv[0];
167 setlocale (LC_ALL, "");
168 bindtextdomain (PACKAGE, LOCALEDIR);
169 textdomain (PACKAGE);
171 posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
173 /* Recognize --help or --version only if POSIXLY_CORRECT is not set. */
174 if (!posixly_correct)
175 parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
180 error (0, 0, _("too few arguments"));
188 error (2, 0, _("syntax error"));
194 /* Return a VALUE for I. */
207 /* Return a VALUE for S. */
216 v->u.s = xstrdup (s);
220 /* Free VALUE V, including structure components. */
225 if (v->type == string)
238 printf ("%d\n", v->u.i);
241 printf ("%s\n", v->u.s);
248 /* Return nonzero if V is a null-string or zero-number. */
258 return v->u.s[0] == '\0' || strcmp (v->u.s, "0") == 0;
264 /* Return nonzero if V is a string value. */
269 return v->type == string;
272 /* Coerce V to a string value (can't fail). */
282 temp = xmalloc (4 * (sizeof (int) / sizeof (char)));
283 sprintf (temp, "%d", v->u.i);
294 /* Coerce V to an integer value. Return 1 on success, 0 on failure. */
310 /* Don't interpret the empty string as an integer. */
319 i = i * 10 + *cp - '0';
324 v->u.i = i * (neg ? -1 : 1);
332 /* Return nonzero if the next token matches STR exactly.
333 STR must not be NULL. */
340 return strcmp (*args, str) == 0;
343 /* Return nonzero if there no more tokens. */
351 /* The comparison operator handling functions. */
353 #define cmpf(name, rel) \
355 int name (l, r) VALUE *l; VALUE *r; \
357 if (isstring (l) || isstring (r)) \
361 return strcmp (l->u.s, r->u.s) rel 0; \
364 return l->u.i rel r->u.i; \
367 cmpf (less_equal, <=)
370 cmpf (greater_equal, >=)
371 cmpf (greater_than, >)
375 /* The arithmetic operator handling functions. */
377 #define arithf(name, op) \
379 int name (l, r) VALUE *l; VALUE *r; \
381 if (!toarith (l) || !toarith (r)) \
382 error (2, 0, _("non-numeric argument")); \
383 return l->u.i op r->u.i; \
386 #define arithdivf(name, op) \
387 int name (l, r) VALUE *l; VALUE *r; \
389 if (!toarith (l) || !toarith (r)) \
390 error (2, 0, _("non-numeric argument")); \
392 error (2, 0, _("division by zero")); \
393 return l->u.i op r->u.i; \
399 arithdivf (divide, /)
406 /* Print evaluation trace and args remaining. */
415 for (a = args; *a; a++)
421 /* Do the : operator.
422 SV is the VALUE for the lhs (the string),
423 PV is the VALUE for the rhs (the pattern). */
426 docolon (VALUE *sv, VALUE *pv)
430 struct re_pattern_buffer re_buffer;
431 struct re_registers re_regs;
437 if (pv->u.s[0] == '^')
440 warning: unportable BRE: `%s': using `^' as the first character\n\
441 of the basic regular expression is not portable; it is being ignored"),
445 len = strlen (pv->u.s);
446 memset (&re_buffer, 0, sizeof (re_buffer));
447 memset (&re_regs, 0, sizeof (re_regs));
448 re_buffer.allocated = 2 * len;
449 re_buffer.buffer = (unsigned char *) xmalloc (re_buffer.allocated);
450 re_buffer.translate = 0;
451 re_syntax_options = RE_SYNTAX_POSIX_BASIC;
452 errmsg = re_compile_pattern (pv->u.s, len, &re_buffer);
454 error (2, 0, "%s", errmsg);
456 len = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs);
459 /* Were \(...\) used? */
460 if (re_buffer.re_nsub > 0)/* was (re_regs.start[1] >= 0) */
462 sv->u.s[re_regs.end[1]] = '\0';
463 v = str_value (sv->u.s + re_regs.start[1]);
470 /* Match failed -- return the right kind of null. */
471 if (re_buffer.re_nsub > 0)
476 free (re_buffer.buffer);
480 /* Handle bare operands and ( expr ) syntax. */
491 error (2, 0, _("syntax error"));
498 error (2, 0, _("syntax error"));
504 error (2, 0, _("syntax error"));
506 return str_value (*args++);
509 /* Handle match, substr, index, length, and quote keywords. */
523 if (!posixly_correct && nextarg ("quote"))
527 error (2, 0, _("syntax error"));
528 return str_value (*args++);
530 else if (nextarg ("length"))
535 v = int_value (strlen (r->u.s));
539 else if (nextarg ("match"))
549 else if (nextarg ("index"))
556 v = int_value (strcspn (l->u.s, r->u.s) + 1);
557 if (v->u.i == (int) strlen (l->u.s) + 1)
563 else if (nextarg ("substr"))
570 if (!toarith (i1) || !toarith (i2)
571 || i1->u.i > (int) strlen (l->u.s)
572 || i1->u.i <= 0 || i2->u.i <= 0)
578 v->u.s = strncpy ((char *) xmalloc (i2->u.i + 1),
579 l->u.s + i1->u.i - 1, i2->u.i);
591 /* Handle : operator (pattern matching).
592 Calls docolon to do the real work. */
621 /* Handle *, /, % operators. */
639 else if (nextarg ("/"))
641 else if (nextarg ("%"))
654 /* Handle +, - operators. */
672 else if (nextarg ("-"))
685 /* Handle comparisons. */
703 else if (nextarg ("<="))
705 else if (nextarg ("=") || nextarg ("=="))
707 else if (nextarg ("!="))
709 else if (nextarg (">="))
711 else if (nextarg (">"))
744 if (null (l) || null (r))