1 /* expr.c -- arithmetic expression evaluation. */
3 /* Copyright (C) 1990, 1991 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 1, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
22 All arithmetic is done as long integers with no checking for overflow
23 (though division by 0 is caught and flagged as an error).
25 The following operators are handled, grouped into a set of levels in
26 order of decreasing precedence.
28 "-", "+" [(unary operators)]
41 "=", "*=", "/=", "%=",
42 "+=", "-=", "<<=", ">>=",
45 (Note that most of these operators have special meaning to bash, and an
46 entire expression should be quoted, e.g. "a=$a+1" or "a=a+1" to ensure
47 that it is passed intact to the evaluator when using `let'. When using
48 the $[] or $(( )) forms, the text between the `[' and `]' or `((' and `))'
49 is treated as if in double quotes.)
51 Sub-expressions within parentheses have a precedence level greater than
52 all of the above levels and are evaluated first. Within a single prece-
53 dence group, evaluation is left-to-right, except for the arithmetic
54 assignment operator (`='), which is evaluated right-to-left (as in C).
56 The expression evaluator returns the value of the expression (assignment
57 statements have as a value what is returned by the RHS). The `let'
58 builtin, on the other hand, returns 0 if the last expression evaluates to
59 a non-zero, and 1 otherwise.
61 Implementation is a recursive-descent parser.
71 #if defined (HAVE_UNISTD_H)
77 /* Because of the $((...)) construct, expressions may include newlines.
78 Here is a macro which accepts newlines, tabs and spaces as whitespace. */
79 #define cr_whitespace(c) (whitespace(c) || ((c) == '\n'))
81 /* Size be which the expression stack grows when neccessary. */
82 #define EXPR_STACK_GROW_SIZE 10
84 /* Maximum amount of recursion allowed. This prevents a non-integer
85 variable such as "num=num+2" from infinitely adding to itself when
86 "let num=num+2" is given. */
87 #define MAX_EXPR_RECURSION_LEVEL 1024
89 /* The Tokens. Singing "The Lion Sleeps Tonight". */
91 #define EQEQ 1 /* "==" */
92 #define NEQ 2 /* "!=" */
93 #define LEQ 3 /* "<=" */
94 #define GEQ 4 /* ">=" */
95 #define STR 5 /* string */
96 #define NUM 6 /* number */
97 #define LAND 7 /* "&&" Logical AND */
98 #define LOR 8 /* "||" Logical OR */
99 #define LSH 9 /* "<<" Left SHift */
100 #define RSH 10 /* ">>" Right SHift */
101 #define OP_ASSIGN 11 /* op= expassign as in Posix.2 */
114 #define BAND '&' /* Bitwise AND */
115 #define BOR '|' /* Bitwise OR. */
116 #define BXOR '^' /* Bitwise eXclusive OR. */
117 #define BNOT '~' /* Bitwise NOT; Two's complement. */
121 static char *expression; /* The current expression */
122 static char *tp; /* token lexical position */
123 static char *lasttp; /* pointer to last token position */
124 static int curtok; /* the current token */
125 static int lasttok; /* the previous token */
126 static int assigntok; /* the OP in OP= */
127 static char *tokstr; /* current token string */
128 static int tokval; /* current token value */
129 static int noeval; /* set to 1 if no assignment to be done */
130 static procenv_t evalbuf;
132 static void readtok (); /* lexical analyzer */
133 static long expassign (), exp0 (), exp1 (), exp2 (), exp3 (),
134 exp4 (), exp5 (), expshift (), expland (), explor (),
135 expband (), expbor (), expbxor (), expcond ();
136 static long strlong ();
137 static void evalerror ();
139 /* A structure defining a single expression context. */
142 char *expression, *tp;
147 /* Global var which contains the stack of expression contexts. */
148 static EXPR_CONTEXT **expr_stack;
149 static int expr_depth; /* Location in the stack. */
150 static int expr_stack_size; /* Number of slots already allocated. */
152 extern char *this_command_name;
154 /* Push and save away the contents of the globals describing the
155 current expression context. */
159 EXPR_CONTEXT *context;
161 context = (EXPR_CONTEXT *)xmalloc (sizeof (EXPR_CONTEXT));
163 if (expr_depth >= MAX_EXPR_RECURSION_LEVEL)
164 evalerror ("expression recursion level exceeded");
166 if (expr_depth >= expr_stack_size)
168 expr_stack = (EXPR_CONTEXT **)
169 xrealloc (expr_stack, (expr_stack_size += EXPR_STACK_GROW_SIZE)
170 * sizeof (EXPR_CONTEXT *));
173 context->curtok = curtok;
174 context->lasttok = lasttok;
175 context->expression = expression;
177 context->tokval = tokval;
178 context->tokstr = tokstr;
179 expr_stack[expr_depth++] = context;
182 /* Pop the the contents of the expression context stack into the
183 globals describing the current expression context. */
187 EXPR_CONTEXT *context;
190 evalerror ("recursion stack underflow");
192 context = expr_stack[--expr_depth];
193 curtok = context->curtok;
194 lasttok = context->lasttok;
195 expression = context->expression;
197 tokval = context->tokval;
198 tokstr = context->tokstr;
202 /* Evaluate EXPR, and return the arithmetic result.
204 The `while' loop after the longjmp is caught relies on the above
205 implementation of pushexp and popexp leaving in expr_stack[0] the
206 values that the variables had when the program started. That is,
207 the first things saved are the initial values of the variables that
208 were assigned at program startup or by the compiler. Therefore, it is
209 safe to let the loop terminate when expr_depth == 0, without freeing up
210 any of the expr_depth[0] stuff. */
216 procenv_t old_evalbuf;
219 for (p = expr; p && *p && cr_whitespace (*p); p++)
222 if (p == NULL || *p == '\0')
225 /* Save the value of evalbuf to protect it around possible recursive
226 calls to evalexp (). */
227 COPY_PROCENV (evalbuf, old_evalbuf);
229 if (setjmp (evalbuf))
231 if (tokstr) /* Clean up local allocation. */
239 if (expr_stack[expr_depth]->tokstr)
240 free (expr_stack[expr_depth]->tokstr);
242 if (expr_stack[expr_depth]->expression)
243 free (expr_stack[expr_depth]->expression);
245 jump_to_top_level (DISCARD);
249 curtok = lasttok = 0;
250 expression = savestring (expr);
253 tokstr = (char *)NULL;
261 evalerror ("syntax error in expression");
270 /* Restore the value of evalbuf so that any subsequent longjmp calls
271 will have a valid location to jump to. */
272 COPY_PROCENV (old_evalbuf, evalbuf);
277 /* Bind/create a shell variable with the name LHS to the RHS.
278 This creates or modifies a variable such that it is an integer.
280 This should really be in variables.c, but it is here so that all of the
281 expression evaluation stuff is localized. Since we don't want any
282 recursive evaluation from bind_variable() (possible without this code,
283 since bind_variable() calls the evaluator for variables with the integer
284 attribute set), we temporarily turn off the integer attribute for each
285 variable we set here, then turn it back on after binding as necessary. */
288 bind_int_variable (lhs, rhs)
291 register SHELL_VAR *v;
294 v = find_variable (lhs);
297 isint = integer_p (v);
298 v->attributes &= ~att_integer;
301 v = bind_variable (lhs, rhs);
303 v->attributes |= att_integer;
313 if (curtok == EQ || curtok == OP_ASSIGN)
318 special = curtok == OP_ASSIGN;
321 evalerror ("attempted assignment to non-variable");
325 op = assigntok; /* a OP= b */
329 lhs = savestring (tokstr);
331 value = expassign ();
365 evalerror ("bug: bad expassign token");
373 bind_int_variable (lhs, rhs);
377 tokstr = (char *)NULL; /* For freeing on errors. */
382 /* Conditional expression (expr?expr:expr) */
386 long cval, val1, val2, rval;
387 rval = cval = explor ();
388 if (curtok == QUES) /* found conditional expr */
391 if (curtok == 0 || curtok == COL)
392 evalerror ("expression expected");
403 evalerror ("`:' expected for conditional expression");
406 evalerror ("expression expected");
412 rval = cval ? val1 : val2;
422 register long val1, val2;
426 while (curtok == LOR)
444 register long val1, val2;
448 while (curtok == LAND)
466 register long val1, val2;
470 while (curtok == BOR)
484 register long val1, val2;
488 while (curtok == BXOR)
502 register long val1, val2;
506 while (curtok == BAND)
519 register long val1, val2;
523 while ((curtok == EQEQ) || (curtok == NEQ))
530 val1 = (val1 == val2);
532 val1 = (val1 != val2);
540 register long val1, val2;
543 while ((curtok == LEQ) ||
565 /* Left and right shifts. */
569 register long val1, val2;
573 while ((curtok == LSH) || (curtok == RSH))
592 register long val1, val2;
596 while ((curtok == PLUS) || (curtok == MINUS))
605 else if (op == MINUS)
614 register long val1, val2;
618 while ((curtok == MUL) ||
628 if (((op == DIV) || (op == MOD)) && (val2 == 0))
629 evalerror ("division by 0");
651 else if (curtok == BNOT)
665 register long val = 0L;
672 else if (curtok == PLUS)
677 else if (curtok == LPAR)
683 evalerror ("missing `)'");
685 /* Skip over closing paren. */
688 else if ((curtok == NUM) || (curtok == STR))
694 evalerror ("syntax error: operand expected");
699 /* Lexical analyzer/token reader for the expression evaluator. Reads the
700 next token and puts its value into curtok, while advancing past it.
701 Updates value of tp. May also set tokval (for number) or tokstr (for
707 register int c, c1, e;
709 /* Skip leading whitespace. */
712 while (cp && (c = *cp) && (cr_whitespace (c)))
718 lasttp = tp = cp - 1;
728 if (legal_variable_starter (c))
730 /* Semi-bogus ksh compatibility feature -- variable names
731 not preceded with a dollar sign are shell variables. */
734 while (legal_variable_char (c))
739 #if defined (ARRAY_VARS)
742 e = skipsubscript (cp, 0);
750 evalerror ("bad array subscript");
752 #endif /* ARRAY_VARS */
757 tokstr = savestring (tp);
759 #if defined (ARRAY_VARS)
760 value = (e == ']') ? get_array_value (tokstr, 0) : get_string_value (tokstr);
762 value = get_string_value (tokstr);
765 tokval = (value && *value) ? evalexp (value) : 0;
773 while (digit (c) || isletter (c) || c == '#' || c == '@' || c == '_')
779 tokval = strlong (tp);
787 if ((c == EQ) && (c1 == EQ))
789 else if ((c == NOT) && (c1 == EQ))
791 else if ((c == GT) && (c1 == EQ))
793 else if ((c == LT) && (c1 == EQ))
795 else if ((c == LT) && (c1 == LT))
797 if (*cp == '=') /* a <<= b */
806 else if ((c == GT) && (c1 == GT))
810 assigntok = RSH; /* a >>= b */
817 else if ((c == BAND) && (c1 == BAND))
819 else if ((c == BOR) && (c1 == BOR))
821 else if (c1 == EQ && member(c, "*/%+-&^|"))
823 assigntok = c; /* a OP= b */
827 cp--; /* `unget' the character */
840 name = this_command_name;
841 for (t = expression; whitespace (*t); t++)
843 internal_error ("%s%s%s: %s (error token is \"%s\")",
844 name ? name : "", name ? ": " : "", t,
845 msg, (lasttp && *lasttp) ? lasttp : "");
846 longjmp (evalbuf, 1);
849 /* Convert a string to a long integer, with an arbitrary base.
852 Anything else: [base#]number (this is implemented to match ksh93)
854 Base may be >=2 and <=64. If base is <= 36, the numbers are drawn
855 from [0-9][a-zA-Z], and lowercase and uppercase letters may be used
856 interchangably. If base is > 36 and <= 64, the numbers are drawn
857 from [0-9][a-z][A-Z]_@ (a = 10, z = 35, A = 36, Z = 61, _ = 62, @ = 63 --
858 you get the picture). */
870 if (s == NULL || *s == '\0')
879 if (s == NULL || *s == '\0')
883 if (*s == 'x' || *s == 'X')
894 for (c = *s++; c; c = *s++)
899 evalerror ("bad number");
903 /* Illegal base specifications raise an evaluation error. */
904 if (base < 2 || base > 64)
905 evalerror ("illegal arithmetic base");
910 else if (isletter(c) || digit(c) || (c == '_') || (c == '@'))
914 else if (c >= 'a' && c <= 'z')
916 else if (c >= 'A' && c <= 'Z')
917 c -= 'A' - ((base <= 36) ? 10 : 36);
924 evalerror ("value too great for base");
926 val = (val * base) + c;
934 #if defined (EXPR_TEST)
947 return (realloc (s, n));
950 SHELL_VAR *find_variable () { return 0;}
951 SHELL_VAR *bind_variable () { return 0; }
953 char *get_string_value () { return 0; }
964 if (setjmp (top_level))
967 for (i = 1; i < argc; i++)
969 v = evalexp (argv[i]);
970 printf ("'%s' -> %ld\n", argv[i], v);
976 builtin_error (format, arg1, arg2, arg3, arg4, arg5)
979 fprintf (stderr, "expr: ");
980 fprintf (stderr, format, arg1, arg2, arg3, arg4, arg5);
981 fprintf (stderr, "\n");
992 #endif /* EXPR_TEST */