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