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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
|
package eval_test
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"testing/fstest"
"github.com/nixos/lix/gonix/eval"
)
// langTestsDir returns the path to tests/functional2/lang, relative to this file.
func langTestsDir() string {
_, thisFile, _, _ := runtime.Caller(0)
// thisFile = .../gonix/eval/lang_test.go
// tests are at .../tests/functional2/lang/
root := filepath.Dir(filepath.Dir(filepath.Dir(thisFile)))
return filepath.Join(root, "tests", "functional2", "lang")
}
// --------------------------------------------------------------------------
// Minimal test.toml parser
// --------------------------------------------------------------------------
type langTestCase struct {
Runner string // "eval-okay", "eval-fail", "parse-okay", "parse-fail"
Name string // optional name prefix for expected output files (overrides runner)
Inputs []string // input .nix filenames (relative to test dir); nil+AutoDiscover=true means glob
Flags []string // CLI flags (we skip tests with flags we don't support)
AutoDiscover bool // true for matrix tests with no explicit `in` (discover in-*.nix at run time)
}
// evalOpts carries EvalState settings and post-eval operations derived from
// supported CLI flags.
type evalOpts struct {
maxCallDepth int // -1 means use EvalState default; otherwise set directly
coerceIntegers bool
attrSelect string // if non-empty, select this attr from the result
args map[string]string // --arg name nixExpr: auto-call result lambda
argstrs map[string]string // --argstr name str: auto-call result lambda
}
// outOfScopeDeprecatedFeatures is the set of --extra-deprecated-features values
// that we have explicitly decided not to implement. Test cases that require
// only these features are excluded from counting entirely.
var outOfScopeDeprecatedFeatures = map[string]bool{
"rec-set-dynamic-attrs": true,
"rec-set-overrides": true,
"rec-set-merges": true,
"ancient-let": true,
"shadow-internal-symbols": true,
"floating-without-zero": true,
"cr-line-endings": true,
"nul-bytes": true,
"floor-ceil-corrupt-integers": true,
}
// isOutOfScope reports whether a test case should be excluded entirely from
// the test run and counters (as opposed to merely skipped at runtime).
//
// Out-of-scope categories:
// 1. parse-okay / parse-fail runners — require a parser-output checker we
// don't have and don't plan to build.
// 2. Tests gated solely on deprecated features we've decided not to implement.
// 3. --option abort-on-warn — requires making builtins.warn fatal; not planned.
func isOutOfScope(tc langTestCase) bool {
// 1. Non-eval runners.
if tc.Runner != "eval-okay" && tc.Runner != "eval-fail" {
return true
}
// 2 & 3. Flag-based exclusions.
for i := 0; i < len(tc.Flags); i++ {
switch tc.Flags[i] {
case "--extra-deprecated-features":
if i+1 >= len(tc.Flags) {
return true // malformed — exclude
}
for _, feat := range strings.Fields(tc.Flags[i+1]) {
if outOfScopeDeprecatedFeatures[feat] {
return true
}
}
i++ // consume value
case "--option":
if i+2 < len(tc.Flags) && tc.Flags[i+1] == "abort-on-warn" {
return true
}
i += 2
case "--xml", "--no-location":
// eval-xml: top-level XML print mode — out of scope (builtins.toXML
// covers the same functionality as a builtin).
return true
}
}
return false
}
// parseSupportedFlags inspects flags and returns (opts, true) if all flags are
// known and handled, or (_, false) if any flag is unsupported (caller skips).
//
// Recognised flags:
//
// --extra-experimental-features coerce-integers → opts.coerceIntegers
// --option max-call-depth N → opts.maxCallDepth
// -A attrName → opts.attrSelect
// --arg name nixExpr → opts.args[name]
// --argstr name strValue → opts.argstrs[name]
func parseSupportedFlags(flags []string) (evalOpts, bool) {
opts := evalOpts{maxCallDepth: -1}
i := 0
for i < len(flags) {
switch flags[i] {
case "--extra-experimental-features":
if i+1 >= len(flags) {
return opts, false
}
for _, feat := range strings.Fields(flags[i+1]) {
if feat != "coerce-integers" {
return opts, false
}
opts.coerceIntegers = true
}
i += 2
case "--option":
if i+2 >= len(flags) {
return opts, false
}
if flags[i+1] != "max-call-depth" {
return opts, false
}
n, err := strconv.Atoi(flags[i+2])
if err != nil {
return opts, false
}
opts.maxCallDepth = n
i += 3
case "-A":
if i+1 >= len(flags) {
return opts, false
}
opts.attrSelect = flags[i+1]
i += 2
case "--arg":
if i+2 >= len(flags) {
return opts, false
}
if opts.args == nil {
opts.args = make(map[string]string)
}
opts.args[flags[i+1]] = flags[i+2]
i += 3
case "--argstr":
if i+2 >= len(flags) {
return opts, false
}
if opts.argstrs == nil {
opts.argstrs = make(map[string]string)
}
opts.argstrs[flags[i+1]] = flags[i+2]
i += 3
default:
return opts, false
}
}
return opts, true
}
// parseTestTOML parses the [[test]] entries from a test.toml file.
// It handles the subset of TOML used in tests/functional2/lang/:
//
// [[test]]
// runner = "eval-okay"
// name = "mypfx" # optional; if set, expected files use "mypfx" prefix instead of runner
// in = "in.nix" # or in = [ "a.nix", "b.nix" ], omit for matrix auto-discovery
// flags = [ "--foo" ] # optional
// matrix = true # optional; if true, each `in` is a separate test
func parseTestTOML(data []byte) []langTestCase {
var cases []langTestCase
var cur *langTestCase
matrix := false
for _, rawLine := range strings.Split(string(data), "\n") {
line := strings.TrimSpace(rawLine)
// Strip inline comments.
if idx := strings.Index(line, "#"); idx >= 0 {
line = strings.TrimSpace(line[:idx])
}
if line == "[[test]]" {
if cur != nil {
cases = appendMatrix(cases, cur, matrix)
}
cur = &langTestCase{}
matrix = false
continue
}
if cur == nil {
continue
}
key, val, ok := strings.Cut(line, "=")
if !ok {
continue
}
key = strings.TrimSpace(key)
val = strings.TrimSpace(val)
switch key {
case "runner":
cur.Runner = unquote(val)
case "name":
cur.Name = unquote(val)
case "matrix":
matrix = val == "true"
case "in":
cur.Inputs = parseStringOrArray(val)
case "flags":
cur.Flags = parseStringOrArray(val)
}
}
if cur != nil {
cases = appendMatrix(cases, cur, matrix)
}
return cases
}
func appendMatrix(cases []langTestCase, cur *langTestCase, matrix bool) []langTestCase {
if matrix {
inputs := cur.Inputs
// If no inputs specified, auto-discover in-*.nix at run time.
if len(inputs) == 0 {
tc := *cur
tc.Inputs = nil
tc.AutoDiscover = true
cases = append(cases, tc)
return cases
}
if len(inputs) > 1 {
for _, inp := range inputs {
tc := *cur
tc.Inputs = []string{inp}
cases = append(cases, tc)
}
return cases
}
}
cases = append(cases, *cur)
return cases
}
// parseStringOrArray parses a TOML value that is either "foo" or [ "foo", "bar" ].
func parseStringOrArray(val string) []string {
val = strings.TrimSpace(val)
if strings.HasPrefix(val, "[") {
// Array: strip [ ], split by comma.
inner := strings.TrimSuffix(strings.TrimPrefix(val, "["), "]")
var out []string
for _, part := range strings.Split(inner, ",") {
if s := unquote(strings.TrimSpace(part)); s != "" {
out = append(out, s)
}
}
return out
}
if s := unquote(val); s != "" {
return []string{s}
}
return nil
}
// unquote strips surrounding double quotes from a TOML string value.
func unquote(s string) string {
s = strings.TrimSpace(s)
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
return s
}
// --------------------------------------------------------------------------
// Test case discovery for dirs without test.toml
// --------------------------------------------------------------------------
// discoverImplicit finds test cases for dirs that don't have a test.toml,
// by scanning for eval-okay*.out.exp and eval-fail*.err.exp files.
func discoverImplicit(dir string) []langTestCase {
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
var cases []langTestCase
for _, e := range entries {
name := e.Name()
var runner, suffix string
if strings.HasPrefix(name, "eval-okay") && strings.HasSuffix(name, ".out.exp") {
runner = "eval-okay"
suffix = strings.TrimSuffix(strings.TrimPrefix(name, "eval-okay"), ".out.exp")
} else if strings.HasPrefix(name, "eval-fail") && strings.HasSuffix(name, ".err.exp") {
runner = "eval-fail"
suffix = strings.TrimSuffix(strings.TrimPrefix(name, "eval-fail"), ".err.exp")
} else {
continue
}
// Derive input filename from suffix.
// eval-okay.out.exp → in.nix
// eval-okay-foo.out.exp → in-foo.nix
var inFile string
if suffix == "" {
inFile = "in.nix"
} else if strings.HasPrefix(suffix, "-") {
inFile = "in" + suffix + ".nix"
} else {
inFile = "in-" + suffix + ".nix"
}
// Only include if the input file exists.
if _, err := os.Stat(filepath.Join(dir, inFile)); err != nil {
continue
}
cases = append(cases, langTestCase{
Runner: runner,
Inputs: []string{inFile},
})
}
return cases
}
// --------------------------------------------------------------------------
// Bulk lang test runner
// --------------------------------------------------------------------------
// sharedLibNix holds the contents of tests/functional2/lang/lib.nix.
// It is read once and injected into every test's virtual fs.FS, mirroring
// what the real Python test runner does (copies lib.nix into each test dir).
var sharedLibNix []byte
// testFS prefix where all test files are scoped.
// Using "pwd" matches the display convention: RealPath returns "/pwd/foo.nix"
// for a file at FS key "pwd/foo.nix", so builtins.toString ./foo.nix returns
// "/pwd/foo.nix" and builtins.pathExists can find it at the same FS key.
// Stray absolute paths like /fnord still miss: fsPath("/fnord") = "fnord" ≠ "pwd/fnord".
const testFSPrefix = "pwd"
const testFSBase = "/" + testFSPrefix + "/"
// langMemFS implements eval.NixFS using an in-memory fstest.MapFS.
// All test files are stored under the "pwd/" prefix.
// RealPath maps "pwd/foo.nix" → "/pwd/foo.nix" for display.
// SearchPath is passed through to EvalState when evaluating.
type langMemFS struct {
fstest.MapFS
SearchPath []eval.SearchPathEntry
}
func (m langMemFS) IsExecutable(path string) bool {
f, ok := m.MapFS[path]
if !ok {
return false
}
return f.Mode&0o111 != 0
}
func (m langMemFS) ReadFileType(path string) (string, error) {
f, ok := m.MapFS[path]
if !ok {
return "", &fs.PathError{Op: "readFileType", Path: path, Err: fs.ErrNotExist}
}
switch {
case f.Mode&fs.ModeSymlink != 0:
return "symlink", nil
case f.Mode&fs.ModeDir != 0:
return "directory", nil
default:
return "regular", nil
}
}
// ReadLink returns the symlink target, which fstest.MapFS stores in Data.
func (m langMemFS) ReadLink(path string) (string, error) {
f, ok := m.MapFS[path]
if !ok || f.Mode&fs.ModeSymlink == 0 {
return "", &fs.PathError{Op: "readlink", Path: path, Err: fs.ErrInvalid}
}
return string(f.Data), nil
}
func (m langMemFS) RealPath(path string, relative bool) string {
if !relative {
if path == "" {
return "/"
}
return "/" + path
}
// Display paths for relative Nix path literals (./foo, ./.., etc.).
//
// The test harness mirrors the real Nix test infrastructure which copies
// test files into a temp directory that lives inside a parent temp dir:
//
// /tmp/nix-test-XYZ/ ← FS root (key "")
// pwd/ ← testFSPrefix (key "pwd")
// in.nix, lib.nix, ...
// test-home/ ← sibling of pwd (only reachable via ../)
// lib.nix
//
// Display rules:
// "" → "/pwd/.." (FS root = parent of pwd, displayed without
// trailing slash so concatenation without "/" is
// non-navigable: "/pwd/.." + "foo" ≠ path in FS)
// "." → "/pwd" (dot = the pwd itself)
// "pwd/foo" → "/pwd/foo"
// "pwd" → "/pwd"
// "foo" → "/pwd/foo" (bare name, relative to pwd — e.g. ~/foo → /foo
// in WASM which displays as /pwd/foo to match real
// test infra where HOME is set to the test dir)
if path == "" {
// FS root: display as the non-cleaned parent path so that string
// concatenation without a separator produces a non-existent FS key.
return "/pwd/.."
}
// Strip the "pwd/" or exact "pwd" prefix.
if path == testFSPrefix {
return "/pwd"
}
stripped := strings.TrimPrefix(path, testFSPrefix+"/")
if stripped == "" || stripped == "." {
return "/pwd"
}
return "/pwd/" + stripped
}
func (m langMemFS) ResolvePath(path string) string { return path }
// buildTestFS reads all test files into an in-memory langMemFS.
// Files are stored under the "testfs/" prefix so that relative path
// imports (./foo.nix with basePath "/testfs/") resolve correctly, while
// stray absolute paths (/fnord) naturally miss.
func buildTestFS(t *testing.T, dir string, libNix []byte) eval.NixFS {
t.Helper()
mfs := make(fstest.MapFS)
// Always add an explicit directory entry for the root (testFSPrefix).
// ReadFileType checks m.MapFS[path] directly, so implicit directories
// inferred by fstest.MapFS from file paths are not visible to it.
mfs[testFSPrefix] = &fstest.MapFile{Mode: fs.ModeDir | 0o755}
// Copy all non-directory files from the test dir into testfs/.
entries, _ := os.ReadDir(dir)
for _, e := range entries {
if e.IsDir() {
continue
}
data, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
mfs[testFSPrefix+"/"+e.Name()] = &fstest.MapFile{Data: data}
}
// Inject shared lib.nix unless the test dir provides its own.
if _, ok := mfs[testFSPrefix+"/lib.nix"]; !ok && len(libNix) > 0 {
mfs[testFSPrefix+"/lib.nix"] = &fstest.MapFile{Data: libNix}
}
// Apply fixture overlays for tests that need symlinks/subdirs.
searchPath := applyTestFixtures(filepath.Base(dir), mfs)
return langMemFS{MapFS: mfs, SearchPath: searchPath}
}
// applyTestFixtures adds synthetic fixture entries to the in-memory FS for
// tests that need symlinks or subdirectories.
// Mirrors the Python test runner's @with_files fixture setup.
// Returns a SearchPath to configure on the EvalState (may be nil).
func applyTestFixtures(dirName string, mfs fstest.MapFS) []eval.SearchPathEntry {
switch dirName {
case "builtins.readDir", "builtins.readFileType":
// readDir/ subdir: foo/ (dir), bar (file), linked (symlink→bar), ldir (symlink→foo)
mfs[testFSPrefix+"/readDir/foo"] = &fstest.MapFile{Mode: fs.ModeDir | 0o755}
mfs[testFSPrefix+"/readDir/bar"] = &fstest.MapFile{}
mfs[testFSPrefix+"/readDir/linked"] = &fstest.MapFile{
Mode: fs.ModeSymlink, Data: []byte("./bar"),
}
mfs[testFSPrefix+"/readDir/ldir"] = &fstest.MapFile{
Mode: fs.ModeSymlink, Data: []byte("./foo"),
}
case "builtins.pathExists":
// symlink-resolution/ subtree + test-home/lib.nix
mfs[testFSPrefix+"/symlink-resolution/foo/lib"] = &fstest.MapFile{Mode: fs.ModeDir | 0o755}
mfs[testFSPrefix+"/symlink-resolution/overlays"] = &fstest.MapFile{Mode: fs.ModeDir | 0o755}
mfs[testFSPrefix+"/symlink-resolution/foo/lib/default.nix"] = &fstest.MapFile{Data: []byte(`"test"`)}
mfs[testFSPrefix+"/symlink-resolution/overlays/overlay.nix"] = &fstest.MapFile{Data: []byte(`import ../lib`)}
mfs[testFSPrefix+"/symlink-resolution/foo/overlays"] = &fstest.MapFile{
Mode: fs.ModeSymlink, Data: []byte("../overlays"),
}
mfs[testFSPrefix+"/symlink-resolution/broken"] = &fstest.MapFile{
Mode: fs.ModeSymlink, Data: []byte("nonexistent"),
}
// test-home is outside testfs — lives at the root for absolute-path access.
// Explicit dir entry so ReadFileType("test-home") returns "directory".
mfs["test-home"] = &fstest.MapFile{Mode: fs.ModeDir | 0o755}
mfs["test-home/lib.nix"] = &fstest.MapFile{Data: []byte(`"home"`)}
case "search-path":
// The Python test sets up:
// -I dir1 -I dir2 -I dir5=dir3 (3 entries from flags)
// NIX_PATH=dir3:dir4 (2 entries from env)
// Total: 5 entries. We copy the dir contents into the FS and build
// a SearchPath list matching the exact order used by the Python test.
langsDir := langTestsDir()
srcDir := filepath.Join(langsDir, "search-path")
for _, d := range []string{"dir1", "dir2", "dir3", "dir4"} {
entries, _ := os.ReadDir(filepath.Join(srcDir, d))
for _, e := range entries {
data, err := os.ReadFile(filepath.Join(srcDir, d, e.Name()))
if err != nil {
continue
}
mfs[testFSPrefix+"/"+d+"/"+e.Name()] = &fstest.MapFile{Data: data}
}
}
return []eval.SearchPathEntry{
{Prefix: "", Path: "/" + testFSPrefix + "/dir1"},
{Prefix: "", Path: "/" + testFSPrefix + "/dir2"},
{Prefix: "dir5", Path: "/" + testFSPrefix + "/dir3"},
{Prefix: "", Path: "/" + testFSPrefix + "/dir3"},
{Prefix: "", Path: "/" + testFSPrefix + "/dir4"},
}
}
return nil
}
func TestLangSuite(t *testing.T) {
langsDir := langTestsDir()
// Read the shared lib.nix once.
libNixPath := filepath.Join(langsDir, "lib.nix")
sharedLibNix, _ = os.ReadFile(libNixPath)
entries, err := os.ReadDir(langsDir)
if err != nil {
t.Fatalf("cannot read lang test dir: %v", err)
}
// LANG_TEST=a,b,c restricts the run to test directories with exactly those
// names. Useful for debugging specific tests without regex footguns.
var langFilter map[string]bool
if env := os.Getenv("LANG_TEST"); env != "" {
langFilter = make(map[string]bool)
for _, name := range strings.Split(env, ",") {
langFilter[strings.TrimSpace(name)] = true
}
}
total, passed, skipped, failed := 0, 0, 0, 0
for _, e := range entries {
if !e.IsDir() {
continue
}
if langFilter != nil && !langFilter[e.Name()] {
continue
}
dir := filepath.Join(langsDir, e.Name())
var cases []langTestCase
tomlPath := filepath.Join(dir, "test.toml")
if data, err := os.ReadFile(tomlPath); err == nil {
cases = parseTestTOML(data)
} else {
cases = discoverImplicit(dir)
}
for _, tc := range cases {
tc := tc
dirName := e.Name()
// Exclude out-of-scope test cases entirely — don't register them
// as subtests and don't count them in any counter.
if isOutOfScope(tc) {
continue
}
// Derive a descriptive sub-test name.
testName := dirName
if len(tc.Inputs) == 1 && tc.Inputs[0] != "in.nix" {
suffix := strings.TrimSuffix(strings.TrimPrefix(tc.Inputs[0], "in"), ".nix")
testName = dirName + suffix
} else if len(tc.Inputs) == 0 && tc.Name != "" {
// Matrix with auto-discover: use name as extra qualifier.
testName = dirName + "-" + tc.Name
}
// Use name prefix in test name if set (e.g. "warn" runner variant).
runner := tc.Runner
if tc.Name != "" && len(tc.Inputs) == 1 {
runner = tc.Runner + "/" + tc.Name
}
testName = runner + "/" + testName
testFS := buildTestFS(t, dir, sharedLibNix)
t.Run(testName, func(t *testing.T) {
switch tc.Runner {
case "eval-okay":
runEvalOkay(t, dir, tc, testFS, &total, &passed, &skipped)
case "eval-fail":
runEvalFail(t, dir, tc, testFS, &total, &passed, &skipped)
default:
// Shouldn't reach here — isOutOfScope filters non-eval runners.
total++
skipped++
t.Skipf("runner %q not supported", tc.Runner)
}
})
}
}
_ = failed
failed = total - passed - skipped
t.Logf("lang suite: %d total, %d passed, %d skipped, %d failed",
total, passed, skipped, failed)
}
// runEvalOkay runs an eval-okay test case: parse → eval → print, compare against .out.exp.
func runEvalOkay(t *testing.T, dir string, tc langTestCase, testFS eval.NixFS, total, passed, skipped *int) {
t.Helper()
opts := evalOpts{maxCallDepth: -1}
if len(tc.Flags) > 0 {
var ok bool
opts, ok = parseSupportedFlags(tc.Flags)
if !ok {
*total++
*skipped++
t.Skipf("flags not supported: %v", tc.Flags)
}
}
// Determine the prefix to use for expected-output filenames.
// If the test has a name, use that; otherwise use the runner name.
expPrefix := tc.Runner
if tc.Name != "" {
expPrefix = tc.Name
}
// Resolve inputs: auto-discover for matrix tests, default to in.nix otherwise.
inputs := tc.Inputs
if tc.AutoDiscover {
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("readdir %s: %v", dir, err)
}
for _, e := range entries {
if strings.HasPrefix(e.Name(), "in-") && strings.HasSuffix(e.Name(), ".nix") {
inputs = append(inputs, e.Name())
}
}
}
if len(inputs) == 0 {
inputs = []string{"in.nix"}
}
for _, inFile := range inputs {
*total++
inPath := filepath.Join(dir, inFile)
src, err := os.ReadFile(inPath)
if err != nil {
t.Fatalf("read %s: %v", inFile, err)
}
// Derive expected output file name from input file name using expPrefix.
outFile := expFileName(inFile, expPrefix, ".out.exp")
expPath := filepath.Join(dir, outFile)
expBytes, err := os.ReadFile(expPath)
if err != nil {
t.Fatalf("read expected output %s: %v", outFile, err)
}
expected := strings.TrimRight(string(expBytes), "\n")
// Always report the file as "in.nix" for position information.
// The real Nix test infrastructure copies each matrix input to a temp
// dir as "in.nix" before running, so expected output always says "in.nix".
got, err := parseAndEvalPrint(t, string(src), testFS, testFSBase+"in.nix", opts)
if err != nil {
t.Fatalf("eval error: %v", err)
return
}
if got != expected {
t.Fatalf("output mismatch:\n got: %s\n want: %s", got, expected)
return
}
*passed++
}
}
// runEvalFail runs an eval-fail test case: parse → eval, expect an error.
// We don't match the exact error message (it includes position info we don't have).
func runEvalFail(t *testing.T, dir string, tc langTestCase, testFS eval.NixFS, total, passed, skipped *int) {
t.Helper()
opts := evalOpts{maxCallDepth: -1}
if len(tc.Flags) > 0 {
var ok bool
opts, ok = parseSupportedFlags(tc.Flags)
if !ok {
*total++
*skipped++
t.Skipf("flags not supported: %v", tc.Flags)
}
}
inputs := tc.Inputs
if len(inputs) == 0 {
inputs = []string{"in.nix"}
}
for _, inFile := range inputs {
*total++
inPath := filepath.Join(dir, inFile)
src, err := os.ReadFile(inPath)
if err != nil {
t.Fatalf("read %s: %v", inFile, err)
}
_, err = parseAndEvalPrint(t, string(src), testFS, testFSBase+"in.nix", opts)
if err == nil {
t.Fatalf("expected an error but eval succeeded")
return
}
// Any error is acceptable for now.
*passed++
}
}
// expFileName derives the expected-output filename from an input filename.
// e.g. "in.nix" → "eval-okay.out.exp"
//
// "in-foo.nix" → "eval-okay-foo.out.exp"
func expFileName(inFile, runner, ext string) string {
base := strings.TrimSuffix(inFile, ".nix") // "in" or "in-foo"
suffix := strings.TrimPrefix(base, "in") // "" or "-foo"
return runner + suffix + ext
}
// parseAndEvalPrint parses expr using the native Go parser, evaluates with Go,
// and prints the result.
func parseAndEvalPrint(t *testing.T, expr string, testFS eval.NixFS, filePath string, opts evalOpts) (string, error) {
t.Helper()
var searchPath []eval.SearchPathEntry
if mfs, ok := testFS.(langMemFS); ok {
searchPath = mfs.SearchPath
}
state := eval.NewEvalStateWithSearch(testBuiltinNames, searchPath)
state.NativeParseFunc = func(s *eval.EvalState, src []byte, basePath, fp string) (eval.Expr, error) {
return eval.NativeParseExprIntoState(s, src, basePath, fp)
}
state.FS = testFS
state.BasePath = testFSBase
if opts.coerceIntegers {
state.CoerceIntegers = true
}
if opts.maxCallDepth >= 0 {
state.MaxDepth = opts.maxCallDepth
}
ast, err := eval.NativeParseExprIntoState(state, []byte(expr), testFSBase, filePath)
if err != nil {
return "", fmt.Errorf("parse: %w", err)
}
v, err := state.Eval(ast)
if err != nil {
return "", err
}
ctx := context.Background()
if len(opts.args) > 0 || len(opts.argstrs) > 0 {
v, err = applyAutoArgs(ctx, state, v, opts)
if err != nil {
return "", err
}
}
if opts.attrSelect != "" {
v, err = selectAttr(state, v, opts.attrSelect)
if err != nil {
return "", err
}
}
s, err := eval.PrintValue(state, v)
if err != nil {
return "", fmt.Errorf("print: %w", err)
}
return s, nil
}
// applyAutoArgs calls the top-level value v as a lambda (or series of lambdas)
// with arguments from --arg (Nix expressions) and --argstr (plain strings).
// Mirrors `nix eval --arg name expr --argstr name str` behaviour.
func applyAutoArgs(ctx context.Context, state *eval.EvalState, v eval.Value, opts evalOpts) (eval.Value, error) {
_ = ctx
// Build an attrset of argument values.
var attrs []eval.Attr
for name, nixExpr := range opts.args {
ast, err := eval.NativeParseExprIntoState(state, []byte(nixExpr), testFSBase, "")
if err != nil {
return nil, fmt.Errorf("--arg %s: parse: %w", name, err)
}
argVal, err := state.Eval(ast)
if err != nil {
return nil, fmt.Errorf("--arg %s: eval: %w", name, err)
}
sym := state.Symbols.Create(name)
attrs = append(attrs, eval.Attr{Name: sym, Value: argVal})
}
for name, str := range opts.argstrs {
sym := state.Symbols.Create(name)
attrs = append(attrs, eval.Attr{Name: sym, Value: eval.VString{V: str}})
}
arg := eval.Value(eval.VAttrs{Bindings: state.NewAttrs(attrs)})
// Call the top-level lambda with the attrset argument.
result, err := state.CallFunction(v, []eval.Value{arg})
if err != nil {
return nil, fmt.Errorf("auto-args call: %w", err)
}
return result, nil
}
// selectAttr selects a single attribute (dot-separated path) from an attrset value.
// Mirrors `nix eval -A foo.bar`.
func selectAttr(state *eval.EvalState, v eval.Value, attrPath string) (eval.Value, error) {
parts := strings.Split(attrPath, ".")
for _, part := range parts {
if err := state.ForceValue(&v); err != nil {
return nil, fmt.Errorf("-A %s: force: %w", attrPath, err)
}
attrs, ok := v.(eval.VAttrs)
if !ok {
return nil, fmt.Errorf("-A %s: expected attrset, got %s", attrPath, eval.ValueTypeName(v))
}
sym := state.Symbols.Create(part)
attr := attrs.Bindings.Get(sym)
if attr == nil {
return nil, fmt.Errorf("-A %s: attribute '%s' missing", attrPath, part)
}
v = attr.Value
}
return v, nil
}
// deepForceValue fully forces a value (lists, attrset values) before printing.
func deepForceValue(s *eval.EvalState, vp *eval.Value) error {
return deepForceWithSeen(s, vp, make(map[*eval.Bindings]bool), make(map[*eval.VList]bool))
}
func deepForceWithSeen(s *eval.EvalState, vp *eval.Value, seenAttrs map[*eval.Bindings]bool, seenLists map[*eval.VList]bool) error {
if err := s.ForceValue(vp); err != nil {
return err
}
switch t := (*vp).(type) {
case *eval.VList:
if seenLists[t] {
return nil
}
seenLists[t] = true
for i := range t.Elems {
if err := deepForceWithSeen(s, &t.Elems[i], seenAttrs, seenLists); err != nil {
return err
}
}
delete(seenLists, t)
case eval.VAttrs:
if seenAttrs[t.Bindings] {
return nil
}
seenAttrs[t.Bindings] = true
all := t.Bindings.All()
for i := range all {
if err := deepForceWithSeen(s, &all[i].Value, seenAttrs, seenLists); err != nil {
return err
}
}
delete(seenAttrs, t.Bindings)
}
return nil
}
|