-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymbol_table.cpp
104 lines (89 loc) · 2.23 KB
/
symbol_table.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
#include "symbol_table.hpp"
#include "err.hpp"
#include "types.hpp"
namespace holeyc{
SymbolTable::SymbolTable(){
scopeTableChain = new std::list<ScopeTable *>();
}
void SymbolTable::print(){
for(auto scope : *scopeTableChain){
std::cout << "--- scope ---\n";
std::cout << scope->toString();
}
}
ScopeTable * SymbolTable::enterScope(){
ScopeTable * newScope = new ScopeTable();
scopeTableChain->push_front(newScope);
return newScope;
}
void SymbolTable::leaveScope(){
if (scopeTableChain->empty()){
throw new InternalError("Attempt to pop"
"empty symbol table");
}
scopeTableChain->pop_front();
}
ScopeTable * SymbolTable::getCurrentScope(){
return scopeTableChain->front();
}
bool SymbolTable::clash(std::string varName){
bool hasClash = getCurrentScope()->clash(varName);
return hasClash;
}
SemSymbol * SymbolTable::find(std::string varName){
for (ScopeTable * scope : *scopeTableChain){
SemSymbol * sym = scope->lookup(varName);
if (sym != nullptr) { return sym; }
}
return nullptr;
}
bool SymbolTable::insert(SemSymbol * symbol){
return scopeTableChain->front()->insert(symbol);
}
ScopeTable::ScopeTable(){
symbols = new HashMap<std::string, SemSymbol *>();
}
std::string ScopeTable::toString(){
std::string result = "";
for (auto entry : *symbols){
result += entry.second->toString();
result += "\n";
}
return result;
}
bool ScopeTable::clash(std::string varName){
SemSymbol * found = lookup(varName);
if (found != nullptr){
return true;
}
return false;
}
SemSymbol * ScopeTable::lookup(std::string name){
auto found = symbols->find(name);
if (found == symbols->end()){
return NULL;
}
return found->second;
}
bool ScopeTable::insert(SemSymbol * symbol){
std::string symName = symbol->getName();
bool alreadyInScope = (this->lookup(symName) != NULL);
if (alreadyInScope){
return false;
}
this->symbols->insert(std::make_pair(symName, symbol));
return true;
}
std::string SemSymbol::toString(){
std::string result = "";
result += "name: " + this->getName();
result += "\nkind: " + kindToString(this->getKind());
DataType * type = this->getDataType();
if (type == nullptr){
result += "\ntype: NULL";
} else {
result += "\ntype: " + this->getDataType()->getString();
}
return result + "\n";
}
}