xref: /netbsd-src/bin/ksh/expr.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: expr.c,v 1.12 2018/05/08 16:37:59 kamil Exp $	*/
2 
3 /*
4  * Korn expression evaluation
5  */
6 /*
7  * todo: better error handling: if in builtin, should be builtin error, etc.
8  */
9 #include <sys/cdefs.h>
10 
11 #ifndef lint
12 __RCSID("$NetBSD: expr.c,v 1.12 2018/05/08 16:37:59 kamil Exp $");
13 #endif
14 
15 
16 #include "sh.h"
17 #include <ctype.h>
18 #include <stdbool.h>
19 
20 /* The order of these enums is constrained by the order of opinfo[] */
21 enum token {
22 	/* some (long) unary operators */
23 	O_PLUSPLUS = 0, O_MINUSMINUS,
24 	/* binary operators */
25 	O_EQ, O_NE,
26 	/* assignments are assumed to be in range O_ASN .. O_BORASN */
27 	O_ASN, O_TIMESASN, O_DIVASN, O_MODASN, O_PLUSASN, O_MINUSASN,
28 	       O_LSHIFTASN, O_RSHIFTASN, O_BANDASN, O_BXORASN, O_BORASN,
29 	O_LSHIFT, O_RSHIFT,
30 	O_LE, O_GE, O_LT, O_GT,
31 	O_LAND,
32 	O_LOR,
33 	O_TIMES, O_DIV, O_MOD,
34 	O_PLUS, O_MINUS,
35 	O_BAND,
36 	O_BXOR,
37 	O_BOR,
38 	O_TERN,
39 	O_COMMA,
40 	/* things after this aren't used as binary operators */
41 	/* unary that are not also binaries */
42 	O_BNOT, O_LNOT,
43 	/* misc */
44 	OPEN_PAREN, CLOSE_PAREN, CTERN,
45 	/* things that don't appear in the opinfo[] table */
46 	VAR, LIT, END, BAD
47     };
48 #define IS_BINOP(op) (((int)op) >= (int)O_EQ && ((int)op) <= (int)O_COMMA)
49 #define IS_ASSIGNOP(op)	((int)(op) >= (int)O_ASN && (int)(op) <= (int)O_BORASN)
50 
51 enum prec {
52 	P_PRIMARY = 0,		/* VAR, LIT, (), ~ ! - + */
53 	P_MULT,			/* * / % */
54 	P_ADD,			/* + - */
55 	P_SHIFT,		/* << >> */
56 	P_RELATION,		/* < <= > >= */
57 	P_EQUALITY,		/* == != */
58 	P_BAND,			/* & */
59 	P_BXOR,			/* ^ */
60 	P_BOR,			/* | */
61 	P_LAND,			/* && */
62 	P_LOR,			/* || */
63 	P_TERN,			/* ?: */
64 	P_ASSIGN,		/* = *= /= %= += -= <<= >>= &= ^= |= */
65 	P_COMMA			/* , */
66     };
67 #define MAX_PREC	P_COMMA
68 
69 struct opinfo {
70 	char		name[4];
71 	int		len;	/* name length */
72 	enum prec	prec;	/* precedence: lower is higher */
73 };
74 
75 /* Tokens in this table must be ordered so the longest are first
76  * (eg, += before +).  If you change something, change the order
77  * of enum token too.
78  */
79 static const struct opinfo opinfo[] = {
80 		{ "++",	 2, P_PRIMARY },	/* before + */
81 		{ "--",	 2, P_PRIMARY },	/* before - */
82 		{ "==",	 2, P_EQUALITY },	/* before = */
83 		{ "!=",	 2, P_EQUALITY },	/* before ! */
84 		{ "=",	 1, P_ASSIGN },		/* keep assigns in a block */
85 		{ "*=",	 2, P_ASSIGN },
86 		{ "/=",	 2, P_ASSIGN },
87 		{ "%=",	 2, P_ASSIGN },
88 		{ "+=",	 2, P_ASSIGN },
89 		{ "-=",	 2, P_ASSIGN },
90 		{ "<<=", 3, P_ASSIGN },
91 		{ ">>=", 3, P_ASSIGN },
92 		{ "&=",	 2, P_ASSIGN },
93 		{ "^=",	 2, P_ASSIGN },
94 		{ "|=",	 2, P_ASSIGN },
95 		{ "<<",	 2, P_SHIFT },
96 		{ ">>",	 2, P_SHIFT },
97 		{ "<=",	 2, P_RELATION },
98 		{ ">=",	 2, P_RELATION },
99 		{ "<",	 1, P_RELATION },
100 		{ ">",	 1, P_RELATION },
101 		{ "&&",	 2, P_LAND },
102 		{ "||",	 2, P_LOR },
103 		{ "*",	 1, P_MULT },
104 		{ "/",	 1, P_MULT },
105 		{ "%",	 1, P_MULT },
106 		{ "+",	 1, P_ADD },
107 		{ "-",	 1, P_ADD },
108 		{ "&",	 1, P_BAND },
109 		{ "^",	 1, P_BXOR },
110 		{ "|",	 1, P_BOR },
111 		{ "?",	 1, P_TERN },
112 		{ ",",	 1, P_COMMA },
113 		{ "~",	 1, P_PRIMARY },
114 		{ "!",	 1, P_PRIMARY },
115 		{ "(",	 1, P_PRIMARY },
116 		{ ")",	 1, P_PRIMARY },
117 		{ ":",	 1, P_PRIMARY },
118 		{ "",	 0, P_PRIMARY } /* end of table */
119 	    };
120 
121 
122 typedef struct expr_state Expr_state;
123 struct expr_state {
124 	const char *expression;		/* expression being evaluated */
125 	const char *tokp;		/* lexical position */
126 	enum token  tok;		/* token from token() */
127 	int	    noassign;		/* don't do assigns (for ?:,&&,||) */
128 	struct tbl *val;		/* value from token() */
129 	struct tbl *evaling;		/* variable that is being recursively
130 					 * expanded (EXPRINEVAL flag set)
131 					 */
132 };
133 
134 enum error_type { ET_UNEXPECTED, ET_BADLIT, ET_RECURSIVE,
135 		  ET_LVALUE, ET_RDONLY, ET_STR };
136 
137 static void        evalerr  ARGS((Expr_state *es, enum error_type type,
138 				  const char *str)) GCC_FUNC_ATTR(noreturn);
139 static struct tbl *evalexpr ARGS((Expr_state *es, enum prec prec));
140 static void        token    ARGS((Expr_state *es));
141 static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, bool);
142 static void	   assign_check ARGS((Expr_state *es, enum token op,
143 				      struct tbl *vasn));
144 static struct tbl *tempvar  ARGS((void));
145 static struct tbl *intvar   ARGS((Expr_state *es, struct tbl *vp));
146 
147 /*
148  * parse and evaluate expression
149  */
150 int
151 evaluate(expr, rval, error_ok)
152 	const char *expr;
153 	long *rval;
154 	int error_ok;
155 {
156 	struct tbl v;
157 	int ret;
158 
159 	v.flag = DEFINED|INTEGER;
160 	v.type = 0;
161 	ret = v_evaluate(&v, expr, error_ok);
162 	*rval = v.val.i;
163 	return ret;
164 }
165 
166 /*
167  * parse and evaluate expression, storing result in vp.
168  */
169 int
170 v_evaluate(vp, expr, error_ok)
171 	struct tbl *vp;
172 	const char *expr;
173 	volatile int error_ok;
174 {
175 	struct tbl *v;
176 	Expr_state curstate;
177 	Expr_state * const es = &curstate;
178 	int i;
179 
180 	/* save state to allow recursive calls */
181 	curstate.expression = curstate.tokp = expr;
182 	curstate.noassign = 0;
183 	curstate.evaling = (struct tbl *) 0;
184 
185 	newenv(E_ERRH);
186 	i = ksh_sigsetjmp(e->jbuf, 0);
187 	if (i) {
188 		/* Clear EXPRINEVAL in of any variables we were playing with */
189 		if (curstate.evaling)
190 			curstate.evaling->flag &= ~EXPRINEVAL;
191 		quitenv();
192 		if (i == LAEXPR) {
193 			if (error_ok == KSH_RETURN_ERROR)
194 				return 0;
195 			errorf("%s", null);
196 		}
197 		unwind(i);
198 		/*NOTREACHED*/
199 	}
200 
201 	token(es);
202 #if 1 /* ifdef-out to disallow empty expressions to be treated as 0 */
203 	if (es->tok == END) {
204 		es->tok = LIT;
205 		es->val = tempvar();
206 	}
207 #endif /* 0 */
208 	v = intvar(es, evalexpr(es, MAX_PREC));
209 
210 	if (es->tok != END)
211 		evalerr(es, ET_UNEXPECTED, (char *) 0);
212 
213 	if (vp->flag & INTEGER)
214 		setint_v(vp, v);
215 	else
216 		/* can fail if readonly */
217 		setstr(vp, str_val(v), error_ok);
218 
219 	quitenv();
220 
221 	return 1;
222 }
223 
224 static void
225 evalerr(es, type, str)
226 	Expr_state *es;
227 	enum error_type type;
228 	const char *str;
229 {
230 	char tbuf[2];
231 	const char *s;
232 
233 	switch (type) {
234 	case ET_UNEXPECTED:
235 		switch (es->tok) {
236 		case VAR:
237 			s = es->val->name;
238 			break;
239 		case LIT:
240 			s = str_val(es->val);
241 			break;
242 		case END:
243 			s = "end of expression";
244 			break;
245 		case BAD:
246 			tbuf[0] = *es->tokp;
247 			tbuf[1] = '\0';
248 			s = tbuf;
249 			break;
250 		default:
251 			s = opinfo[(int)es->tok].name;
252 		}
253 		warningf(true, "%s: unexpected `%s'", es->expression, s);
254 		break;
255 
256 	case ET_BADLIT:
257 		warningf(true, "%s: bad number `%s'", es->expression, str);
258 		break;
259 
260 	case ET_RECURSIVE:
261 		warningf(true, "%s: expression recurses on parameter `%s'",
262 			es->expression, str);
263 		break;
264 
265 	case ET_LVALUE:
266 		warningf(true, "%s: %s requires lvalue",
267 			es->expression, str);
268 		break;
269 
270 	case ET_RDONLY:
271 		warningf(true, "%s: %s applied to read only variable",
272 			es->expression, str);
273 		break;
274 
275 	default: /* keep gcc happy */
276 	case ET_STR:
277 		warningf(true, "%s: %s", es->expression, str);
278 		break;
279 	}
280 	unwind(LAEXPR);
281 }
282 
283 static struct tbl *
284 evalexpr(es, prec)
285 	Expr_state *es;
286 	enum prec prec;
287 {
288 	struct tbl *vl, UNINITIALIZED(*vr), *vasn;
289 	enum token op;
290 	long UNINITIALIZED(res);
291 
292 	if (prec == P_PRIMARY) {
293 		op = es->tok;
294 		if (op == O_BNOT || op == O_LNOT || op == O_MINUS
295 		    || op == O_PLUS)
296 		{
297 			token(es);
298 			vl = intvar(es, evalexpr(es, P_PRIMARY));
299 			if (op == O_BNOT)
300 				vl->val.i = ~vl->val.i;
301 			else if (op == O_LNOT)
302 				vl->val.i = !vl->val.i;
303 			else if (op == O_MINUS)
304 				vl->val.i = -vl->val.i;
305 			/* op == O_PLUS is a no-op */
306 		} else if (op == OPEN_PAREN) {
307 			token(es);
308 			vl = evalexpr(es, MAX_PREC);
309 			if (es->tok != CLOSE_PAREN)
310 				evalerr(es, ET_STR, "missing )");
311 			token(es);
312 		} else if (op == O_PLUSPLUS || op == O_MINUSMINUS) {
313 			token(es);
314 			vl = do_ppmm(es, op, es->val, true);
315 			token(es);
316 		} else if (op == VAR || op == LIT) {
317 			vl = es->val;
318 			token(es);
319 		} else {
320 			evalerr(es, ET_UNEXPECTED, (char *) 0);
321 			/*NOTREACHED*/
322 		}
323 		if (es->tok == O_PLUSPLUS || es->tok == O_MINUSMINUS) {
324 			vl = do_ppmm(es, es->tok, vl, false);
325 			token(es);
326 		}
327 		return vl;
328 	}
329 	vl = evalexpr(es, ((int) prec) - 1);
330 	for (op = es->tok; IS_BINOP(op) && opinfo[(int) op].prec == prec;
331 		op = es->tok)
332 	{
333 		token(es);
334 		vasn = vl;
335 		if (op != O_ASN) /* vl may not have a value yet */
336 			vl = intvar(es, vl);
337 		if (IS_ASSIGNOP(op)) {
338 			assign_check(es, op, vasn);
339 			vr = intvar(es, evalexpr(es, P_ASSIGN));
340 		} else if (op != O_TERN && op != O_LAND && op != O_LOR)
341 			vr = intvar(es, evalexpr(es, ((int) prec) - 1));
342 		if ((op == O_DIV || op == O_MOD || op == O_DIVASN
343 		     || op == O_MODASN) && vr->val.i == 0)
344 		{
345 			if (es->noassign)
346 				vr->val.i = 1;
347 			else
348 				evalerr(es, ET_STR, "zero divisor");
349 		}
350 		switch ((int) op) {
351 		case O_TIMES:
352 		case O_TIMESASN:
353 			res = vl->val.i * vr->val.i;
354 			break;
355 		case O_DIV:
356 		case O_DIVASN:
357 			res = vl->val.i / vr->val.i;
358 			break;
359 		case O_MOD:
360 		case O_MODASN:
361 			res = vl->val.i % vr->val.i;
362 			break;
363 		case O_PLUS:
364 		case O_PLUSASN:
365 			res = vl->val.i + vr->val.i;
366 			break;
367 		case O_MINUS:
368 		case O_MINUSASN:
369 			res = vl->val.i - vr->val.i;
370 			break;
371 		case O_LSHIFT:
372 		case O_LSHIFTASN:
373 			res = vl->val.i << vr->val.i;
374 			break;
375 		case O_RSHIFT:
376 		case O_RSHIFTASN:
377 			res = vl->val.i >> vr->val.i;
378 			break;
379 		case O_LT:
380 			res = vl->val.i < vr->val.i;
381 			break;
382 		case O_LE:
383 			res = vl->val.i <= vr->val.i;
384 			break;
385 		case O_GT:
386 			res = vl->val.i > vr->val.i;
387 			break;
388 		case O_GE:
389 			res = vl->val.i >= vr->val.i;
390 			break;
391 		case O_EQ:
392 			res = vl->val.i == vr->val.i;
393 			break;
394 		case O_NE:
395 			res = vl->val.i != vr->val.i;
396 			break;
397 		case O_BAND:
398 		case O_BANDASN:
399 			res = vl->val.i & vr->val.i;
400 			break;
401 		case O_BXOR:
402 		case O_BXORASN:
403 			res = vl->val.i ^ vr->val.i;
404 			break;
405 		case O_BOR:
406 		case O_BORASN:
407 			res = vl->val.i | vr->val.i;
408 			break;
409 		case O_LAND:
410 			if (!vl->val.i)
411 				es->noassign++;
412 			vr = intvar(es, evalexpr(es, ((int) prec) - 1));
413 			res = vl->val.i && vr->val.i;
414 			if (!vl->val.i)
415 				es->noassign--;
416 			break;
417 		case O_LOR:
418 			if (vl->val.i)
419 				es->noassign++;
420 			vr = intvar(es, evalexpr(es, ((int) prec) - 1));
421 			res = vl->val.i || vr->val.i;
422 			if (vl->val.i)
423 				es->noassign--;
424 			break;
425 		case O_TERN:
426 			{
427 				int ex = vl->val.i != 0;
428 				if (!ex)
429 					es->noassign++;
430 				vl = evalexpr(es, MAX_PREC);
431 				if (!ex)
432 					es->noassign--;
433 				if (es->tok != CTERN)
434 					evalerr(es, ET_STR, "missing :");
435 				token(es);
436 				if (ex)
437 					es->noassign++;
438 				vr = evalexpr(es, P_TERN);
439 				if (ex)
440 					es->noassign--;
441 				vl = ex ? vl : vr;
442 			}
443 			break;
444 		case O_ASN:
445 			res = vr->val.i;
446 			break;
447 		case O_COMMA:
448 			res = vr->val.i;
449 			break;
450 		}
451 		if (IS_ASSIGNOP(op)) {
452 			vr->val.i = res;
453 			if (vasn->flag & INTEGER)
454 				setint_v(vasn, vr);
455 			else
456 				setint(vasn, res);
457 			vl = vr;
458 		} else if (op != O_TERN)
459 			vl->val.i = res;
460 	}
461 	return vl;
462 }
463 
464 static void
465 token(es)
466 	Expr_state *es;
467 {
468 	const char *cp;
469 	int c;
470 	char *tvar;
471 
472 	/* skip white space */
473 	for (cp = es->tokp; (c = *cp), isspace((unsigned char)c); cp++)
474 		;
475 	es->tokp = cp;
476 
477 	if (c == '\0')
478 		es->tok = END;
479 	else if (letter(c)) {
480 		for (; letnum(c); c = *cp)
481 			cp++;
482 		if (c == '[') {
483 			int len;
484 
485 			len = array_ref_len(cp);
486 			if (len == 0)
487 				evalerr(es, ET_STR, "missing ]");
488 			cp += len;
489 		}
490 #ifdef KSH
491 		else if (c == '(' /*)*/ ) {
492 		    /* todo: add math functions (all take single argument):
493 		     * abs acos asin atan cos cosh exp int log sin sinh sqrt
494 		     * tan tanh
495 		     */
496 		    ;
497 		}
498 #endif /* KSH */
499 		if (es->noassign) {
500 			es->val = tempvar();
501 			es->val->flag |= EXPRLVALUE;
502 		} else {
503 			tvar = str_nsave(es->tokp, cp - es->tokp, ATEMP);
504 			es->val = global(tvar);
505 			afree(tvar, ATEMP);
506 		}
507 		es->tok = VAR;
508 	} else if (digit(c)) {
509 		for (; c != '_' && (letnum(c) || c == '#'); c = *cp++)
510 			;
511 		tvar = str_nsave(es->tokp, --cp - es->tokp, ATEMP);
512 		es->val = tempvar();
513 		es->val->flag &= ~INTEGER;
514 		es->val->type = 0;
515 		es->val->val.s = tvar;
516 		if (setint_v(es->val, es->val) == NULL)
517 			evalerr(es, ET_BADLIT, tvar);
518 		afree(tvar, ATEMP);
519 		es->tok = LIT;
520 	} else {
521 		int i, n0;
522 
523 		for (i = 0; (n0 = opinfo[i].name[0]); i++)
524 			if (c == n0
525 			    && strncmp(cp, opinfo[i].name, opinfo[i].len) == 0)
526 			{
527 				es->tok = (enum token) i;
528 				cp += opinfo[i].len;
529 				break;
530 			}
531 		if (!n0)
532 			es->tok = BAD;
533 	}
534 	es->tokp = cp;
535 }
536 
537 /* Do a ++ or -- operation */
538 static struct tbl *
539 do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, bool is_prefix)
540 {
541 	struct tbl *vl;
542 	int oval;
543 
544 	assign_check(es, op, vasn);
545 
546 	vl = intvar(es, vasn);
547 	oval = op == O_PLUSPLUS ? vl->val.i++ : vl->val.i--;
548 	if (vasn->flag & INTEGER)
549 		setint_v(vasn, vl);
550 	else
551 		setint(vasn, vl->val.i);
552 	if (!is_prefix)		/* undo the inc/dec */
553 		vl->val.i = oval;
554 
555 	return vl;
556 }
557 
558 static void
559 assign_check(es, op, vasn)
560 	Expr_state *es;
561 	enum token op;
562 	struct tbl *vasn;
563 {
564 	if (vasn->name[0] == '\0' && !(vasn->flag & EXPRLVALUE))
565 		evalerr(es, ET_LVALUE, opinfo[(int) op].name);
566 	else if (vasn->flag & RDONLY)
567 		evalerr(es, ET_RDONLY, opinfo[(int) op].name);
568 }
569 
570 static struct tbl *
571 tempvar()
572 {
573 	struct tbl *vp;
574 
575 	vp = (struct tbl*) alloc(sizeof(struct tbl), ATEMP);
576 	vp->flag = ISSET|INTEGER;
577 	vp->type = 0;
578 	vp->areap = ATEMP;
579 	vp->val.i = 0;
580 	vp->name[0] = '\0';
581 	return vp;
582 }
583 
584 /* cast (string) variable to temporary integer variable */
585 static struct tbl *
586 intvar(es, vp)
587 	Expr_state *es;
588 	struct tbl *vp;
589 {
590 	struct tbl *vq;
591 
592 	/* try to avoid replacing a temp var with another temp var */
593 	if (vp->name[0] == '\0'
594 	    && (vp->flag & (ISSET|INTEGER|EXPRLVALUE)) == (ISSET|INTEGER))
595 		return vp;
596 
597 	vq = tempvar();
598 	if (setint_v(vq, vp) == NULL) {
599 		if (vp->flag & EXPRINEVAL)
600 			evalerr(es, ET_RECURSIVE, vp->name);
601 		es->evaling = vp;
602 		vp->flag |= EXPRINEVAL;
603 		v_evaluate(vq, str_val(vp), KSH_UNWIND_ERROR);
604 		vp->flag &= ~EXPRINEVAL;
605 		es->evaling = (struct tbl *) 0;
606 	}
607 	return vq;
608 }
609