forked from zakirullin/tiny-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.h
More file actions
126 lines (102 loc) · 2.22 KB
/
parser.h
File metadata and controls
126 lines (102 loc) · 2.22 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
#ifndef PARSER_H
#define PARSER_H
#include <stdio.h>
#include <stdlib.h>
#include "defs.h"
#include "error.h"
#include "symbol_table.h"
#include "lexer.h"
#include "ast.h"
struct Token tok;
int accept(int type)
{
if (tok.type == type) {
tok = next_tok();
return TRUE;
} else {
return FALSE;
}
}
int accept_two(int type1, int type2)
{
if (tok.type == type1 && lookahead().type == type2) {
accept(type1);
accept(type2);
return TRUE;
} else {
return FALSE;
}
}
void expect(int type)
{
if (!accept(type)) {
fatal_error("parser: syntax error");
}
}
struct Node* expr();
struct Node* factor()
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->op1 = NULL;
node->op2 = NULL;
int tok_attr = tok.attr;
if (accept(ID)) {
node->type = VAR_TYPE;
node->val = tok_attr;
} else if (accept(NUM)) {
node->type = NUM_TYPE;
node->val = tok_attr;
} else if (accept(LBR)) {
free(node);
node = expr();
accept(RBR);
} else {
fatal_error("parser: unexpected factor");
}
return node;
}
struct Node* term()
{
struct Node* node;
node = factor();
int tok_attr = tok.attr;
while (accept(OP2)) {
node = make_node(tok_attr, node, factor(), 0);
tok_attr = tok.attr;
}
return node;
}
struct Node* expr()
{
struct Node* node = NULL;
int tok_attr = tok.attr;
if (accept_two(ID, EQ)) {
node = (struct Node*)malloc(sizeof(struct Node));
node->type = SET_TYPE;
node->op1 = make_node(VAR_TYPE, 0, 0, tok_attr);
node->op2 = expr();
} else {
node = term();
tok_attr = tok.attr;
while (accept(OP1)) {
node = make_node(tok_attr, node, term(), 0);
tok_attr = tok.attr;
}
}
return node;
}
struct Node* parse()
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->op1 = expr();
node->op2 = NULL;
expect(SEM);
if (tok.type != EOP) {
node->type = SEQ_TYPE;
node->op2 = parse();
} else {
node->type = RET_TYPE;
}
return node;
}
#endif