symbol_table_test.go 898 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package compiler
  2. import "testing"
  3. func TestDefine(t *testing.T) {
  4. expected := map[string]Symbol{
  5. "a": {"a", GlobalScope, 0},
  6. "b": {"b", GlobalScope, 1},
  7. }
  8. global := NewSymbolTable()
  9. a := global.Define("a")
  10. if a != expected["a"] {
  11. t.Errorf("expected a=%+v, got=%+v", expected["a"], a)
  12. }
  13. b := global.Define("b")
  14. if b != expected["b"] {
  15. t.Errorf("expected b=%+v, got=%+v", expected["b"], b)
  16. }
  17. }
  18. func TestResolveGlobal(t *testing.T) {
  19. global := NewSymbolTable()
  20. global.Define("a")
  21. global.Define("b")
  22. expected := []Symbol{
  23. {Name: "a", Scope: GlobalScope, Index: 0},
  24. {Name: "b", Scope: GlobalScope, Index: 1},
  25. }
  26. for _, sym := range expected {
  27. result, ok := global.Resolve(sym.Name)
  28. if !ok {
  29. t.Errorf("name %s not resolvable", sym.Name)
  30. continue
  31. }
  32. if result != sym {
  33. t.Errorf("expected %s to resolve to %+v, got=%+v",
  34. sym.Name, sym, result)
  35. }
  36. }
  37. }