government

commit b9cb2994f443455b061cf4e3054f9b89234f78a0

tree

parent:
912e56eddc8c1e6341ea2c0b844e37334a96050f

nmyk <nick@nmyk.io>

2026-11-14T11:51:49-05:00

add eval

diff --git a/eval/error.go b/eval/error.go
new file mode 100644
index 0000000000000000000000000000000000000000..0ae0b64796576886e741c22ec590e69e884d2c8a
--- /dev/null
+++ b/eval/error.go
@@ -0,0 +1,23 @@
+package eval
+
+import "fmt"
+
+// Error codes. Step 1.13 adds source locations; the codes are stable.
+const (
+	ErrUnbound        = "E-UNBOUND"
+	ErrSyntax         = "E-SYNTAX"
+	ErrSpecialForm    = "E-SPECIAL-FORM"
+	ErrNotAFunction   = "E-NOT-A-FUNCTION"
+	ErrNotImplemented = "E-NOT-IMPLEMENTED"
+)
+
+type Error struct {
+	Code string
+	Msg  string
+}
+
+func (e *Error) Error() string { return e.Code + ": " + e.Msg }
+
+func errorf(code, format string, args ...any) *Error {
+	return &Error{Code: code, Msg: fmt.Sprintf(format, args...)}
+}
diff --git a/eval/eval.go b/eval/eval.go
new file mode 100644
index 0000000000000000000000000000000000000000..8313ea6e171f68e1f7ca80effabc89c1bebf724c
--- /dev/null
+++ b/eval/eval.go
@@ -0,0 +1,120 @@
+package eval
+
+import "government/sexpr"
+
+// specialForm receives its operands unevaluated and decides itself which of
+// them to evaluate. That is the whole difference from a function, and the
+// reason if cannot be one: a function's arguments are all evaluated before
+// it runs, so both branches would run.
+type specialForm func(operands []sexpr.Value, env *Env) (sexpr.Value, error)
+
+var specialForms map[sexpr.Symbol]specialForm
+
+func init() {
+	specialForms = map[sexpr.Symbol]specialForm{
+		"quote": evalQuote,
+		"if":    evalIf,
+	}
+}
+
+// Eval evaluates expr in env.
+//
+// Atoms other than symbols evaluate to themselves. A symbol evaluates to its
+// binding. A non-empty list is either a special form, chosen by its head
+// symbol, or a function call.
+func Eval(expr sexpr.Value, env *Env) (sexpr.Value, error) {
+	switch x := expr.(type) {
+	case sexpr.Symbol:
+		return evalSymbol(x, env)
+	case *sexpr.Pair:
+		return evalList(x, env)
+	}
+	return expr, nil
+}
+
+func evalSymbol(name sexpr.Symbol, env *Env) (sexpr.Value, error) {
+	if _, ok := specialForms[name]; ok {
+		return nil, errorf(ErrSpecialForm, "%s is a special form, not a value", name)
+	}
+	v, ok := env.Lookup(name)
+	if !ok {
+		return nil, errorf(ErrUnbound, "no statute for symbol %s", name)
+	}
+	return v, nil
+}
+
+func evalList(list *sexpr.Pair, env *Env) (sexpr.Value, error) {
+	items, ok := properList(list)
+	if !ok {
+		return nil, errorf(ErrSyntax, "cannot evaluate improper list %s", sexpr.Print(list))
+	}
+	if head, ok := items[0].(sexpr.Symbol); ok {
+		if form, ok := specialForms[head]; ok {
+			return form(items[1:], env)
+		}
+	}
+	return evalCall(items, env)
+}
+
+// evalCall is the function-call case. No function values exist until step
+// 1.7 adds builtins, so for now it can only report what went wrong.
+func evalCall(items []sexpr.Value, env *Env) (sexpr.Value, error) {
+	f, err := Eval(items[0], env)
+	if err != nil {
+		return nil, err
+	}
+	if _, ok := f.(sexpr.Function); !ok {
+		return nil, errorf(ErrNotAFunction, "%s is not a function", sexpr.Print(f))
+	}
+	return nil, errorf(ErrNotImplemented, "function calls are not implemented")
+}
+
+// (quote d) returns d without evaluating it.
+func evalQuote(operands []sexpr.Value, env *Env) (sexpr.Value, error) {
+	if len(operands) != 1 {
+		return nil, errorf(ErrSyntax, "quote takes 1 operand, got %d", len(operands))
+	}
+	return operands[0], nil
+}
+
+// (if c a b) evaluates a unless c is F, else b. (if c a) gives () when c is
+// F. Only the chosen branch is evaluated.
+func evalIf(operands []sexpr.Value, env *Env) (sexpr.Value, error) {
+	if len(operands) != 2 && len(operands) != 3 {
+		return nil, errorf(ErrSyntax, "if takes 2 or 3 operands, got %d", len(operands))
+	}
+	c, err := Eval(operands[0], env)
+	if err != nil {
+		return nil, err
+	}
+	if isTrue(c) {
+		return Eval(operands[1], env)
+	}
+	if len(operands) == 3 {
+		return Eval(operands[2], env)
+	}
+	return sexpr.Nil, nil
+}
+
+// isTrue implements Scheme truthiness: F is the only false value.
+func isTrue(v sexpr.Value) bool {
+	b, ok := v.(sexpr.Bool)
+	return !ok || bool(b)
+}
+
+// properList returns the elements of a list that ends in (), or false if
+// the list ends in anything else.
+func properList(v sexpr.Value) ([]sexpr.Value, bool) {
+	var items []sexpr.Value
+	for {
+		switch x := v.(type) {
+		case sexpr.Empty:
+			return items, true
+		case *sexpr.Pair:
+			items = append(items, x.Car)
+			v = x.Cdr
+		default:
+			return nil, false
+		}
+	}
+}
diff --git a/eval/eval_test.go b/eval/eval_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..82641695728a191e0816e8bb3016cec6c7597d53
--- /dev/null
+++ b/eval/eval_test.go
@@ -0,0 +1,126 @@
+package eval
+
+import (
+	"errors"
+	"testing"
+
+	"government/sexpr"
+)
+
+// testEnv binds a few names. "boom" is deliberately unbound: evaluating it
+// fails, which shows whether an expression was evaluated at all.
+func testEnv() *Env {
+	return (*Env)(nil).
+		Extend("x", sexpr.Int(1)).
+		Extend("s", sexpr.String("hi")).
+		Extend("no", sexpr.F).
+		Extend("empty", sexpr.Nil)
+}
+
+func evalString(t *testing.T, src string) (sexpr.Value, error) {
+	t.Helper()
+	forms, err := sexpr.ReadAll(src)
+	if err != nil {
+		t.Fatalf("ReadAll(%q): %v", src, err)
+	}
+	if len(forms) != 1 {
+		t.Fatalf("ReadAll(%q) returned %d forms, want 1", src, len(forms))
+	}
+	return Eval(forms[0], testEnv())
+}
+
+func TestEval(t *testing.T) {
+	tests := []struct{ src, want string }{
+		// Atoms evaluate to themselves.
+		{"42", "42"},
+		{"-1.5", "-1.5"},
+		{`"hello"`, `"hello"`},
+		{"T", "T"},
+		{"F", "F"},
+		{"()", "()"},
+
+		{"x", "1"},
+		{"s", `"hi"`},
+
+		{"'boom", "boom"},
+		{"(quote boom)", "boom"},
+		{"'(boom 1 2)", "(boom 1 2)"},
+		{"'(1 . 2)", "(1 . 2)"},
+		{"''x", "(quote x)"},
+		{"'()", "()"},
+		{"'T", "T"},
+
+		// Only F is false.
+		{"(if T 1 2)", "1"},
+		{"(if F 1 2)", "2"},
+		{"(if 0 1 2)", "1"},
+		{"(if 0.0 1 2)", "1"},
+		{`(if "" 1 2)`, "1"},
+		{"(if () 1 2)", "1"},
+		{"(if 'sym 1 2)", "1"},
+		{"(if no 1 2)", "2"},
+		{"(if empty 1 2)", "1"},
+		{"(if x 'yes 'no)", "yes"},
+
+		{"(if T 1)", "1"},
+		{"(if F 1)", "()"},
+
+		// The branch not taken is never evaluated.
+		{"(if T 1 boom)", "1"},
+		{"(if F boom 2)", "2"},
+		{"(if F boom)", "()"},
+
+		{"(if (if F T F) 1 2)", "2"},
+		{"(if T (if F 1 2) 3)", "2"},
+		{"(if T 'x)", "x"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.src, func(t *testing.T) {
+			v, err := evalString(t, tt.src)
+			if err != nil {
+				t.Fatalf("Eval(%s): %v", tt.src, err)
+			}
+			if got := sexpr.Print(v); got != tt.want {
+				t.Errorf("Eval(%s) = %s, want %s", tt.src, got, tt.want)
+			}
+		})
+	}
+}
+
+func TestEvalErrors(t *testing.T) {
+	tests := []struct{ src, code, msg string }{
+		{"boom", ErrUnbound, "no statute for symbol boom"},
+		{"(if boom 1 2)", ErrUnbound, "no statute for symbol boom"},
+		{"(if T boom 2)", ErrUnbound, "no statute for symbol boom"},
+
+		{"(quote)", ErrSyntax, "quote takes 1 operand, got 0"},
+		{"(quote a b)", ErrSyntax, "quote takes 1 operand, got 2"},
+		{"(if)", ErrSyntax, "if takes 2 or 3 operands, got 0"},
+		{"(if T)", ErrSyntax, "if takes 2 or 3 operands, got 1"},
+		{"(if T 1 2 3)", ErrSyntax, "if takes 2 or 3 operands, got 4"},
+		{"(if T . 1)", ErrSyntax, "cannot evaluate improper list (if T . 1)"},
+
+		// Special forms are syntax, not values.
+		{"if", ErrSpecialForm, "if is a special form, not a value"},
+		{"quote", ErrSpecialForm, "quote is a special form, not a value"},
+		{"(if T if)", ErrSpecialForm, "if is a special form, not a value"},
+
+		{"(1 2)", ErrNotAFunction, "1 is not a function"},
+		{"(x)", ErrNotAFunction, "1 is not a function"},
+		{`("f" 1)`, ErrNotAFunction, `"f" is not a function`},
+		{"(boom 1)", ErrUnbound, "no statute for symbol boom"},
+		{"((if T 1 2) 3)", ErrNotAFunction, "1 is not a function"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.src, func(t *testing.T) {
+			_, err := evalString(t, tt.src)
+			var e *Error
+			if !errors.As(err, &e) {
+				t.Fatalf("Eval(%s) error = %v, want *Error", tt.src, err)
+			}
+			if e.Code != tt.code || e.Msg != tt.msg {
+				t.Errorf("Eval(%s) error = %s: %s, want %s: %s", tt.src, e.Code, e.Msg, tt.code, tt.msg)
+			}
+		})
+	}
+}