1 /* expr -- evaluate expressions.
2 Copyright (C) 86, 1991-1997, 1999-2008 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 3 of the License, or
7 (at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
17 /* Author: Mike Parker.
18 Modified for arbitrary-precision calculation by James Youngman.
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>
43 #include "strnumcmp.h"
46 /* The official name of this program (e.g., no `g' prefix). */
47 #define PROGRAM_NAME "expr"
49 #define AUTHORS proper_name ("Mike Parker"), proper_name ("James Youngman")
54 /* Invalid expression: e.g., its form does not conform to the
55 grammar for expressions. Our grammar is an extension of the
59 /* An internal error occurred, e.g., arithmetic overflow, storage
64 /* The kinds of value we can have.
65 In the comments below, a variable is described as "arithmetic" if
66 it is either integer or mp_integer. Variables are of type mp_integer
67 only if GNU MP is available, but the type designator is always defined. */
74 typedef enum valtype TYPE;
79 TYPE type; /* Which kind. */
81 { /* The value itself. */
82 /* We could use intmax_t but that would integrate less well with GMP,
83 since GMP has mpz_set_si but no intmax_t equivalent. */
91 typedef struct valinfo VALUE;
93 /* The arguments given to the program, minus the program name. */
96 static VALUE *eval (bool);
97 static bool nomoreargs (void);
98 static bool null (VALUE *v);
99 static void printv (VALUE *v);
101 /* Arithmetic is done in one of three modes.
103 The --bignum option forces all arithmetic to use bignums other than
104 string indexing (mode==MP_ALWAYS). The --no-bignum option forces
105 all arithmetic to use native types rather than bignums
108 The default mode is MP_AUTO if GMP is available and MP_NEVER if
109 not. Most functions will process a bignum if one is found, but
110 will not convert a native integer to a string if the mode is
114 MP_NEVER, /* Never use bignums */
116 MP_ALWAYS, /* Always use bignums. */
117 MP_AUTO, /* Switch if result would otherwise overflow */
120 static enum arithmetic_mode mode =
132 if (status != EXIT_SUCCESS)
133 fprintf (stderr, _("Try `%s --help' for more information.\n"),
138 Usage: %s EXPRESSION\n\
141 program_name, program_name);
144 --bignum always use arbitrary-precision arithmetic\n\
145 --no-bignum always use single-precision arithmetic\n"),
147 fputs (HELP_OPTION_DESCRIPTION, stdout);
148 fputs (VERSION_OPTION_DESCRIPTION, stdout);
151 Print the value of EXPRESSION to standard output. A blank line below\n\
152 separates increasing precedence groups. EXPRESSION may be:\n\
154 ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n\
156 ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0\n\
160 ARG1 < ARG2 ARG1 is less than ARG2\n\
161 ARG1 <= ARG2 ARG1 is less than or equal to ARG2\n\
162 ARG1 = ARG2 ARG1 is equal to ARG2\n\
163 ARG1 != ARG2 ARG1 is unequal to ARG2\n\
164 ARG1 >= ARG2 ARG1 is greater than or equal to ARG2\n\
165 ARG1 > ARG2 ARG1 is greater than ARG2\n\
169 ARG1 + ARG2 arithmetic sum of ARG1 and ARG2\n\
170 ARG1 - ARG2 arithmetic difference of ARG1 and ARG2\n\
172 /* Tell xgettext that the "% A" below is not a printf-style
173 format string: xgettext:no-c-format */
176 ARG1 * ARG2 arithmetic product of ARG1 and ARG2\n\
177 ARG1 / ARG2 arithmetic quotient of ARG1 divided by ARG2\n\
178 ARG1 % ARG2 arithmetic remainder of ARG1 divided by ARG2\n\
182 STRING : REGEXP anchored pattern match of REGEXP in STRING\n\
184 match STRING REGEXP same as STRING : REGEXP\n\
185 substr STRING POS LENGTH substring of STRING, POS counted from 1\n\
186 index STRING CHARS index in STRING where any CHARS is found, or 0\n\
187 length STRING length of STRING\n\
190 + TOKEN interpret TOKEN as a string, even if it is a\n\
191 keyword like `match' or an operator like `/'\n\
193 ( EXPRESSION ) value of EXPRESSION\n\
197 Beware that many operators need to be escaped or quoted for shells.\n\
198 Comparisons are arithmetic if both ARGs are numbers, else lexicographical.\n\
199 Pattern matches return the string matched between \\( and \\) or null; if\n\
200 \\( and \\) are not used, they return the number of characters matched or 0.\n\
204 Exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null\n\
205 or 0, 2 if EXPRESSION is syntactically invalid, and 3 if an error occurred.\n\
207 emit_bug_reporting_address ();
212 /* Report a syntax error and exit. */
216 error (EXPR_INVALID, 0, _("syntax error"));
219 /* Report an integer overflow for operation OP and exit. */
221 integer_overflow (char op)
223 error (EXPR_FAILURE, 0,
224 _("arithmetic operation %c produced an out of range value, "
225 "but arbitrary-precision arithmetic is not available"), op);
228 static void die (int exit_status, int errno_val, char const *msg)
231 die (int exit_status, int errno_val, char const *msg)
233 assert (exit_status != 0);
234 error (exit_status, errno_val, "%s", msg);
235 abort (); /* notreached */
239 string_too_long (void)
241 die (EXPR_FAILURE, ERANGE, _("string too long"));
246 USE_BIGNUM = CHAR_MAX + 1,
250 static struct option const long_options[] =
252 {"bignum", no_argument, NULL, USE_BIGNUM},
253 {"no-bignum", no_argument, NULL, NO_USE_BIGNUM},
254 {GETOPT_HELP_OPTION_DECL},
255 {GETOPT_VERSION_OPTION_DECL},
260 main (int argc, char **argv)
265 initialize_main (&argc, &argv);
266 set_program_name (argv[0]);
267 setlocale (LC_ALL, "");
268 bindtextdomain (PACKAGE, LOCALEDIR);
269 textdomain (PACKAGE);
271 initialize_exit_failure (EXPR_FAILURE);
272 atexit (close_stdout);
274 /* The argument -0 should not result in an error message. */
277 while ((c = getopt_long (argc, argv, "+", long_options, NULL)) != -1)
279 /* "expr -0" should interpret the -0 as an integer argument.
280 arguments like --foo should also be interpreted as a string
281 argument to be "evaluated".
295 error (0, 0, _("arbitrary-precision support is not available"));
303 case_GETOPT_HELP_CHAR;
305 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
311 error (0, 0, _("missing operand"));
312 usage (EXPR_INVALID);
315 args = argv + optind;
325 /* Return a VALUE for I. */
328 int_value (long int i)
330 VALUE *v = xmalloc (sizeof *v);
332 if (mode == MP_ALWAYS)
334 /* all integer values are handled as bignums. */
335 mpz_init_set_si (v->u.z, i);
336 v->type = mp_integer;
346 /* Return a VALUE for S. */
349 str_value (char const *s)
351 VALUE *v = xmalloc (sizeof *v);
353 v->u.s = xstrdup (s);
359 substr_value (char const *s, size_t len, size_t pos, size_t nchars_wanted)
362 return str_value ("");
365 VALUE *v = xmalloc (sizeof *v);
366 size_t vlen = MIN (nchars_wanted, len - pos + 1);
369 v->u.s = xmalloc (vlen + 1);
370 vlim = mempcpy (v->u.s, s + pos, vlen);
377 /* Free VALUE V, including structure components. */
382 if (v->type == string)
386 else if (v->type == mp_integer)
388 assert (mode != MP_NEVER);
404 printf ("%ld\n", v->u.i);
411 mpz_out_str (stdout, 10, v->u.z);
421 /* Return true if V is a null-string or zero-number. */
432 return mpz_sgn (v->u.z) == 0;
436 char const *cp = v->u.s;
456 /* Return true if CP takes the form of an integer. */
459 looks_like_integer (char const *cp)
471 /* Coerce V to a string value (can't fail). */
476 char buf[INT_BUFSIZE_BOUND (long int)];
481 snprintf (buf, sizeof buf, "%ld", v->u.i);
482 v->u.s = xstrdup (buf);
488 char *s = mpz_get_str (NULL, 10, v->u.z);
506 /* Coerce V to an arithmetic value.
507 Return true on success, false on failure. */
522 if (! looks_like_integer (v->u.s))
524 if (xstrtol (v->u.s, NULL, 10, &value, NULL) != LONGINT_OK)
527 if (mode != MP_NEVER)
530 if (mpz_init_set_str (v->u.z, s, 10))
531 abort (); /* Bug in looks_like_integer, perhaps. */
532 v->type = mp_integer;
537 error (EXPR_FAILURE, ERANGE, "%s", v->u.s);
540 error (EXPR_FAILURE, ERANGE, "%s", v->u.s);
556 /* Extract a size_t value from a positive arithmetic value, V.
557 The extracted value is stored in *VAL. */
559 getsize (const VALUE *v, size_t *val, bool *negative)
561 if (v->type == integer)
575 else if (v->type == mp_integer)
578 if (mpz_sgn (v->u.z) < 0)
583 else if (mpz_fits_ulong_p (v->u.z))
586 ul = mpz_get_ui (v->u.z);
602 abort (); /* should not pass a string. */
608 /* Return true and advance if the next token matches STR exactly.
609 STR must not be NULL. */
612 nextarg (char const *str)
618 bool r = STREQ (*args, str);
624 /* Return true if there no more tokens. */
633 /* Print evaluation trace and args remaining. */
642 for (a = args; *a; a++)
648 /* Do the : operator.
649 SV is the VALUE for the lhs (the string),
650 PV is the VALUE for the rhs (the pattern). */
653 docolon (VALUE *sv, VALUE *pv)
655 VALUE *v IF_LINT (= NULL);
657 struct re_pattern_buffer re_buffer;
658 char fastmap[UCHAR_MAX + 1];
659 struct re_registers re_regs;
665 re_regs.num_regs = 0;
666 re_regs.start = NULL;
669 re_buffer.buffer = NULL;
670 re_buffer.allocated = 0;
671 re_buffer.fastmap = fastmap;
672 re_buffer.translate = NULL;
674 RE_SYNTAX_POSIX_BASIC & ~RE_CONTEXT_INVALID_DUP & ~RE_NO_EMPTY_RANGES;
675 errmsg = re_compile_pattern (pv->u.s, strlen (pv->u.s), &re_buffer);
677 error (EXPR_INVALID, 0, "%s", errmsg);
678 re_buffer.newline_anchor = 0;
680 matchlen = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs);
683 /* Were \(...\) used? */
684 if (re_buffer.re_nsub > 0)
686 sv->u.s[re_regs.end[1]] = '\0';
687 v = str_value (sv->u.s + re_regs.start[1]);
690 v = int_value (matchlen);
692 else if (matchlen == -1)
694 /* Match failed -- return the right kind of null. */
695 if (re_buffer.re_nsub > 0)
702 (matchlen == -2 ? errno : EOVERFLOW),
703 _("error in regular expression matcher"));
705 if (0 < re_regs.num_regs)
707 free (re_regs.start);
710 re_buffer.fastmap = NULL;
711 regfree (&re_buffer);
715 /* Handle bare operands and ( expr ) syntax. */
718 eval7 (bool evaluate)
739 return str_value (*args++);
742 /* Handle match, substr, index, and length keywords, and quoting "+". */
745 eval6 (bool evaluate)
760 return str_value (*args++);
762 else if (nextarg ("length"))
764 r = eval6 (evaluate);
766 v = int_value (strlen (r->u.s));
770 else if (nextarg ("match"))
772 l = eval6 (evaluate);
773 r = eval6 (evaluate);
784 else if (nextarg ("index"))
788 l = eval6 (evaluate);
789 r = eval6 (evaluate);
792 pos = strcspn (l->u.s, r->u.s);
793 len = strlen (l->u.s);
802 v = int_value (pos + 1);
810 v = xmalloc (sizeof *v);
811 mpz_init_set_ui (v->u.z, pos+1);
812 v->type = mp_integer;
825 else if (nextarg ("substr"))
828 l = eval6 (evaluate);
829 i1 = eval6 (evaluate);
830 i2 = eval6 (evaluate);
832 llen = strlen (l->u.s);
834 if (!toarith (i1) || !toarith (i2))
839 bool negative = false;
841 if (getsize (i1, &pos, &negative))
842 if (getsize (i2, &len, &negative))
843 if (pos == 0 || len == 0)
846 v = substr_value (l->u.s, llen, pos-1, len);
851 die (EXPR_FAILURE, ERANGE, _("string offset is too large"));
856 die (EXPR_FAILURE, ERANGE, _("substring length too large"));
864 return eval7 (evaluate);
867 /* Handle : operator (pattern matching).
868 Calls docolon to do the real work. */
871 eval5 (bool evaluate)
880 l = eval6 (evaluate);
885 r = eval6 (evaluate);
904 if (x->type == integer)
905 mpz_init_set_si (x->u.z, x->u.i);
909 /* L = L * R. Both L and R are arithmetic. */
911 domult (VALUE *l, VALUE *r)
913 if (l->type == integer && r->type == integer)
916 val = l->u.i * r->u.i;
917 if (! (l->u.i == 0 || r->u.i == 0
918 || ((val < 0) == ((l->u.i < 0) ^ (r->u.i < 0))
919 && val / l->u.i == r->u.i)))
921 /* Result would (did) overflow. Handle with MP if available. */
922 if (mode != MP_NEVER)
925 mpz_init_set_si (l->u.z, l->u.i);
926 mpz_mul_si (l->u.z, l->u.z, r->u.i); /* L*=R */
927 l->type = mp_integer;
932 integer_overflow ('*');
942 /* At least one operand is already mp_integer, so promote the other. */
944 /* We could use mpz_mul_si here if R is not already mp_integer,
945 but for the moment we'll try to minimise code paths. */
946 if (l->type == integer)
947 mpz_init_set_si (l->u.z, l->u.i);
948 if (r->type == integer)
949 mpz_init_set_si (r->u.z, r->u.i);
950 l->type = r->type = mp_integer;
951 mpz_mul (l->u.z, l->u.z, r->u.z); /* L*=R */
958 /* L = L / R or (if WANT_MODULUS) L = L % R */
960 dodivide (VALUE *l, VALUE *r, bool want_modulus)
962 if (r->type == integer && r->u.i == 0)
963 error (EXPR_INVALID, 0, _("division by zero"));
965 if (r->type == mp_integer && mpz_sgn (r->u.z) == 0)
966 error (EXPR_INVALID, 0, _("division by zero"));
968 if (l->type == integer && r->type == integer)
970 if (l->u.i < - INT_MAX && r->u.i == -1)
972 /* Some x86-style hosts raise an exception for
973 INT_MIN / -1 and INT_MIN % -1, so handle these
974 problematic cases specially. */
977 /* X mod -1 is zero for all negative X.
978 Although strictly this is implementation-defined,
979 we don't want to coredump, so we avoid the calculation. */
985 if (mode != MP_NEVER)
988 /* Handle the case by promoting. */
989 mpz_init_set_si (l->u.z, l->u.i);
990 l->type = mp_integer;
995 integer_overflow ('/');
1001 l->u.i = want_modulus ? l->u.i % r->u.i : l->u.i / r->u.i;
1005 /* If we get to here, at least one operand is mp_integer
1012 sign_l = mpz_sgn (l->u.z);
1013 sign_r = mpz_sgn (r->u.z);
1019 mpz_set_si (l->u.z, 0);
1021 else if (sign_l < 0 || sign_r < 0)
1023 /* At least one operand is negative. For integer arithmetic,
1024 it's platform-dependent if the operation rounds up or down.
1025 We mirror what the implementation does. */
1026 switch ((3*sign_l) / (2*sign_r))
1028 case 2: /* round toward +inf. */
1029 case -1: /* round toward +inf. */
1030 mpz_cdiv_q (l->u.z, l->u.z, r->u.z);
1032 case -2: /* round toward -inf. */
1033 case 1: /* round toward -inf */
1034 mpz_fdiv_q (l->u.z, l->u.z, r->u.z);
1042 /* Both operands positive. Round toward -inf. */
1043 mpz_fdiv_q (l->u.z, l->u.z, r->u.z);
1048 mpz_mod (l->u.z, l->u.z, r->u.z); /* L = L % R */
1050 /* If either operand is negative, it's platform-dependent if
1051 the remainer is positive or negative. We mirror what the
1052 implementation does. */
1053 if (sign_l % sign_r < 0)
1054 mpz_neg (l->u.z, l->u.z); /* L = (-L) */
1063 /* Handle *, /, % operators. */
1066 eval4 (bool evaluate)
1070 enum { multiply, divide, mod } fxn;
1075 l = eval5 (evaluate);
1080 else if (nextarg ("/"))
1082 else if (nextarg ("%"))
1086 r = eval5 (evaluate);
1089 if (!toarith (l) || !toarith (r))
1090 error (EXPR_INVALID, 0, _("non-numeric argument"));
1098 dodivide (l, r, fxn==mod);
1106 /* L = L + R, or L = L - R */
1108 doadd (VALUE *l, VALUE *r, bool add)
1112 if (!toarith (l) || !toarith (r))
1113 error (EXPR_INVALID, 0, _("non-numeric argument"));
1114 if (l->type == integer && r->type == integer)
1118 val = l->u.i + r->u.i;
1119 if ((val < l->u.i) == (r->u.i < 0))
1127 val = l->u.i - r->u.i;
1128 if ((l->u.i < val) == (r->u.i < 0))
1135 /* If we get to here, either the operation overflowed or at least
1136 one operand is an mp_integer. */
1137 if (mode != MP_NEVER)
1143 mpz_add (l->u.z, l->u.z, r->u.z);
1145 mpz_sub (l->u.z, l->u.z, r->u.z);
1150 integer_overflow ('-');
1156 /* Handle +, - operators. */
1159 eval3 (bool evaluate)
1168 l = eval4 (evaluate);
1173 else if (nextarg ("-"))
1177 r = eval4 (evaluate);
1186 /* Handle comparisons. */
1189 eval2 (bool evaluate)
1196 l = eval3 (evaluate);
1202 less_than, less_equal, equal, not_equal, greater_equal, greater_than
1208 else if (nextarg ("<="))
1210 else if (nextarg ("=") || nextarg ("=="))
1212 else if (nextarg ("!="))
1214 else if (nextarg (">="))
1215 fxn = greater_equal;
1216 else if (nextarg (">"))
1220 r = eval3 (evaluate);
1228 if (looks_like_integer (l->u.s) && looks_like_integer (r->u.s))
1229 cmp = strintcmp (l->u.s, r->u.s);
1233 cmp = strcoll (l->u.s, r->u.s);
1237 error (0, errno, _("string comparison failed"));
1238 error (0, 0, _("set LC_ALL='C' to work around the problem"));
1239 error (EXPR_INVALID, 0,
1240 _("the strings compared were %s and %s"),
1241 quotearg_n_style (0, locale_quoting_style, l->u.s),
1242 quotearg_n_style (1, locale_quoting_style, r->u.s));
1248 case less_than: val = (cmp < 0); break;
1249 case less_equal: val = (cmp <= 0); break;
1250 case equal: val = (cmp == 0); break;
1251 case not_equal: val = (cmp != 0); break;
1252 case greater_equal: val = (cmp >= 0); break;
1253 case greater_than: val = (cmp > 0); break;
1260 l = int_value (val);
1267 eval1 (bool evaluate)
1275 l = eval2 (evaluate);
1280 r = eval2 (evaluate & ~ null (l));
1281 if (null (l) || null (r))
1298 eval (bool evaluate)
1306 l = eval1 (evaluate);
1311 r = eval1 (evaluate & null (l));