-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSymbolTable.py
More file actions
59 lines (43 loc) · 1.47 KB
/
SymbolTable.py
File metadata and controls
59 lines (43 loc) · 1.47 KB
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
class SymbolTable:
def __init__(self):
super().__init__()
self.globalTable = ScopedTable(None)
self.currentScope = self.globalTable
def contains(self, name):
return self.currentScope.contains(name)
def put(self, name, symbol):
self.currentScope.put(name, symbol)
def replace(self, name, symbol):
self.currentScope.replace(name, symbol)
def get(self, name):
return self.currentScope.get(name)
def pushScope(self):
self.currentScope = ScopedTable(self.currentScope)
def popScope(self):
self.currentScope = self.currentScope.parentTable()
class ScopedTable:
def __init__(self, parent: 'ScopedTable'):
self.parent = parent
self.tbl = {}
def parentTable(self):
return self.parent
def contains(self, name):
if name in self.tbl:
return True
if self.parentTable() is not None:
return self.parentTable().contains(name)
else:
return False
def put(self, name, symbol):
self.tbl[name] = symbol
def replace(self, name, symbol):
if name in self.tbl:
self.tbl[name] = symbol
else:
self.parentTable().replace(name, symbol)
def get(self, name):
if name in self.tbl:
return self.tbl[name]
if self.parentTable() is None:
raise Exception('Name not found - ' + name)
return self.parentTable().get(name)