government / eval / closure.go

@ 60772087cdbbe3e7543eaf73a6f0ffc9a26570c7 | history


package eval

import "government/sexpr"

// Closure is a lambda's code paired with the environment it was created
// in. Calling it extends that environment, never the caller's, which is
// what makes scope lexical.
type Closure struct {
	sexpr.FunctionBase
	params []sexpr.Symbol
	body   []sexpr.Value
	env    *Env
}

func (*Closure) Name() string { return "" }

// (lambda (p1 ... pk) body...)
//
// The parameter list is checked once, here, rather than on every call.
func evalLambda(operands []sexpr.Value, env *Env) (sexpr.Value, error) {
	if len(operands) == 0 {
		return nil, errorf(ErrSyntax, "lambda needs a parameter list and a body")
	}
	params, err := parseParams(operands[0])
	if err != nil {
		return nil, err
	}
	body := operands[1:]
	if len(body) == 0 {
		return nil, errorf(ErrSyntax, "lambda needs a body")
	}
	return &Closure{params: params, body: body, env: env}, nil
}

func parseParams(v sexpr.Value) ([]sexpr.Symbol, error) {
	items, ok := properList(v)
	if !ok {
		return nil, errorf(ErrSyntax, "lambda parameters must be a list of symbols, got %s", sexpr.Print(v))
	}
	params := make([]sexpr.Symbol, len(items))
	seen := make(map[sexpr.Symbol]bool, len(items))
	for i, item := range items {
		name, ok := item.(sexpr.Symbol)
		if !ok {
			return nil, errorf(ErrSyntax, "lambda parameter %s is not a symbol", sexpr.Print(item))
		}
		if isReserved(name) {
			return nil, errorf(ErrSyntax, "lambda parameter %s is a reserved name", name)
		}
		if seen[name] {
			return nil, errorf(ErrSyntax, "duplicate lambda parameter %s", name)
		}
		seen[name] = true
		params[i] = name
	}
	return params, nil
}

// applyClosure binds each parameter to its argument in the closure's own
// environment, then evaluates the body forms in order. The value of the
// last one is the result.
func applyClosure(c *Closure, args []sexpr.Value) (sexpr.Value, error) {
	if len(args) != len(c.params) {
		return nil, errorf(ErrArity, "lambda takes %s, got %d", plural(len(c.params), "argument"), len(args))
	}
	env := c.env
	for i, p := range c.params {
		env = env.Extend(p, args[i])
	}
	var result sexpr.Value
	for _, form := range c.body {
		var err error
		if result, err = Eval(form, env); err != nil {
			return nil, err
		}
	}
	return result, nil
}

// Reserved names are the special forms and builtins. In a .gov program
// they are a separate namespace from user symbols, so they can never be
// rebound; rejecting them here keeps source-mode programs consistent with
// that.
func isReserved(name sexpr.Symbol) bool {
	if _, ok := specialForms[name]; ok {
		return true
	}
	return builtinNames[name]
}