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