-
Notifications
You must be signed in to change notification settings - Fork 0
/
symbol_table.py
54 lines (42 loc) · 1.25 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
import enum
from collections import namedtuple
import ir
from tokens import TokenKind
class ScopeType(enum.Enum):
"""
Would help to differentiate local and global variables memory binding.
Because global vars will have absolute memory address, while local would
have offset from BP register.
"""
LOCAL = 'local'
GLOBAL = 'global'
# Describe C types
CType = namedtuple('CType', ['size'])
CTypeInt = CType(4)
CTypeChar = CType(2)
CTypeVoid = CType(0)
class NewSymbolTable:
def __init__(self):
self.tables = []
self.open_scope()
def add_variable(self, name, c_type=CTypeInt, binding=ScopeType.LOCAL):
"""Add variable to symbol table."""
curr_table = self.tables[len(self.tables) - 1]
var = ir.IRValue(c_type, name)
curr_table[name] = (var, binding)
return var
def lookup(self, name):
var = None
for table in self.tables[::-1]:
if name in table:
(var, _) = table[name]
break
return var
def open_scope(self):
self.tables.append({})
def close_scope(self):
self.tables.pop()
def get_c_type_from_token(token):
return {
TokenKind.INT: CTypeInt
}.get(token.kind)