-
Notifications
You must be signed in to change notification settings - Fork 0
/
SymbolTable.h
79 lines (66 loc) · 1.81 KB
/
SymbolTable.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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct SymbolInfo {
string type; // type of the thingy
string symbol; // assembly variable name
string code; // assembly codes
vector<string> parameters; // parameters if function/argument_list
vector<string> variables; // variables created in a compound_statement
string function_id; // proc name
SymbolInfo(string symbol="", string type="") :
symbol(symbol), type(type), code(""), parameters() { }
SymbolInfo(const SymbolInfo *ptr) :
symbol(ptr->symbol), type(ptr->type), code(ptr->code), parameters(ptr->parameters) { }
void print(ostream &out=cout) {
out << "type = " << type << "\n"
<< "symbol = " << symbol << "\n"
<< "code = " << code << "\n"
<< "parameters: ";
for(auto para : parameters) out << para << " ";
out << "\n";
}
};
struct SymbolTable {
typedef map< string, SymbolInfo* > scope;
vector< scope > scopes;
SymbolTable() {
scopes.resize(1);
}
void insert(string key, SymbolInfo *ptr) {
// cerr << "To insert " << key << ": " << ptr->symbol << "\n";
assert(!scopes.empty());
auto &tail = scopes.back();
tail[key] = ptr;
}
void insert(vector< pair<string, SymbolInfo*> > &v) {
for(auto &qq : v) {
insert(qq.first, qq.second);
}
v.clear();
}
SymbolInfo* search(string key) {
for(int i=(int) scopes.size()-1; i>=0; --i) {
auto &cur = scopes[i];
// cerr << "To search: " << key << ": " << i << "\n";
auto it = cur.find(key);
if(it != cur.end()) {
// cerr << "Found " << key << "\n";
return it->second;
}
}
// cerr << "Not found " << key << "\n";
return nullptr;
}
void add_scope() {
scopes.push_back(scope());
}
void remove_scope() {
assert(!scopes.empty());
scopes.pop_back();
}
int current_scope() {
return (int) scopes.size() - 1;
}
};