-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast.h
100 lines (90 loc) · 2.38 KB
/
ast.h
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
//This file gives implemenation of relevent functions to constructing the abstract syntax tree.
#ifndef FILE_AST_H
#define FILE_AST_H
//s
#include "def.h"
#include "header.h"
TreeNode* create_node(TreeNodeType, char*, int, ...);
TreeNode* merge_node(TreeNode*, TreeNode*);
void double_space(TreeNode*);
void print_ast(TreeNode*, int);
TreeNode* treeroot;
void double_space(TreeNode* p) { //check if need to extend
if (p->size == p->capacity) {
assert(p->capacity > 0); //these tree nodes need to double space cannot be the leaf
TreeNode** children = (TreeNode**)malloc(sizeof(TreeNode*) * (p->capacity << 1));
int i;
for (i = 0; i < p->size; i++) {
children[i] = p->children[i];
}
free(p->children);
p->children = children;
p->capacity <<= 1;
}
}
TreeNode* create_node(int lineno,TreeNodeType type, char* data, int cnt, ...) {
TreeNode* ptr = (TreeNode*)malloc(sizeof(TreeNode));
ptr->line_num = lineno;
ptr->type = type;
ptr->data = strdup(data);
ptr->size = ptr->capacity = cnt;
ptr->children = (TreeNode**)malloc(sizeof(TreeNode*) * cnt);
va_list ap;
va_start(ap, cnt);
int i;
for (i = 0; i < cnt; i++) {
ptr->children[i] = va_arg(ap, TreeNode*);
}
va_end(ap);
return ptr;
}
TreeNode* merge_node(TreeNode* a, TreeNode* b) {
double_space(a);
a->children[a->size++] = b;
return a;
}
#define MAX_LENGTH 10000000
char buffer[MAX_LENGTH];
void print_ast(TreeNode* ptr, int depth) {
int i;
int n = (depth - 1) * 2;
/*
if (depth > 0) {
for (i = 0; i < n; i++) {
putchar(buffer[i]);
}
putchar('|');
puts("");
}
*/
for (i = 0; i < n; i++) {
putchar(buffer[i]);
}
if (depth > 0) {
putchar('|');
putchar('_');
}
n = depth * 2;
buffer[n] = '|';
buffer[n + 1] = ' ';
//printf("%s\n", ptr->data);
// terminal customized configuration
if (ptr->size > 0) {
printf("%s\n", ptr->data);
} else {
printf("\033[31;1m%s\033[0m\n", ptr->data);
/*
for (i = 0; i < n; i++) {
putchar(buffer[i]);
}
puts("");
*/
}
for (i = 0; i < ptr->size; i++) {
if (i == ptr->size - 1) {
buffer[n] = ' ';
}
print_ast(ptr->children[i], depth + 1);
}
}
#endif