@ efc0e8ad4d88be48a5cdedd9b62e88420b8b6e5e | history
package eval
import "nmyk.io/government/sexpr"
// Env is a lexical environment: a linked list of bindings, innermost first.
// The nil *Env is the empty environment.
//
// Extending returns a new head that points at the old list, so a closure
// can capture an environment just by keeping the pointer: later extensions
// by anyone else are invisible to it. Lookup walks the chain, so the first
// match is the innermost binding, which is what makes shadowing work.
//
// Bindings never change, with one exception that exists for recursion: a
// define creates its binding empty (pending), evaluates the value in an
// environment that already contains the binding, then fills it exactly
// once. Until then any use of the name is an error, so no one can observe
// the binding changing.
type Env struct {
name sexpr.Symbol
value sexpr.Value
pending bool
parent *Env
}
func (e *Env) Extend(name sexpr.Symbol, value sexpr.Value) *Env {
return &Env{name: name, value: value, parent: e}
}
func (e *Env) Lookup(name sexpr.Symbol) (sexpr.Value, bool) {
b := e.binding(name)
if b == nil || b.pending {
return nil, false
}
return b.value, true
}
func (e *Env) binding(name sexpr.Symbol) *Env {
for b := e; b != nil; b = b.parent {
if b.name == name {
return b
}
}
return nil
}
func (e *Env) extendPending(name sexpr.Symbol) *Env {
return &Env{name: name, pending: true, parent: e}
}
func (e *Env) fill(value sexpr.Value) {
e.value = value
e.pending = false
}