symbol_table.go 648 B

123456789101112131415161718192021222324252627282930313233343536
  1. package compiler
  2. type SymbolScope string
  3. const (
  4. GlobalScope SymbolScope = "GLOBAL"
  5. )
  6. type Symbol struct {
  7. Name string // identifier
  8. Scope SymbolScope
  9. Index int
  10. }
  11. type SymbolTable struct {
  12. store map[string]Symbol
  13. numDefinitions int
  14. }
  15. func NewSymbolTable() *SymbolTable {
  16. s := make(map[string]Symbol)
  17. return &SymbolTable{store: s}
  18. }
  19. func (s *SymbolTable) Define(name string) Symbol {
  20. symbol := Symbol{Name: name, Index: s.numDefinitions, Scope: GlobalScope}
  21. s.store[name] = symbol
  22. s.numDefinitions++
  23. return symbol
  24. }
  25. func (s *SymbolTable) Resolve(name string) (Symbol, bool) {
  26. obj, ok := s.store[name]
  27. return obj, ok
  28. }