/
parser.y
97 lines (73 loc) · 2.14 KB
/
parser.y
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
96
97
%{
void yyerror (char *s);
int yylex();
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int symbols[52];
int symbolVal(char symbol);
/* Variable to store the last executed statement*/
int lastValOfExpr = 0;
void updateSymbolVal(char symbol, int val);
%}
%union {int num; char id;} /* Yacc definitions */
%start program
%token PRINT ADD WITH ASSIGN TO SUBSTRACT FROM MULTIPLY DIVIDE BY
%token <num> number
%token <id> identifier
%type <num> program statement expression term
%%
/* CFG */
program
: statement '\n' {;}
| program statement '\n' {;}
;
statement
: expression {$$ = $1;}
| PRINT statement {$$ = $2; printf("%d\n", $2); lastValOfExpr = $$;}
| ADD statement WITH statement {$$ = $2 + $4; lastValOfExpr = $$;}
| SUBSTRACT statement FROM statement {$$ = $2 - $4; lastValOfExpr = $$;}
| MULTIPLY statement BY statement {$$ = $2 * $4; lastValOfExpr = $$;}
| DIVIDE statement BY statement {$$ = $2 / $4; lastValOfExpr = $$;}
| ASSIGN identifier TO statement {$$ = $4; updateSymbolVal($2,$4); lastValOfExpr = $$;}
;
expression
: term {$$ = $1;}
| expression term '*' {$$ = $1 * $2;}
| expression term '/' {$$ = $1 / $2;}
| expression term '+' {$$ = $1 + $2;}
| expression term '-' {$$ = $1 - $2;}
;
term
: number {$$ = $1;}
| identifier {$$ = symbolVal($1);}
;
%% /* C code */
int computeSymbolIndex(char token){
int idx = -1;
if(islower(token)) {
idx = token - 'a' + 26;
} else if(isupper(token)) {
idx = token - 'A';
}
return idx;
}
/* returns the value of a given symbol */
int symbolVal(char symbol){
int bucket = computeSymbolIndex(symbol);
return symbols[bucket];
}
/* updates the value of a given symbol */
void updateSymbolVal(char symbol, int val){
int bucket = computeSymbolIndex(symbol);
symbols[bucket] = val;
}
int main (void) {
/* init symbol table */
int i;
for(i=0; i<52; i++) {
symbols[i] = 0;
}
return yyparse ();
}
void yyerror (char *s) {fprintf (stderr, "%s\n", s);}