Home | History | Annotate | Line # | Download | only in expr
expr.y revision 1.51
      1 /* $NetBSD: expr.y,v 1.51 2025/03/15 14:26:16 rillig Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2000, 2025 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>, J.T. Conklin <jtc (at) NetBSD.org>
      9  * and Roland Illig <rillig (at) NetBSD.org>.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 %{
     34 #include <sys/cdefs.h>
     35 __RCSID("$NetBSD: expr.y,v 1.51 2025/03/15 14:26:16 rillig Exp $");
     36 
     37 #include <sys/types.h>
     38 
     39 #include <err.h>
     40 #include <errno.h>
     41 #include <limits.h>
     42 #include <locale.h>
     43 #include <regex.h>
     44 #include <stdarg.h>
     45 #include <stdio.h>
     46 #include <stdlib.h>
     47 #include <string.h>
     48 
     49 static const char * const *av;
     50 static unsigned skip_level;
     51 
     52 static void yyerror(const char *, ...) __dead;
     53 static int yylex(void);
     54 static int is_empty_or_zero(const char *);
     55 static int is_integer(const char *);
     56 static const char *eval_arith(const char *, const char *, const char *);
     57 static int eval_compare(const char *, const char *, const char *);
     58 static const char *eval_match(const char *, const char *);
     59 
     60 #define YYSTYPE	const char *
     61 
     62 %}
     63 
     64 %expect 0
     65 
     66 %token STRING LPAREN RPAREN
     67 %left SPEC_OR
     68 %left SPEC_AND
     69 %left COMPARE
     70 %left ADD_SUB_OPERATOR
     71 %left MUL_DIV_MOD_OPERATOR
     72 %left SPEC_REG
     73 %left LENGTH
     74 
     75 %%
     76 
     77 exp:	expr {
     78 		(void)printf("%s\n", $1);
     79 		return is_empty_or_zero($1);
     80 	}
     81 ;
     82 
     83 expr:	item
     84 |	expr SPEC_OR {
     85 		$$ = is_empty_or_zero($1) ? NULL : "1";
     86 		if ($$)
     87 			skip_level++;
     88 	} expr {
     89 		$$ = $3 ? $1 : $4;
     90 		if ($3)
     91 			skip_level--;
     92 	}
     93 |	expr SPEC_AND {
     94 		$$ = is_empty_or_zero($1) ? NULL : "1";
     95 		if (!$$)
     96 			skip_level++;
     97 	} expr {
     98 		$$ = $3 && !is_empty_or_zero($4) ? $1 : "0";
     99 		if (!$3)
    100 			skip_level--;
    101 	}
    102 |	expr SPEC_REG expr {
    103 		$$ = skip_level == 0 ? eval_match($1, $3) : "";
    104 	}
    105 |	expr ADD_SUB_OPERATOR expr {
    106 		$$ = skip_level == 0 ? eval_arith($1, $2, $3) : "";
    107 	}
    108 |	expr MUL_DIV_MOD_OPERATOR expr {
    109 		$$ = skip_level == 0 ? eval_arith($1, $2, $3) : "";
    110 	}
    111 |	expr COMPARE expr {
    112 		$$ = skip_level == 0 && eval_compare($1, $2, $3) ? "1" : "0";
    113 	}
    114 |	LPAREN expr RPAREN {
    115 		$$ = $2;
    116 	}
    117 |	LENGTH expr {
    118 		char *ln;
    119 
    120 		asprintf(&ln, "%ld", (long)strlen($2));
    121 		if (ln == NULL)
    122 			err(1, NULL);
    123 		$$ = ln;
    124 	}
    125 ;
    126 
    127 item:	STRING
    128 |	ADD_SUB_OPERATOR
    129 |	MUL_DIV_MOD_OPERATOR
    130 |	COMPARE
    131 |	SPEC_OR
    132 |	SPEC_AND
    133 |	SPEC_REG
    134 |	LENGTH
    135 ;
    136 
    137 %%
    138 
    139 static int
    140 is_empty_or_zero(const char *str)
    141 {
    142 	char *endptr;
    143 
    144 	return str[0] == '\0'
    145 		|| (strtoll(str, &endptr, 10) == 0 && endptr[0] == '\0');
    146 }
    147 
    148 static int
    149 is_integer(const char *str)
    150 {
    151 	char *endptr;
    152 
    153 	(void)strtoll(str, &endptr, 10);
    154 	/* note we treat empty string as valid number */
    155 	return endptr[0] == '\0';
    156 }
    157 
    158 static int64_t
    159 to_integer(const char *str)
    160 {
    161 	errno = 0;
    162 	int64_t num = strtoll(str, NULL, 10);
    163 	if (errno == ERANGE) {
    164 		yyerror("value '%s' is too %s is %lld", str,
    165 		    num > 0 ? "big, maximum" : "small, minimum",
    166 		    num > 0 ? LLONG_MAX : LLONG_MIN);
    167 	}
    168 	return num;
    169 }
    170 
    171 static const char *
    172 eval_arith(const char *left, const char *op, const char *right)
    173 {
    174 	int64_t res, l, r;
    175 
    176 	res = 0;
    177 
    178 	if (!is_integer(left))
    179 		yyerror("non-integer argument '%s'", left);
    180 	if (!is_integer(right))
    181 		yyerror("non-integer argument '%s'", right);
    182 
    183 	l = to_integer(left);
    184 	r = to_integer(right);
    185 
    186 	switch (op[0]) {
    187 	case '+':
    188 		if ((r > 0 && l > INT64_MAX - r) ||
    189 		    (r < 0 && l < INT64_MIN - r))
    190 			goto integer_overflow;
    191 		res = l + r;
    192 		break;
    193 	case '-':
    194 		if ((r > 0 && l < INT64_MIN + r) ||
    195 		    (r < 0 && l > INT64_MAX + r))
    196 			goto integer_overflow;
    197 		res = l - r;
    198 		break;
    199 	case '/':
    200 		if (r == 0)
    201 			goto invalid_zero;
    202 		if (l == INT64_MIN && r == -1)
    203 			goto integer_overflow;
    204 		res = l / r;
    205 		break;
    206 	case '%':
    207 		if (r == 0)
    208 			goto invalid_zero;
    209 		if (l == INT64_MIN && r == -1)
    210 			goto integer_overflow;
    211 		res = l % r;
    212 		break;
    213 	case '*':
    214 		if (l < 0 && r < 0 && l != INT64_MIN && r != INT64_MIN) {
    215 			l = -l;
    216 			r = -r;
    217 		}
    218 
    219 		if (l < 0 && r >= 0) {
    220 			int64_t tmp = l;
    221 			l = r;
    222 			r = tmp;
    223 		}
    224 
    225 		if ((l < 0 && r < 0) ||
    226 		    (r > 0 && l > INT64_MAX / r) ||
    227 		    (r <= 0 && l != 0 && r < INT64_MIN / l))
    228 			goto integer_overflow;
    229 		res = l * r;
    230 		break;
    231 	}
    232 
    233 	char *val;
    234 	(void)asprintf(&val, "%lld", (long long int)res);
    235 	if (val == NULL)
    236 		err(1, NULL);
    237 	return val;
    238 
    239 integer_overflow:
    240 	yyerror("integer overflow or underflow occurred for "
    241 	    "operation '%s %s %s'", left, op, right);
    242 
    243 invalid_zero:
    244 	yyerror("second argument to '%s' must not be zero", op);
    245 }
    246 
    247 static int
    248 eval_compare(const char *left, const char *op, const char *right)
    249 {
    250 	int64_t l, r;
    251 
    252 	if (is_integer(left) && is_integer(right)) {
    253 		l = strtoll(left, NULL, 10);
    254 		r = strtoll(right, NULL, 10);
    255 	} else {
    256 		l = strcoll(left, right);
    257 		r = 0;
    258 	}
    259 
    260 	switch (op[0]) {
    261 	case '=':
    262 		return l == r;
    263 	case '>':
    264 		if (op[1] == '=')
    265 			return l >= r;
    266 		else
    267 			return l > r;
    268 	case '<':
    269 		if (op[1] == '=')
    270 			return l <= r;
    271 		else
    272 			return l < r;
    273 	default:
    274 		return l != r;
    275 	}
    276 }
    277 
    278 static const char *
    279 eval_match(const char *str, const char *re)
    280 {
    281 	regex_t rp;
    282 	regmatch_t rm[2];
    283 	int rc;
    284 
    285 	if ((rc = regcomp(&rp, re, REG_BASIC)) != 0) {
    286 		char errbuf[256];
    287 		(void)regerror(rc, &rp, errbuf, sizeof(errbuf));
    288 		yyerror("%s", errbuf);
    289 	}
    290 
    291 	if (regexec(&rp, str, 2, rm, 0) == 0 && rm[0].rm_so == 0) {
    292 		char *val;
    293 		if (rm[1].rm_so >= 0) {
    294 			(void)asprintf(&val, "%.*s",
    295 				(int)(rm[1].rm_eo - rm[1].rm_so),
    296 				str + rm[1].rm_so);
    297 		} else {
    298 			(void)asprintf(&val, "%d",
    299 				(int)(rm[0].rm_eo - rm[0].rm_so));
    300 		}
    301 		if (val == NULL)
    302 			err(1, NULL);
    303 		return val;
    304 	}
    305 
    306 	if (rp.re_nsub == 0)
    307 		return "0";
    308 	else
    309 		return "";
    310 }
    311 
    312 static const char x[] = "|&=<>+-*/%:()";
    313 static const int x_token[] = {
    314 	SPEC_OR, SPEC_AND, COMPARE, COMPARE, COMPARE, ADD_SUB_OPERATOR,
    315 	ADD_SUB_OPERATOR, MUL_DIV_MOD_OPERATOR, MUL_DIV_MOD_OPERATOR,
    316 	MUL_DIV_MOD_OPERATOR, SPEC_REG, LPAREN, RPAREN
    317 };
    318 
    319 static int handle_ddash = 1;
    320 
    321 int
    322 yylex(void)
    323 {
    324 	const char *p = *av++;
    325 	int retval;
    326 
    327 	if (p == NULL)
    328 		retval = 0;
    329 	else if (p[0] == '\0')
    330 		retval = STRING;
    331 	else if (p[1] == '\0') {
    332 		const char *w = strchr(x, p[0]);
    333 		retval = w != NULL ? x_token[w - x] : STRING;
    334 	} else if (p[1] == '=' && p[2] == '\0'
    335 		    && (p[0] == '>' || p[0] == '<' || p[0] == '!'))
    336 		retval = COMPARE;
    337 	else if (handle_ddash && strcmp(p, "--") == 0) {
    338 		retval = yylex();
    339 		if (retval != STRING && retval != LPAREN && retval != RPAREN) {
    340 			retval = STRING;
    341 			av--;	/* was increased in call to yylex() above */
    342 			p = "--";
    343 		} else
    344 			p = yylval;
    345 	} else if (strcmp(p, "length") == 0)
    346 		retval = LENGTH;
    347 	else
    348 		retval = STRING;
    349 
    350 	handle_ddash = 0;
    351 	yylval = p;
    352 
    353 	return retval;
    354 }
    355 
    356 /*
    357  * Print error message and exit with error 2 (syntax error).
    358  */
    359 static __printflike(1, 2) void
    360 yyerror(const char *fmt, ...)
    361 {
    362 	va_list arg;
    363 
    364 	va_start(arg, fmt);
    365 	verrx(2, fmt, arg);
    366 	va_end(arg);
    367 }
    368 
    369 int
    370 main(int argc, const char * const *argv)
    371 {
    372 	setprogname(argv[0]);
    373 	(void)setlocale(LC_ALL, "");
    374 
    375 	if (argc == 1) {
    376 		(void)fprintf(stderr, "usage: %s expression\n",
    377 		    getprogname());
    378 		exit(2);
    379 	}
    380 
    381 	av = argv + 1;
    382 
    383 	return yyparse();
    384 }
    385