-
Notifications
You must be signed in to change notification settings - Fork 0
/
myprogram.y
114 lines (102 loc) · 2.71 KB
/
myprogram.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
98
99
100
101
102
103
104
105
106
107
108
109
110
%{
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void yyerror (char *s);
int yylex();
int symbols[52];
int symbolVal(char symbol);
void updateSymbolVal(char symbol, int val);
%}
%start program
%union {int num; float numfloat; char id;}
%token EXIT
%token INT
%token WHILE
%token FOR
%token IF
%token ELSE
%token PRINT
%token DO
%token THEN
%token TRUE
%token FALSE
%token COLON
%token SEMICOLON
%token <id> ID
%token <num> INTNUM
%type <id> assignment
%type <num> program exp term factor
%left AND OR
%left LESSTHAN GREATERTHAN EQUAL
%left '+' '-'
%left '*' '/' '%'
%%
program : assignment ';' {;}
| EXIT ';' {exit(EXIT_SUCCESS);}
| PRINT exp ';' {printf("\n",$2);}
| program assignment ';' {;}
| program PRINT exp ';' {printf("\n",$3);}
| program EXIT ';' {exit(EXIT_SUCCESS);}
| program FOR '('exp ';' exp ';' exp')' body {printf("For loop");}
| WHILE '(' exp ')' body {printf("While loop");}
| DO codeblock WHILE exp ';' {printf("DO while");}
| IF '(' exp ')' body {printf("IF");}
| IF '(' exp ')'body ELSE body {printf("IF..ELSE");}
;
body: stmt
| codeblock
;
codeblock:'{' stmt_list '}'
;
stmt_list: stmt_list stmt
|
;
stmt: exp ';'
;
;
assignment : ID '=' exp { updateSymbolVal($1,$3); }
exp : term {$$ = $1;}
| exp '+' term {$$ = $1 + $3;}
| exp '-' term {$$ = $1 - $3;}
;
term : factor {$$ = $1;}
|term '*' factor {$$ = $1 * $3;}
|term '/' factor {$$ = $1 / $3;}
;
factor : INTNUM {$$ = $1;}
| '('exp')' {$$ = $2;}
;
%%
main()
{
yyparse();
}
int computeSymbolIndex(char token)
{
int idx = -1;
if(islower(token)) {
idx = token - 'a' + 26;
} else if(isupper(token)) {
idx = token - 'A';
}
return idx;
}
int symbolVal(char symbol)
{
int bucket = computeSymbolIndex(symbol);
return symbols[bucket];
}
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 ( );
}