1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package eval

import "testing"

// TestPrimOpArityMatchesRegistration checks every registered builtin against
// the arity its implementation claims.
//
// This is cheap insurance on the property the whole PrimOpN design exists to
// guarantee: because the arity lives in the *type*, a builtin cannot be
// registered with an arity that disagrees with the function it holds. The test
// is here to catch the reverse mistake — a builtin wired up with the wrong
// PrimOpN wrapper, e.g. a genuinely binary primop wrapped as PrimOp1, which
// the compiler cannot see because both are just func values.
func TestPrimOpArityMatchesRegistration(t *testing.T) {
	for name, v := range makeBuiltinTable() {
		p, ok := v.(VPrimOp)
		if !ok {
			continue // constants like true/false/null
		}
		if p.Name != name {
			t.Errorf("builtin %q registered under name %q", name, p.Name)
		}
		switch n := p.Arity(); n {
		case 1, 2, 3:
			// The only legal arities; Nix has no 0-ary or 4-ary builtins.
		default:
			t.Errorf("builtin %q has arity %d, want 1..3", name, n)
		}
	}
}

// TestPrimOpPartialApplication exercises currying, which is the one path that
// needs the arity as a *number* rather than as a type. A primop applied to
// fewer arguments than it takes must produce a value that can be applied
// again later, and the resumed call must see the arguments in the original
// order.
//
// This matters for the arity refactor specifically: callFunction computes
// `needed := arity - len(collected)` when resuming, so an off-by-one in any
// arity() would show up here as either a premature call or a stuck thunk.
func TestPrimOpPartialApplication(t *testing.T) {
	s := NewEvalState(DefaultBuiltinNames)
	for _, c := range []struct{ src, want string }{
		// Binary primop, applied one argument at a time.
		{`(builtins.map (x: x + 1)) [ 1 2 ]`, `[ 2 3 ]`},
		{`let f = builtins.map (x: x * 2); in f [ 1 2 3 ]`, `[ 2 4 6 ]`},
		// Ternary primop: every split point must work.
		{`builtins.substring 1 3 "abcdef"`, `"bcd"`},
		{`(builtins.substring 1) 3 "abcdef"`, `"bcd"`},
		{`((builtins.substring 1) 3) "abcdef"`, `"bcd"`},
		{`let f = builtins.substring 1 3; in f "abcdef"`, `"bcd"`},
		// Argument order must survive being collected across applications.
		{`(builtins.elemAt [ 10 20 30 ]) 1`, `20`},
		{`(builtins.replaceStrings [ "a" ]) [ "z" ] "abc"`, `"zbc"`},
		// A partially applied primop is a first-class value.
		{`builtins.isFunction (builtins.map (x: x))`, `true`},
		{`builtins.isFunction (builtins.substring 1)`, `true`},
	} {
		if got := evalSrc(t, s, c.src); got != c.want {
			t.Errorf("%s = %s, want %s", c.src, got, c.want)
		}
	}
}