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