8 Expr = Or | Or '?' Expr ':' Expr
10 And = Eq | And '&&' Eq
11 Eq = Rel | Eq '==' Rel | Eq '!=' Rel
12 Rel = Add | Rel '<=' Add | Rel '>=' Add | Rel '<' Add | Rel '>' Add
13 Add = Mul | Add '+' Mul | Add '-' Mul
14 Mul = Prim | Mul '*' Prim | Mul '/' Prim | Mul '%' Prim
15 Prim = '(' Expr ')' | '!' Prim | decimal | 'n'
19 recursive descent expression evaluator with stack depth limit.
20 for binary operators an operator-precedence parser is used.
21 eval* functions store the result of the parsed subexpression
22 and return a pointer to the next non-space character.
31 /* TODO: this should go into ctypes.h */
33 #define isspace(a) __isspace(a)
34 static __inline int __isspace(int _c)
36 return _c == ' ' || (unsigned)_c-'\t' < 5;
39 static const char *skipspace(const char *s)
41 while (isspace(*s)) s++;
45 static const char *evalexpr(struct st *st, const char *s, int d);
47 static const char *evalprim(struct st *st, const char *s, int d)
50 if (--d < 0) return "";
53 st->r = strtoul(s, &e, 10);
54 if (e == s || st->r == -1) return "";
59 return skipspace(s+1);
62 s = evalexpr(st, s+1, d);
63 if (*s != ')') return "";
64 return skipspace(s+1);
67 s = evalprim(st, s+1, d);
74 static int binop(struct st *st, int op, unsigned long left)
76 unsigned long a = left, b = st->r;
78 case 0: st->r = a||b; return 0;
79 case 1: st->r = a&&b; return 0;
80 case 2: st->r = a==b; return 0;
81 case 3: st->r = a!=b; return 0;
82 case 4: st->r = a>=b; return 0;
83 case 5: st->r = a<=b; return 0;
84 case 6: st->r = a>b; return 0;
85 case 7: st->r = a<b; return 0;
86 case 8: st->r = a+b; return 0;
87 case 9: st->r = a-b; return 0;
88 case 10: st->r = a*b; return 0;
89 case 11: if (b) {st->r = a%b; return 0;} return 1;
90 case 12: if (b) {st->r = a/b; return 0;} return 1;
95 static const char *parseop(struct st *st, const char *s)
97 static const char opch[11] = "|&=!><+-*%/";
98 static const char opch2[6] = "|&====";
102 /* note: >,< are accepted with or without = */
103 if (i<6 && s[1] == opch2[i]) {
117 static const char *evalbinop(struct st *st, const char *s, int minprec, int d)
119 static const char prec[14] = {1,2,3,3,4,4,4,4,5,5,6,6,6,0};
123 s = evalprim(st, s, d);
127 st->r (left hand side value) and st->op are now set,
128 get the right hand side or back out if op has low prec,
129 if op was missing then prec[op]==0
132 if (prec[op] <= minprec)
135 s = evalbinop(st, s, prec[op], d);
136 if (binop(st, op, left))
141 static const char *evalexpr(struct st *st, const char *s, int d)
146 s = evalbinop(st, s, 0, d);
150 s = evalexpr(st, s+1, d);
154 s = evalexpr(st, s+1, d);
155 st->r = a ? b : st->r;
159 unsigned long __pleval(const char *s, unsigned long n)
163 s = evalexpr(&st, s, 100);
164 return *s == ';' ? st.r : -1;