parent:
68160212362299a3894c7ae88d7b2c018f5cc3aa
nmyk <nick@nmyk.io>
2026-11-14T12:28:06-05:00
add lambda, closures
diff --git a/eval/builtin.go b/eval/builtin.go
index c25c4574fa2dc86af5414ee587aebc180eb8a477..bb1a55aee2cdf84b9e012870c821d0e5975fa99f 100644
--- a/eval/builtin.go
+++ b/eval/builtin.go
@@ -40,6 +40,14 @@ {name: "strcat", minArgs: 0, maxArgs: -1, fn: strcat},
{name: "str?", minArgs: 1, maxArgs: 1, fn: isString},
}
+var builtinNames = func() map[sexpr.Symbol]bool {
+ names := make(map[sexpr.Symbol]bool, len(builtins))
+ for _, b := range builtins {
+ names[sexpr.Symbol(b.name)] = true
+ }
+ return names
+}()
+
// Builtins returns the top-level environment: every builtin bound to its
// name.
func Builtins() *Env {
@@ -57,6 +65,8 @@ if err := checkArity(f, len(args)); err != nil {
return nil, err
}
return f.fn(args)
+ case *Closure:
+ return applyClosure(f, args)
}
panic(fmt.Sprintf("eval: cannot apply %T", f))
}
diff --git a/eval/closure.go b/eval/closure.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e8542af041ab35565d18512a1071b4f38335b74
--- /dev/null
+++ b/eval/closure.go
@@ -0,0 +1,89 @@
+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]
+}
diff --git a/eval/closure_test.go b/eval/closure_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..277820185c807de35eb9fc278ffe43b8f4fedf50
--- /dev/null
+++ b/eval/closure_test.go
@@ -0,0 +1,83 @@
+package eval
+
+import "testing"
+
+func TestLambda(t *testing.T) {
+ runEvalCases(t, []evalCase{
+ {"(lambda (x) x)", "#<lambda>"},
+ {"((lambda (x) (* x x)) 7)", "49"},
+ {"((lambda () 42))", "42"},
+ {"((lambda (a b c) (- a b c)) 10 3 2)", "5"},
+ {"((lambda (x) 1 2 x) 3)", "3"},
+ {"((lambda (x) 'x) 1)", "x"},
+
+ // Arguments are evaluated before the call; parameters bind values.
+ {"((lambda (x) x) (+ 1 2))", "3"},
+ {"((lambda (x y) (cons y x)) 1 2)", "(2 . 1)"},
+
+ // Functions are values: passed in, returned, stored in lists.
+ {"((lambda (f) (f 1 2)) +)", "3"},
+ {"((lambda (f) (f 1 2)) (lambda (a b) (- a b)))", "-1"},
+ {"((car (cons (lambda (x) (+ x 1)) ())) 41)", "42"},
+ {"(((lambda (n) (lambda (x) (+ x n))) 3) 4)", "7"},
+
+ // A closure keeps the environment it was created in. Each call to
+ // the outer lambda creates a new n, captured separately.
+ {"((lambda (make-adder) (+ ((make-adder 1) 10) ((make-adder 2) 10))) (lambda (n) (lambda (x) (+ x n))))", "23"},
+
+ // Parameters shadow outer bindings, including the test env's x = 1.
+ {"((lambda (x) x) 99)", "99"},
+ {"x", "1"},
+ {"((lambda (x) ((lambda (x) x) 2)) 1)", "2"},
+ {"((lambda (y) ((lambda (x) (+ x y)) 2)) 1)", "3"},
+
+ // The design's scoping test, with lambdas standing in for define
+ // until step 1.10. f is created where x is 1; g calls f from a
+ // scope where x is 2. Lexical scope gives 1; dynamic scope would
+ // give 2.
+ {`((lambda (x)
+ ((lambda (f)
+ ((lambda (g) (g 2))
+ (lambda (x) (f))))
+ (lambda () x)))
+ 1)`, "1"},
+
+ // Recursion without define: the function receives itself as an
+ // argument (self-application). Step 1.10 makes this unnecessary.
+ {`((lambda (fact) (fact fact 5))
+ (lambda (self n) (if (== n 0) 1 (* n (self self (- n 1))))))`, "120"},
+
+ // Unbound names inside a body are only an error when evaluated.
+ {"((lambda (x) (if x 1 boom)) T)", "1"},
+ {"(lambda () boom)", "#<lambda>"},
+ })
+}
+
+func TestLambdaErrors(t *testing.T) {
+ runErrorCases(t, []errorCase{
+ {"((lambda (x) x))", ErrArity, "lambda takes 1 argument, got 0"},
+ {"((lambda (x) x) 1 2)", ErrArity, "lambda takes 1 argument, got 2"},
+ {"((lambda () 1) 1)", ErrArity, "lambda takes 0 arguments, got 1"},
+ {"((lambda (a b) a) 1)", ErrArity, "lambda takes 2 arguments, got 1"},
+
+ {"(lambda)", ErrSyntax, "lambda needs a parameter list and a body"},
+ {"(lambda (x))", ErrSyntax, "lambda needs a body"},
+ {"(lambda x x)", ErrSyntax, "lambda parameters must be a list of symbols, got x"},
+ {"(lambda (x . y) x)", ErrSyntax, "lambda parameters must be a list of symbols, got (x . y)"},
+ {"(lambda (1) 1)", ErrSyntax, "lambda parameter 1 is not a symbol"},
+ {`(lambda ("s") 1)`, ErrSyntax, `lambda parameter "s" is not a symbol`},
+ {"(lambda ((x)) 1)", ErrSyntax, "lambda parameter (x) is not a symbol"},
+ {"(lambda (T) 1)", ErrSyntax, "lambda parameter T is not a symbol"},
+ {"(lambda (x y x) x)", ErrSyntax, "duplicate lambda parameter x"},
+
+ {"(lambda (+) 1)", ErrSyntax, "lambda parameter + is a reserved name"},
+ {"(lambda (car) 1)", ErrSyntax, "lambda parameter car is a reserved name"},
+ {"(lambda (if) 1)", ErrSyntax, "lambda parameter if is a reserved name"},
+ {"(lambda (lambda) 1)", ErrSyntax, "lambda parameter lambda is a reserved name"},
+ {"lambda", ErrSpecialForm, "lambda is a special form, not a value"},
+
+ {"((lambda (x) (car x)) 1)", ErrType, "car needs a pair, got 1"},
+ {"((lambda (x) boom x) 1)", ErrUnbound, "no statute for symbol boom"},
+ {"(== (lambda () 1) (lambda () 1))", ErrType, "cannot compare functions"},
+ })
+}
diff --git a/eval/eval.go b/eval/eval.go
index 7ed997fd95bdb2157acb84a6da97995ca9a6aba4..031daba4eab67f18fbc298e6ebd5647498f71ae4 100644
--- a/eval/eval.go
+++ b/eval/eval.go
@@ -12,8 +12,9 @@ var specialForms map[sexpr.Symbol]specialForm
func init() {
specialForms = map[sexpr.Symbol]specialForm{
- "quote": evalQuote,
- "if": evalIf,
+ "quote": evalQuote,
+ "if": evalIf,
+ "lambda": evalLambda,
}
}