parent:
b9cb2994f443455b061cf4e3054f9b89234f78a0
nmyk <nick@nmyk.io>
2026-11-14T12:02:43-05:00
add arithmetic
diff --git a/eval/arith.go b/eval/arith.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7397d6da26dfc716b7c554e38ef436878a1c170
--- /dev/null
+++ b/eval/arith.go
@@ -0,0 +1,150 @@
+package eval
+
+import (
+ "math"
+
+ "government/sexpr"
+)
+
+// The numeric tower has two levels: Int below Float. An operation on two
+// Ints gives an Int; if either operand is a Float, both are treated as
+// Floats and so is the result. Each step of a fold is promoted separately,
+// so (+ 1 2 3.0) adds 1 and 2 as Ints, then 3 and 3.0 as Floats.
+//
+// Results never wrap or go non-finite: integer overflow, division by zero
+// and NaN or infinite floats are all errors.
+
+type binaryOp struct {
+ name string
+ ints func(a, b int64) (int64, bool) // false on overflow
+ floats func(a, b float64) float64
+}
+
+func add(args []sexpr.Value) (sexpr.Value, error) {
+ return fold(opAdd, sexpr.Int(0), args)
+}
+
+func multiply(args []sexpr.Value) (sexpr.Value, error) {
+ return fold(opMul, sexpr.Int(1), args)
+}
+
+// (- x) is 0 - x; with more arguments, - subtracts from the first.
+func subtract(args []sexpr.Value) (sexpr.Value, error) {
+ if len(args) == 1 {
+ return foldFrom(opSub, sexpr.Int(0), args, 0)
+ }
+ return foldFrom(opSub, args[0], args[1:], 1)
+}
+
+// (/ x) is 1 / x; with more arguments, / divides the first by the rest.
+func divide(args []sexpr.Value) (sexpr.Value, error) {
+ if len(args) == 1 {
+ return foldFrom(opDiv, sexpr.Int(1), args, 0)
+ }
+ return foldFrom(opDiv, args[0], args[1:], 1)
+}
+
+var (
+ opAdd = binaryOp{"+", checkedAdd, func(a, b float64) float64 { return a + b }}
+ opSub = binaryOp{"-", checkedSub, func(a, b float64) float64 { return a - b }}
+ opMul = binaryOp{"*", checkedMul, func(a, b float64) float64 { return a * b }}
+ opDiv = binaryOp{"/", checkedDiv, func(a, b float64) float64 { return a / b }}
+)
+
+func fold(op binaryOp, start sexpr.Value, args []sexpr.Value) (sexpr.Value, error) {
+ return foldFrom(op, start, args, 0)
+}
+
+// foldFrom combines acc with each of args in turn. offset is the position
+// of args[0] in the original call, so type errors name the right argument.
+func foldFrom(op binaryOp, acc sexpr.Value, args []sexpr.Value, offset int) (sexpr.Value, error) {
+ if offset == 1 {
+ if err := checkNumber(op.name, 0, acc); err != nil {
+ return nil, err
+ }
+ }
+ for i, arg := range args {
+ if err := checkNumber(op.name, offset+i, arg); err != nil {
+ return nil, err
+ }
+ var err error
+ if acc, err = applyBinary(op, acc, arg); err != nil {
+ return nil, err
+ }
+ }
+ return acc, nil
+}
+
+func applyBinary(op binaryOp, a, b sexpr.Value) (sexpr.Value, error) {
+ ai, aIsInt := a.(sexpr.Int)
+ bi, bIsInt := b.(sexpr.Int)
+ if aIsInt && bIsInt {
+ if op.name == "/" && bi == 0 {
+ return nil, errorf(ErrArith, "division by zero")
+ }
+ r, ok := op.ints(int64(ai), int64(bi))
+ if !ok {
+ return nil, errorf(ErrArith, "integer overflow in %s", op.name)
+ }
+ return sexpr.Int(r), nil
+ }
+
+ af, bf := toFloat(a), toFloat(b)
+ if op.name == "/" && bf == 0 {
+ return nil, errorf(ErrArith, "division by zero")
+ }
+ r := op.floats(af, bf)
+ if math.IsInf(r, 0) || math.IsNaN(r) {
+ return nil, errorf(ErrArith, "float overflow in %s", op.name)
+ }
+ return sexpr.Float(r), nil
+}
+
+func checkNumber(fn string, position int, v sexpr.Value) error {
+ switch v.(type) {
+ case sexpr.Int, sexpr.Float:
+ return nil
+ }
+ return errorf(ErrType, "argument %d of %s must be a number, got %s", position+1, fn, sexpr.Print(v))
+}
+
+func toFloat(v sexpr.Value) float64 {
+ if i, ok := v.(sexpr.Int); ok {
+ return float64(i)
+ }
+ return float64(v.(sexpr.Float))
+}
+
+// Overflow checks without a wider integer type. A signed sum overflows
+// exactly when both operands have the same sign and the result's sign
+// differs; the XOR expressions test that with the sign bit.
+
+func checkedAdd(a, b int64) (int64, bool) {
+ s := a + b
+ return s, (a^s)&(b^s) >= 0
+}
+
+func checkedSub(a, b int64) (int64, bool) {
+ d := a - b
+ return d, (a^b)&(a^d) >= 0
+}
+
+func checkedMul(a, b int64) (int64, bool) {
+ if a == 0 || b == 0 {
+ return 0, true
+ }
+ if (a == -1 && b == math.MinInt64) || (b == -1 && a == math.MinInt64) {
+ return 0, false
+ }
+ p := a * b
+ return p, p/b == a
+}
+
+// Integer division truncates toward zero: (/ -7 2) is -3. The only
+// overflowing case is MinInt64 / -1, whose true result is MaxInt64 + 1.
+func checkedDiv(a, b int64) (int64, bool) {
+ if a == math.MinInt64 && b == -1 {
+ return 0, false
+ }
+ return a / b, true
+}
diff --git a/eval/arith_test.go b/eval/arith_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c92dce64c1f0cda0e7c1f0e413fe1fba05bb3c3c
--- /dev/null
+++ b/eval/arith_test.go
@@ -0,0 +1,121 @@
+package eval
+
+import (
+ "errors"
+ "testing"
+
+ "government/sexpr"
+)
+
+func TestArithmetic(t *testing.T) {
+ tests := []struct{ src, want string }{
+ {"(+)", "0"},
+ {"(+ 5)", "5"},
+ {"(+ 1 2)", "3"},
+ {"(+ 1 2 3 4)", "10"},
+ {"(*)", "1"},
+ {"(* 6)", "6"},
+ {"(* 2 3 4)", "24"},
+ {"(- 5)", "-5"},
+ {"(- -5)", "5"},
+ {"(- 10 3)", "7"},
+ {"(- 10 3 2)", "5"},
+ {"(/ 7 2)", "3"},
+ {"(/ -7 2)", "-3"},
+ {"(/ 7 -2)", "-3"},
+ {"(/ 100 2 5)", "10"},
+ {"(/ 2)", "0"},
+ {"(/ 1)", "1"},
+
+ // Any Float makes the result a Float.
+ {"(+ 1 2.0)", "3.0"},
+ {"(+ 1.5 1.5)", "3.0"},
+ {"(* 2 0.5)", "1.0"},
+ {"(- 1.5)", "-1.5"},
+ {"(/ 7.0 2)", "3.5"},
+ {"(/ 7 2.0)", "3.5"},
+ {"(/ 2.0)", "0.5"},
+ {"(+ 0.1 0.2)", "0.30000000000000004"},
+
+ // Promotion happens per step of the fold.
+ {"(+ 1 2 3.0)", "6.0"},
+ {"(/ 7 2 1.0)", "3.0"},
+ {"(/ 7.0 2 1)", "3.5"},
+
+ {"(+ (* 2 3) (- 10 4))", "12"},
+ {"(* (+ 1 2) (/ 9 3))", "9"},
+ {"(if (- 1 1) 'zero-is-true 'no)", "zero-is-true"},
+
+ // Builtins are values.
+ {"+", "#<builtin +>"},
+ {"((if T + *) 2 3)", "5"},
+ {"((if F + *) 2 3)", "6"},
+
+ {"(+ 9223372036854775806 1)", "9223372036854775807"},
+ {"(- -9223372036854775807 1)", "-9223372036854775808"},
+ {"(* -1 9223372036854775807)", "-9223372036854775807"},
+ {"(/ -9223372036854775808 1)", "-9223372036854775808"},
+ {"(* 1.0e308 1.0)", "1.0e+308"},
+ }
+ 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 TestArithmeticErrors(t *testing.T) {
+ tests := []struct{ src, code, msg string }{
+ {"(* 9223372036854775807 2)", ErrArith, "integer overflow in *"},
+ {"(+ 9223372036854775807 1)", ErrArith, "integer overflow in +"},
+ {"(- -9223372036854775808 1)", ErrArith, "integer overflow in -"},
+ {"(- -9223372036854775808)", ErrArith, "integer overflow in -"},
+ {"(* -1 -9223372036854775808)", ErrArith, "integer overflow in *"},
+ {"(* -9223372036854775808 -1)", ErrArith, "integer overflow in *"},
+ {"(/ -9223372036854775808 -1)", ErrArith, "integer overflow in /"},
+ {"(* 4294967296 4294967296)", ErrArith, "integer overflow in *"},
+
+ {"(/ 1 0)", ErrArith, "division by zero"},
+ {"(/ 0)", ErrArith, "division by zero"},
+ {"(/ 1.0 0)", ErrArith, "division by zero"},
+ {"(/ 1 0.0)", ErrArith, "division by zero"},
+ {"(/ 0.0 0.0)", ErrArith, "division by zero"},
+ {"(* 1.0e308 10)", ErrArith, "float overflow in *"},
+ {"(+ 1.0e308 1.0e308)", ErrArith, "float overflow in +"},
+ {"(- -1.0e308 1.0e308)", ErrArith, "float overflow in -"},
+ {"(/ 1.0e308 1.0e-308)", ErrArith, "float overflow in /"},
+
+ {"(-)", ErrArity, "- takes at least 1 argument, got 0"},
+ {"(/)", ErrArity, "/ takes at least 1 argument, got 0"},
+
+ {`(+ 1 "2")`, ErrType, `argument 2 of + must be a number, got "2"`},
+ {"(+ 'a)", ErrType, "argument 1 of + must be a number, got a"},
+ {"(- T 1)", ErrType, "argument 1 of - must be a number, got T"},
+ {"(- 1 2 ())", ErrType, "argument 3 of - must be a number, got ()"},
+ {"(- ())", ErrType, "argument 1 of - must be a number, got ()"},
+ {"(/ 1 +)", ErrType, "argument 2 of / must be a number, got #<builtin +>"},
+
+ // Arguments are evaluated before the call, left to right.
+ {"(+ boom (/ 1 0))", ErrUnbound, "no statute for symbol boom"},
+ {"(+ (/ 1 0) boom)", ErrArith, "division by zero"},
+ {"(+ 1 (if))", ErrSyntax, "if takes 2 or 3 operands, got 0"},
+ }
+ 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)
+ }
+ })
+ }
+}
diff --git a/eval/builtin.go b/eval/builtin.go
new file mode 100644
index 0000000000000000000000000000000000000000..b5695b3e6755b4bb9ff3e5ee0f8e20251fd411cb
--- /dev/null
+++ b/eval/builtin.go
@@ -0,0 +1,69 @@
+package eval
+
+import (
+ "fmt"
+
+ "government/sexpr"
+)
+
+// Builtin is a function implemented in Go. Builtins are ordinary values:
+// 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)
+}
+
+func (b *Builtin) Name() string { return b.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},
+}
+
+// Builtins returns the top-level environment: every builtin bound to its
+// name.
+func Builtins() *Env {
+ var env *Env
+ for _, b := range builtins {
+ env = env.Extend(sexpr.Symbol(b.name), b)
+ }
+ return env
+}
+
+func apply(f sexpr.Function, args []sexpr.Value) (sexpr.Value, error) {
+ switch f := f.(type) {
+ case *Builtin:
+ if err := checkArity(f, len(args)); err != nil {
+ return nil, err
+ }
+ return f.fn(args)
+ }
+ panic(fmt.Sprintf("eval: cannot apply %T", f))
+}
+
+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)
+ }
+ return nil
+}
+
+func plural(n int, noun string) string {
+ if n == 1 {
+ return "1 " + noun
+ }
+ return fmt.Sprintf("%d %ss", n, noun)
+}
diff --git a/eval/error.go b/eval/error.go
index 0ae0b64796576886e741c22ec590e69e884d2c8a..8c4e1bb34973a7542b811ee83a92acfc556e9a88 100644
--- a/eval/error.go
+++ b/eval/error.go
@@ -4,11 +4,13 @@ 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"
+ ErrUnbound = "E-UNBOUND"
+ ErrSyntax = "E-SYNTAX"
+ ErrSpecialForm = "E-SPECIAL-FORM"
+ ErrNotAFunction = "E-NOT-A-FUNCTION"
+ ErrArity = "E-ARITY"
+ ErrType = "E-TYPE"
+ ErrArith = "E-ARITH"
)
type Error struct {
diff --git a/eval/eval.go b/eval/eval.go
index 8313ea6e171f68e1f7ca80effabc89c1bebf724c..7ed997fd95bdb2157acb84a6da97995ca9a6aba4 100644
--- a/eval/eval.go
+++ b/eval/eval.go
@@ -56,17 +56,25 @@ }
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.
+// evalCall evaluates the head, then the arguments left to right, then
+// applies the function. Every argument is evaluated before the call; special
+// forms exist for the cases where that is wrong.
func evalCall(items []sexpr.Value, env *Env) (sexpr.Value, error) {
- f, err := Eval(items[0], env)
+ head, 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))
+ f, ok := head.(sexpr.Function)
+ if !ok {
+ return nil, errorf(ErrNotAFunction, "%s is not a function", sexpr.Print(head))
}
- return nil, errorf(ErrNotImplemented, "function calls are not implemented")
+ args := make([]sexpr.Value, len(items)-1)
+ for i, item := range items[1:] {
+ if args[i], err = Eval(item, env); err != nil {
+ return nil, err
+ }
+ }
+ return apply(f, args)
}
// (quote d) returns d without evaluating it.
diff --git a/eval/eval_test.go b/eval/eval_test.go
index 82641695728a191e0816e8bb3016cec6c7597d53..266903ff30d77f151c42b7a3a35adb975aaaf1d5 100644
--- a/eval/eval_test.go
+++ b/eval/eval_test.go
@@ -10,7 +10,7 @@
// 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).
+ return Builtins().
Extend("x", sexpr.Int(1)).
Extend("s", sexpr.String("hi")).
Extend("no", sexpr.F).