closures and they can recurse!!!
Some checks failed
Build / build (push) Failing after 1m35s
Test / build (push) Has been cancelled

This commit is contained in:
Chuck Smith
2024-03-14 20:08:40 -04:00
parent 78b560e457
commit cc78fee3c8
10 changed files with 640 additions and 39 deletions

View File

@@ -3,9 +3,11 @@ package compiler
type SymbolScope string
const (
LocalScope SymbolScope = "LOCAL"
GlobalScope SymbolScope = "GLOBAL"
BuiltinScope SymbolScope = "BUILTIN"
LocalScope SymbolScope = "LOCAL"
GlobalScope SymbolScope = "GLOBAL"
BuiltinScope SymbolScope = "BUILTIN"
FreeScope SymbolScope = "FREE"
FunctionScope SymbolScope = "FUNCTION"
)
type Symbol struct {
@@ -19,6 +21,8 @@ type SymbolTable struct {
store map[string]Symbol
numDefinitions int
FreeSymbols []Symbol
}
func NewEnclosedSymbolTable(outer *SymbolTable) *SymbolTable {
@@ -29,7 +33,8 @@ func NewEnclosedSymbolTable(outer *SymbolTable) *SymbolTable {
func NewSymbolTable() *SymbolTable {
s := make(map[string]Symbol)
return &SymbolTable{store: s}
free := []Symbol{}
return &SymbolTable{store: s, FreeSymbols: free}
}
func (s *SymbolTable) Define(name string) Symbol {
@@ -49,7 +54,17 @@ 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
if !ok {
return obj, ok
}
if obj.Scope == GlobalScope || obj.Scope == BuiltinScope {
return obj, ok
}
free := s.DefineFree(obj)
return free, true
}
return obj, ok
@@ -60,3 +75,19 @@ func (s *SymbolTable) DefineBuiltin(index int, name string) Symbol {
s.store[name] = symbol
return symbol
}
func (s *SymbolTable) DefineFree(original Symbol) Symbol {
s.FreeSymbols = append(s.FreeSymbols, original)
symbol := Symbol{Name: original.Name, Index: len(s.FreeSymbols) - 1}
symbol.Scope = FreeScope
s.store[original.Name] = symbol
return symbol
}
func (s *SymbolTable) DefineFunctionName(name string) Symbol {
symbol := Symbol{Name: name, Index: 0, Scope: FunctionScope}
s.store[name] = symbol
return symbol
}