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