parent:
b16190dee4ae781544f8119bec44f00f5224c810
nmyk <nick@nmyk.io>
2026-11-14T18:44:55-05:00
register builtins in a single place
diff --git a/DESIGN.md b/DESIGN.md
index 6af8829a7a5aa3365a19bfed49e2865c65a21b95..f924b897218a69fd31c456ce5967afc103a3ff7c 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -135,7 +135,7 @@ **Why text for numbers.** It is uniform with strings and symbols, follows your ASCII-arc idea, round-trips floats exactly as written, and is readable in an `openssl` dump with a one-line decoder. The alternative (a sign arc plus a magnitude arc for integers, IEEE-754 bits for floats) is shorter but opaque.
## Builtin symbol table
-There are 28 builtins, all in namespace 0. Each has a fixed numeric code, which is its whole payload: one arc. `<id>` is the node's own id. Names are case-sensitive.
+There are 28 builtins, all in namespace 0. Package `builtin` holds this table; the OID encoding and the evaluator both read it, and the evaluator refuses to start if a builtin there has no implementation. Each has a fixed numeric code, which is its whole payload: one arc. `<id>` is the node's own id. Names are case-sensitive.
Codes are grouped with room to grow: structure 1–2, constants 3–5, special forms 10–15, functions 20 and up. A code is permanent: it is never reused or renumbered, and a new builtin takes the next free code in its group.
@@ -309,6 +309,7 @@ | `ratify` | PEM loading; path validation (§6.1.3 a–c, 6.1.4 k–n); critical-extension check |
| `policy` | RFC 9618 policy graph; strict check; node budget |
| `ast` | Graph to AST: skipping copies, ordering, OID decoding, structural errors |
| `program` | The whole load path: ratify, policy graph, decode; maps runtime errors back to node OIDs |
+| `builtin` | The one table of builtins: name, OID code, kind and operand count, read by `ast` and `eval` |
| `eval` | Values, environments, special forms, builtins, trampoline for tail calls |
| `sexpr` | Lisp reader and printer, shared by the transpiler, decompiler and tests |
| `lisp2gov` | Transpiler: s-expressions to `.gov` |
diff --git a/ast/builtin.go b/ast/builtin.go
index a74bd00b1e9a2c10574be15f86d8b78e02726539..34dfcdfa42cc15433eea47bd5311e404a0930933 100644
--- a/ast/builtin.go
+++ b/ast/builtin.go
@@ -1,70 +1,26 @@
package ast
-// Names for the builtins that have no source spelling as a symbol. The
-// reader turns "()", "T" and "F" into values and handles "." itself, so none
-// of these can collide with a user symbol.
-const (
- ListNode = "(...)"
- Dot = "."
- True = "T"
- False = "F"
- Empty = "()"
-)
-
-// builtinCodes is the table from DESIGN.md. A code is permanent once
-// published: changing one would change the meaning of every .gov file
-// already compiled, so new builtins only ever take a free code.
-var builtinCodes = []struct {
- code uint64
- name string
-}{
- {1, ListNode},
- {2, Dot},
- {3, True},
- {4, False},
- {5, Empty},
-
- {10, "quote"},
- {11, "if"},
- {12, "define"},
- {13, "lambda"},
- {14, "and"},
- {15, "or"},
-
- {20, "not"},
- {21, "+"},
- {22, "-"},
- {23, "*"},
- {24, "/"},
- {25, "<"},
- {26, ">"},
- {27, "<="},
- {28, ">="},
- {29, "=="},
- {30, "!="},
- {31, "cons"},
- {32, "car"},
- {33, "cdr"},
- {34, "strlen"},
- {35, "strcat"},
- {36, "str?"},
-}
+import "government/builtin"
-var (
- codeByName = map[string]uint64{}
- nameByCode = map[uint64]string{}
+// The structural and constant builtins' names, from package builtin.
+const (
+ ListNode = builtin.ListNode
+ Dot = builtin.Dot
+ True = builtin.True
+ False = builtin.False
+ Empty = builtin.Empty
)
-func init() {
- for _, b := range builtinCodes {
- codeByName[b.name] = b.code
- nameByCode[b.code] = b.name
- }
-}
-
-// IsBuiltin reports whether name is in namespace 0. A symbol with this name
-// is always encoded as the builtin, which is why programs cannot rebind one.
+// IsBuiltin reports whether name is in namespace 0.
func IsBuiltin(name string) bool {
- _, ok := codeByName[name]
+ _, ok := builtin.Lookup(name)
return ok
}
+
+// isReservedSymbol reports whether a source symbol names a builtin, and so
+// goes in namespace 0. The structural names never come out of the reader
+// as symbols; if one did, it must stay a symbol rather than turn into
+// structure.
+func isReservedSymbol(name string) bool {
+ return builtin.IsReserved(name)
+}
diff --git a/ast/oid.go b/ast/oid.go
index 04c5e52a43c9275f081cec86e19206349f55f9ba..bf7553f4c45c6f6a665be5b0babcecb9f0a92ce0 100644
--- a/ast/oid.go
+++ b/ast/oid.go
@@ -7,6 +7,7 @@ "fmt"
"strings"
"unicode/utf8"
+ "government/builtin"
"government/internal/der"
"government/sexpr"
)
@@ -59,11 +60,11 @@ return x509.OID{}, errors.New("node id must be positive")
}
var payload []uint64
if ns == NSBuiltin {
- code, ok := codeByName[text]
+ spec, ok := builtin.Lookup(text)
if !ok {
return x509.OID{}, fmt.Errorf("%q is not a builtin", text)
}
- payload = []uint64{code}
+ payload = []uint64{spec.Code}
} else {
if !utf8.ValidString(text) {
return x509.OID{}, fmt.Errorf("%s %q is not valid UTF-8", ns, text)
@@ -121,11 +122,11 @@ if ns == NSBuiltin {
if len(payload) != 1 {
return 0, 0, "", fmt.Errorf("OID %s: a builtin has exactly one payload arc, got %d", oid, len(payload))
}
- name, ok := nameByCode[payload[0]]
+ spec, ok := builtin.ByCode(payload[0])
if !ok {
return 0, 0, "", fmt.Errorf("OID %s: unknown builtin code %d", oid, payload[0])
}
- return ns, id, name, nil
+ return ns, id, spec.Name, nil
}
var sb strings.Builder
diff --git a/ast/oid_test.go b/ast/oid_test.go
index acedb1f6119fe2ea245c4d7298c26e1cb639f489..26aecca8bcdabaabb33f75572b43ee4c1516b0ce 100644
--- a/ast/oid_test.go
+++ b/ast/oid_test.go
@@ -115,26 +115,3 @@ t.Errorf("DecodeOID(%s) error = %v, want %q", tt.oid, err, tt.want)
}
}
}
-
-func TestBuiltinCodesArePinned(t *testing.T) {
- // Published codes must never change; this list is a second copy of the
- // DESIGN.md table so an accidental edit to builtinCodes fails here.
- want := map[string]uint64{
- ListNode: 1, Dot: 2, True: 3, False: 4, Empty: 5,
- "quote": 10, "if": 11, "define": 12, "lambda": 13, "and": 14, "or": 15,
- "not": 20, "+": 21, "-": 22, "*": 23, "/": 24, "<": 25, ">": 26,
- "<=": 27, ">=": 28, "==": 29, "!=": 30, "cons": 31, "car": 32,
- "cdr": 33, "strlen": 34, "strcat": 35, "str?": 36,
- }
- if len(builtinCodes) != len(want) {
- t.Errorf("%d builtins, want %d", len(builtinCodes), len(want))
- }
- for _, b := range builtinCodes {
- if want[b.name] != b.code {
- t.Errorf("%s has code %d, want %d", b.name, b.code, want[b.name])
- }
- }
- if len(nameByCode) != len(builtinCodes) {
- t.Error("two builtins share a code")
- }
-}
diff --git a/ast/reserved_test.go b/ast/reserved_test.go
deleted file mode 100644
index 8b8db2874b0d828cd0804ea90105c251162a5f65..0000000000000000000000000000000000000000
--- a/ast/reserved_test.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ast
-
-import (
- "slices"
- "testing"
-
- "government/eval"
-)
-
-func TestBuiltinsMatchEvaluator(t *testing.T) {
- // The structural names are values in source (or reader syntax), not
- // symbols, so the evaluator never sees them as names.
- structural := []string{ListNode, Dot, True, False, Empty}
- var named []string
- for _, b := range builtinCodes {
- if !slices.Contains(structural, b.name) {
- named = append(named, b.name)
- }
- }
- slices.Sort(named)
- if reserved := eval.ReservedNames(); !slices.Equal(named, reserved) {
- t.Errorf("builtin codes name %v\nevaluator reserves %v", named, reserved)
- }
-}
diff --git a/ast/tree.go b/ast/tree.go
index cdb6465e4ff5a0353e7702394f7a8ea50a5dba6b..9a0d7149f19461c2fa6ed091a127ac771f6f4e1d 100644
--- a/ast/tree.go
+++ b/ast/tree.go
@@ -114,17 +114,6 @@ }
return n, nil
}
-// isReservedSymbol reports whether a source symbol names a builtin. The
-// structural names never come out of the reader as symbols; if one did, it
-// must stay a symbol rather than turn into structure.
-func isReservedSymbol(name string) bool {
- switch name {
- case ListNode, Dot, True, False, Empty:
- return false
- }
- return IsBuiltin(name)
-}
-
// Origins maps each list FromTree produced back to its node, so an evaluation
// error inside a .gov program can name the OID it came from, the way the
// reader's positions name a line and column.
diff --git a/builtin/builtin.go b/builtin/builtin.go
new file mode 100644
index 0000000000000000000000000000000000000000..e7d10a5e9813a09ae316854881bedf81a2f08acd
--- /dev/null
+++ b/builtin/builtin.go
@@ -0,0 +1,149 @@
+// Package builtin is the one list of GOVERNMENT's builtins: for each, its
+// name, its permanent OID code, its kind and how many operands it takes.
+// The OID encoding (package ast) and the evaluator (package eval) both read
+// it, so they cannot disagree. eval supplies the implementations and
+// refuses to start if any builtin lacks one.
+package builtin
+
+import "fmt"
+
+type Kind int
+
+const (
+ // Structural nodes shape the tree and are never values or names.
+ Structural Kind = iota
+ // Constants are values with no symbol spelling: the reader makes them.
+ Constant
+ // Special forms see their operands unevaluated.
+ SpecialForm
+ // Functions are values bound to their names in every program.
+ Function
+)
+
+func (k Kind) String() string {
+ return [...]string{"structural", "constant", "special form", "function"}[k]
+}
+
+// Names of the builtins that are not symbols. The reader turns "()", "T"
+// and "F" into values and handles "." itself, so none of these can collide
+// with a user symbol.
+const (
+ ListNode = "(...)"
+ Dot = "."
+ True = "T"
+ False = "F"
+ Empty = "()"
+)
+
+// Spec says everything about one builtin except how it runs.
+type Spec struct {
+ // Code is the builtin's whole OID payload, GOV.0.<id>.<code>. A code is
+ // permanent once published: changing one would change the meaning of
+ // every .gov file already compiled, so a new builtin takes a free code
+ // in its kind's range (structural 1-2, constants 3-5, special forms
+ // 10-15, functions 20 and up).
+ Code uint64
+ Name string
+ Kind Kind
+ // Min and Max bound the operands of a special form or the arguments of
+ // a function. Max < 0 means no upper bound.
+ Min, Max int
+}
+
+// All is every builtin, in code order.
+var All = []Spec{
+ {1, ListNode, Structural, 0, 0},
+ {2, Dot, Structural, 0, 0},
+ {3, True, Constant, 0, 0},
+ {4, False, Constant, 0, 0},
+ {5, Empty, Constant, 0, 0},
+
+ {10, "quote", SpecialForm, 1, 1},
+ {11, "if", SpecialForm, 2, 3},
+ {12, "define", SpecialForm, 2, 2},
+ {13, "lambda", SpecialForm, 2, -1}, // a parameter list and a body of one or more forms
+ {14, "and", SpecialForm, 0, -1},
+ {15, "or", SpecialForm, 0, -1},
+
+ {20, "not", Function, 1, 1},
+ {21, "+", Function, 0, -1},
+ {22, "-", Function, 1, -1},
+ {23, "*", Function, 0, -1},
+ {24, "/", Function, 1, -1},
+ {25, "<", Function, 2, 2},
+ {26, ">", Function, 2, 2},
+ {27, "<=", Function, 2, 2},
+ {28, ">=", Function, 2, 2},
+ {29, "==", Function, 2, 2},
+ {30, "!=", Function, 2, 2},
+ {31, "cons", Function, 2, 2},
+ {32, "car", Function, 1, 1},
+ {33, "cdr", Function, 1, 1},
+ {34, "strlen", Function, 1, 1},
+ {35, "strcat", Function, 0, -1},
+ {36, "str?", Function, 1, 1},
+}
+
+var (
+ byName = map[string]Spec{}
+ byCode = map[uint64]Spec{}
+)
+
+func init() {
+ for _, s := range All {
+ if _, dup := byName[s.Name]; dup {
+ panic("builtin: two builtins named " + s.Name)
+ }
+ if _, dup := byCode[s.Code]; dup {
+ panic(fmt.Sprintf("builtin: two builtins with code %d", s.Code))
+ }
+ byName[s.Name] = s
+ byCode[s.Code] = s
+ }
+}
+
+func Lookup(name string) (Spec, bool) {
+ s, ok := byName[name]
+ return s, ok
+}
+
+func ByCode(code uint64) (Spec, bool) {
+ s, ok := byCode[code]
+ return s, ok
+}
+
+// IsReserved reports whether name is a special form or function. A source
+// symbol with such a name is the builtin, in its own namespace, so a
+// program can never define or bind it.
+func IsReserved(name string) bool {
+ s, ok := byName[name]
+ return ok && (s.Kind == SpecialForm || s.Kind == Function)
+}
+
+// CheckCount reports whether n operands (or arguments) are allowed, and if
+// not, says how many are, e.g. "if takes 2 or 3 operands, got 4". noun is
+// "operand" for a special form and "argument" for a function.
+func (s Spec) CheckCount(n int, noun string) error {
+ if n >= s.Min && (s.Max < 0 || n <= s.Max) {
+ return nil
+ }
+ var takes string
+ switch {
+ case s.Max < 0:
+ takes = "at least " + plural(s.Min, noun)
+ case s.Min == s.Max:
+ takes = plural(s.Min, noun)
+ case s.Max == s.Min+1:
+ takes = fmt.Sprintf("%d or %d %ss", s.Min, s.Max, noun)
+ default:
+ takes = fmt.Sprintf("%d to %d %ss", s.Min, s.Max, noun)
+ }
+ return fmt.Errorf("%s takes %s, got %d", s.Name, takes, n)
+}
+
+func plural(n int, noun string) string {
+ if n == 1 {
+ return "1 " + noun
+ }
+ return fmt.Sprintf("%d %ss", n, noun)
+}
diff --git a/builtin/builtin_test.go b/builtin/builtin_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2f6aed3bb8378bfde72b67e50fec99d5dd66b199
--- /dev/null
+++ b/builtin/builtin_test.go
@@ -0,0 +1,71 @@
+package builtin
+
+import "testing"
+
+// TestCodesArePinned is a deliberate second copy of the codes. Published
+// codes must never change; an accidental edit to All fails here.
+func TestCodesArePinned(t *testing.T) {
+ want := map[string]uint64{
+ ListNode: 1, Dot: 2, True: 3, False: 4, Empty: 5,
+ "quote": 10, "if": 11, "define": 12, "lambda": 13, "and": 14, "or": 15,
+ "not": 20, "+": 21, "-": 22, "*": 23, "/": 24, "<": 25, ">": 26,
+ "<=": 27, ">=": 28, "==": 29, "!=": 30, "cons": 31, "car": 32,
+ "cdr": 33, "strlen": 34, "strcat": 35, "str?": 36,
+ }
+ if len(All) != len(want) {
+ t.Errorf("%d builtins, want %d", len(All), len(want))
+ }
+ for _, s := range All {
+ if want[s.Name] != s.Code {
+ t.Errorf("%s has code %d, want %d", s.Name, s.Code, want[s.Name])
+ }
+ }
+}
+
+func TestCodeRanges(t *testing.T) {
+ ranges := map[Kind][2]uint64{Structural: {1, 2}, Constant: {3, 5}, SpecialForm: {10, 15}, Function: {20, 1 << 63}}
+ for _, s := range All {
+ r := ranges[s.Kind]
+ if s.Code < r[0] || s.Code > r[1] {
+ t.Errorf("%s is a %s with code %d, outside %d-%d", s.Name, s.Kind, s.Code, r[0], r[1])
+ }
+ }
+}
+
+func TestReserved(t *testing.T) {
+ for name, want := range map[string]bool{"if": true, "+": true, "str?": true, ListNode: false, True: false, Empty: false, "foo": false} {
+ if IsReserved(name) != want {
+ t.Errorf("IsReserved(%q) = %v", name, !want)
+ }
+ }
+}
+
+func TestCheckCount(t *testing.T) {
+ spec := func(name string) Spec { s, _ := Lookup(name); return s }
+ tests := []struct {
+ name, noun string
+ n int
+ want string
+ }{
+ {"quote", "operand", 0, "quote takes 1 operand, got 0"},
+ {"if", "operand", 4, "if takes 2 or 3 operands, got 4"},
+ {"define", "operand", 1, "define takes 2 operands, got 1"},
+ {"lambda", "operand", 1, "lambda takes at least 2 operands, got 1"},
+ {"-", "argument", 0, "- takes at least 1 argument, got 0"},
+ {"cons", "argument", 3, "cons takes 2 arguments, got 3"},
+ }
+ for _, tt := range tests {
+ err := spec(tt.name).CheckCount(tt.n, tt.noun)
+ if err == nil || err.Error() != tt.want {
+ t.Errorf("%s with %d: %v, want %q", tt.name, tt.n, err, tt.want)
+ }
+ }
+ for _, ok := range []struct {
+ name string
+ n int
+ }{{"and", 0}, {"or", 7}, {"if", 2}, {"if", 3}, {"+", 0}, {"strcat", 9}} {
+ if err := spec(ok.name).CheckCount(ok.n, "operand"); err != nil {
+ t.Errorf("%s with %d: %v", ok.name, ok.n, err)
+ }
+ }
+}
diff --git a/eval/builtin.go b/eval/builtin.go
index 9c4f1e13c5b9aeabebc16f955861e9617e34a51e..fc369b6b9d9ce1c6b73bdee1e12f0f4a880a1ce4 100644
--- a/eval/builtin.go
+++ b/eval/builtin.go
@@ -3,6 +3,7 @@
import (
"fmt"
+ "government/builtin"
"government/sexpr"
)
@@ -11,42 +12,52 @@ // they live in the environment under their names, so (define add +) works
// and + can be passed to a higher-order function.
type Builtin struct {
sexpr.FunctionBase
- name string
- // minArgs and maxArgs bound the argument count; maxArgs < 0 means any
- // number. The arity check happens once, in apply.
- minArgs, maxArgs int
- fn func(args []sexpr.Value) (sexpr.Value, error)
+ spec builtin.Spec
+ fn func(args []sexpr.Value) (sexpr.Value, error)
}
func (b *Builtin) Builtin() bool { return true }
-func (b *Builtin) Name() string { return b.name }
+func (b *Builtin) Name() string { return b.spec.Name }
-var builtins = []*Builtin{
- {name: "+", minArgs: 0, maxArgs: -1, fn: add},
- {name: "-", minArgs: 1, maxArgs: -1, fn: subtract},
- {name: "*", minArgs: 0, maxArgs: -1, fn: multiply},
- {name: "/", minArgs: 1, maxArgs: -1, fn: divide},
- {name: "<", minArgs: 2, maxArgs: 2, fn: less},
- {name: ">", minArgs: 2, maxArgs: 2, fn: greater},
- {name: "<=", minArgs: 2, maxArgs: 2, fn: lessEq},
- {name: ">=", minArgs: 2, maxArgs: 2, fn: greaterEq},
- {name: "==", minArgs: 2, maxArgs: 2, fn: equal},
- {name: "!=", minArgs: 2, maxArgs: 2, fn: notEqual},
- {name: "not", minArgs: 1, maxArgs: 1, fn: not},
- {name: "cons", minArgs: 2, maxArgs: 2, fn: cons},
- {name: "car", minArgs: 1, maxArgs: 1, fn: car},
- {name: "cdr", minArgs: 1, maxArgs: 1, fn: cdr},
- {name: "strlen", minArgs: 1, maxArgs: 1, fn: strlen},
- {name: "strcat", minArgs: 0, maxArgs: -1, fn: strcat},
- {name: "str?", minArgs: 1, maxArgs: 1, fn: isString},
+// functions are the builtin functions' implementations. Their names,
+// codes and argument counts are in package builtin; builtins pairs the two
+// and refuses to start if either side has a name the other lacks.
+var functions = map[string]func(args []sexpr.Value) (sexpr.Value, error){
+ "+": add,
+ "-": subtract,
+ "*": multiply,
+ "/": divide,
+ "<": less,
+ ">": greater,
+ "<=": lessEq,
+ ">=": greaterEq,
+ "==": equal,
+ "!=": notEqual,
+ "not": not,
+ "cons": cons,
+ "car": car,
+ "cdr": cdr,
+ "strlen": strlen,
+ "strcat": strcat,
+ "str?": 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
+var builtins = func() []*Builtin {
+ var bs []*Builtin
+ for _, spec := range builtin.All {
+ if spec.Kind != builtin.Function {
+ continue
+ }
+ fn, ok := functions[spec.Name]
+ if !ok {
+ panic("eval: builtin function " + spec.Name + " has no implementation")
+ }
+ bs = append(bs, &Builtin{spec: spec, fn: fn})
}
- return names
+ if len(bs) != len(functions) {
+ panic("eval: an implemented function is not in package builtin")
+ }
+ return bs
}()
// Builtins returns the top-level environment: every builtin bound to its
@@ -54,20 +65,14 @@ // name.
func Builtins() *Env {
var env *Env
for _, b := range builtins {
- env = env.Extend(sexpr.Symbol(b.name), b)
+ env = env.Extend(sexpr.Symbol(b.spec.Name), b)
}
return env
}
func checkArity(b *Builtin, n int) error {
- switch {
- case b.maxArgs < 0 && n < b.minArgs:
- return errorf(ErrArity, "%s takes at least %s, got %d", b.name, plural(b.minArgs, "argument"), n)
- case b.maxArgs >= 0 && (n < b.minArgs || n > b.maxArgs):
- if b.minArgs == b.maxArgs {
- return errorf(ErrArity, "%s takes %s, got %d", b.name, plural(b.minArgs, "argument"), n)
- }
- return errorf(ErrArity, "%s takes %d to %d arguments, got %d", b.name, b.minArgs, b.maxArgs, n)
+ if err := b.spec.CheckCount(n, "argument"); err != nil {
+ return errorf(ErrArity, "%v", err)
}
return nil
}
diff --git a/eval/closure.go b/eval/closure.go
index d70b4fd54ca6c0cd11c46a8cbab8b3afd06a99e8..e7bf912ef32ec6466f92670e3fe9949d92740595 100644
--- a/eval/closure.go
+++ b/eval/closure.go
@@ -1,8 +1,7 @@
package eval
import (
- "sort"
-
+ "government/builtin"
"government/sexpr"
)
@@ -32,17 +31,11 @@ //
// The parameter list and the shape of the body are checked once, here,
// rather than on every call.
func evalLambda(operands []sexpr.Value, env *Env) (outcome, error) {
- if len(operands) == 0 {
- return outcome{}, errorf(ErrSyntax, "lambda needs a parameter list and a body")
- }
params, err := parseParams(operands[0])
if err != nil {
return outcome{}, err
}
body := operands[1:]
- if len(body) == 0 {
- return outcome{}, errorf(ErrSyntax, "lambda needs a body")
- }
if err := checkBodyShape(body); err != nil {
return outcome{}, err
}
@@ -124,28 +117,10 @@ }
return c.body[last], s.env, 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.
+// Reserved names are the special forms and builtin functions. 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]
-}
-
-// ReservedNames lists the names isReserved accepts. The ast package checks
-// its builtin code table against this list, so the evaluator and the OID
-// encoding cannot disagree about which names are builtins.
-func ReservedNames() []string {
- names := make([]string, 0, len(specialForms)+len(builtins))
- for name := range specialForms {
- names = append(names, string(name))
- }
- for _, b := range builtins {
- names = append(names, b.name)
- }
- sort.Strings(names)
- return names
+ return builtin.IsReserved(string(name))
}
diff --git a/eval/closure_test.go b/eval/closure_test.go
index 277820185c807de35eb9fc278ffe43b8f4fedf50..6c0ffd0b3b4a8fc8260eae294f4b30f4b9044fc9 100644
--- a/eval/closure_test.go
+++ b/eval/closure_test.go
@@ -60,8 +60,8 @@ {"((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)", ErrSyntax, "lambda takes at least 2 operands, got 0"},
+ {"(lambda (x))", ErrSyntax, "lambda takes at least 2 operands, got 1"},
{"(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"},
diff --git a/eval/define.go b/eval/define.go
index 6d08815ff504a56096890971a2a2ffac680cecab..9bda6fcf026d40e8973f5c993a62068ad207c87f 100644
--- a/eval/define.go
+++ b/eval/define.go
@@ -17,8 +17,8 @@ }
// 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"))
+ if err := checkOperands(specialForms["define"].spec, len(form)-1); err != nil {
+ return nil, err
}
name, ok := form[1].(sexpr.Symbol)
if !ok {
diff --git a/eval/define_test.go b/eval/define_test.go
index 0c76c243e254789fd359343af9cdbcbb32111950..3e7b302e156af7ee8c74b913b1b368d5dd80ef36 100644
--- a/eval/define_test.go
+++ b/eval/define_test.go
@@ -71,9 +71,9 @@ // existed, so b is not in its environment.
{"((lambda () (define a (lambda () (b))) (define b (lambda () 1)) (a)))", ErrUnbound, "no statute for symbol b"},
{"(define even? (lambda (n) (if (== n 0) T (odd? (- n 1))))) (define odd? (lambda (n) (if (== n 0) F (even? (- n 1))))) (even? 4)", ErrUnbound, "no statute for symbol odd?"},
- {"(define)", ErrSyntax, "define takes a name and a value, got 0 operands"},
- {"(define y)", ErrSyntax, "define takes a name and a value, got 1 operand"},
- {"(define y 1 2)", ErrSyntax, "define takes a name and a value, got 3 operands"},
+ {"(define)", ErrSyntax, "define takes 2 operands, got 0"},
+ {"(define y)", ErrSyntax, "define takes 2 operands, got 1"},
+ {"(define y 1 2)", ErrSyntax, "define takes 2 operands, got 3"},
{"(define 1 2)", ErrSyntax, "define needs a symbol name, got 1"},
{"(define (f x) x)", ErrSyntax, "define needs a symbol name, got (f x)"},
{"(define + 1)", ErrSyntax, "cannot define reserved name +"},
diff --git a/eval/eval.go b/eval/eval.go
index 97081fb00624ca10e094a83f55f51fbe76a10cff..16a8cc06f9e357e4afb03d9e941ca9a2e69a0d86 100644
--- a/eval/eval.go
+++ b/eval/eval.go
@@ -1,6 +1,9 @@
package eval
-import "government/sexpr"
+import (
+ "government/builtin"
+ "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
@@ -25,10 +28,20 @@ func tailIn(expr sexpr.Value, env *Env) (outcome, error) {
return outcome{tail: expr, env: env}, nil
}
-var specialForms map[sexpr.Symbol]specialForm
+// form is a special form's implementation with its spec, which says how
+// many operands it takes.
+type form struct {
+ spec builtin.Spec
+ run specialForm
+}
+var specialForms map[sexpr.Symbol]form
+
+// init pairs each special form in package builtin with its
+// implementation. (It cannot be a plain initializer: the implementations
+// call Eval, which reads specialForms.)
func init() {
- specialForms = map[sexpr.Symbol]specialForm{
+ impls := map[string]specialForm{
"quote": evalQuote,
"if": evalIf,
"lambda": evalLambda,
@@ -36,6 +49,28 @@ "define": evalMisplacedDefine,
"and": evalAnd,
"or": evalOr,
}
+ specialForms = map[sexpr.Symbol]form{}
+ for _, spec := range builtin.All {
+ if spec.Kind != builtin.SpecialForm {
+ continue
+ }
+ run, ok := impls[spec.Name]
+ if !ok {
+ panic("eval: special form " + spec.Name + " has no implementation")
+ }
+ specialForms[sexpr.Symbol(spec.Name)] = form{spec, run}
+ }
+ if len(specialForms) != len(impls) {
+ panic("eval: an implemented special form is not in package builtin")
+ }
+}
+
+// checkOperands applies a special form's operand count from its spec.
+func checkOperands(spec builtin.Spec, n int) error {
+ if err := spec.CheckCount(n, "operand"); err != nil {
+ return errorf(ErrSyntax, "%v", err)
+ }
+ return nil
}
// Eval evaluates expr in env.
@@ -68,7 +103,10 @@ return nil, at(errorf(ErrSyntax, "cannot evaluate improper list %s", sexpr.Print(list)), list)
}
if head, ok := items[0].(sexpr.Symbol); ok {
if form, ok := specialForms[head]; ok {
- out, err := form(items[1:], env)
+ if err := checkOperands(form.spec, len(items)-1); err != nil {
+ return nil, at(err, list)
+ }
+ out, err := form.run(items[1:], env)
if err != nil {
return nil, at(err, list)
}
@@ -138,9 +176,6 @@ }
// (quote d) returns d without evaluating it.
func evalQuote(operands []sexpr.Value, env *Env) (outcome, error) {
- if len(operands) != 1 {
- return outcome{}, errorf(ErrSyntax, "quote takes 1 operand, got %d", len(operands))
- }
return done(operands[0])
}
@@ -148,9 +183,6 @@ // (if c a b) continues with a unless c is F, else with b. (if c a) gives ()
// when c is F. Only the chosen branch is evaluated, and it is in tail
// position.
func evalIf(operands []sexpr.Value, env *Env) (outcome, error) {
- if len(operands) != 2 && len(operands) != 3 {
- return outcome{}, errorf(ErrSyntax, "if takes 2 or 3 operands, got %d", len(operands))
- }
c, err := Eval(operands[0], env)
if err != nil {
return outcome{}, err