-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymbol_table.go
80 lines (69 loc) · 1.85 KB
/
symbol_table.go
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
package main
import "fmt"
type Scope string
const (
FunctionScope Scope = "FunctionScope"
ClassScope = "ClassScope"
)
type SymbolTable struct {
classScopeTable map[string]Symbol
functionScopeTable map[string]Symbol
}
func NewSymbolTable() SymbolTable {
return SymbolTable{
classScopeTable: make(map[string]Symbol),
functionScopeTable: make(map[string]Symbol),
}
}
func nextIndex(table *map[string]Symbol, symbolType SymbolType) (index MachineWord) {
for _, symbol := range *table {
if symbol.symbolType == symbolType {
index += 1
}
}
return
}
func registerSymbol(table *map[string]Symbol, name string, symbol Symbol) Symbol {
symbol.index = nextIndex(table, symbol.symbolType)
(*table)[name] = symbol
return symbol
}
func (s *SymbolTable) Count(symbolType SymbolType, scope Scope) (index MachineWord) {
switch scope {
case ClassScope:
index = nextIndex(&s.classScopeTable, symbolType)
case FunctionScope:
index = nextIndex(&s.functionScopeTable, symbolType)
}
return
}
func (s *SymbolTable) Declare(symbol Symbol, name string, scope Scope) Symbol {
switch scope {
case ClassScope:
symbol = registerSymbol(&s.classScopeTable, name, symbol)
case FunctionScope:
symbol = registerSymbol(&s.functionScopeTable, name, symbol)
}
return symbol
}
func (s *SymbolTable) Lookup(name string) (Symbol, error) {
// Try to find it in the method scope table
if symbol, ok := s.functionScopeTable[name]; ok {
return symbol, nil
}
// Try to find it in the class scope table
if symbol, ok := s.classScopeTable[name]; ok {
return symbol, nil
}
// error
return Symbol{}, fmt.Errorf("no symbol with name %q declared", name)
}
func (s *SymbolTable) Clear(scope Scope) {
switch scope {
case ClassScope:
s.classScopeTable = make(map[string]Symbol)
fallthrough
case FunctionScope:
s.functionScopeTable = make(map[string]Symbol)
}
}