xref: /netbsd-src/bin/expr/expr.y (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /* $NetBSD: expr.y,v 1.31 2004/04/20 19:44:51 jdolecek 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.31 2004/04/20 19:44:51 jdolecek Exp $");
42 #endif /* not lint */
43 
44 #include <sys/types.h>
45 
46 #include <err.h>
47 #include <errno.h>
48 #include <limits.h>
49 #include <locale.h>
50 #include <regex.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 
56 static const char * const *av;
57 
58 static void yyerror(const char *, ...);
59 static int yylex(void);
60 static int is_zero_or_null(const char *);
61 static int is_integer(const char *);
62 static int64_t perform_arith_op(const char *, const char *, const char *);
63 
64 int main(int, const char * const *);
65 
66 #define YYSTYPE	const char *
67 
68 %}
69 %token STRING
70 %left SPEC_OR
71 %left SPEC_AND
72 %left COMPARE
73 %left ADD_SUB_OPERATOR
74 %left MUL_DIV_MOD_OPERATOR
75 %left SPEC_REG
76 %left LENGTH
77 %left LEFT_PARENT RIGHT_PARENT
78 
79 %%
80 
81 exp:	expr = {
82 		(void) printf("%s\n", $1);
83 		return (is_zero_or_null($1));
84 		}
85 	;
86 
87 expr:	item { $$ = $1; }
88 	| expr SPEC_OR expr = {
89 		/*
90 		 * Return evaluation of first expression if it is neither
91 		 * an empty string nor zero; otherwise, returns the evaluation
92 		 * of second expression.
93 		 */
94 		if (!is_zero_or_null($1))
95 			$$ = $1;
96 		else
97 			$$ = $3;
98 		}
99 	| expr SPEC_AND expr = {
100 		/*
101 		 * Returns the evaluation of first expr if neither expression
102 		 * evaluates to an empty string or zero; otherwise, returns
103 		 * zero.
104 		 */
105 		if (!is_zero_or_null($1) && !is_zero_or_null($3))
106 			$$ = $1;
107 		else
108 			$$ = "0";
109 		}
110 	| expr SPEC_REG expr = {
111 		/*
112 		 * The ``:'' operator matches first expr against the second,
113 		 * which must be a regular expression.
114 		 */
115 		regex_t rp;
116 		regmatch_t rm[2];
117 		int eval;
118 
119 		/* compile regular expression */
120 		if ((eval = regcomp(&rp, $3, REG_BASIC)) != 0) {
121 			char errbuf[256];
122 			(void)regerror(eval, &rp, errbuf, sizeof(errbuf));
123 			yyerror("%s", errbuf);
124 			/* NOT REACHED */
125 		}
126 
127 		/* compare string against pattern --  remember that patterns
128 		   are anchored to the beginning of the line */
129 		if (regexec(&rp, $1, 2, rm, 0) == 0 && rm[0].rm_so == 0) {
130 			char *val;
131 			if (rm[1].rm_so >= 0) {
132 				(void) asprintf(&val, "%.*s",
133 					(int) (rm[1].rm_eo - rm[1].rm_so),
134 					$1 + rm[1].rm_so);
135 			} else {
136 				(void) asprintf(&val, "%d",
137 					(int)(rm[0].rm_eo - rm[0].rm_so));
138 			}
139 			$$ = val;
140 		} else {
141 			if (rp.re_nsub == 0) {
142 				$$ = "0";
143 			} else {
144 				$$ = "";
145 			}
146 		}
147 
148 		}
149 	| expr ADD_SUB_OPERATOR expr = {
150 		/* Returns the results of addition, subtraction */
151 		char *val;
152 		int64_t res;
153 
154 		res = perform_arith_op($1, $2, $3);
155 		(void) asprintf(&val, "%lld", (long long int) res);
156 		$$ = val;
157                 }
158 
159 	| expr MUL_DIV_MOD_OPERATOR expr = {
160 		/*
161 		 * Returns the results of multiply, divide or remainder of
162 		 * numeric-valued arguments.
163 		 */
164 		char *val;
165 		int64_t res;
166 
167 		res = perform_arith_op($1, $2, $3);
168 		(void) asprintf(&val, "%lld", (long long int) res);
169 		$$ = val;
170 
171 		}
172 	| expr COMPARE expr = {
173 		/*
174 		 * Returns the results of integer comparison if both arguments
175 		 * are integers; otherwise, returns the results of string
176 		 * comparison using the locale-specific collation sequence.
177 		 * The result of each comparison is 1 if the specified relation
178 		 * is true, or 0 if the relation is false.
179 		 */
180 
181 		int64_t l, r;
182 		int res;
183 
184 		/*
185 		 * Slight hack to avoid differences in the compare code
186 		 * between string and numeric compare.
187 		 */
188 		if (is_integer($1) && is_integer($3)) {
189 			/* numeric comparison */
190 			l = strtoll($1, NULL, 10);
191 			r = strtoll($3, NULL, 10);
192 		} else {
193 			/* string comparison */
194 			l = strcoll($1, $3);
195 			r = 0;
196 		}
197 
198 		switch($2[0]) {
199 		case '=': /* equal */
200 			res = (l == r);
201 			break;
202 		case '>': /* greater or greater-equal */
203 			if ($2[1] == '=')
204 				res = (l >= r);
205 			else
206 				res = (l > r);
207 			break;
208 		case '<': /* lower or lower-equal */
209 			if ($2[1] == '=')
210 				res = (l <= r);
211 			else
212 				res = (l < r);
213 			break;
214 		case '!': /* not equal */
215 			/* the check if this is != was done in yylex() */
216 			res = (l != r);
217 		}
218 
219 		$$ = (res) ? "1" : "0";
220 
221 		}
222 	| LEFT_PARENT expr RIGHT_PARENT { $$ = $2; }
223 	| LENGTH expr {
224 		/*
225 		 * Return length of 'expr' in bytes.
226 		 */
227 		char *ln;
228 
229 		asprintf(&ln, "%ld", (long) strlen($2));
230 		$$ = ln;
231 		}
232 	;
233 
234 item:	STRING
235 	| ADD_SUB_OPERATOR
236 	| MUL_DIV_MOD_OPERATOR
237 	| COMPARE
238 	| SPEC_OR
239 	| SPEC_AND
240 	| SPEC_REG
241 	| LENGTH
242 	;
243 %%
244 
245 /*
246  * Returns 1 if the string is empty or contains only numeric zero.
247  */
248 static int
249 is_zero_or_null(const char *str)
250 {
251 	char *endptr;
252 
253 	return str[0] == '\0'
254 		|| ( strtoll(str, &endptr, 10) == 0LL
255 			&& endptr[0] == '\0');
256 }
257 
258 /*
259  * Returns 1 if the string is an integer.
260  */
261 static int
262 is_integer(const char *str)
263 {
264 	char *endptr;
265 
266 	(void) strtoll(str, &endptr, 10);
267 	/* note we treat empty string as valid number */
268 	return (endptr[0] == '\0');
269 }
270 
271 static int64_t
272 perform_arith_op(const char *left, const char *op, const char *right)
273 {
274 	int64_t res, sign, l, r;
275 	u_int64_t temp;
276 
277 	if (!is_integer(left)) {
278 		yyerror("non-integer argument '%s'", left);
279 		/* NOTREACHED */
280 	}
281 	if (!is_integer(right)) {
282 		yyerror("non-integer argument '%s'", right);
283 		/* NOTREACHED */
284 	}
285 
286 	errno = 0;
287 	l = strtoll(left, NULL, 10);
288 	if (errno == ERANGE) {
289 		yyerror("value '%s' is %s is %lld", left,
290 		    (l > 0) ? "too big, maximum" : "too small, minimum",
291 		    (l > 0) ? LLONG_MAX : LLONG_MIN);
292 		/* NOTREACHED */
293 	}
294 
295 	errno = 0;
296 	r = strtoll(right, NULL, 10);
297 	if (errno == ERANGE) {
298 		yyerror("value '%s' is %s is %lld", right,
299 		    (l > 0) ? "too big, maximum" : "too small, minimum",
300 	  	    (l > 0) ? LLONG_MAX : LLONG_MIN);
301 		/* NOTREACHED */
302 	}
303 
304 	switch(op[0]) {
305 	case '+':
306 		/*
307 		 * Do the op into an unsigned to avoid overflow and then cast
308 		 * back to check the resulting signage.
309 		 */
310 		temp = l + r;
311 		res = (int64_t) temp;
312 		/* very simplistic check for over-& underflow */
313 		if ((res < 0 && l > 0 && r > 0)
314 	  	    || (res > 0 && l < 0 && r < 0))
315 			yyerror("integer overflow or underflow occurred for "
316                             "operation '%s %s %s'", left, op, right);
317 		break;
318 	case '-':
319 		/*
320 		 * Do the op into an unsigned to avoid overflow and then cast
321 		 * back to check the resulting signage.
322 		 */
323 		temp = l - r;
324 		res = (int64_t) temp;
325 		/* very simplistic check for over-& underflow */
326 		if ((res < 0 && l > 0 && l > r)
327 		    || (res > 0 && l < 0 && l < r) )
328 			yyerror("integer overflow or underflow occurred for "
329 			    "operation '%s %s %s'", left, op, right);
330 		break;
331 	case '/':
332 		if (r == 0)
333 			yyerror("second argument to '%s' must not be zero", op);
334 		res = l / r;
335 
336 		break;
337 	case '%':
338 		if (r == 0)
339 			yyerror("second argument to '%s' must not be zero", op);
340 		res = l % r;
341 		break;
342 	case '*':
343 		/* shortcut */
344 		if ((l == 0) || (r == 0)) {
345 			res = 0;
346 			break;
347 		}
348 
349 		sign = 1;
350 		if (l < 0)
351 			sign *= -1;
352 		if (r < 0)
353 			sign *= -1;
354 
355 		res = l * r;
356 		/*
357 		 * XXX: not the most portable but works on anything with 2's
358 		 * complement arithmetic. If the signs don't match or the
359 		 * result was 0 on 2's complement this overflowed.
360 		 */
361 		if ((res < 0 && sign > 0) || (res > 0 && sign < 0) ||
362 		    (res == 0))
363 			yyerror("integer overflow or underflow occurred for "
364 			    "operation '%s %s %s'", left, op, right);
365 			/* NOTREACHED */
366 		break;
367 	}
368 	return res;
369 }
370 
371 static const char *x = "|&=<>+-*/%:()";
372 static const int x_token[] = {
373 	SPEC_OR, SPEC_AND, COMPARE, COMPARE, COMPARE, ADD_SUB_OPERATOR,
374 	ADD_SUB_OPERATOR, MUL_DIV_MOD_OPERATOR, MUL_DIV_MOD_OPERATOR,
375 	MUL_DIV_MOD_OPERATOR, SPEC_REG, LEFT_PARENT, RIGHT_PARENT
376 };
377 
378 static int handle_ddash = 1;
379 
380 int
381 yylex(void)
382 {
383 	const char *p = *av++;
384 	int retval;
385 
386 	if (!p)
387 		retval = 0;
388 	else if (p[1] == '\0') {
389 		const char *w = strchr(x, p[0]);
390 		if (w) {
391 			retval = x_token[w-x];
392 		} else {
393 			retval = STRING;
394 		}
395 	} else if (p[1] == '=' && p[2] == '\0'
396 			&& (p[0] == '>' || p[0] == '<' || p[0] == '!'))
397 		retval = COMPARE;
398 	else if (handle_ddash && p[0] == '-' && p[1] == '-' && p[2] == '\0') {
399 		/* ignore "--" if passed as first argument and isn't followed
400 		 * by another STRING */
401 		retval = yylex();
402 		if (retval != STRING && retval != LEFT_PARENT
403 		    && retval != RIGHT_PARENT) {
404 			/* is not followed by string or parenthesis, use as
405 			 * STRING */
406 			retval = STRING;
407 			av--;	/* was increased in call to yylex() above */
408 			p = "--";
409 		} else {
410 			/* "--" is to be ignored */
411 			p = yylval;
412 		}
413 	} else if (strcmp(p, "length") == 0)
414 		retval = LENGTH;
415 	else
416 		retval = STRING;
417 
418 	handle_ddash = 0;
419 	yylval = p;
420 
421 	return retval;
422 }
423 
424 /*
425  * Print error message and exit with error 2 (syntax error).
426  */
427 static void
428 yyerror(const char *fmt, ...)
429 {
430 	va_list arg;
431 
432 	va_start(arg, fmt);
433 	verrx(2, fmt, arg);
434 	va_end(arg);
435 }
436 
437 int
438 main(int argc, const char * const *argv)
439 {
440 	setprogname(argv[0]);
441 	(void)setlocale(LC_ALL, "");
442 
443 	if (argc == 1) {
444 		(void)fprintf(stderr, "usage: %s expression\n",
445 		    getprogname());
446 		exit(2);
447 	}
448 
449 	av = argv + 1;
450 
451 	exit(yyparse());
452 	/* NOTREACHED */
453 }
454