-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinyC_grammar.y
executable file
·151 lines (120 loc) · 2.29 KB
/
tinyC_grammar.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
%{
#include "table.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void yyerror (char *string); /* Implementación de la función yyerror */
extern int yylex(void);
extern int numberLines;
%}
%union{
int intVal; /* valor entero */
float floatVal; /* valor flotante */
char *string; /* string */
struct symtab *symp; /* apuntador a la tabla */
}
%token <intVal> INT_NUM
%token <floatVal> FLOAT_NUM
%token <symp> ID
%token LBRACE
%token RBRACE
%token LPAREN
%token RPAREN
%token SEMICOLON
%token IF
%token THEN
%token ELSE
%token INT
%token FLOAT
%token WHILE
%token DO
%token READ
%token WRITE
%token PLUS
%token MINUS
%token TIMES
%token DIV
%token ASSIGNMENT
%token RELATIONAL
%type <string> type
%nonassoc NOT_ELSE
%nonassoc ELSE
%%
program: var_dec stmt_seq
;
var_dec: var_dec single_dec
| epsilon
;
single_dec: type ID SEMICOLON {
$2->type = strdup($<string>1);
}
;
type: INT {$<string>$ = "int";}
| FLOAT {$<string>$ = "float";}
;
stmt_seq: stmt_seq stmt
| epsilon
;
stmt: IF exp THEN stmt %prec NOT_ELSE
| IF exp THEN stmt ELSE stmt
| WHILE exp DO stmt
| variable ASSIGNMENT exp SEMICOLON
| READ LPAREN variable RPAREN SEMICOLON
| WRITE LPAREN exp RPAREN SEMICOLON
| block
;
block: LBRACE stmt_seq RBRACE
;
exp: simple_exp RELATIONAL simple_exp
| simple_exp
;
simple_exp: simple_exp PLUS term
| simple_exp MINUS term
| term
;
term: term TIMES factor
| term DIV factor
| factor
;
factor: LPAREN exp RPAREN
| INT_NUM
| FLOAT_NUM
| variable
;
variable: ID
;
epsilon: ;
%%
void yyerror(char *string){
printf("Error en la linea %d \n\n", numberLines);
exit(-1);
}
struct symtab *symlook(char *s) {
char *p;
struct symtab *sp;
for(sp = symtab; sp < &symtab[NSYMS]; sp++) {
if(sp->name && !strcmp(sp->name, s))
return sp;
if(!sp->name) {
sp->name = strdup(s);
return sp;
}
}
yyerror("exceeded");
exit(1);
}
void printTable(){
struct symtab *sp;
for(sp = symtab; sp < &symtab[NSYMS]; sp++){
if(sp->name){
printf("%5s | %5s \n", sp->type, sp->name);
}
}
}
int main(){
yyparse();
printf("No hay errores \n\n");
printf("type | actual symbol \n");
printTable();
return 0;
}