symbol_table.go 974 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package compiler
  2. type SymbolScope string
  3. const (
  4. GlobalScope SymbolScope = "GLOBAL"
  5. LocalScope SymbolScope = "LOCAL"
  6. )
  7. type Symbol struct {
  8. Name string // identifier
  9. Scope SymbolScope
  10. Index int
  11. }
  12. type SymbolTable struct {
  13. Outer *SymbolTable
  14. store map[string]Symbol
  15. numDefinitions int
  16. }
  17. func NewSymbolTable() *SymbolTable {
  18. s := make(map[string]Symbol)
  19. return &SymbolTable{store: s}
  20. }
  21. func NewEnclosedSymbolTable(outer *SymbolTable) *SymbolTable {
  22. s := NewSymbolTable()
  23. s.Outer = outer
  24. return s
  25. }
  26. func (s *SymbolTable) Define(name string) Symbol {
  27. symbol := Symbol{Name: name, Index: s.numDefinitions}
  28. if s.Outer == nil {
  29. symbol.Scope = GlobalScope
  30. } else {
  31. symbol.Scope = LocalScope
  32. }
  33. s.store[name] = symbol
  34. s.numDefinitions++
  35. return symbol
  36. }
  37. func (s *SymbolTable) Resolve(name string) (Symbol, bool) {
  38. obj, ok := s.store[name]
  39. if !ok && s.Outer != nil {
  40. obj, ok = s.Outer.Resolve(name)
  41. return obj, ok
  42. }
  43. return obj, ok
  44. }