forked from Uyouii/cCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.cpp
118 lines (112 loc) · 3.27 KB
/
tree.cpp
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
#include"tree.h"
#include"tools.h"
gramTree* create_tree(string name, int num,...) {
va_list valist;
gramTree* head = new gramTree();
if(!head) {
printf("Out of space \n");
exit(0);
}
head->left = NULL;
head->right = NULL;
head->content = "";
gramTree* temp = NULL;
head->name = name;
va_start(valist,num);
if(num > 0) {
temp = va_arg(valist,gramTree*);
head->left = temp;
head->line = temp->line;
if(num == 1) {
//head->content = temp->content;
if(temp->content.size() > 0) {
head->content = temp->content;
}
else head->content = "";
}
else {
for(int i = 1; i < num; ++i ) {
temp->right = va_arg(valist,gramTree*);
temp = temp->right;
}
}
}
else {
int line = va_arg(valist,int);
head->line = line;
if(head->name == "CONSTANT_INT") {
int value;
if(strlen(yytext) > 1 && yytext[0] == '0' && yytext[1] != 'x') {
sscanf(yytext,"%o",&value); //8进制整数
}
else if(strlen(yytext) > 1 && yytext[1] == 'x'){
sscanf(yytext,"%x",&value); //16进制整数
}
else value = atoi(yytext); //10进制整数
head->content = inttostr(value);
//printf("%d",value);
}
else if(head->name == "CONSTANT_DOUBLE") {
head->content = yytext;
}
else if(head->name == "TRUE") {
head->content = inttostr(1);
}
else if(head->name == "FALSE") {
head->content = inttostr(0);
}
else if(head->name == "STRING_LITERAL") {
head->content = yytext;
}
else {
head->content = yytext;
}
}
return head;
}
void eval(gramTree *head,int leavel) {
if(head!=NULL) {
string Name = head->name;
if(head->line!=-1) {
for(int i=0;i<leavel;++i) {
cout << ". ";
}
cout << head->name;
if(head->name == "IDENTIFIER"||head->name == "BOOL"|| head->name == "INT" ||
head->name == "CHAR" || head->name == "DOUBLE") {
cout << ":" << head->content;
}
else if(head->name == "CONSTANT_INT" || head->name == "TRUE" || head->name == "FALSE") {
cout << ":" << head->content << " ";
}
else if(head->name == "CONSTANT_DOUBLE") {
cout << ":" << head->content << " ";
}
else if(head->name=="STRING_LITERAL") {
cout << ":" << head->content;
}
else {
cout << " <" << head->line << ">";
}
cout << endl;
}
eval(head->left,leavel+1);
eval(head->right,leavel);
}
}
void freeGramTree(gramTree* node) {
if (node == NULL)
return;
freeGramTree(node->left);
delete node;
freeGramTree(node->right);
}
char* my_substring(char* s, int begin, int end) {
char* result = (char*)malloc(end - begin + 1);
int i;
for(i = begin; i < end; i++) {
result[i - begin] = s[i];
}
result[i - begin] = 0;
return result;
}