xref: /netbsd-src/usr.bin/m4/expr.c (revision da5f4674a3fc214be3572d358b66af40ab9401e7)
1 /*	$NetBSD: expr.c,v 1.15 2003/08/07 11:14:31 agc Exp $	*/
2 /*	$OpenBSD: expr.c,v 1.11 2000/01/11 14:00:57 espie Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Ozan Yigit at York University.
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  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #if defined(__RCSID) && !defined(lint)
38 #if 0
39 static char sccsid[] = "@(#)expr.c	8.2 (Berkeley) 4/29/95";
40 #else
41 __RCSID("$NetBSD: expr.c,v 1.15 2003/08/07 11:14:31 agc Exp $");
42 #endif
43 #endif /* not lint */
44 
45 #include <sys/types.h>
46 #include <ctype.h>
47 #include <stddef.h>
48 #include <stdio.h>
49 #include "mdef.h"
50 #include "extern.h"
51 
52 /*
53  *      expression evaluator: performs a standard recursive
54  *      descent parse to evaluate any expression permissible
55  *      within the following grammar:
56  *
57  *      expr    :       query EOS
58  *      query   :       lor
59  *              |       lor "?" query ":" query
60  *      lor     :       land { "||" land }
61  *      land    :       not { "&&" not }
62  *	not	:	eqrel
63  *		|	'!' not
64  *      eqrel   :       shift { eqrelop shift }
65  *      shift   :       primary { shop primary }
66  *      primary :       term { addop term }
67  *      term    :       exp { mulop exp }
68  *	exp	:	unary { expop unary }
69  *      unary   :       factor
70  *              |       unop unary
71  *      factor  :       constant
72  *              |       "(" query ")"
73  *      constant:       num
74  *              |       "'" CHAR "'"
75  *      num     :       DIGIT
76  *              |       DIGIT num
77  *      shop    :       "<<"
78  *              |       ">>"
79  *      eqrel   :       "="
80  *              |       "=="
81  *              |       "!="
82  *      	|       "<"
83  *              |       ">"
84  *              |       "<="
85  *              |       ">="
86  *
87  *
88  *      This expression evaluator is lifted from a public-domain
89  *      C Pre-Processor included with the DECUS C Compiler distribution.
90  *      It is hacked somewhat to be suitable for m4.
91  *
92  *      Originally by:  Mike Lutz
93  *                      Bob Harper
94  */
95 
96 #define EQL     0
97 #define NEQ     1
98 #define LSS     2
99 #define LEQ     3
100 #define GTR     4
101 #define GEQ     5
102 #define OCTAL   8
103 #define DECIMAL 10
104 #define HEX	16
105 
106 static const char *nxtch;		       /* Parser scan pointer */
107 static const char *where;
108 
109 static int query __P((void));
110 static int lor __P((void));
111 static int land __P((void));
112 static int not __P((void));
113 static int eqrel __P((void));
114 static int shift __P((void));
115 static int primary __P((void));
116 static int term __P((void));
117 static int exp __P((void));
118 static int unary __P((void));
119 static int factor __P((void));
120 static int constant __P((void));
121 static int num __P((void));
122 static int geteqrel __P((void));
123 static int skipws __P((void));
124 static void experr __P((const char *));
125 
126 /*
127  * For longjmp
128  */
129 #include <setjmp.h>
130 static jmp_buf expjump;
131 
132 /*
133  * macros:
134  *      ungetch - Put back the last character examined.
135  *      getch   - return the next character from expr string.
136  */
137 #define ungetch()       nxtch--
138 #define getch()         *nxtch++
139 
140 int
141 expr(expbuf)
142 	const char *expbuf;
143 {
144 	int rval;
145 
146 	nxtch = expbuf;
147 	where = expbuf;
148 	if (setjmp(expjump) != 0)
149 		return FALSE;
150 
151 	rval = query();
152 	if (skipws() == EOS)
153 		return rval;
154 
155 	printf("m4: ill-formed expression.\n");
156 	return FALSE;
157 }
158 
159 /*
160  * query : lor | lor '?' query ':' query
161  */
162 static int
163 query()
164 {
165 	int bool, true_val, false_val;
166 
167 	bool = lor();
168 	if (skipws() != '?') {
169 		ungetch();
170 		return bool;
171 	}
172 
173 	true_val = query();
174 	if (skipws() != ':')
175 		experr("bad query");
176 
177 	false_val = query();
178 	return bool ? true_val : false_val;
179 }
180 
181 /*
182  * lor : land { '||' land }
183  */
184 static int
185 lor()
186 {
187 	int c, vl, vr;
188 
189 	vl = land();
190 	while ((c = skipws()) == '|') {
191 		if (getch() != '|')
192 			ungetch();
193 		vr = land();
194 		vl = vl || vr;
195 	}
196 
197 	ungetch();
198 	return vl;
199 }
200 
201 /*
202  * land : not { '&&' not }
203  */
204 static int
205 land()
206 {
207 	int c, vl, vr;
208 
209 	vl = not();
210 	while ((c = skipws()) == '&') {
211 		if (getch() != '&')
212 			ungetch();
213 		vr = not();
214 		vl = vl && vr;
215 	}
216 
217 	ungetch();
218 	return vl;
219 }
220 
221 /*
222  * not : eqrel | '!' not
223  */
224 static int
225 not()
226 {
227 	int val, c;
228 
229 	if ((c = skipws()) == '!' && getch() != '=') {
230 		ungetch();
231 		val = not();
232 		return !val;
233 	}
234 
235 	if (c == '!')
236 		ungetch();
237 	ungetch();
238 	return eqrel();
239 }
240 
241 /*
242  * eqrel : shift { eqrelop shift }
243  */
244 static int
245 eqrel()
246 {
247 	int vl, vr, eqrelvar;
248 
249 	vl = shift();
250 	while ((eqrelvar = geteqrel()) != -1) {
251 		vr = shift();
252 
253 		switch (eqrelvar) {
254 
255 		case EQL:
256 			vl = (vl == vr);
257 			break;
258 		case NEQ:
259 			vl = (vl != vr);
260 			break;
261 
262 		case LEQ:
263 			vl = (vl <= vr);
264 			break;
265 		case LSS:
266 			vl = (vl < vr);
267 			break;
268 		case GTR:
269 			vl = (vl > vr);
270 			break;
271 		case GEQ:
272 			vl = (vl >= vr);
273 			break;
274 		}
275 	}
276 	return vl;
277 }
278 
279 /*
280  * shift : primary { shop primary }
281  */
282 static int
283 shift()
284 {
285 	int vl, vr, c;
286 
287 	vl = primary();
288 	while (((c = skipws()) == '<' || c == '>') && getch() == c) {
289 		vr = primary();
290 
291 		if (c == '<')
292 			vl <<= vr;
293 		else
294 			vl >>= vr;
295 	}
296 
297 	if (c == '<' || c == '>')
298 		ungetch();
299 	ungetch();
300 	return vl;
301 }
302 
303 /*
304  * primary : term { addop term }
305  */
306 static int
307 primary()
308 {
309 	int c, vl, vr;
310 
311 	vl = term();
312 	while ((c = skipws()) == '+' || c == '-') {
313 		vr = term();
314 
315 		if (c == '+')
316 			vl += vr;
317 		else
318 			vl -= vr;
319 	}
320 
321 	ungetch();
322 	return vl;
323 }
324 
325 /*
326  * <term> := <exp> { <mulop> <exp> }
327  */
328 static int
329 term()
330 {
331 	int c, vl, vr;
332 
333 	vl = exp();
334 	while ((c = skipws()) == '*' || c == '/' || c == '%') {
335 		vr = exp();
336 
337 		switch (c) {
338 		case '*':
339 			vl *= vr;
340 			break;
341 		case '/':
342 			if (vr == 0)
343 				errx(1, "division by zero in eval.");
344 			else
345 				vl /= vr;
346 			break;
347 		case '%':
348 			if (vr == 0)
349 				errx(1, "modulo zero in eval.");
350 			else
351 				vl %= vr;
352 			break;
353 		}
354 	}
355 	ungetch();
356 	return vl;
357 }
358 
359 /*
360  * <term> := <unary> { <expop> <unary> }
361  */
362 static int
363 exp()
364 {
365 	int c, vl, vr, n;
366 
367 	vl = unary();
368 	switch (c = skipws()) {
369 
370 	case '*':
371 		if (getch() != '*') {
372 			ungetch();
373 			break;
374 		}
375 
376 	case '^':
377 		vr = exp();
378 		n = 1;
379 		while (vr-- > 0)
380 			n *= vl;
381 		return n;
382 	}
383 
384 	ungetch();
385 	return vl;
386 }
387 
388 /*
389  * unary : factor | unop unary
390  */
391 static int
392 unary()
393 {
394 	int val, c;
395 
396 	if ((c = skipws()) == '+' || c == '-' || c == '~') {
397 		val = unary();
398 
399 		switch (c) {
400 		case '+':
401 			return val;
402 		case '-':
403 			return -val;
404 		case '~':
405 			return ~val;
406 		}
407 	}
408 
409 	ungetch();
410 	return factor();
411 }
412 
413 /*
414  * factor : constant | '(' query ')'
415  */
416 static int
417 factor()
418 {
419 	int val;
420 
421 	if (skipws() == '(') {
422 		val = query();
423 		if (skipws() != ')')
424 			experr("bad factor");
425 		return val;
426 	}
427 
428 	ungetch();
429 	return constant();
430 }
431 
432 /*
433  * constant: num | 'char'
434  * Note: constant() handles multi-byte constants
435  */
436 static int
437 constant()
438 {
439 	int i;
440 	int value;
441 	char c;
442 	int v[sizeof(int)];
443 
444 	if (skipws() != '\'') {
445 		ungetch();
446 		return num();
447 	}
448 	for (i = 0; i < sizeof(int); i++) {
449 		if ((c = getch()) == '\'') {
450 			ungetch();
451 			break;
452 		}
453 		if (c == '\\') {
454 			switch (c = getch()) {
455 			case '0':
456 			case '1':
457 			case '2':
458 			case '3':
459 			case '4':
460 			case '5':
461 			case '6':
462 			case '7':
463 				ungetch();
464 				c = num();
465 				break;
466 			case 'n':
467 				c = 012;
468 				break;
469 			case 'r':
470 				c = 015;
471 				break;
472 			case 't':
473 				c = 011;
474 				break;
475 			case 'b':
476 				c = 010;
477 				break;
478 			case 'f':
479 				c = 014;
480 				break;
481 			}
482 		}
483 		v[i] = c;
484 	}
485 	if (i == 0 || getch() != '\'')
486 		experr("illegal character constant");
487 	for (value = 0; --i >= 0;) {
488 		value <<= 8;
489 		value += v[i];
490 	}
491 	return value;
492 }
493 
494 /*
495  * num : digit | num digit
496  */
497 static int
498 num()
499 {
500 	int rval, c, base;
501 	int ndig;
502 
503 	base = ((c = skipws()) == '0') ? OCTAL : DECIMAL;
504 	rval = 0;
505 	ndig = 0;
506 	if (base == OCTAL) {
507 		c = skipws();
508 		if (c == 'x' || c == 'X') {
509 			base = HEX;
510 			c = skipws();
511 		} else
512 			ndig++;
513 	}
514 	while ((base == HEX && isxdigit(c)) ||
515 			(c >= '0' && c <= (base == OCTAL ? '7' : '9'))) {
516 		rval *= base;
517 		if (isalpha(c))
518 			rval += (tolower(c) - 'a' + 10);
519 		else
520 			rval += (c - '0');
521 		c = getch();
522 		ndig++;
523 	}
524 	ungetch();
525 
526 	if (ndig == 0)
527 		experr("bad constant");
528 
529 	return rval;
530 }
531 
532 /*
533  * eqrel : '=' | '==' | '!=' | '<' | '>' | '<=' | '>='
534  */
535 static int
536 geteqrel()
537 {
538 	int c1, c2;
539 
540 	c1 = skipws();
541 	c2 = getch();
542 
543 	switch (c1) {
544 
545 	case '=':
546 		if (c2 != '=')
547 			ungetch();
548 		return EQL;
549 
550 	case '!':
551 		if (c2 == '=')
552 			return NEQ;
553 		ungetch();
554 		ungetch();
555 		return -1;
556 
557 	case '<':
558 		if (c2 == '=')
559 			return LEQ;
560 		ungetch();
561 		return LSS;
562 
563 	case '>':
564 		if (c2 == '=')
565 			return GEQ;
566 		ungetch();
567 		return GTR;
568 
569 	default:
570 		ungetch();
571 		ungetch();
572 		return -1;
573 	}
574 }
575 
576 /*
577  * Skip over any white space and return terminating char.
578  */
579 static int
580 skipws()
581 {
582 	char c;
583 
584 	while ((c = getch()) <= ' ' && c > EOS)
585 		;
586 	return c;
587 }
588 
589 /*
590  * resets environment to eval(), prints an error
591  * and forces eval to return FALSE.
592  */
593 static void
594 experr(msg)
595 	const char *msg;
596 {
597 	printf("m4: %s in expr %s.\n", msg, where);
598 	longjmp(expjump, -1);
599 }
600