-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval.c
113 lines (91 loc) · 2.3 KB
/
eval.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "common.h"
#include "eval.h"
// Used for returning to the main eval() function on syntax errors
static jmp_buf err_jmp_buf;
// The parsing functions below consume as much of the input as can be part of
// the current construction and then delegate to a higher level without looking
// at the rest. This makes it straightforward to catch all syntax errors since
// we detect them at the highest possible level.
static int eval_sum(const char **s);
static int eval_num(const char **s)
{
int res = 0;
if (!isdigit(**s))
longjmp(err_jmp_buf, 1);
do
res = 10*res + *(*s)++ - '0';
while (isdigit(**s));
return res;
}
static int eval_exp(const char **s)
{
int base;
while (isspace(**s))
++*s;
switch (**s) {
// Unary '+' and '-' operators
case '+': ++*s; base = eval_exp(s); break;
case '-': ++*s; base = -eval_exp(s); break;
case '(':
++*s; // Eat "("
base = eval_sum(s);
if (**s != ')')
longjmp(err_jmp_buf, 1);
++*s; // Eat ")"
break;
default:
base = eval_num(s);
}
// Check if we have an exponent
while (isspace(**s))
++*s;
if (**s == '*' && *(*s + 1) == '*') {
*s += 2; // Eat "**"
return pow(base, eval_exp(s));
}
return base;
}
static int eval_product(const char **s)
{
bool is_times = true;
int product = 1;
for (;;) {
if (is_times)
product *= eval_exp(s);
else
product /= eval_exp(s);
switch (**s) {
case '*': ++*s; is_times = true; continue;
case '/': ++*s; is_times = false; continue;
default: return product;
}
}
}
static int eval_sum(const char **s)
{
bool is_plus = true;
int sum = 0;
for (;;) {
if (is_plus)
sum += eval_product(s);
else
sum -= eval_product(s);
switch (**s) {
case '+': ++*s; is_plus = true; continue;
case '-': ++*s; is_plus = false; continue;
default: return sum;
}
}
}
bool eval(const char *s, int *res)
{
int tmp;
if (setjmp(err_jmp_buf) == 1)
return false;
tmp = eval_sum(&s);
if (*s != '\0')
// Found extra trailing characters
return false;
*res = tmp;
return true;
}