-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
64 lines (48 loc) · 1.17 KB
/
main.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
#include "functions.h"
#include "parser.h"
#include "lexer.h"
#include <stdio.h>
int yyparse(SExpression** expression, yyscan_t scanner);
SExpression* getAST(const char* expr)
{
SExpression* expression;
yyscan_t scanner;
YY_BUFFER_STATE state;
if (yylex_init(&scanner)) {
// couldn't initialize
return NULL;
}
state = yy_scan_string(expr, scanner);
if (yyparse(&expression, scanner)) {
// error parsing
return NULL;
}
yy_delete_buffer(state, scanner);
yylex_destroy(scanner);
return expression;
}
int evaluate(SExpression* e)
{
switch (e->type) {
case eVALUE:
return e->value;
case eMULTIPLY:
return evaluate(e->left) * evaluate(e->right);
case ePLUS:
return evaluate(e->left) + evaluate(e->right);
default:
// shouldn't be here
return 0;
}
}
int main(void)
{
SExpression* e = NULL;
char test[]=" 4 + 2*10 + 3*( 5 + 1 )";
int result = 0;
e = getAST(test);
result = evaluate(e);
printf("Result of '%s' is %d\n", test, result);
deleteExpression(e);
return 0;
}