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
package eval_test

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
	"testing"

	"github.com/nixos/lix/gonix/eval"
)

// ---------------------------------------------------------------------------
// Unit tests: ParseNixJSON round-trip
// ---------------------------------------------------------------------------

func TestParseNixJSON_Literal(t *testing.T) {
	json := `{"_type":"ExprLiteral","value":42,"valueType":"Int"}`
	n, err := eval.ParseNixJSON([]byte(json))
	if err != nil {
		t.Fatal(err)
	}
	if n.Type != "ExprLiteral" || n.LitValueType != "Int" || n.LitValue != int64(42) {
		t.Errorf("got %+v", n)
	}
}

func TestParseNixJSON_Var(t *testing.T) {
	json := `{"_type":"ExprVar","value":"foo"}`
	n, err := eval.ParseNixJSON([]byte(json))
	if err != nil {
		t.Fatal(err)
	}
	if n.Type != "ExprVar" || n.VarName != "foo" {
		t.Errorf("got %+v", n)
	}
}

func TestParseNixJSON_Lambda(t *testing.T) {
	json := `{
		"_type": "ExprLambda",
		"arg": "x",
		"body": {"_type":"ExprVar","value":"x"},
		"formals": {"a": null, "b": {"_type":"ExprLiteral","value":1,"valueType":"Int"}},
		"formalsEllipsis": true
	}`
	n, err := eval.ParseNixJSON([]byte(json))
	if err != nil {
		t.Fatal(err)
	}
	if n.LambdaArg != "x" {
		t.Errorf("arg = %q", n.LambdaArg)
	}
	if !n.LambdaEllipsis {
		t.Error("expected ellipsis")
	}
	if n.LambdaFormals["a"] != nil {
		t.Error("formal a should have nil default")
	}
	if n.LambdaFormals["b"] == nil || n.LambdaFormals["b"].LitValue != int64(1) {
		t.Error("formal b should have default 1")
	}
}

// ---------------------------------------------------------------------------
// Unit tests: ExprToNode
// ---------------------------------------------------------------------------

func TestExprToNode_IntLiteral(t *testing.T) {
	symbols := eval.NewSymbolTable()
	expr := eval.NewExprInt(eval.PosIdx(0), 42)
	n := eval.ExprToNode(expr, symbols)
	if n.Type != "ExprLiteral" || n.LitValueType != "Int" || n.LitValue != int64(42) {
		t.Errorf("got %+v", n)
	}
}

func TestExprToNode_Var(t *testing.T) {
	symbols := eval.NewSymbolTable()
	sym := symbols.Create("foo")
	expr := &eval.ExprVar{Name: sym}
	n := eval.ExprToNode(expr, symbols)
	if n.Type != "ExprVar" || n.VarName != "foo" {
		t.Errorf("got %+v", n)
	}
}

// ---------------------------------------------------------------------------
// Integration: compare Go parser against nix-instantiate --parse
// ---------------------------------------------------------------------------

// nixInstantiateParse runs `nix-instantiate --parse <file>` and returns the
// JSON output. Returns an error if the command fails.
func nixInstantiateParse(filePath string) ([]byte, error) {
	cmd := exec.Command("nix-instantiate", "--parse", filePath)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("%v: %s", err, stderr.String())
	}
	return stdout.Bytes(), nil
}

// compareFileAST parses a .nix file with both nix-instantiate and our Go parser,
// then compares the resulting ASTs.
func compareFileAST(t *testing.T, filePath string, symbols *eval.SymbolTable, builtinNames []string) []eval.Diff {
	t.Helper()

	// Get nix-instantiate --parse output
	nixJSON, err := nixInstantiateParse(filePath)
	if err != nil {
		t.Fatalf("nix-instantiate --parse %s: %v", filePath, err)
	}

	nixNode, err := eval.ParseNixJSON(nixJSON)
	if err != nil {
		t.Fatalf("ParseNixJSON for %s: %v", filePath, err)
	}

	// Parse with Go native parser
	src, err := os.ReadFile(filePath)
	if err != nil {
		t.Fatalf("read %s: %v", filePath, err)
	}

	basePath := filepath.Dir(filePath) + "/"
	goExpr, err := eval.NativeParseExpr(src, basePath, filePath, symbols, builtinNames)
	if err != nil {
		t.Fatalf("NativeParseExpr %s: %v", filePath, err)
	}

	goNode := eval.ExprToNode(goExpr, symbols)

	return eval.CompareAST(nixNode, goNode)
}

// TestASTCompare_SimpleExprs tests the comparison on inline expressions.
// We write them to temp files so nix-instantiate can parse them.
func TestASTCompare_SimpleExprs(t *testing.T) {
	if _, err := exec.LookPath("nix-instantiate"); err != nil {
		t.Skip("nix-instantiate not in PATH")
	}
	requireWasm(t)

	exprs := []struct {
		name string
		src  string
	}{
		{"int", "42"},
		{"float", "3.14"},
		{"string", `"hello world"`},
		{"true", "a: true"},
		{"null", "a: null"},
		{"lambda_simple", "x: x"},
		{"lambda_formals", "{ a, b ? 1, ...}@args: a"},
		{"lambda_formals_no_at", "{ a, b }: a"},
		{"call", "a: b: a b"},
		{"call_multi", "f: a: b: f a b"},
		{"attrset", "{ a = 1; b = 2; }"},
		{"attrset_rec", "rec { a = 1; b = a; }"},
		{"attrset_nested", "{ a.b = 1; a.c = 2; }"},
		{"let", "let a = 1; in a"},
		{"let_inherit", "a: let inherit a; b = 1; in b"},
		{"with", "x: with x; x"},
		{"if", "a: if a then 1 else 2"},
		{"assert", "a: assert a; a"},
		{"list", "[ 1 2 3 ]"},
		{"select", "a: a.b"},
		{"select_or", "a: a.b or 1"},
		{"has_attr", "a: a ? b"},
		{"not", "a: !a"},
		{"eq", "a: b: a == b"},
		{"neq", "a: b: a != b"},
		{"and", "a: b: a && b"},
		{"or", "a: b: a || b"},
		{"impl", "a: b: a -> b"},
		{"update", "a: b: a // b"},
		{"concat_lists", "a: b: a ++ b"},
		{"add", "a: b: a + b"},
		{"sub", "a: b: a - b"},
		{"mul", "a: b: a * b"},
		{"div", "a: b: a / b"},
		{"lt", "a: b: a < b"},
		{"gt", "a: b: a > b"},
		{"le", "a: b: a <= b"},
		{"ge", "a: b: a >= b"},
		{"negate", "a: -a"},
		{"concat_strings", `a: "hello ${a} world"`},
		{"inherit_from", "a: { inherit (a) b c; }"},
		{"search_path", "a: <nixpkgs>"},
		{"cur_pos", "a: __curPos"},
		{"indented_string", "a: ''\n  hello ${a}\n  world\n''"},
		{"path_absolute", "a: /foo/bar"},
		{"dynamic_attr_select", "a: b: a.${b}"},
		{"mixed_inherit", "a: b: { inherit a; inherit (b) c; d = 1; }"},
	}

	for _, tc := range exprs {
		t.Run(tc.name, func(t *testing.T) {
			// Write to temp file
			tmpFile := filepath.Join(t.TempDir(), "in.nix")
			if err := os.WriteFile(tmpFile, []byte(tc.src), 0644); err != nil {
				t.Fatal(err)
			}

			symbols := eval.NewSymbolTable()
			diffs := compareFileAST(t, tmpFile, symbols, testBuiltinNames)
			if len(diffs) > 0 {
				t.Errorf("AST diff for %q:\n%s", tc.src, eval.FormatDiffs(diffs))
			}
		})
	}
}

// ---------------------------------------------------------------------------
// Mass comparison: all .nix files in a directory tree
// ---------------------------------------------------------------------------

// TestASTCompare_Nixpkgs runs the AST comparison against every .nix file in
// the directory specified by the NIXPKGS_PATH environment variable.
//
// Usage:
//
//	NIXPKGS_PATH=~/nixpkgs go test ./eval -run TestASTCompare_Nixpkgs -count=1 -timeout=30m
func TestASTCompare_Nixpkgs(t *testing.T) {
	nixpkgsPath := os.Getenv("NIXPKGS_PATH")
	if nixpkgsPath == "" {
		t.Skip("NIXPKGS_PATH not set; skipping nixpkgs AST comparison")
	}
	if _, err := exec.LookPath("nix-instantiate"); err != nil {
		t.Skip("nix-instantiate not in PATH")
	}
	requireWasm(t)

	// Collect all .nix files
	var files []string
	err := filepath.Walk(nixpkgsPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return nil // skip unreadable dirs
		}
		// Skip .git and other hidden directories
		if info.IsDir() && strings.HasPrefix(info.Name(), ".") {
			return filepath.SkipDir
		}
		if !info.IsDir() && strings.HasSuffix(path, ".nix") {
			files = append(files, path)
		}
		return nil
	})
	if err != nil {
		t.Fatalf("walking %s: %v", nixpkgsPath, err)
	}
	t.Logf("found %d .nix files in %s", len(files), nixpkgsPath)

	// Determine parallelism
	numWorkers := runtime.NumCPU()
	if numWorkers > 16 {
		numWorkers = 16
	}

	var (
		total      atomic.Int64
		passed     atomic.Int64
		nixFailed  atomic.Int64 // nix-instantiate --parse failed
		goFailed   atomic.Int64 // Go parser failed
		bothFailed atomic.Int64 // both failed (expected — e.g. syntax errors)
		diffCount  atomic.Int64 // AST mismatch
		mu         sync.Mutex
		diffFiles  []string // files with AST differences (collect first N)
	)
	const maxDiffReport = 50

	// Work queue
	fileCh := make(chan string, numWorkers*2)
	var wg sync.WaitGroup

	for i := 0; i < numWorkers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			// Each worker gets its own SymbolTable to avoid contention
			symbols := eval.NewSymbolTable()

			for filePath := range fileCh {
				total.Add(1)

				// Run nix-instantiate --parse
				nixJSON, nixErr := nixInstantiateParse(filePath)

				// Run Go native parser
				src, readErr := os.ReadFile(filePath)
				if readErr != nil {
					continue
				}

				basePath := filepath.Dir(filePath) + "/"
				goExpr, goErr := eval.NativeParseExpr(src, basePath, filePath, symbols, testBuiltinNames)

				if nixErr != nil && goErr != nil {
					// Both failed — expected for malformed files
					bothFailed.Add(1)
					continue
				}
				if nixErr != nil {
					// nix-instantiate failed but Go succeeded — nix rejects but we accept
					nixFailed.Add(1)
					continue
				}
				if goErr != nil {
					// Go parser failed but nix-instantiate succeeded — parser bug
					goFailed.Add(1)
					mu.Lock()
					if len(diffFiles) < maxDiffReport {
						diffFiles = append(diffFiles, fmt.Sprintf("GO_PARSE_FAIL: %s: %v", filePath, goErr))
					}
					mu.Unlock()
					continue
				}

				// Both succeeded — compare ASTs
				nixNode, err := eval.ParseNixJSON(nixJSON)
				if err != nil {
					mu.Lock()
					if len(diffFiles) < maxDiffReport {
						diffFiles = append(diffFiles, fmt.Sprintf("JSON_PARSE_FAIL: %s: %v", filePath, err))
					}
					mu.Unlock()
					continue
				}

				goNode := eval.ExprToNode(goExpr, symbols)
				diffs := eval.CompareAST(nixNode, goNode)
				if len(diffs) > 0 {
					diffCount.Add(1)
					mu.Lock()
					if len(diffFiles) < maxDiffReport {
						// Show first diff only for brevity
						diffFiles = append(diffFiles, fmt.Sprintf("DIFF: %s: %s", filePath, diffs[0].String()))
					}
					mu.Unlock()
				} else {
					passed.Add(1)
				}
			}
		}()
	}

	// Feed files to workers
	for _, f := range files {
		fileCh <- f
	}
	close(fileCh)
	wg.Wait()

	// Report
	t.Logf("Results:")
	t.Logf("  total:        %d", total.Load())
	t.Logf("  passed:       %d", passed.Load())
	t.Logf("  both failed:  %d (expected)", bothFailed.Load())
	t.Logf("  nix rejected: %d (nix failed, go succeeded)", nixFailed.Load())
	t.Logf("  go failed:    %d (go failed, nix succeeded)", goFailed.Load())
	t.Logf("  AST diff:     %d", diffCount.Load())

	if len(diffFiles) > 0 {
		t.Logf("\nFirst %d issues:", len(diffFiles))
		for _, s := range diffFiles {
			t.Logf("  %s", s)
		}
	}

	goFailedN := goFailed.Load()
	diffN := diffCount.Load()
	if goFailedN > 0 || diffN > 0 {
		t.Errorf("%d parse failures + %d AST mismatches (see above)", goFailedN, diffN)
	}
}