|
|
@ -4,6 +4,31 @@
|
|
4
|
4
|
|
|
5
|
5
|
#include "mpc.h"
|
|
6
|
6
|
|
|
|
7
|
long eval_op(long x, char* op, long y) {
|
|
|
8
|
if (strcmp(op, "+") == 0) { return x + y; }
|
|
|
9
|
if (strcmp(op, "-") == 0) { return x - y; }
|
|
|
10
|
if (strcmp(op, "*") == 0) { return x * y; }
|
|
|
11
|
if (strcmp(op, "/") == 0) { return x / y; }
|
|
|
12
|
return 0;
|
|
|
13
|
}
|
|
|
14
|
|
|
|
15
|
long eval(mpc_ast_t* t) {
|
|
|
16
|
if (strstr(t->tag, "number")) {
|
|
|
17
|
return atoi(t->contents);
|
|
|
18
|
}
|
|
|
19
|
|
|
|
20
|
char* op = t->children[1]->contents;
|
|
|
21
|
long x = eval(t->children[2]);
|
|
|
22
|
|
|
|
23
|
int i = 3;
|
|
|
24
|
while (strstr(t->children[i]->tag, "expr")) {
|
|
|
25
|
x = eval_op(x, op, eval(t->children[i]));
|
|
|
26
|
i++;
|
|
|
27
|
}
|
|
|
28
|
|
|
|
29
|
return x;
|
|
|
30
|
}
|
|
|
31
|
|
|
7
|
32
|
int main(int argc, char** argv) {
|
|
8
|
33
|
mpc_parser_t* Number = mpc_new("number");
|
|
9
|
34
|
mpc_parser_t* Operator = mpc_new("operator");
|
|
|
@ -27,7 +52,10 @@ lang : /^/ <expr>+ /$/ ; \
|
|
27
|
52
|
|
|
28
|
53
|
mpc_result_t r;
|
|
29
|
54
|
if (mpc_parse("<stdin>", input, Lang, &r)) {
|
|
30
|
|
mpc_ast_print(r.output);
|
|
|
55
|
mpc_ast_t* t = r.output;
|
|
|
56
|
mpc_ast_print(t->children[1]);
|
|
|
57
|
long result = eval(t->children[1]);
|
|
|
58
|
printf("%li\n", result);
|
|
31
|
59
|
mpc_ast_delete(r.output);
|
|
32
|
60
|
} else {
|
|
33
|
61
|
mpc_err_print(r.error);
|