|
|
@ -5,7 +5,7 @@
|
|
5
|
5
|
|
|
6
|
6
|
#include "mpc.h"
|
|
7
|
7
|
|
|
8
|
|
long eval_op(long x, char* op, long y) {
|
|
|
8
|
long eval_binary_op(char* op, long x, long y) {
|
|
9
|
9
|
if (strcmp(op, "+") == 0) { return x + y; }
|
|
10
|
10
|
if (strcmp(op, "-") == 0) { return x - y; }
|
|
11
|
11
|
if (strcmp(op, "*") == 0) { return x * y; }
|
|
|
@ -17,6 +17,11 @@ long eval_op(long x, char* op, long y) {
|
|
17
|
17
|
return 0;
|
|
18
|
18
|
}
|
|
19
|
19
|
|
|
|
20
|
long eval_unary_op(char* op, long x) {
|
|
|
21
|
if (strcmp(op, "-") == 0) { return -x; }
|
|
|
22
|
return x;
|
|
|
23
|
}
|
|
|
24
|
|
|
20
|
25
|
long eval(mpc_ast_t* t) {
|
|
21
|
26
|
if (strstr(t->tag, "number")) {
|
|
22
|
27
|
return atoi(t->contents);
|
|
|
@ -25,13 +30,17 @@ long eval(mpc_ast_t* t) {
|
|
25
|
30
|
char* op = t->children[1]->contents;
|
|
26
|
31
|
long x = eval(t->children[2]);
|
|
27
|
32
|
|
|
28
|
|
int i = 3;
|
|
29
|
|
while (strstr(t->children[i]->tag, "expr")) {
|
|
30
|
|
x = eval_op(x, op, eval(t->children[i]));
|
|
31
|
|
i++;
|
|
32
|
|
}
|
|
|
33
|
if (t->children_num == 4) {
|
|
|
34
|
return eval_unary_op(op, x);
|
|
|
35
|
} else {
|
|
|
36
|
int i = 3;
|
|
|
37
|
while (strstr(t->children[i]->tag, "expr")) {
|
|
|
38
|
x = eval_binary_op(op, x, eval(t->children[i]));
|
|
|
39
|
i++;
|
|
|
40
|
}
|
|
33
|
41
|
|
|
34
|
|
return x;
|
|
|
42
|
return x;
|
|
|
43
|
}
|
|
35
|
44
|
}
|
|
36
|
45
|
|
|
37
|
46
|
int main(int argc, char** argv) {
|