Home | History | Annotate | Line # | Download | only in expr
expr.y revision 1.32
      1 /* $NetBSD: expr.y,v 1.32 2005/06/01 15:21:52 lukem 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 (at) NetBSD.org> and J.T. Conklin <jtc (at) 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.32 2005/06/01 15:21:52 lukem 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 		res = 0;
    185 
    186 		/*
    187 		 * Slight hack to avoid differences in the compare code
    188 		 * between string and numeric compare.
    189 		 */
    190 		if (is_integer($1) && is_integer($3)) {
    191 			/* numeric comparison */
    192 			l = strtoll($1, NULL, 10);
    193 			r = strtoll($3, NULL, 10);
    194 		} else {
    195 			/* string comparison */
    196 			l = strcoll($1, $3);
    197 			r = 0;
    198 		}
    199 
    200 		switch($2[0]) {
    201 		case '=': /* equal */
    202 			res = (l == r);
    203 			break;
    204 		case '>': /* greater or greater-equal */
    205 			if ($2[1] == '=')
    206 				res = (l >= r);
    207 			else
    208 				res = (l > r);
    209 			break;
    210 		case '<': /* lower or lower-equal */
    211 			if ($2[1] == '=')
    212 				res = (l <= r);
    213 			else
    214 				res = (l < r);
    215 			break;
    216 		case '!': /* not equal */
    217 			/* the check if this is != was done in yylex() */
    218 			res = (l != r);
    219 		}
    220 
    221 		$$ = (res) ? "1" : "0";
    222 
    223 		}
    224 	| LEFT_PARENT expr RIGHT_PARENT { $$ = $2; }
    225 	| LENGTH expr {
    226 		/*
    227 		 * Return length of 'expr' in bytes.
    228 		 */
    229 		char *ln;
    230 
    231 		asprintf(&ln, "%ld", (long) strlen($2));
    232 		$$ = ln;
    233 		}
    234 	;
    235 
    236 item:	STRING
    237 	| ADD_SUB_OPERATOR
    238 	| MUL_DIV_MOD_OPERATOR
    239 	| COMPARE
    240 	| SPEC_OR
    241 	| SPEC_AND
    242 	| SPEC_REG
    243 	| LENGTH
    244 	;
    245 %%
    246 
    247 /*
    248  * Returns 1 if the string is empty or contains only numeric zero.
    249  */
    250 static int
    251 is_zero_or_null(const char *str)
    252 {
    253 	char *endptr;
    254 
    255 	return str[0] == '\0'
    256 		|| ( strtoll(str, &endptr, 10) == 0LL
    257 			&& endptr[0] == '\0');
    258 }
    259 
    260 /*
    261  * Returns 1 if the string is an integer.
    262  */
    263 static int
    264 is_integer(const char *str)
    265 {
    266 	char *endptr;
    267 
    268 	(void) strtoll(str, &endptr, 10);
    269 	/* note we treat empty string as valid number */
    270 	return (endptr[0] == '\0');
    271 }
    272 
    273 static int64_t
    274 perform_arith_op(const char *left, const char *op, const char *right)
    275 {
    276 	int64_t res, sign, l, r;
    277 	u_int64_t temp;
    278 
    279 	res = 0;
    280 
    281 	if (!is_integer(left)) {
    282 		yyerror("non-integer argument '%s'", left);
    283 		/* NOTREACHED */
    284 	}
    285 	if (!is_integer(right)) {
    286 		yyerror("non-integer argument '%s'", right);
    287 		/* NOTREACHED */
    288 	}
    289 
    290 	errno = 0;
    291 	l = strtoll(left, NULL, 10);
    292 	if (errno == ERANGE) {
    293 		yyerror("value '%s' is %s is %lld", left,
    294 		    (l > 0) ? "too big, maximum" : "too small, minimum",
    295 		    (l > 0) ? LLONG_MAX : LLONG_MIN);
    296 		/* NOTREACHED */
    297 	}
    298 
    299 	errno = 0;
    300 	r = strtoll(right, NULL, 10);
    301 	if (errno == ERANGE) {
    302 		yyerror("value '%s' is %s is %lld", right,
    303 		    (l > 0) ? "too big, maximum" : "too small, minimum",
    304 	  	    (l > 0) ? LLONG_MAX : LLONG_MIN);
    305 		/* NOTREACHED */
    306 	}
    307 
    308 	switch(op[0]) {
    309 	case '+':
    310 		/*
    311 		 * Do the op into an unsigned to avoid overflow and then cast
    312 		 * back to check the resulting signage.
    313 		 */
    314 		temp = l + r;
    315 		res = (int64_t) temp;
    316 		/* very simplistic check for over-& underflow */
    317 		if ((res < 0 && l > 0 && r > 0)
    318 	  	    || (res > 0 && l < 0 && r < 0))
    319 			yyerror("integer overflow or underflow occurred for "
    320                             "operation '%s %s %s'", left, op, right);
    321 		break;
    322 	case '-':
    323 		/*
    324 		 * Do the op into an unsigned to avoid overflow and then cast
    325 		 * back to check the resulting signage.
    326 		 */
    327 		temp = l - r;
    328 		res = (int64_t) temp;
    329 		/* very simplistic check for over-& underflow */
    330 		if ((res < 0 && l > 0 && l > r)
    331 		    || (res > 0 && l < 0 && l < r) )
    332 			yyerror("integer overflow or underflow occurred for "
    333 			    "operation '%s %s %s'", left, op, right);
    334 		break;
    335 	case '/':
    336 		if (r == 0)
    337 			yyerror("second argument to '%s' must not be zero", op);
    338 		res = l / r;
    339 
    340 		break;
    341 	case '%':
    342 		if (r == 0)
    343 			yyerror("second argument to '%s' must not be zero", op);
    344 		res = l % r;
    345 		break;
    346 	case '*':
    347 		/* shortcut */
    348 		if ((l == 0) || (r == 0)) {
    349 			res = 0;
    350 			break;
    351 		}
    352 
    353 		sign = 1;
    354 		if (l < 0)
    355 			sign *= -1;
    356 		if (r < 0)
    357 			sign *= -1;
    358 
    359 		res = l * r;
    360 		/*
    361 		 * XXX: not the most portable but works on anything with 2's
    362 		 * complement arithmetic. If the signs don't match or the
    363 		 * result was 0 on 2's complement this overflowed.
    364 		 */
    365 		if ((res < 0 && sign > 0) || (res > 0 && sign < 0) ||
    366 		    (res == 0))
    367 			yyerror("integer overflow or underflow occurred for "
    368 			    "operation '%s %s %s'", left, op, right);
    369 			/* NOTREACHED */
    370 		break;
    371 	}
    372 	return res;
    373 }
    374 
    375 static const char *x = "|&=<>+-*/%:()";
    376 static const int x_token[] = {
    377 	SPEC_OR, SPEC_AND, COMPARE, COMPARE, COMPARE, ADD_SUB_OPERATOR,
    378 	ADD_SUB_OPERATOR, MUL_DIV_MOD_OPERATOR, MUL_DIV_MOD_OPERATOR,
    379 	MUL_DIV_MOD_OPERATOR, SPEC_REG, LEFT_PARENT, RIGHT_PARENT
    380 };
    381 
    382 static int handle_ddash = 1;
    383 
    384 int
    385 yylex(void)
    386 {
    387 	const char *p = *av++;
    388 	int retval;
    389 
    390 	if (!p)
    391 		retval = 0;
    392 	else if (p[1] == '\0') {
    393 		const char *w = strchr(x, p[0]);
    394 		if (w) {
    395 			retval = x_token[w-x];
    396 		} else {
    397 			retval = STRING;
    398 		}
    399 	} else if (p[1] == '=' && p[2] == '\0'
    400 			&& (p[0] == '>' || p[0] == '<' || p[0] == '!'))
    401 		retval = COMPARE;
    402 	else if (handle_ddash && p[0] == '-' && p[1] == '-' && p[2] == '\0') {
    403 		/* ignore "--" if passed as first argument and isn't followed
    404 		 * by another STRING */
    405 		retval = yylex();
    406 		if (retval != STRING && retval != LEFT_PARENT
    407 		    && retval != RIGHT_PARENT) {
    408 			/* is not followed by string or parenthesis, use as
    409 			 * STRING */
    410 			retval = STRING;
    411 			av--;	/* was increased in call to yylex() above */
    412 			p = "--";
    413 		} else {
    414 			/* "--" is to be ignored */
    415 			p = yylval;
    416 		}
    417 	} else if (strcmp(p, "length") == 0)
    418 		retval = LENGTH;
    419 	else
    420 		retval = STRING;
    421 
    422 	handle_ddash = 0;
    423 	yylval = p;
    424 
    425 	return retval;
    426 }
    427 
    428 /*
    429  * Print error message and exit with error 2 (syntax error).
    430  */
    431 static void
    432 yyerror(const char *fmt, ...)
    433 {
    434 	va_list arg;
    435 
    436 	va_start(arg, fmt);
    437 	verrx(2, fmt, arg);
    438 	va_end(arg);
    439 }
    440 
    441 int
    442 main(int argc, const char * const *argv)
    443 {
    444 	setprogname(argv[0]);
    445 	(void)setlocale(LC_ALL, "");
    446 
    447 	if (argc == 1) {
    448 		(void)fprintf(stderr, "usage: %s expression\n",
    449 		    getprogname());
    450 		exit(2);
    451 	}
    452 
    453 	av = argv + 1;
    454 
    455 	exit(yyparse());
    456 	/* NOTREACHED */
    457 }
    458