forked from bhargavkulk/CSF363-baseline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.yy
95 lines (74 loc) · 1.85 KB
/
parser.yy
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
%define api.value.type { ParserValue }
%code requires {
#include <iostream>
#include <vector>
#include <string>
#include "parser_util.hh"
#include "symbol.hh"
}
%code {
#include <cstdlib>
extern int yylex();
extern int yyparse();
extern NodeStmts* final_values;
SymbolTable symbol_table;
int yyerror(std::string msg);
}
%token TPLUS TDASH TSTAR TSLASH
%token <lexeme> TINT_LIT TIDENT
%token INT TLET TDBG
%token TSCOL TLPAREN TRPAREN TEQUAL
%type <node> Expr Stmt
%type <stmts> Program StmtList
%left TPLUS TDASH
%left TSTAR TSLASH
%%
Program :
{ final_values = nullptr; }
| StmtList TSCOL
{ final_values = $1; }
;
StmtList : Stmt
{ $$ = new NodeStmts(); $$->push_back($1); }
| StmtList TSCOL Stmt
{ $$->push_back($3); }
;
Stmt : TLET TIDENT TEQUAL Expr
{
if(symbol_table.contains($2)) {
// tried to redeclare variable, so error
yyerror("tried to redeclare variable.\n");
} else {
symbol_table.insert($2);
$$ = new NodeAssn($2, $4);
}
}
| TDBG Expr
{
$$ = new NodeDebug($2);
}
;
Expr : TINT_LIT
{ $$ = new NodeInt(stoi($1)); }
| TIDENT
{
if(symbol_table.contains($1))
$$ = new NodeIdent($1);
else
yyerror("using undeclared variable.\n");
}
| Expr TPLUS Expr
{ $$ = new NodeBinOp(NodeBinOp::PLUS, $1, $3); }
| Expr TDASH Expr
{ $$ = new NodeBinOp(NodeBinOp::MINUS, $1, $3); }
| Expr TSTAR Expr
{ $$ = new NodeBinOp(NodeBinOp::MULT, $1, $3); }
| Expr TSLASH Expr
{ $$ = new NodeBinOp(NodeBinOp::DIV, $1, $3); }
| TLPAREN Expr TRPAREN { $$ = $2; }
;
%%
int yyerror(std::string msg) {
std::cerr << "Error! " << msg << std::endl;
exit(1);
}