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
// gonix-eval — evaluate a Nix expression using the native Go parser + evaluator.
//
// Usage:
//
//	gonix-eval [--impure] [-I prefix=path] [-A attr] [--print-drv] <expr>
//	gonix-eval [--drv-db path] [--trace] <expr>
//
// Example:
//
//	gonix-eval -I nixpkgs=/home/user/nixpkgs '(import <nixpkgs> {}).hello.name'
//	gonix-eval --drv-db /tmp/hello.db --trace -I nixpkgs=... '(import <nixpkgs> {}).hello.drvPath'
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"runtime/pprof"
	"strconv"
	"strings"
	"time"

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

func fatal(msg string, err error) {
	fmt.Fprintf(os.Stderr, "error: %s: %v\n", msg, err)
	os.Exit(1)
}

// heapSnapshot writes a heap profile to dir/<stage>.mprof after running GC.
func heapSnapshot(dir, stage string) {
	if dir == "" {
		return
	}
	runtime.GC()
	path := filepath.Join(dir, stage+".mprof")
	f, err := os.Create(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "[memprofile] error creating %s: %v\n", path, err)
		return
	}
	defer f.Close()
	if err := pprof.WriteHeapProfile(f); err != nil {
		fmt.Fprintf(os.Stderr, "[memprofile] error writing %s: %v\n", path, err)
		return
	}
	var ms runtime.MemStats
	runtime.ReadMemStats(&ms)
	fmt.Fprintf(os.Stderr, "[memprofile] %s: inuse=%.1fMB alloc=%.1fMB sys=%.1fMB\n",
		stage, float64(ms.HeapInuse)/1e6, float64(ms.HeapAlloc)/1e6, float64(ms.Sys)/1e6)
}

func main() {
	// If re-exec'd as the sandbox launcher, run it and never return.
	maybeRunBuilder()
	// If invoked as the build driver, run it and exit.
	maybeRunBuild()

	args := os.Args[1:]

	impure := false
	printDrv := false
	drvDB := ""
	prefetchModel := ""
	prefetchWorkers := 2
	trace := false
	cpuprofile := ""
	memprofile := ""
	memprofileDir := ""
	maxCallDepth := 0 // 0 = use default (10000)
	daemonSocket := ""
	var searchPath []eval.SearchPathEntry
	attrSelect := ""

	for i := 0; i < len(args); i++ {
		switch args[i] {
		case "--impure":
			impure = true
			args = append(args[:i], args[i+1:]...)
			i--
		case "--print-drv":
			printDrv = true
			args = append(args[:i], args[i+1:]...)
			i--
		case "--trace":
			trace = true
			args = append(args[:i], args[i+1:]...)
			i--
		case "--cpuprofile":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --cpuprofile requires an argument")
				os.Exit(1)
			}
			cpuprofile = args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
		case "--memprofile":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --memprofile requires an argument")
				os.Exit(1)
			}
			memprofile = args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
		case "--memprofile-dir":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --memprofile-dir requires an argument")
				os.Exit(1)
			}
			memprofileDir = args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
		case "-I":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: -I requires an argument")
				os.Exit(1)
			}
			entry := args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
			if idx := strings.IndexByte(entry, '='); idx >= 0 {
				searchPath = append(searchPath, eval.SearchPathEntry{
					Prefix: entry[:idx],
					Path:   entry[idx+1:],
				})
			} else {
				searchPath = append(searchPath, eval.SearchPathEntry{Path: entry})
			}
		case "--prefetch":
			// --prefetch <model-file> [--prefetch-workers N]
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --prefetch requires a model path")
				os.Exit(1)
			}
			prefetchModel = args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
		case "--prefetch-workers":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --prefetch-workers requires an argument")
				os.Exit(1)
			}
			n, err := strconv.Atoi(args[i+1])
			if err != nil || n < 0 {
				fmt.Fprintf(os.Stderr, "error: --prefetch-workers: invalid value %q\n", args[i+1])
				os.Exit(1)
			}
			prefetchWorkers = n
			args = append(args[:i], args[i+2:]...)
			i--
		case "--drv-db":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --drv-db requires an argument")
				os.Exit(1)
			}
			drvDB = args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
		case "--daemon":
			// Optional argument: --daemon [socket-path]
			// If the next arg doesn't start with "-" treat it as the socket path.
			if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
				daemonSocket = args[i+1]
				args = append(args[:i], args[i+2:]...)
			} else {
				daemonSocket = eval.DefaultDaemonSocket
				args = append(args[:i], args[i+1:]...)
			}
			i--
		case "--max-call-depth":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: --max-call-depth requires an argument")
				os.Exit(1)
			}
			n, err := strconv.Atoi(args[i+1])
			if err != nil || n <= 0 {
				fmt.Fprintf(os.Stderr, "error: --max-call-depth: invalid value %q\n", args[i+1])
				os.Exit(1)
			}
			maxCallDepth = n
			args = append(args[:i], args[i+2:]...)
			i--
		case "-A":
			if i+1 >= len(args) {
				fmt.Fprintln(os.Stderr, "error: -A requires an argument")
				os.Exit(1)
			}
			attrSelect = args[i+1]
			args = append(args[:i], args[i+2:]...)
			i--
		}
	}

	if len(args) < 1 {
		fmt.Fprintf(os.Stderr, "usage: %s [--impure] [-I prefix=path] [-A attr] [--drv-db path] [--trace] <expr>\n", os.Args[0])
		os.Exit(1)
	}

	expr := args[0]

	// --- Evaluator setup ---
	state := eval.NewEvalStateWithSearch(eval.DefaultBuiltinNames, searchPath)
	state.FS = eval.OsNixFS{}
	state.BasePath = "/"
	state.Impure = impure
	if maxCallDepth > 0 {
		state.MaxDepth = maxCallDepth
	}
	state.NativeParseFunc = func(s *eval.EvalState, src []byte, basePath, filePath string) (eval.Expr, error) {
		return eval.NativeParseExprIntoState(s, src, basePath, filePath)
	}

	// Set up the store: daemon (if requested), otherwise plain MemStore.
	// Background parsing, if a model path was given. The model is a hint: it
	// is loaded best-effort and saved best-effort, and neither failing
	// changes what is evaluated.
	var model *eval.SuccessorModel
	if prefetchModel != "" {
		model = eval.LoadSuccessorModel(prefetchModel)
		state.StartPrefetch(prefetchWorkers, model)
	}

	var daemonStore *eval.DaemonStore
	if daemonSocket != "" {
		daemonStore = eval.NewDaemonStore(daemonSocket)
		defer daemonStore.Close()
		state.Store = daemonStore
	}

	// Attach the DB on top of whichever store we're using, via the hook.
	var ddb *DrvDB
	if drvDB != "" {
		// Get the MemStore that is (or is embedded in) the active store.
		var ms *eval.MemStore
		if daemonStore != nil {
			ms = daemonStore.MemStore
		} else {
			ms = state.Store.(*eval.MemStore)
		}
		var err error
		ddb, err = openDrvDB(drvDB, ms)
		if err != nil {
			fatal("open drv-db", err)
		}
		defer ddb.Close()
	}

	if trace {
		if ddb == nil {
			fmt.Fprintln(os.Stderr, "error: --trace requires --drv-db")
			os.Exit(1)
		}
		state.Store.SetTracing(true)
	}

	// --- CPU profiling ---
	if cpuprofile != "" {
		f, err := os.Create(cpuprofile)
		if err != nil {
			fatal("create cpuprofile", err)
		}
		defer f.Close()
		if err := pprof.StartCPUProfile(f); err != nil {
			fatal("start cpuprofile", err)
		}
		defer pprof.StopCPUProfile()
	}

	// --- Parse + evaluate ---
	t0 := time.Now()
	// The expression came from the command line, not from a file, so it is
	// parsed with OriginString: builtins.unsafeGetAttrPos must report null for
	// it, exactly as C++ does. This is not cosmetic — see the mkPos comment in
	// eval.go for how a spurious position reorders NixOS module definitions and
	// changes the resulting derivation hash.
	ast, err := eval.NativeParseExprWithOrigin(state, []byte(expr), "/", "<cmdline>", eval.OriginString)
	if err != nil {
		fatal("parse", err)
	}
	fmt.Fprintf(os.Stderr, "[timing] parse expr: %s\n", time.Since(t0).Round(time.Millisecond))
	heapSnapshot(memprofileDir, "1-after-parse")

	t1 := time.Now()
	v, err := state.Eval(ast)
	evalDur := time.Since(t1)
	if err != nil {
		fatal("eval", err)
	}
	st := &state.Stats
	fmt.Fprintf(os.Stderr, "[timing] eval total: %s\n", evalDur.Round(time.Millisecond))
	fmt.Fprintf(os.Stderr, "[timing] imports: %d files, %d KB, %s parsing\n",
		st.ParseCalls.Load(), st.ParseBytes.Load()/1024,
		time.Duration(st.ParseNs.Load()).Round(time.Millisecond))
	// Named and ordered to line up with what `NIX_SHOW_STATS=1 nix-instantiate`
	// prints, so the two can be read side by side. callThunks has no C++
	// counterpart in nrThunks: map/genList/mapAttrs/zipAttrsWith build their
	// thunks via NewValueAs::app, which C++ does not count at all.
	fmt.Fprintf(os.Stderr, "[stats] thunks=%d (elided=%d) avoided=%d calls=%d callThunks=%d\n",
		st.NrThunks, st.NrThunksElided, st.NrAvoided, st.NrFunctionCalls, st.NrCallThunks)
	fmt.Fprintf(os.Stderr, "[stats] primOpCalls=%d opUpdates=%d listConcats=%d envs=%d valuesInEnvs=%d\n",
		st.NrPrimOpCalls, st.NrOpUpdates, st.NrListConcats, st.NrEnvs, st.NrValuesInEnvs)
	fmt.Fprintf(os.Stderr, "[stats] attrsets=%d attrsInAttrsets=%d listElems=%d\n",
		st.NrAttrsets, st.NrAttrsInAttrsets, st.NrListElems)
	// gonix-only: Lix merges // eagerly and has no counterpart. overlays is
	// how many // results were left lazy; the rest say why one stopped being.
	ovN, ovTrav, ovFalls, ovLeaves, ovCount := eval.ReadOverlayStats()
	fmt.Fprintf(os.Stderr, "[stats] overlays=%d materialised: traversal=%d falls=%d leaves=%d count=%d\n",
		ovN, ovTrav, ovFalls, ovLeaves, ovCount)
	if model != nil {
		pre, hits, waits, wasted, waited := state.StopPrefetch()
		fmt.Fprintf(os.Stderr, "[prefetch] %d parsed ahead, %d hits, %d waits (%s), %d wasted\n",
			pre, hits, waits, waited.Round(time.Millisecond), wasted)
		if err := model.Save(prefetchModel); err != nil {
			fmt.Fprintf(os.Stderr, "[prefetch] warning: could not save model: %v\n", err)
		}
	}
	heapSnapshot(memprofileDir, "2-after-eval")

	// --- Attribute selection (-A flag) ---
	if attrSelect != "" {
		parts := strings.Split(attrSelect, ".")
		for _, part := range parts {
			if err := state.ForceValue(&v); err != nil {
				fatal("force", err)
			}
			attrs, ok := v.(eval.VAttrs)
			if !ok {
				fmt.Fprintf(os.Stderr, "error: -A: expected attrset, got %T\n", v)
				os.Exit(1)
			}
			sym := state.Symbols.Create(part)
			attr := attrs.Bindings.Get(sym)
			if attr == nil {
				fmt.Fprintf(os.Stderr, "error: -A: attribute '%s' not found\n", part)
				os.Exit(1)
			}
			v = attr.Value
		}
	}

	if err := state.ForceValue(&v); err != nil {
		fatal("force result", err)
	}
	heapSnapshot(memprofileDir, "3-after-force")

	// --- Memory profiling ---
	if memprofile != "" {
		f, err := os.Create(memprofile)
		if err != nil {
			fatal("create memprofile", err)
		}
		defer f.Close()
		runtime.GC() // get up-to-date statistics
		if err := pprof.WriteHeapProfile(f); err != nil {
			fatal("write memprofile", err)
		}
		fmt.Fprintf(os.Stderr, "[profiling] heap profile written to %s\n", memprofile)
	}

	// Flush hash traces to the DB if tracing was enabled.
	if trace && ddb != nil {
		t2 := time.Now()
		if err := ddb.FlushTraces(state.Store); err != nil {
			fatal("flush traces", err)
		}
		fmt.Fprintf(os.Stderr, "[timing] flush traces: %s\n", time.Since(t2).Round(time.Millisecond))
		heapSnapshot(memprofileDir, "4-after-flush")
	}

	if printDrv {
		attrs, ok := v.(eval.VAttrs)
		if !ok {
			fmt.Fprintf(os.Stderr, "error: --print-drv: result is not a set\n")
			os.Exit(1)
		}
		drvPathSym := state.Symbols.Create("drvPath")
		drvAttr := attrs.Bindings.Get(drvPathSym)
		if drvAttr == nil {
			fmt.Fprintf(os.Stderr, "error: --print-drv: result has no 'drvPath' attribute\n")
			os.Exit(1)
		}
		drvPathVal := drvAttr.Value
		if err := state.ForceValue(&drvPathVal); err != nil {
			fatal("force drvPath", err)
		}
		drvPathStr, ok := drvPathVal.(eval.VString)
		if !ok {
			fmt.Fprintf(os.Stderr, "error: --print-drv: drvPath is not a string\n")
			os.Exit(1)
		}
		aterm, ok := state.Store.ATermFor(drvPathStr.V)
		if !ok {
			fmt.Fprintf(os.Stderr, "error: --print-drv: no ATerm cached for %s\n", drvPathStr.V)
			os.Exit(1)
		}
		fmt.Println(aterm)
		return
	}

	out, err := eval.PrintValue(state, v)
	if err != nil {
		fatal("print", err)
	}
	fmt.Println(out)
}