@ 60772087cdbbe3e7543eaf73a6f0ffc9a26570c7 | history
package eval
import (
"testing"
"government/sexpr"
)
func mustLookup(t *testing.T, e *Env, name sexpr.Symbol, want sexpr.Value) {
t.Helper()
got, ok := e.Lookup(name)
if !ok {
t.Fatalf("Lookup(%s): unbound, want %s", name, sexpr.Print(want))
}
if got != want {
t.Errorf("Lookup(%s) = %s, want %s", name, sexpr.Print(got), sexpr.Print(want))
}
}
func mustBeUnbound(t *testing.T, e *Env, name sexpr.Symbol) {
t.Helper()
if got, ok := e.Lookup(name); ok {
t.Errorf("Lookup(%s) = %s, want unbound", name, sexpr.Print(got))
}
}
func TestEmptyEnv(t *testing.T) {
var empty *Env
mustBeUnbound(t, empty, "x")
}
func TestLookup(t *testing.T) {
e := (*Env)(nil).Extend("x", sexpr.Int(1)).Extend("y", sexpr.Int(2))
mustLookup(t, e, "x", sexpr.Int(1))
mustLookup(t, e, "y", sexpr.Int(2))
mustBeUnbound(t, e, "z")
}
func TestShadowing(t *testing.T) {
outer := (*Env)(nil).Extend("x", sexpr.Int(1))
inner := outer.Extend("x", sexpr.Int(2))
mustLookup(t, inner, "x", sexpr.Int(2))
mustLookup(t, outer, "x", sexpr.Int(1))
}
// What a closure relies on: an environment never changes after it is
// captured, no matter how it is extended later.
func TestExtendNeverAffectsParent(t *testing.T) {
parent := (*Env)(nil).Extend("x", sexpr.Int(1))
a := parent.Extend("y", sexpr.String("a"))
b := parent.Extend("y", sexpr.String("b"))
mustBeUnbound(t, parent, "y")
mustLookup(t, a, "y", sexpr.String("a"))
mustLookup(t, b, "y", sexpr.String("b"))
mustLookup(t, a, "x", sexpr.Int(1))
mustLookup(t, b, "x", sexpr.Int(1))
}