forked from sabrsorensen/Compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
symbol_table.py
78 lines (65 loc) · 2.66 KB
/
symbol_table.py
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
__authors__ = 'Sam Sorensen', 'Keith Smith', 'Anna Andriyanova'
__date__ = 'Spring 2012'
from semantic_entry import SemanticEntry
from semantic_record import SemanticRecord
from collections import OrderedDict
class SymbolTable(object):
def __init__(self, parent):
self.parent_table = parent
self.name = ''
if parent:
self.cur_depth = self.parent_table.cur_depth
else:
self.cur_depth = 0
self.context_attributes_stack = []
self.cur_context_attributes = None
self.sym_table = OrderedDict()
self.record = SemanticRecord()
self.cur_offset = 0
def create(self): #subtables
self.cur_context_attributes = ContextAttrs()
self.cur_depth += 1
def create_root(self): #Root table
self.cur_context_attributes = ContextAttrs()
def destroy(self):
self.cur_lexeme = ''
for lexeme in self.cur_context_attributes.context_lexemes:
self.cur_entry = self.find(lexeme)
if self.cur_entry:
self.cur_entry.back_out()
if self.cur_entry.semantic_record_stack is None:
del self.sym_table[lexeme]
def insert(self, record):
self.record = record
self.cur_context_attributes.context_lexemes.append(self.record.lexeme)
self.record.offset = self.cur_offset
self.cur_offset += self.record.size
self.existing_entry = self.find(self.record.lexeme)
if self.existing_entry is None:
self.new_entry = SemanticEntry()
# self.record.depth = 0
self.new_entry.put(self.record)
self.sym_table[self.record.lexeme] = self.new_entry
else:
self.record.depth = self.existing_entry.depth
self.existing_entry.put(self.record)
def find(self, lexeme):
if self.sym_table.get(lexeme, None):
return self.sym_table.get(lexeme, None)
elif self.parent_table and self.parent_table.sym_table.get(lexeme,None):
return self.parent_table.find(lexeme)
else:
return None
def __repr__(self):
output = "\n[%7s |%7s |%7s |%7s |%7s |%7s ]" % ("lexeme", "kind",
"type", "size",
"offset", "depth")
for k,v in self.sym_table.items():
output = output + '\n' + v.cur_record.__repr__()
return output
class ContextAttrs(object):
def __init__(self):
self.context_lexemes = []
self.nesting_level = 1
self.cur_offset = None
# note: no need for size; len(ex.context_lexemes) works.