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