aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/LuaSL/src/LuaSL_parser.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--LuaSL/src/LuaSL_parser.c86
1 files changed, 86 insertions, 0 deletions
diff --git a/LuaSL/src/LuaSL_parser.c b/LuaSL/src/LuaSL_parser.c
new file mode 100644
index 0000000..9e1d3ca
--- /dev/null
+++ b/LuaSL/src/LuaSL_parser.c
@@ -0,0 +1,86 @@
1#include "LuaSL_parser_param.h"
2#include "LuaSL_yaccer.tab.h"
3
4
5int yyparse(void *param);
6
7static int initParserParam(SParserParam* param)
8{
9 int ret = 0;
10
11 ret = yylex_init(&param->scanner);
12 param->expression = NULL;
13
14 return ret;
15}
16
17static int destroyParserParam(SParserParam* param)
18{
19 return yylex_destroy(param->scanner);
20}
21
22SExpression *getAST(const char *expr)
23{
24 SParserParam p;
25 YY_BUFFER_STATE state;
26
27 if ( initParserParam(&p) )
28 {
29 // couldn't initialize
30 return NULL;
31 }
32
33 state = yy_scan_string(expr, p.scanner);
34
35 if ( yyparse(&p) )
36 {
37 // error parsing
38 return NULL;
39 }
40
41 yy_delete_buffer(state, p.scanner);
42
43 destroyParserParam(&p);
44
45 return p.expression;
46}
47
48int evaluate(SExpression *e)
49{
50 switch(e->type)
51 {
52 case eVALUE:
53 return e->value;
54 case eMULTIPLY:
55 return evaluate(e->left) * evaluate(e->right);
56 case ePLUS:
57 return evaluate(e->left) + evaluate(e->right);
58 default:
59 // shouldn't be here
60 return 0;
61 }
62}
63
64int yyerror(const char *msg)
65{
66 fprintf(stderr,"Error:%s\n",msg); return 0;
67}
68
69int main(void)
70{
71 SExpression *e = NULL;
72 char test[]=" 4 + 2*10 + 3*( 5 + 1 )";
73 int result = 0;
74
75 e = getAST(test);
76
77 result = evaluate(e);
78
79 printf("Result of '%s' is %d\n", test, result);
80
81 deleteExpression(e);
82
83 return 0;
84}
85
86