xref: /netbsd-src/bin/expr/expr.y (revision 3b01aba77a7a698587faaae455bbfe740923c1f5)
1 /* $NetBSD: expr.y,v 1.27 2001/05/06 06:20:39 jmc Exp $ */
2 
3 /*_
4  * Copyright (c) 2000 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jaromir Dolecek <jdolecek@NetBSD.org> and J.T. Conklin <jtc@netbsd.org>.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the NetBSD
21  *      Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 %{
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __RCSID("$NetBSD: expr.y,v 1.27 2001/05/06 06:20:39 jmc Exp $");
42 #endif /* not lint */
43 
44 #include <sys/types.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <limits.h>
48 #include <locale.h>
49 #include <regex.h>
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 
55 static const char * const *av;
56 
57 static void yyerror(const char *, ...);
58 static int yylex(void);
59 static int is_zero_or_null(const char *);
60 static int is_integer(const char *);
61 static int64_t perform_arith_op(const char *, const char *, const char *);
62 
63 int main(int, const char * const *);
64 
65 #define YYSTYPE	const char *
66 
67 %}
68 %token STRING
69 %left SPEC_OR
70 %left SPEC_AND
71 %left COMPARE
72 %left ADD_SUB_OPERATOR
73 %left MUL_DIV_MOD_OPERATOR
74 %left SPEC_REG
75 %left LEFT_PARENT RIGHT_PARENT
76 
77 %%
78 
79 exp:	expr = {
80 		(void) printf("%s\n", $1);
81 		return (is_zero_or_null($1));
82 		}
83 	;
84 
85 expr:	item { $$ = $1; }
86 	| expr SPEC_OR expr = {
87 		/*
88 		 * Return evaluation of first expression if it is neither
89 		 * an empty string nor zero; otherwise, returns the evaluation
90 		 * of second expression.
91 		 */
92 		if (!is_zero_or_null($1))
93 			$$ = $1;
94 		else
95 			$$ = $3;
96 		}
97 	| expr SPEC_AND expr = {
98 		/*
99 		 * Returns the evaluation of first expr if neither expression
100 		 * evaluates to an empty string or zero; otherwise, returns
101 		 * zero.
102 		 */
103 		if (!is_zero_or_null($1) && !is_zero_or_null($3))
104 			$$ = $1;
105 		else
106 			$$ = "0";
107 		}
108 	| expr SPEC_REG expr = {
109 		/*
110 		 * The ``:'' operator matches first expr against the second,
111 		 * which must be a regular expression.
112 		 */
113 		regex_t rp;
114 		regmatch_t rm[2];
115 		int eval;
116 
117 		/* compile regular expression */
118 		if ((eval = regcomp(&rp, $3, 0)) != 0) {
119 			char errbuf[256];
120 			(void)regerror(eval, &rp, errbuf, sizeof(errbuf));
121 			yyerror("%s", errbuf);
122 			/* NOT REACHED */
123 		}
124 
125 		/* compare string against pattern --  remember that patterns
126 		   are anchored to the beginning of the line */
127 		if (regexec(&rp, $1, 2, rm, 0) == 0 && rm[0].rm_so == 0) {
128 			char *val;
129 			if (rm[1].rm_so >= 0) {
130 				(void) asprintf(&val, "%.*s",
131 					(int) (rm[1].rm_eo - rm[1].rm_so),
132 					$1 + rm[1].rm_so);
133 			} else {
134 				(void) asprintf(&val, "%d",
135 					(int)(rm[0].rm_eo - rm[0].rm_so));
136 			}
137 			$$ = val;
138 		} else {
139 			if (rp.re_nsub == 0) {
140 				$$ = "0";
141 			} else {
142 				$$ = "";
143 			}
144 		}
145 
146 		}
147 	| expr ADD_SUB_OPERATOR expr = {
148 		/* Returns the results of addition, subtraction */
149 		char *val;
150 		int64_t res;
151 
152 		res = perform_arith_op($1, $2, $3);
153 		(void) asprintf(&val, "%lld", (long long int) res);
154 		$$ = val;
155                 }
156 
157 	| expr MUL_DIV_MOD_OPERATOR expr = {
158 		/*
159 		 * Returns the results of multiply, divide or remainder of
160 		 * numeric-valued arguments.
161 		 */
162 		char *val;
163 		int64_t res;
164 
165 		res = perform_arith_op($1, $2, $3);
166 		(void) asprintf(&val, "%lld", (long long int) res);
167 		$$ = val;
168 
169 		}
170 	| expr COMPARE expr = {
171 		/*
172 		 * Returns the results of integer comparison if both arguments
173 		 * are integers; otherwise, returns the results of string
174 		 * comparison using the locale-specific collation sequence.
175 		 * The result of each comparison is 1 if the specified relation
176 		 * is true, or 0 if the relation is false.
177 		 */
178 
179 		int64_t l, r;
180 		int res;
181 
182 		/*
183 		 * Slight hack to avoid differences in the compare code
184 		 * between string and numeric compare.
185 		 */
186 		if (is_integer($1) && is_integer($3)) {
187 			/* numeric comparison */
188 			l = strtoll($1, NULL, 10);
189 			r = strtoll($3, NULL, 10);
190 		} else {
191 			/* string comparison */
192 			l = strcoll($1, $3);
193 			r = 0;
194 		}
195 
196 		switch($2[0]) {
197 		case '=': /* equal */
198 			res = (l == r);
199 			break;
200 		case '>': /* greater or greater-equal */
201 			if ($2[1] == '=')
202 				res = (l >= r);
203 			else
204 				res = (l > r);
205 			break;
206 		case '<': /* lower or lower-equal */
207 			if ($2[1] == '=')
208 				res = (l <= r);
209 			else
210 				res = (l < r);
211 			break;
212 		case '!': /* not equal */
213 			/* the check if this is != was done in yylex() */
214 			res = (l != r);
215 		}
216 
217 		$$ = (res) ? "1" : "0";
218 
219 		}
220 	| LEFT_PARENT expr RIGHT_PARENT { $$ = $2; }
221 	;
222 
223 item:	STRING
224 	| ADD_SUB_OPERATOR
225 	| MUL_DIV_MOD_OPERATOR
226 	| COMPARE
227 	| SPEC_OR
228 	| SPEC_AND
229 	| SPEC_REG
230 	;
231 %%
232 
233 /*
234  * Returns 1 if the string is empty or contains only numeric zero.
235  */
236 static int
237 is_zero_or_null(const char *str)
238 {
239 	char *endptr;
240 
241 	return str[0] == '\0'
242 		|| ( strtoll(str, &endptr, 10) == 0LL
243 			&& endptr[0] == '\0');
244 }
245 
246 /*
247  * Returns 1 if the string is an integer.
248  */
249 static int
250 is_integer(const char *str)
251 {
252 	char *endptr;
253 
254 	(void) strtoll(str, &endptr, 10);
255 	/* note we treat empty string as valid number */
256 	return (endptr[0] == '\0');
257 }
258 
259 static int64_t
260 perform_arith_op(const char *left, const char *op, const char *right)
261 {
262 	int64_t res, sign, l, r;
263 	u_int64_t temp;
264 
265 	if (!is_integer(left)) {
266 		yyerror("non-integer argument '%s'", left);
267 		/* NOTREACHED */
268 	}
269 	if (!is_integer(right)) {
270 		yyerror("non-integer argument '%s'", right);
271 		/* NOTREACHED */
272 	}
273 
274 	errno = 0;
275 	l = strtoll(left, NULL, 10);
276 	if (errno == ERANGE) {
277 		yyerror("value '%s' is %s is %lld", left,
278 		    (l > 0) ? "too big, maximum" : "too small, minimum",
279 		    (l > 0) ? LLONG_MAX : LLONG_MIN);
280 		/* NOTREACHED */
281 	}
282 
283 	errno = 0;
284 	r = strtoll(right, NULL, 10);
285 	if (errno == ERANGE) {
286 		yyerror("value '%s' is %s is %lld", right,
287 		    (l > 0) ? "too big, maximum" : "too small, minimum",
288 	  	    (l > 0) ? LLONG_MAX : LLONG_MIN);
289 		/* NOTREACHED */
290 	}
291 
292 	switch(op[0]) {
293 	case '+':
294 		/*
295 		 * Do the op into an unsigned to avoid overflow and then cast
296 		 * back to check the resulting signage.
297 		 */
298 		temp = l + r;
299 		res = (int64_t) temp;
300 		/* very simplistic check for over-& underflow */
301 		if ((res < 0 && l > 0 && r > 0)
302 	  	    || (res > 0 && l < 0 && r < 0))
303 			yyerror("integer overflow or underflow occurred for "
304                             "operation '%s %s %s'", left, op, right);
305 		break;
306 	case '-':
307 		/*
308 		 * Do the op into an unsigned to avoid overflow and then cast
309 		 * back to check the resulting signage.
310 		 */
311 		temp = l - r;
312 		res = (int64_t) temp;
313 		/* very simplistic check for over-& underflow */
314 		if ((res < 0 && l > 0 && l > r)
315 		    || (res > 0 && l < 0 && l < r) )
316 			yyerror("integer overflow or underflow occurred for "
317 			    "operation '%s %s %s'", left, op, right);
318 		break;
319 	case '/':
320 		if (r == 0)
321 			yyerror("second argument to '%s' must not be zero", op);
322 		res = l / r;
323 
324 		break;
325 	case '%':
326 		if (r == 0)
327 			yyerror("second argument to '%s' must not be zero", op);
328 		res = l % r;
329 		break;
330 	case '*':
331 		/* shortcut */
332 		if ((l == 0) || (r == 0)) {
333 			res = 0;
334 			break;
335 		}
336 
337 		sign = 1;
338 		if (l < 0)
339 			sign *= -1;
340 		if (r < 0)
341 			sign *= -1;
342 
343 		res = l * r;
344 		/*
345 		 * XXX: not the most portable but works on anything with 2's
346 		 * complement arithmetic. If the signs don't match or the
347 		 * result was 0 on 2's complement this overflowed.
348 		 */
349 		if ((res < 0 && sign > 0) || (res > 0 && sign < 0) ||
350 		    (res == 0))
351 			yyerror("integer overflow or underflow occurred for "
352 			    "operation '%s %s %s'", left, op, right);
353 			/* NOTREACHED */
354 		break;
355 	}
356 	return res;
357 }
358 
359 static const char *x = "|&=<>+-*/%:()";
360 static const int x_token[] = {
361 	SPEC_OR, SPEC_AND, COMPARE, COMPARE, COMPARE, ADD_SUB_OPERATOR,
362 	ADD_SUB_OPERATOR, MUL_DIV_MOD_OPERATOR, MUL_DIV_MOD_OPERATOR,
363 	MUL_DIV_MOD_OPERATOR, SPEC_REG, LEFT_PARENT, RIGHT_PARENT
364 };
365 
366 static int handle_ddash = 1;
367 
368 int
369 yylex(void)
370 {
371 	const char *p = *av++;
372 	int retval;
373 
374 	if (!p)
375 		retval = 0;
376 	else if (p[1] == '\0') {
377 		const char *w = strchr(x, p[0]);
378 		if (w) {
379 			retval = x_token[w-x];
380 		} else {
381 			retval = STRING;
382 		}
383 	} else if (p[1] == '=' && p[2] == '\0'
384 			&& (p[0] == '>' || p[0] == '<' || p[0] == '!'))
385 		retval = COMPARE;
386 	else if (handle_ddash && p[0] == '-' && p[1] == '-' && p[2] == '\0') {
387 		/* ignore "--" if passed as first argument and isn't followed
388 		 * by another STRING */
389 		retval = yylex();
390 		if (retval != STRING && retval != LEFT_PARENT
391 		    && retval != RIGHT_PARENT) {
392 			/* is not followed by string or parenthesis, use as
393 			 * STRING */
394 			retval = STRING;
395 			av--;	/* was increased in call to yylex() above */
396 			p = "--";
397 		} else {
398 			/* "--" is to be ignored */
399 			p = yylval;
400 		}
401 	} else
402 		retval = STRING;
403 
404 	handle_ddash = 0;
405 	yylval = p;
406 
407 	return retval;
408 }
409 
410 /*
411  * Print error message and exit with error 2 (syntax error).
412  */
413 static void
414 yyerror(const char *fmt, ...)
415 {
416 	va_list arg;
417 
418 	va_start(arg, fmt);
419 	verrx(2, fmt, arg);
420 	va_end(arg);
421 }
422 
423 int
424 main(int argc, const char * const *argv)
425 {
426 	(void) setlocale(LC_ALL, "");
427 
428 	if (argc == 1) {
429 		(void) fprintf(stderr, "usage: expr expression\n");
430 		exit(2);
431 	}
432 
433 	av = argv + 1;
434 
435 	exit(yyparse());
436 	/* NOTREACHED */
437 }
438