-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.y
More file actions
130 lines (111 loc) · 2.61 KB
/
parser.y
File metadata and controls
130 lines (111 loc) · 2.61 KB
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
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "table.h"
extern int yylex(void);
extern FILE* yyin;
void yyerror(const char* s) {
fprintf(stderr, "Error: %s\n", s);
}
%}
%union {
int num_value;
char* str_value;
}
%token DECLARE PRINT EQ
%token PLUS MINUS TIMES DIVIDE
%token COMMA
%token <num_value> NUMBER
%token <str_value> STRING
%token <str_value> VARNAME
%token DUMP
%type <num_value> expr
%left PLUS MINUS
%left TIMES DIVIDE
%nonassoc UMINUS
%%
program: lines ;
lines:
line lines
| /* empty */
;
line:
declaration
| assignment
| print
| DUMP { print_table(); }
;
declaration:
DECLARE VARNAME EQ expr { declare_symbol_with_number($2, $4); }
| DECLARE VARNAME EQ STRING { declare_symbol_with_string($2, $4); }
| DECLARE VARNAME { declare_symbol_empty($2); }
| DECLARE var_list
;
var_list:
var_init
| var_init COMMA var_list
;
var_init:
VARNAME EQ expr { declare_symbol_with_number($1, $3); }
| VARNAME EQ STRING { declare_symbol_with_string($1, $3); }
| VARNAME { declare_symbol_empty($1); }
;
assignment:
VARNAME EQ expr { set_symbol_number($1, $3); }
| VARNAME EQ STRING { set_symbol_string($1, $3); }
;
print:
PRINT VARNAME {
struct symbol* s = find_symbol($2);
if (!s) {
printf("Undeclared variable %s\n", $2);
exit(1);
}
if (s->is_string) {
printf("%s\n", s->str_value);
} else {
printf("%d\n", s->value);
}
}
;
expr:
expr PLUS expr { $$ = $1 + $3; }
| expr MINUS expr { $$ = $1 - $3; }
| expr TIMES expr { $$ = $1 * $3; }
| expr DIVIDE expr {
if ($3 == 0) {
yyerror("Division by zero");
exit(1);
}
$$ = $1 / $3;
}
| MINUS expr %prec UMINUS { $$ = -$2; }
| NUMBER { $$ = $1; }
| VARNAME {
struct symbol* s = find_symbol($1);
if (!s) {
printf("Undeclared variable %s\n", $1);
exit(1);
}
if (s->is_string) {
printf("Variable %s is a string, not a number\n", $1);
exit(1);
}
$$ = s->value;
}
| '(' expr ')' { $$ = $2; }
;
%%
int main(int argc, char *argv[]) {
if (argc > 1) {
yyin = fopen(argv[1], "r");
if (!yyin) {
perror("Error opening file");
return 1;
}
} else {
yyin = stdin;
}
return yyparse();
}