-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.y
More file actions
83 lines (65 loc) · 1.76 KB
/
parser.y
File metadata and controls
83 lines (65 loc) · 1.76 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
%{
#include <stdio.h>
#include <stdlib.h>
#include "ast.h"
extern int yylex();
extern FILE *yyin;
void yyerror(const char *s);
Node *ast_root = NULL;
%}
%union {
int value;
char *id;
struct Node *node;
}
%token <value> NUMBER
%token <id> ID
%token VAR PRINT
%type <node> program statement_list statement expression
%left '+' '-'
%left '*' '/'
%%
program:
statement_list { ast_root = $1; }
;
statement_list:
statement { $$ = $1; }
| statement_list statement { $$ = create_op_node(';', $1, $2); }
;
statement:
VAR ID '=' expression ';' { $$ = create_op_node('=', create_id_node($2), $4); }
| PRINT expression ';' { $$ = create_op_node('P', $2, NULL); }
;
expression:
NUMBER { $$ = create_num_node($1); }
| ID { $$ = create_id_node($1); }
| expression '+' expression { $$ = create_op_node('+', $1, $3); }
| expression '-' expression { $$ = create_op_node('-', $1, $3); }
| expression '*' expression { $$ = create_op_node('*', $1, $3); }
| expression '/' expression { $$ = create_op_node('/', $1, $3); }
| '(' expression ')' { $$ = $2; }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Syntax error: %s\n", s);
}
int main(int argc, char **argv) {
if (argc > 1) {
FILE *file = fopen(argv[1], "r");
if (!file) {
perror(argv[1]);
return 1;
}
yyin = file;
}
if (yyparse() == 0) {
printf("/* --- Generated code --- */\n");
printf("#include <stdio.h>\n\n");
printf("int main() {\n\t");
generate_c_code(ast_root);
printf(";\n\treturn 0;\n}\n");
} else {
printf("Compilation was aborted due to some errors.\n");
}
return 0;
}