-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree.cpp
150 lines (142 loc) · 2.66 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include "Tree.h"
#include "y.tab.hpp"
Tree::Tree(char* cstr) {
lr[0] = lr[1] = NULL;
attr.sval = new string(cstr);
type = ID;
}
Tree::Tree(int a) {
lr[0] = lr[1] = NULL;
attr.ival = a;
type = INUM;
}
Tree::Tree(float rv) {
lr[0] = lr[1] = NULL;
attr.rval = rv;
type = RNUM;
}
Tree::Tree(Tree* l, int op, Tree* r, int op_t) {
lr[0] = l; lr[1] = r;
attr.opval = op;
type = op_t;
}
Tree::Tree(Tree* l, int op, Tree* r) {
lr[0] = l; lr[1] = r;
attr.opval = op;
type = op;
}
string Tree::opint2str(int opint) {
switch (opint) {
case STAR:
return "*";
case SLASH:
return "/";
case EQ:
return "=";
case NE:
return "<>";
case LT:
return "<";
case LE:
return "<=";
case GT:
return ">";
case GE:
return ">=";
case OR:
return "or";
case PLUS:
return "+";
case MINUS:
return "-";
case AND:
return "and";
}
}
ostream& Tree::display(ostream& out, int level) {
string spacer = string(level, '\t');
out << spacer;
switch (this->type) {
case 0:
out << "LEAF";
break;
case ID:
out << *(this->attr.sval);
break;
case INUM:
out << this->attr.ival;
break;
case RNUM:
out << this->attr.rval;
break;
case FUNCTION_CALL:
out << "FUNCTION_CALL";
break;
case ARRAY_ACCESS:
out << "ARRAY_ACCESS";
break;
case ASSIGNOP:
out << ":=";
break;
case RELOP:
out << "RELOP:" << opint2str(this->attr.opval);
break;
case MULOP:
out << "MULOP:" << opint2str(this->attr.opval);
break;
case ADDOP:
out << "ADDOP:" << opint2str(this->attr.opval);
break;
case NOT:
out << "NOT";
break;
case COMMA:
out << ",";
break;
case WHILE:
out << "WHILE";
break;
case FOR:
out << "FOR";
break;
case TO:
out << "TO";
break;
case IF:
out << "IF";
break;
case ELSE:
out << "ELSE";
break;
case SEMICOLON:
out << ";";
break;
default:
out << "reached default case.";
}
out << endl;
if (this->lr[0] != NULL) {
this->lr[0]->display(out, level+1);
}
if (this->lr[1] != NULL) {
this->lr[1]->display(out, level+1);
}
return out;
}
void Tree::chained_relop_fixer() {
if (this == NULL) return;
if (this->type == 0) return;
if (this->type == RELOP && this->lr[0]->type == RELOP) {
// found RELOP chain.
Tree *r = new Tree(this->lr[0]->lr[1],
this->attr.opval,
this->lr[1],
this->type);
this->lr[0]->chained_relop_fixer();
this->type = MULOP;
this->attr.opval = AND;
this->lr[1] = r;
}
this->lr[0]->chained_relop_fixer();
this->lr[1]->chained_relop_fixer();
}