-
Notifications
You must be signed in to change notification settings - Fork 41
/
parser.c
134 lines (110 loc) · 2.46 KB
/
parser.c
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
#include <stdio.h>
#include <stdlib.h>
#include "parser.h"
#include "defs.h"
#include "func.h"
#include "sym.h"
#include "lex.h"
#include "ast.h"
struct Token tok;
static bool accept(int type);
static bool accept_two(int type1, int type2);
static void expect(int type);
static struct Node *expr();
static struct Node *factor();
static struct Node *term();
static bool accept(int type)
{
if (tok.type == type) {
tok = lex();
return true;
} else {
return false;
}
}
static bool accept_two(int type1, int type2)
{
if (tok.type == type1 && lookahead().type == type2) {
accept(type1);
accept(type2);
return true;
} else {
return false;
}
}
static void expect(int type)
{
if (!accept(type)) {
fatal_error("Parser: Syntax error");
}
}
static struct Node *factor()
{
struct Node* node = safe_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;
}
static 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;
}
static struct Node *expr()
{
struct Node* node = NULL;
int tok_attr = tok.attr;
if (accept_two(ID, EQ)) {
node = safe_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 *produce()
{
struct Node* node = safe_malloc(sizeof(struct Node));
node->op1 = expr();
node->op2 = NULL;
expect(SEM);
if (tok.type != EOP) {
node->type = SEQ_TYPE;
node->op2 = produce();
} else {
node->type = RET_TYPE;
}
return node;
}
struct Node *parse(struct Token start_tok)
{
tok = start_tok;
return produce();
}