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