@ b16190dee4ae781544f8119bec44f00f5224c810 | history
package eval
import "government/sexpr"
// A scope is one run of sequential definitions: the top level of a program,
// or the defines at the start of one lambda call's body. Each define extends env, so a definition sees the ones before
// it and itself, never the ones after it: self-recursion works, mutual
// recursion does not.
type scope struct {
env *Env
names map[sexpr.Symbol]bool
}
func newScope(env *Env) *scope {
return &scope{env: env, names: map[sexpr.Symbol]bool{}}
}
// define evaluates (define name expr) and adds name to the scope.
func (s *scope) define(form []sexpr.Value) (sexpr.Value, error) {
if len(form) != 3 {
return nil, errorf(ErrSyntax, "define takes a name and a value, got %s", plural(len(form)-1, "operand"))
}
name, ok := form[1].(sexpr.Symbol)
if !ok {
return nil, errorf(ErrSyntax, "define needs a symbol name, got %s", sexpr.Print(form[1]))
}
if isReserved(name) {
return nil, errorf(ErrSyntax, "cannot define reserved name %s", name)
}
if s.names[name] {
return nil, errorf(ErrImmutable, "%s is already defined in this scope; bindings are immutable", name)
}
slot := s.env.extendPending(name)
v, err := Eval(form[2], slot)
if err != nil {
return nil, err
}
// A closure takes the name it is first defined under, for printing and
// error messages. Only a lambda written directly in the define is
// named: (define g f) must not rename f's closure.
if c, ok := v.(*Closure); ok && isFormNamed(form[2], "lambda") {
c.name = string(name)
}
slot.fill(v)
s.env = slot
s.names[name] = true
return name, nil
}
// TopLevel evaluates a program one top-level form at a time, keeping the
// definitions made so far.
type TopLevel struct {
scope *scope
}
func NewTopLevel() *TopLevel {
return NewTopLevelIn(Builtins())
}
// NewTopLevelIn starts a program in env instead of the builtins alone.
func NewTopLevelIn(env *Env) *TopLevel {
return &TopLevel{scope: newScope(env)}
}
func (t *TopLevel) Eval(form sexpr.Value) (sexpr.Value, error) {
if items, ok := defineForm(form); ok {
v, err := t.scope.define(items)
return v, at(err, form)
}
return Eval(form, t.scope.env)
}
// define reached through Eval is in expression position, such as inside an
// if. Scope-level code intercepts the defines that are allowed before they
// get here.
func evalMisplacedDefine(operands []sexpr.Value, env *Env) (outcome, error) {
return outcome{}, errorf(ErrSyntax, "define is only allowed at top level or at the start of a lambda body")
}
func defineForm(v sexpr.Value) ([]sexpr.Value, bool) {
if !isFormNamed(v, "define") {
return nil, false
}
return properList(v)
}
func isFormNamed(v sexpr.Value, head sexpr.Symbol) bool {
p, ok := v.(*sexpr.Pair)
return ok && p.Car == sexpr.Value(head)
}