1 /* expr -- evaluate expressions.
2 Copyright (C) 86, 1991-1997, 1999, 2000 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"
42 /* The official name of this program (e.g., no `g' prefix). */
43 #define PROGRAM_NAME "expr"
45 #define AUTHORS "Mike Parker"
48 #define NEW(Type) XMALLOC (Type, 1)
49 #define OLD(x) free ((char *) x)
51 /* The kinds of value we can have. */
57 typedef enum valtype TYPE;
62 TYPE type; /* Which kind. */
64 { /* The value itself. */
69 typedef struct valinfo VALUE;
71 /* Non-zero if the POSIXLY_CORRECT environment variable is set.
72 The unary operator `quote' is disabled when this variable is zero. */
73 static int posixly_correct;
75 /* The arguments given to the program, minus the program name. */
78 /* The name this program was run with. */
81 static VALUE *eval PARAMS ((void));
82 static int nomoreargs PARAMS ((void));
83 static int null PARAMS ((VALUE *v));
84 static void printv PARAMS ((VALUE *v));
90 fprintf (stderr, _("Try `%s --help' for more information.\n"),
95 Usage: %s EXPRESSION\n\
98 program_name, program_name);
101 --help display this help and exit\n\
102 --version output version information and exit\n\
106 Print the value of EXPRESSION to standard output. A blank line below\n\
107 separates increasing precedence groups. EXPRESSION may be:\n\
109 ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n\
111 ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0\n\
113 ARG1 < ARG2 ARG1 is less than ARG2\n\
114 ARG1 <= ARG2 ARG1 is less than or equal to ARG2\n\
115 ARG1 = ARG2 ARG1 is equal to ARG2\n\
116 ARG1 != ARG2 ARG1 is unequal to ARG2\n\
117 ARG1 >= ARG2 ARG1 is greater than or equal to ARG2\n\
118 ARG1 > ARG2 ARG1 is greater than ARG2\n\
120 ARG1 + ARG2 arithmetic sum of ARG1 and ARG2\n\
121 ARG1 - ARG2 arithmetic difference of ARG1 and ARG2\n\
123 ARG1 * ARG2 arithmetic product of ARG1 and ARG2\n\
124 ARG1 / ARG2 arithmetic quotient of ARG1 divided by ARG2\n\
125 ARG1 %% ARG2 arithmetic remainder of ARG1 divided by ARG2\n\
127 STRING : REGEXP anchored pattern match of REGEXP in STRING\n\
129 match STRING REGEXP same as STRING : REGEXP\n\
130 substr STRING POS LENGTH substring of STRING, POS counted from 1\n\
131 index STRING CHARS index in STRING where any CHARS is found, or 0\n\
132 length STRING length of STRING\n\
133 quote TOKEN interpret TOKEN as a string, even if it is a\n\
134 keyword like `match' or an operator like `/'\n\
136 ( EXPRESSION ) value of EXPRESSION\n\
140 Beware that many operators need to be escaped or quoted for shells.\n\
141 Comparisons are arithmetic if both ARGs are numbers, else lexicographical.\n\
142 Pattern matches return the string matched between \\( and \\) or null; if\n\
143 \\( and \\) are not used, they return the number of characters matched or 0.\n\
145 puts (_("\nReport bugs to <bug-sh-utils@gnu.org>."));
151 main (int argc, char **argv)
155 program_name = argv[0];
156 setlocale (LC_ALL, "");
157 bindtextdomain (PACKAGE, LOCALEDIR);
158 textdomain (PACKAGE);
160 atexit (close_stdout);
162 posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
164 /* Recognize --help or --version only if POSIXLY_CORRECT is not set. */
165 if (!posixly_correct)
166 parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
171 error (0, 0, _("too few arguments"));
179 error (2, 0, _("syntax error"));
185 /* Return a VALUE for I. */
188 int_value (intmax_t i)
198 /* Return a VALUE for S. */
207 v->u.s = xstrdup (s);
211 /* Free VALUE V, including structure components. */
216 if (v->type == string)
221 /* Store a printable representation of I somewhere into BUF, and
222 return a pointer to the stored representation. */
225 inttostr (intmax_t i, char buf[INT_STRLEN_BOUND (intmax_t) + 1])
228 char *p = buf + INT_STRLEN_BOUND (intmax_t);
233 *--p = '0' + ui % 10;
234 while ((ui /= 10) != 0);
246 char buf[INT_STRLEN_BOUND (intmax_t) + 1];
251 p = inttostr (v->u.i, buf);
263 /* Return nonzero if V is a null-string or zero-number. */
273 return v->u.s[0] == '\0' || strcmp (v->u.s, "0") == 0;
279 /* Return nonzero if V is a string value. */
284 return v->type == string;
287 /* Coerce V to a string value (can't fail). */
292 char buf[INT_STRLEN_BOUND (intmax_t) + 1];
297 v->u.s = xstrdup (inttostr (v->u.i, buf));
307 /* Coerce V to an integer value. Return 1 on success, 0 on failure. */
323 /* Don't interpret the empty string as an integer. */
332 i = i * 10 + *cp - '0';
337 v->u.i = i * (neg ? -1 : 1);
345 /* Return nonzero if the next token matches STR exactly.
346 STR must not be NULL. */
353 return strcmp (*args, str) == 0;
356 /* Return nonzero if there no more tokens. */
364 /* The comparison operator handling functions. */
366 #define cmpf(name, rel) \
368 int name (l, r) VALUE *l; VALUE *r; \
370 if (isstring (l) || isstring (r)) \
374 return strcmp (l->u.s, r->u.s) rel 0; \
377 return l->u.i rel r->u.i; \
380 cmpf (less_equal, <=)
383 cmpf (greater_equal, >=)
384 cmpf (greater_than, >)
388 /* The arithmetic operator handling functions. */
390 #define arithf(name, op) \
392 name (l, r) VALUE *l; VALUE *r; \
394 if (!toarith (l) || !toarith (r)) \
395 error (2, 0, _("non-numeric argument")); \
396 return l->u.i op r->u.i; \
399 #define arithdivf(name, op) \
401 name (l, r) VALUE *l; VALUE *r; \
403 if (!toarith (l) || !toarith (r)) \
404 error (2, 0, _("non-numeric argument")); \
406 error (2, 0, _("division by zero")); \
407 return l->u.i op r->u.i; \
413 arithdivf (divide, /)
420 /* Print evaluation trace and args remaining. */
429 for (a = args; *a; a++)
435 /* Do the : operator.
436 SV is the VALUE for the lhs (the string),
437 PV is the VALUE for the rhs (the pattern). */
440 docolon (VALUE *sv, VALUE *pv)
444 struct re_pattern_buffer re_buffer;
445 struct re_registers re_regs;
452 if (pv->u.s[0] == '^')
455 warning: unportable BRE: `%s': using `^' as the first character\n\
456 of the basic regular expression is not portable; it is being ignored"),
460 len = strlen (pv->u.s);
461 memset (&re_buffer, 0, sizeof (re_buffer));
462 memset (&re_regs, 0, sizeof (re_regs));
463 re_buffer.allocated = 2 * len;
464 if (re_buffer.allocated < len)
466 re_buffer.buffer = (unsigned char *) xmalloc (re_buffer.allocated);
467 re_buffer.translate = 0;
468 re_syntax_options = RE_SYNTAX_POSIX_BASIC;
469 errmsg = re_compile_pattern (pv->u.s, len, &re_buffer);
471 error (2, 0, "%s", errmsg);
473 matchlen = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs);
476 /* Were \(...\) used? */
477 if (re_buffer.re_nsub > 0)/* was (re_regs.start[1] >= 0) */
479 sv->u.s[re_regs.end[1]] = '\0';
480 v = str_value (sv->u.s + re_regs.start[1]);
483 v = int_value (matchlen);
487 /* Match failed -- return the right kind of null. */
488 if (re_buffer.re_nsub > 0)
493 free (re_buffer.buffer);
497 /* Handle bare operands and ( expr ) syntax. */
508 error (2, 0, _("syntax error"));
515 error (2, 0, _("syntax error"));
521 error (2, 0, _("syntax error"));
523 return str_value (*args++);
526 /* Handle match, substr, index, length, and quote keywords. */
540 if (!posixly_correct && nextarg ("quote"))
544 error (2, 0, _("syntax error"));
545 return str_value (*args++);
547 else if (nextarg ("length"))
552 v = int_value (strlen (r->u.s));
556 else if (nextarg ("match"))
566 else if (nextarg ("index"))
573 v = int_value (strcspn (l->u.s, r->u.s) + 1);
574 if (v->u.i == strlen (l->u.s) + 1)
580 else if (nextarg ("substr"))
587 if (!toarith (i1) || !toarith (i2)
588 || strlen (l->u.s) < i1->u.i
589 || i1->u.i <= 0 || i2->u.i <= 0)
595 v->u.s = strncpy ((char *) xmalloc (i2->u.i + 1),
596 l->u.s + i1->u.i - 1, i2->u.i);
608 /* Handle : operator (pattern matching).
609 Calls docolon to do the real work. */
638 /* Handle *, /, % operators. */
656 else if (nextarg ("/"))
658 else if (nextarg ("%"))
671 /* Handle +, - operators. */
689 else if (nextarg ("-"))
702 /* Handle comparisons. */
720 else if (nextarg ("<="))
722 else if (nextarg ("=") || nextarg ("=="))
724 else if (nextarg ("!="))
726 else if (nextarg (">="))
728 else if (nextarg (">"))
761 if (null (l) || null (r))