-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast.c
More file actions
101 lines (89 loc) · 1.98 KB
/
ast.c
File metadata and controls
101 lines (89 loc) · 1.98 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
#include "ast.h"
tree root;
#define STACK_SIZE 100
tree ast_stack[STACK_SIZE];
static int nStack = 0;
void print_tree(tree, int);
tree add_child(tree, int);
static void push(tree t) {
ast_stack[nStack++] = t;
}
static void pop(){
nStack--;
}
static tree stacktop() {
return ast_stack[nStack - 1];
}
void add_ast(int type) {
tree parent = stacktop();
tree child = add_child(parent, type);
push(child);
leave_ast();
}
void enter_ast(int type) {
tree parent = stacktop();
tree child = add_child(parent, type);
push(child);
}
void leave_ast() {
pop();
}
tree new_tree(int type) {
tree t = (tree)malloc(sizeof(struct tree_struct));
t->val.type = type;
t->children = malloc(sizeof(struct list_struct));
t->children->node = NULL;
t->children->next = NULL;
return t;
}
void init_tree() {
root = new_tree(nPROGRAM);
push(root);
}
tree add_child(tree parent, int type) {
assert(parent);
assert(parent->children);
// allocate memory for child
tree child = new_tree(type);
// add child to parent's children list
list l = malloc(sizeof(struct list_struct));
l->node = child;
l->next = parent->children->next;
parent->children->next = l;
return child;
}
void print_ast() {
print_tree(root, 0);
}
void print_tree(tree t, int depth) {
if (!t) return;
for (int i = 0; i < depth; i++) printf(" ");
printf("%s\n", node_type_str[t->val.type]);
list l = t->children->next;
while (l) {
print_tree(l->node, depth + 1);
l = l->next;
}
}
void free_tree(tree t) {
if (!t) return;
list l = t->children->next;
while (l) {
free_tree(l->node);
l = l->next;
}
free(t->children);
free(t);
}
// int main() {
// // try to build a tree
// init_tree();
// tree t = root;
// add(nCONST_DECL);
// leave();
// add(nVAR_DECL);
// add(nCONST_DECL);
// add(nPROGRAM);
// print_tree(root, 0);
// free_tree(root);
// }