-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymbol.hpp
110 lines (100 loc) · 1.93 KB
/
symbol.hpp
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
#pragma once
#include <cstdlib>
#include <vector>
#include <map>
#include <unordered_set>
void semerror(std::string msg);
class Type;
class SymbolEntry
{
public:
SymbolEntry(Type *t, int ofs) : type(t), offset(ofs) {}
SymbolEntry() {}
Type *type;
int offset;
};
class Scope
{
public:
Scope() : locals(), offset(-1), size(0) {}
Scope(int ofs) : locals(), offset(ofs), size(0) {}
SymbolEntry *lookup(std::string &id)
{
if (locals.find(id) == locals.end())
{
return nullptr;
}
return &locals[id];
}
void insert(std::string &id, Type *t)
{
if (locals.find(id) != locals.end())
{
semerror("Redeclared identifier " + id);
}
locals[id] = SymbolEntry(t, offset++);
++size;
}
private:
std::map<std::string, SymbolEntry> locals;
public:
int offset;
int size;
};
class SymbolTable
{
public:
void openScope()
{
int ofs = scopes.empty() ? 0 : scopes.back().offset;
scopes.push_back(Scope(ofs));
}
void closeScope()
{
int ofs = scopes.back().offset;
scopes.pop_back();
scopes.back().offset = ofs;
}
SymbolEntry *lookup(std::string &id)
{
for (auto i = scopes.rbegin(); i != scopes.rend(); ++i)
{
SymbolEntry *e = i->lookup(id);
if (e != nullptr)
{
id = id + "_" + std::to_string(e->offset);
return e;
}
}
semerror("Unknown identifier " + id);
return nullptr;
}
void insert(std::string &id, Type *t)
{
scopes.back().insert(id, t);
id = id + "_" + std::to_string(scopes.back().offset - 1);
}
private:
std::vector<Scope> scopes;
};
class TypeDefTable
{
public:
void lookup(std::string &id)
{
if (types.count(id) == 0)
{
semerror("Unknown identifier " + id);
}
}
void insert(std::string &id)
{
if (types.count(id) > 0)
{
semerror("Redeclared identifier " + id);
}
types.insert(id);
}
private:
std::unordered_set<std::string> types = {};
};