Home | History | Annotate | Line # | Download | only in expr
expr.y revision 1.22
      1 /* $NetBSD: expr.y,v 1.22 2000/10/29 17:16:02 thorpej 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.22 2000/10/29 17:16:02 thorpej 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 const char **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 int yyparse(void);
     62 
     63 #define YYSTYPE	const char *
     64 
     65 %}
     66 %token STRING
     67 %left SPEC_OR
     68 %left SPEC_AND
     69 %left COMPARE ARITH_OPERATOR SPEC_REG
     70 %left LEFT_PARENT RIGHT_PARENT
     71 
     72 %%
     73 
     74 exp:	expr = {
     75 		(void) printf("%s\n", $1);
     76 		return (is_zero_or_null($1));
     77 		}
     78 	;
     79 
     80 expr:	item	{ $$ = $1; }
     81 	| expr SPEC_OR expr = {
     82 		/*
     83 		 * Return evaluation of first expression if it is neither
     84 		 * an empty string nor zero; otherwise, returns the evaluation
     85 		 * of second expression.
     86 		 */
     87 		if (!is_zero_or_null($1))
     88 			$$ = $1;
     89 		else
     90 			$$ = $3;
     91 		}
     92 	| expr SPEC_AND expr = {
     93 		/*
     94 		 * Returns the evaluation of first expr if neither expression
     95 		 * evaluates to an empty string or zero; otherwise, returns
     96 		 * zero.
     97 		 */
     98 		if (!is_zero_or_null($1) && !is_zero_or_null($3))
     99 			$$ = $1;
    100 		else
    101 			$$ = "0";
    102 		}
    103 	| expr SPEC_REG expr = {
    104 		/*
    105 		 * The ``:'' operator matches first expr against the second,
    106 		 * which must be a regular expression.
    107 		 */
    108 		regex_t rp;
    109 		regmatch_t rm[2];
    110 		int eval;
    111 
    112 		/* compile regular expression */
    113 		if ((eval = regcomp(&rp, $3, 0)) != 0) {
    114 			char errbuf[256];
    115 			(void)regerror(eval, &rp, errbuf, sizeof(errbuf));
    116 			yyerror("%s", errbuf);
    117 			/* NOT REACHED */
    118 		}
    119 
    120 		/* compare string against pattern --  remember that patterns
    121 		   are anchored to the beginning of the line */
    122 		if (regexec(&rp, $1, 2, rm, 0) == 0 && rm[0].rm_so == 0) {
    123 			char *val;
    124 			if (rm[1].rm_so >= 0) {
    125 				(void) asprintf(&val, "%.*s",
    126 					(int) (rm[1].rm_eo - rm[1].rm_so),
    127 					$1 + rm[1].rm_so);
    128 			} else {
    129 				(void) asprintf(&val, "%d",
    130 					(int)(rm[0].rm_eo - rm[0].rm_so));
    131 			}
    132 			$$ = val;
    133 		} else {
    134 			if (rp.re_nsub == 0) {
    135 				$$ = "0";
    136 			} else {
    137 				$$ = "";
    138 			}
    139 		}
    140 
    141 		}
    142 	| expr ARITH_OPERATOR expr = {
    143 		/*
    144 		 * Returns the results of multiplication, division,
    145 		 * addition, subtraction, remainder of numeric-valued arguments.
    146 		 */
    147 		char *val;
    148 		int64_t res, l, r;
    149 
    150 		if (!is_integer($1)) {
    151 			yyerror("non-integer argument '%s'", $1);
    152 			/* NOTREACHED */
    153 		}
    154 		if (!is_integer($3)) {
    155 			yyerror("non-integer argument '%s'", $3);
    156 			/* NOTREACHED */
    157 		}
    158 
    159 		errno = 0;
    160 		l = strtoll($1, NULL, 10);
    161 		if (errno == ERANGE) {
    162 			yyerror("value '%s' is %s is %lld", $1,
    163 				(l > 0)
    164 				? "too big, maximum" : "too small, minimum",
    165 				(l > 0) ? LLONG_MAX : LLONG_MIN
    166 			);
    167 			/* NOTREACHED */
    168 		}
    169 
    170 		errno = 0;
    171 		r = strtoll($3, NULL, 10);
    172 		if (errno == ERANGE) {
    173 			yyerror("value '%s' is %s is %lld", $3,
    174 				(l > 0)
    175 				? "too big, maximum" : "too small, minimum",
    176 				(l > 0) ? LLONG_MAX : LLONG_MIN
    177 			);
    178 			/* NOTREACHED */
    179 		}
    180 
    181 		switch($2[0]) {
    182 		case '+':
    183 			res = l + r;
    184 			/* very simplistic check for over-& underflow */
    185 			if ((res < 0 && l > 0 && r > 0 && l > r)
    186 				|| (res > 0 && l < 0 && r < 0 && l < r)) {
    187 				yyerror("integer overflow or underflow occured\
    188  for operation '%s %s %s'", $1, $2, $3);
    189 				/* NOTREACHED */
    190 			}
    191 			break;
    192 		case '-':
    193 			res = l - r;
    194 			/* very simplistic check for over-& underflow */
    195 			if ((res < 0 && l > 0 && l > r)
    196 				|| (res > 0 && l < 0 && l < r) ) {
    197 				yyerror("integer overflow or underflow occured\
    198  for operation '%s %s %s'", $1, $2, $3);
    199 				/* NOTREACHED */
    200 			}
    201 			break;
    202 		case '/':
    203 			if (r == 0) {
    204 				yyerror("second argument to '%s' must not be\
    205  zero", $2);
    206 				/* NOTREACHED */
    207 			}
    208 			res = l / r;
    209 
    210 			break;
    211 		case '%':
    212 			if (r == 0) {
    213 				yyerror("second argument to '%s' must not be zero", $2);
    214 				/* NOTREACHED */
    215 			}
    216 			res = l % r;
    217 			break;
    218 		case '*':
    219 			if (r == 0) {
    220 				res = 0;
    221 				break;
    222 			}
    223 
    224 			/* check if the result would over- or underflow */
    225 			if ((l > 0 && l > (LLONG_MAX / r))
    226 				|| (l < 0 && l < (LLONG_MIN / r))) {
    227 				yyerror("operation '%s %s %s' would cause over-\
    228  or underflow",
    229 					$1, $2, $3);
    230 				/* NOTREACHED */
    231 			}
    232 
    233 			res = l * r;
    234 			break;
    235 		}
    236 
    237 		(void) asprintf(&val, "%lld", (long long int) res);
    238 		$$ = val;
    239 
    240 		}
    241 	| expr COMPARE expr = {
    242 		/*
    243 		 * Returns the results of integer comparison if both arguments
    244 		 * are integers; otherwise, returns the results of string
    245 		 * comparison using the locale-specific collation sequence.
    246 		 * The result of each comparison is 1 if the specified relation
    247 		 * is true, or 0 if the relation is false.
    248 		 */
    249 
    250 		int64_t l, r;
    251 		int res;
    252 
    253 		/*
    254 		 * Slight hack to avoid differences in the compare code
    255 		 * between string and numeric compare.
    256 		 */
    257 		if (is_integer($1) && is_integer($3)) {
    258 			/* numeric comparison */
    259 			l = strtoll($1, NULL, 10);
    260 			r = strtoll($3, NULL, 10);
    261 		} else {
    262 			/* string comparison */
    263 			l = strcoll($1, $3);
    264 			r = 0;
    265 		}
    266 
    267 		switch($2[0]) {
    268 		case '=': /* equal */
    269 			res = (l == r);
    270 			break;
    271 		case '>': /* greater or greater-equal */
    272 			if ($2[1] == '=')
    273 				res = (l >= r);
    274 			else
    275 				res = (l > r);
    276 			break;
    277 		case '<': /* lower or lower-equal */
    278 			if ($2[1] == '=')
    279 				res = (l <= r);
    280 			else
    281 				res = (l < r);
    282 			break;
    283 		case '!': /* not equal */
    284 			/* the check if this is != was done in yylex() */
    285 			res = (l != r);
    286 		}
    287 
    288 		$$ = (res) ? "1" : "0";
    289 
    290 		}
    291 	| LEFT_PARENT expr RIGHT_PARENT { $$ = $2; }
    292 	;
    293 
    294 item:	STRING
    295 	| ARITH_OPERATOR
    296 	| COMPARE
    297 	| SPEC_OR
    298 	| SPEC_AND
    299 	| SPEC_REG
    300 	;
    301 %%
    302 
    303 /*
    304  * Returns 1 if the string is empty or contains only numeric zero.
    305  */
    306 static int
    307 is_zero_or_null(const char *str)
    308 {
    309 	char *endptr;
    310 
    311 	return str[0] == '\0'
    312 		|| ( strtoll(str, &endptr, 10) == 0LL
    313 			&& endptr[0] == '\0');
    314 }
    315 
    316 /*
    317  * Returns 1 if the string is an integer.
    318  */
    319 static int
    320 is_integer(const char *str)
    321 {
    322 	char *endptr;
    323 
    324 	(void) strtoll(str, &endptr, 10);
    325 	/* note we treat empty string as valid number */
    326 	return (endptr[0] == '\0');
    327 }
    328 
    329 
    330 const char *x = "|&=<>+-*/%:()";
    331 const int x_token[] = {
    332 	SPEC_OR, SPEC_AND, COMPARE, COMPARE, COMPARE, ARITH_OPERATOR,
    333 	ARITH_OPERATOR, ARITH_OPERATOR, ARITH_OPERATOR, ARITH_OPERATOR,
    334 	SPEC_REG, LEFT_PARENT, RIGHT_PARENT
    335 };
    336 
    337 int
    338 yylex(void)
    339 {
    340 	const char *p = *av++;
    341 	int retval = 0;
    342 
    343 	if (!p) {
    344 		return 0;
    345 	}
    346 
    347 	if (p[1] == '\0') {
    348 		const char *w = strchr(x, p[0]);
    349 		if (w) {
    350 			retval = x_token[w-x];
    351 		} else {
    352 			retval = STRING;
    353 		}
    354 	} else if (p[1] == '=' && p[2] == '\0'
    355 			&& (p[0] == '>' || p[0] == '<' || p[0] == '!'))
    356 		retval = COMPARE;
    357 	else
    358 		retval = STRING;
    359 
    360 	yylval = p;
    361 
    362 	return retval;
    363 }
    364 
    365 /*
    366  * Print error message and exit with error 2 (syntax error).
    367  */
    368 static void
    369 yyerror(const char *fmt, ...)
    370 {
    371 	va_list arg;
    372 
    373 	va_start(arg, fmt);
    374 	verrx(2, fmt, arg);
    375 	va_end(arg);
    376 }
    377 
    378 int
    379 main(int argc, const char **argv)
    380 {
    381 	(void) setlocale(LC_ALL, "");
    382 
    383 	if (argc == 1) {
    384 		(void) fprintf(stderr, "usage: expr expression\n");
    385 		exit(2);
    386 	}
    387 
    388 	av = argv + 1;
    389 
    390 	exit(yyparse());
    391 	/* NOTREACHED */
    392 }
    393