Files
monkey/compiler/symbol_table.go
Chuck Smith e373e9f68a
Some checks failed
Build / build (push) Failing after 1h2m55s
Test / build (push) Failing after 29m38s
builtins
2024-03-12 16:35:24 -04:00

63 lines
1.1 KiB
Go

package compiler
type SymbolScope string
const (
LocalScope SymbolScope = "LOCAL"
GlobalScope SymbolScope = "GLOBAL"
BuiltinScope SymbolScope = "BUILTIN"
)
type Symbol struct {
Name string
Scope SymbolScope
Index int
}
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, Index: s.numDefinitions}
if s.Outer == nil {
symbol.Scope = GlobalScope
} else {
symbol.Scope = LocalScope
}
s.store[name] = symbol
s.numDefinitions++
return 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
}
func (s *SymbolTable) DefineBuiltin(index int, name string) Symbol {
symbol := Symbol{Name: name, Index: index, Scope: BuiltinScope}
s.store[name] = symbol
return symbol
}