functions with bindings
This commit is contained in:
@@ -3,7 +3,8 @@ package compiler
|
||||
type SymbolScope string
|
||||
|
||||
const (
|
||||
GlobalScope SymbolScope = "Global"
|
||||
LocalScope SymbolScope = "LOCAL"
|
||||
GlobalScope SymbolScope = "GLOBAL"
|
||||
)
|
||||
|
||||
type Symbol struct {
|
||||
@@ -13,21 +14,31 @@ type Symbol struct {
|
||||
}
|
||||
|
||||
type SymbolTable struct {
|
||||
Outer *SymbolTable
|
||||
|
||||
store map[string]Symbol
|
||||
numDefinitions int
|
||||
}
|
||||
|
||||
func NewEnclosedSymbolTable(outer *SymbolTable) *SymbolTable {
|
||||
s := NewSymbolTable()
|
||||
s.Outer = outer
|
||||
return s
|
||||
}
|
||||
|
||||
func NewSymbolTable() *SymbolTable {
|
||||
s := make(map[string]Symbol)
|
||||
return &SymbolTable{store: s}
|
||||
}
|
||||
|
||||
func (s *SymbolTable) Define(name string) Symbol {
|
||||
symbol := Symbol{
|
||||
Name: name,
|
||||
Scope: GlobalScope,
|
||||
Index: s.numDefinitions,
|
||||
symbol := Symbol{Name: name, Index: s.numDefinitions}
|
||||
if s.Outer == nil {
|
||||
symbol.Scope = GlobalScope
|
||||
} else {
|
||||
symbol.Scope = LocalScope
|
||||
}
|
||||
|
||||
s.store[name] = symbol
|
||||
s.numDefinitions++
|
||||
return symbol
|
||||
@@ -35,5 +46,10 @@ func (s *SymbolTable) Define(name string) Symbol {
|
||||
|
||||
func (s *SymbolTable) Resolve(name string) (Symbol, bool) {
|
||||
obj, ok := s.store[name]
|
||||
if !ok && s.Outer != nil {
|
||||
obj, ok = s.Outer.Resolve(name)
|
||||
return obj, ok
|
||||
}
|
||||
|
||||
return obj, ok
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user