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
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
package eval

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"regexp"
	"runtime"
	"strings"
	"sync/atomic"
)

// ErrNotImplemented is returned by eval methods that haven't been written yet.
var ErrNotImplemented = errors.New("not implemented")

// EvalError wraps a Nix-level error with a message.
type EvalError struct {
	Msg string
}

func (e *EvalError) Error() string { return e.Msg }

func evalErrorf(format string, args ...any) error {
	return &EvalError{Msg: fmt.Sprintf(format, args...)}
}

// NixFS is the filesystem interface for the evaluator. It extends fs.FS with:
//   - ReadFileType: lstat-like file type detection (no symlink follow), used by
//     builtins.readFileType to distinguish "regular", "directory", "symlink".
//   - RealPath: maps a virtual fs.FS key (e.g. "lib.nix") back to the
//     real-world absolute path (e.g. "/home/user/myproject/lib.nix"). Used
//     only for path-to-string coercion (builtins.toString, string interpolation
//     of path values) — not for file I/O.
//
// The WASM parser resolves all relative paths against basePath "/" so that
// "./lib.nix" becomes "/lib.nix" in the AST, which maps to "lib.nix" in the
// fs.FS. Absolute paths like "/foo" also map to "foo" — the two are
// indistinguishable (known limitation of basePath "/").
type NixFS interface {
	fs.FS
	// IsExecutable reports whether a regular file at the given fs.FS key has
	// the executable bit set (mirrors C++ lstat + S_IXUSR check in NAR dump).
	// Called only for regular files; behaviour for other types is undefined.
	IsExecutable(path string) bool
	// ReadFileType returns "regular", "directory", "symlink", or "unknown"
	// for the file at the given fs.FS key, without following symlinks.
	ReadFileType(path string) (string, error)
	// ReadLink returns the target of the symlink at the given fs.FS key,
	// verbatim and without resolving it (mirrors readlink(2), not realpath).
	// The target is the string that goes into a NAR, so it must not be
	// canonicalised, made absolute, or followed: a relative target stays
	// relative and a dangling target is still a valid answer.
	// Called only for symlinks; behaviour for other types is undefined.
	ReadLink(path string) (string, error)
	// RealPath maps an fs.FS key to its display/real-world path string.
	// relative indicates whether the path originated from a relative source
	// literal (./foo, ../foo, ~/foo) — these are mapped through the FS root.
	// Absolute source literals (/foo) have relative=false and are returned
	// with just the leading "/" restored (no FS root prefix).
	// Does not perform any I/O.
	RealPath(path string, relative bool) string
	// ResolvePath returns the canonical absolute path with all symlinks
	// resolved. Used by import to compute the correct base path for
	// relative imports (matching C++ nix's realpath behaviour) and to
	// ensure the import cache uses canonical paths.
	// If symlink resolution is not supported or fails, returns the input
	// unchanged.
	ResolvePath(path string) string
}

// EvalState holds all mutable state for one evaluation session.
type EvalState struct {
	Symbols  *SymbolTable
	Builtins *Env // base environment with all registered primops and constants
	MaxDepth int

	// NativeParseFunc, if set, is used by importFile to parse imported files.
	// The *EvalState is passed so the function can store lineOffsets for lazy
	// position resolution. Signature: func(state, src, basePath, filePath) (Expr, error)
	NativeParseFunc func(state *EvalState, src []byte, basePath, filePath string) (Expr, error)

	// FS is the virtual filesystem. All file I/O and path coercion go through
	// this interface. Must be set before evaluating any expression that touches
	// the filesystem.
	FS NixFS

	// CurrentSystem is the value returned by builtins.currentSystem.
	// Defaults to "x86_64-linux" if empty.
	CurrentSystem string

	// BasePath is the base directory for parsing the top-level expression.
	// Relative path literals like ./foo.nix are resolved against BasePath.
	// Defaults to "/" (CanonPath::root) if empty, matching the old behaviour.
	// importFile updates the basePath per-call to the directory of the imported file.
	BasePath string

	// SearchPath is the Nix search path used to resolve <foo> angle-bracket
	// lookups.  Each entry has an optional Prefix (e.g. "nixpkgs") and a
	// required Path (e.g. "/testfs/dir1").  Entries are tried in order; the
	// first match wins.  A special fallback maps "nix/<name>" to the internal
	// /__corepkgs__/<name> virtual path.
	SearchPath []SearchPathEntry

	// CoerceIntegers enables the experimental "coerce-integers" feature:
	// allows integers to be interpolated in strings ("${42}" → "42").
	// When false (the default), integer interpolation is a type error.
	CoerceIntegers bool

	// MaxSteps limits the total number of forceValue calls. 0 means unlimited.
	// Used by the fuzzer to prevent runaway evaluations.
	MaxSteps int
	steps    int

	// Impure enables impure builtins: builtins.getEnv reads real environment
	// variables instead of returning empty string. Default false (pure mode).
	Impure bool

	// importCache caches the evaluated result of each imported path, keyed by
	// the fs.FS key (i.e. the absolute path with leading "/" stripped).
	// Mirrors C++ EvalState's fileEvalCache.
	importCache map[string]Value

	// prefetch holds each imported file's parse, so that a file is parsed
	// exactly once no matter who asks for it first. See prefetch.go.
	prefetch *prefetcher

	// resolveCache memoises FS.ResolvePath, which is realpath(3) and costs a
	// walk of lstat(2) calls per component. It is worth caching because the
	// import path calls it before consulting importCache, so every repeated
	// import of an already-evaluated file — the overwhelming majority of the
	// ~3800 imports in a system evaluation — re-resolves the same name.
	//
	// See resolvePath for why caching filesystem state across an evaluation is
	// sound, and the one case where it is not.
	resolveCache map[string]resolvedPath

	// regexCache memoises compiled regexes for builtins.match and
	// builtins.split, which otherwise recompile on every call while Nix code
	// reuses a small fixed set of patterns. See EvalState.regex for the
	// measurements and for why it is unbounded.
	regexCache map[regexKey]compiledRegex

	// ifdHappened records that realiseContext has actually built something,
	// i.e. that the store has been mutated during this evaluation. Until that
	// occurs the store is immutable from the evaluator's point of view and no
	// cached resolution can have gone stale.
	ifdHappened bool

	// Store handles all Nix store operations: path-to-store-path coercion,
	// text file store paths, fixed-output paths, and derivation recording.
	// Defaults to a MemStore if not set.
	Store Store

	// Pos is the position table mapping file IDs to filenames and newline
	// offset arrays. Populated during parsing; used on demand by posStr/mkPos.
	Pos PosTable

	// derivationFn caches the evaluated derivation.nix lambda (set on first use).
	derivationFn Value

	callDepth int

	// Stats — counters updated during evaluation, readable afterwards.
	Stats EvalStats
}

// EvalStats holds counters updated during evaluation.
//
// The Parse* counters are atomic because background prefetch workers update
// them. The Nr* ones below are deliberately *not*: they are incremented only
// from the serial evaluation path (maybeThunk, callFunction, the callThunk
// constructors, newEnv and the operator eval methods), which prefetch workers
// never enter — a worker parses and finalizes, and neither creates a thunk nor
// calls a function nor allocates an environment.
//
// That distinction is worth the asymmetry because of where the counters sit.
// Together they are ~35M increments per system evaluation, all of it on the
// one core that wall time measures: as plain adds that is ~40ms, as atomics
// closer to 250ms, which is most of the 0.30s noise floor. Paying that to
// protect against a writer that does not exist would be the exact trade
// consequence 2 of the premise warns against.
//
// If evaluation ever becomes concurrent these must become atomic. The race
// detector is what will say so — a full evaluation under -race is already a
// gate for anything touching concurrency.
type EvalStats struct {
	ParseCalls atomic.Int64 // number of import calls
	ParseBytes atomic.Int64 // total source bytes parsed
	ParseNs    atomic.Int64 // total nanoseconds in parse+finalize

	// Counters C++ reports under NIX_SHOW_STATS, named after their Lix
	// counterparts (lix/libexpr/eval.hh:457-462, eval.hh:182-186) and placed
	// at the corresponding site rather than an approximately similar one, so
	// that the two can be compared as arithmetic. See "Where gonix stands
	// against Lix" in OPTIMIZATION.md.
	//
	// Each of these has a way to be wrong that makes gonix look *better* than
	// C++ while doing identical work, and in every case it is the same shape:
	// an optimisation fuses or elides something C++ does separately, so the
	// obvious place to increment undercounts. The comment at each site says
	// which. Being wrong in the flattering direction is the failure mode to
	// watch for, because nothing else will flag it.
	NrThunks uint64 // maybeThunk calls that C++ would answer with makeThunk
	// NrThunksElided is the part of NrThunks that gonix does *not* allocate
	// (expressions whose value peek can already determine). It is split
	// out rather than subtracted so that NrThunks keeps matching Lix's
	// nrThunks exactly; thunks actually allocated = NrThunks - NrThunksElided.
	NrThunksElided  uint64
	NrAvoided       uint64 // maybeThunk calls that returned an existing value
	NrFunctionCalls uint64 // lambda applications
	NrCallThunks    uint64 // thunks built by map/genList/mapAttrs/zipAttrsWith

	NrPrimOpCalls  uint64 // saturated primop applications (not partial ones)
	NrOpUpdates    uint64 // `//` evaluations, including no-op ones
	NrListConcats  uint64 // `++` and builtins.concatLists evaluations
	NrEnvs         uint64 // environment frames, counted logically not by allocation
	NrValuesInEnvs uint64 // total slots across those frames

	NrAttrsets        uint64 // non-empty Bindings allocated
	NrAttrsInAttrsets uint64 // attr slots *allocated for* them, not slots filled
	NrListElems       uint64 // elements across every VList allocated
}

// fsPath converts an absolute Nix path (e.g. "/lib.nix") to an fs.FS key
// (e.g. "lib.nix") by stripping the leading slash.
func fsPath(absPath string) string {
	return strings.TrimLeft(absPath, "/")
}

// readFile reads a file from s.FS using an absolute Nix path.
// If the path is a /nix/store path that doesn't exist yet and the Store
// implements Realizer (IFD support), it attempts to build the derivation
// that produces it before retrying the read.
func (s *EvalState) readFile(absPath string) ([]byte, error) {
	data, err := fs.ReadFile(s.FS, fsPath(absPath))
	if err != nil {
		// IFD: if this is a missing /nix/store path and the store can realize
		// derivations, try to build it and retry.
		if r, ok := s.Store.(Realizer); ok && strings.HasPrefix(absPath, "/nix/store/") {
			if rerr := r.EnsureRealized(absPath); rerr == nil {
				data, err = fs.ReadFile(s.FS, fsPath(absPath))
			}
		}
	}
	if err != nil {
		return nil, evalErrorf("reading '%s': %v", absPath, err)
	}
	return data, nil
}

// readFileNoIFD reads a file without ever building anything.
//
// It is the read used by speculative prefetch, and the difference from
// readFile is the whole point: readFile falls through to
// Realizer.EnsureRealized for missing store paths, i.e. it may *build a
// derivation*. Doing that on a guess would run builds nothing asked for,
// mutate the store from a background goroutine, and set ifdHappened — which
// the resolvePath cache's invalidation rule depends on. A prefetch that
// cannot find its file simply gives up; if the evaluator really needs it, the
// inline path will read it properly, IFD and all.
func (s *EvalState) readFileNoIFD(absPath string) ([]byte, error) {
	data, err := fs.ReadFile(s.FS, fsPath(absPath))
	if err != nil {
		return nil, evalErrorf("reading '%s': %v", absPath, err)
	}
	return data, nil
}

// NewEvalState creates an EvalState whose builtins env is populated in the
// order given by names. names must match the displacement order from the WASM
// parser (obtained via Runtime.BuiltinNames). If names is nil, a default
// order is used (only correct when not using the WASM parser).
func NewEvalState(names []string) *EvalState {
	return NewEvalStateWithSearch(names, nil)
}

// NewEvalStateWithSearch creates an EvalState with a pre-configured search
// path.  The search path is baked into __nixPath at construction time, so it
// must be provided before registerBuiltins is called.
func NewEvalStateWithSearch(names []string, searchPath []SearchPathEntry) *EvalState {
	s := &EvalState{
		Symbols:       NewSymbolTable(),
		MaxDepth:      10000,
		CurrentSystem: "x86_64-linux",
		SearchPath:    searchPath,
		importCache:   make(map[string]Value),
		resolveCache:  make(map[string]resolvedPath),
		regexCache:    make(map[regexKey]compiledRegex),
		prefetch:      newPrefetcher(),
		Store:         NewMemStore(),
	}
	s.Builtins = registerBuiltins(s, names)
	return s
}

// regexKey identifies a compiled regex. The anchored flag is part of the key
// because builtins.match wraps the pattern to force a whole-subject match and
// builtins.split does not, so one pattern has two distinct compiled forms.
type regexKey struct {
	pat      string
	anchored bool
}

// compiledRegex is a memoised compilation result. A compile *failure* is
// cached as well as a success, so that a bad pattern reached repeatedly (a
// failing match inside tryEval, say) does not re-run the compiler each time.
type compiledRegex struct {
	re  *regexp.Regexp
	err error
}

// resolvedPath is a memoised FS.ResolvePath answer.
type resolvedPath struct {
	// real is what ResolvePath returned.
	real string
	// missing records that ResolvePath returned its input unchanged, which is
	// what it does when resolution fails — but also what it does for a path
	// that exists and simply contains no symlinks, since NixFS.ResolvePath
	// reports no error. The flag therefore over-approximates "absent", which
	// is the safe direction: it can only cause a redundant re-resolution of a
	// path that was already canonical, never a stale answer for one that was
	// genuinely absent.
	missing bool
	// imp is the path `import` finally reads: real, plus "/default.nix" when
	// real names a directory. Empty means the directory probe has not run for
	// this entry yet — it is filled in lazily by importPath, because most
	// resolvePath callers never ask the question.
	//
	// It lives here, rather than in a second map, so that the cache has one
	// key and one invalidation rule. Re-resolving an entry resets it to the
	// zero value, which re-arms the probe along with the resolution; two maps
	// would make that a thing to remember instead of a thing that follows.
	imp string
}

// resolvePath is FS.ResolvePath memoised for the lifetime of the evaluation.
//
// Caching filesystem state is only legitimate because of what the evaluator is
// allowed to assume: a Nix evaluation is pure with respect to the filesystem,
// and the sources it reads are required not to change underneath it. The one
// exception is the evaluator's own side effect — import-from-derivation, where
// realiseContext builds a derivation and thereby creates store paths that did
// not exist when evaluation started.
//
// That exception is narrow in a useful way. A *successful* resolution cannot be
// invalidated by IFD, because store paths are immutable once created and IFD
// only ever adds them. Only a *failed* resolution — a path that did not exist,
// so ResolvePath returned it unchanged — can become correct later, and only if
// it is a store path, since IFD cannot create anything outside the store. So a
// cached miss on a store path is re-checked once IFD has actually run, and
// every other cache hit is returned directly.
func (s *EvalState) resolvePath(path string) string {
	if s.FS == nil {
		return path
	}
	return s.resolveEntry(path).real
}

// resolveEntry is the one place the invalidation rule above is applied, so that
// everything memoised per path is armed and discarded together.
func (s *EvalState) resolveEntry(path string) resolvedPath {
	if s.resolveCache == nil {
		s.resolveCache = make(map[string]resolvedPath)
	}
	if e, ok := s.resolveCache[path]; ok {
		if !(e.missing && s.ifdHappened && strings.HasPrefix(path, StoreDir+"/")) {
			return e
		}
		// A store path that was absent when we last looked, asked for again
		// after a derivation was built: it may exist now, so look again. The
		// entry is rebuilt whole, which drops the directory probe along with
		// the resolution — a path that did not exist cannot have been a
		// directory, and now may be one.
	}
	real := s.FS.ResolvePath(path)
	e := resolvedPath{real: real, missing: real == path}
	s.resolveCache[path] = e
	return e
}

// importPath is the path `import` actually reads: the resolved path, plus
// "/default.nix" when it names a directory.
//
// The directory probe is memoised for the same reason and under the same
// assumption as the resolution it sits behind — it is a pure function of the
// resolved path given a filesystem that does not change underneath the
// evaluation. That matters because it runs *before* importFile consults
// importCache, so without this every repeated import of an already-evaluated
// file re-probed the filesystem. Over a system evaluation that is ~17300
// probes for ~4070 distinct paths.
//
// Corepkgs paths are answered without touching the filesystem at all. They are
// served from embedded Go constants (see importFile) and cannot exist on disk,
// so statting one is not a slow way to get the right answer but a guaranteed
// ENOENT — and the same mistake prefetch.go refuses to make for the same
// reason. The saving is a single syscall, since the memoisation would collapse
// the repeats anyway; it is here because the probe is meaningless, not because
// it is expensive.
func (s *EvalState) importPath(path string) string {
	if s.FS == nil {
		return path
	}
	e := s.resolveEntry(path)
	if e.imp != "" {
		return e.imp
	}
	imp := e.real
	if !strings.HasPrefix(imp, corepkgsPrefix) {
		if info, err := fs.Stat(s.FS, fsPath(imp)); err == nil && info.IsDir() {
			imp += "/default.nix"
		}
	}
	e.imp = imp
	s.resolveCache[path] = e
	return imp
}

// Eval evaluates e in the builtins environment and returns the result.
func (s *EvalState) Eval(e Expr) (Value, error) {
	return e.eval(s, s.Builtins)
}

// posStr formats a PosIdx for inclusion in error messages.
// Returns "at file:line:col: " if the position is valid, otherwise "".
// Line and column are resolved on demand from the PosTable —
// this is only called when an error is actually being constructed, so normal
// evaluation pays zero resolution cost.
func (s *EvalState) posStr(pos PosIdx) string {
	if !pos.Valid() {
		return ""
	}
	file, line, col := s.Pos.Resolve(pos)
	return fmt.Sprintf("at %s:%d:%d: ", file, line, col)
}

// ForceValue is the exported wrapper for forceValue, used by tests and the printer.
func (s *EvalState) ForceValue(vp *Value) error {
	return s.forceValue(vp, NoPosIdx)
}

// CallFunction is the exported wrapper for callFunction, used by tests.
func (s *EvalState) CallFunction(fun Value, args []Value) (Value, error) {
	return s.callFunction(fun, args, NoPosIdx)
}

// ValueTypeName returns the string type name of a Value for error messages.
func ValueTypeName(v Value) string {
	return valueType(v).String()
}

// forceValue forces v to weak-head normal form.
// If v is a thunk, it is evaluated and the result replaces v.
// Loops to resolve thunk chains (which can occur via mapAttrs/zipAttrsWith
// thunks referencing other thunks). Each step mirrors C++ forceValue: resolve
// one thunk level, cache the result.
// pos is included in error messages if the force fails.
func (s *EvalState) forceValue(vp *Value, pos PosIdx) error {
	if s.MaxSteps > 0 {
		s.steps++
		if s.steps > s.MaxSteps {
			return evalErrorf("evaluation step limit exceeded (%d steps)", s.MaxSteps)
		}
	}
	for {
		t, ok := (*vp).(*VThunk)
		if !ok {
			return nil
		}
		if t.Result != nil {
			if t.Result == blackHoleValue {
				buf := make([]byte, 32*1024)
				n := runtime.Stack(buf, false)
				fmt.Fprintf(os.Stderr, "[trace] infinite recursion at %s, thunk expr type=%T\n%s\n", s.posStr(pos), *t.Expr, buf[:n])
				return evalErrorf("%sinfinite recursion encountered", s.posStr(pos))
			}
			*vp = t.Result
			continue // follow the chain
		}
		// Set blackhole sentinel before evaluating to detect cycles.
		t.Result = blackHoleValue
		result, err := (*t.Expr).eval(s, t.Env)
		if err != nil {
			t.Result = nil // clear sentinel so the thunk can be retried
			return err
		}
		t.Result = result
		*vp = result
		// loop: result may itself be a thunk (from thunk chains)
	}
}

// forceString forces v and asserts it is *already* a string, mirroring C++
// EvalState::forceString (eval.cc:1543).
//
// This is one of three string-taking operations, and they are not
// interchangeable. C++ has exactly these three, and which one a primop wants
// is decided by which one the C++ primop calls — never by which name reads
// better in Go:
//
//	forceString           strings only, context allowed     eval.cc:1543
//	forceStringNoContext  strings only, context refused     eval.cc:1577
//	coerceToString        also paths, __toString/outPath sets, and
//	                      (by mode) ints, bools, null, lists
//
// Collapsing them is not a stylistic matter: it decides whether
// `builtins.match { __toString = _: "a"; } "a"` is a type error (C++) or
// evaluates (what this did until the sites were audited), and whether a
// store-path dependency recorded in a string's context survives being turned
// into an attribute name.
func (s *EvalState) forceString(vp *Value, pos PosIdx, errorCtx string) (VString, error) {
	if err := s.forceValue(vp, pos); err != nil {
		return VString{}, err
	}
	sv, ok := (*vp).(VString)
	if !ok {
		if errorCtx != "" {
			return VString{}, evalErrorf("%sexpected a string but found %s, %s", s.posStr(pos), valueType(*vp), errorCtx)
		}
		return VString{}, evalErrorf("%sexpected a string but found %s", s.posStr(pos), valueType(*vp))
	}
	return sv, nil
}

// forceStringNoContext forces v to a string without coercing, and rejects a
// string that carries context. This is what C++ EvalState::forceStringNoCtx
// (eval.cc:1577) does: forceString, then refuse a context.
//
// A store-path string must be refused rather than silently accepted, because
// the caller is about to use it as a plain name — e.g. builtins.removeAttrs
// turning it into a Symbol — which would discard the dependency the context
// records.
func (s *EvalState) forceStringNoContext(vp *Value, pos PosIdx, errorCtx string) (string, error) {
	sv, err := s.forceString(vp, pos, errorCtx)
	if err != nil {
		return "", err
	}
	if !sv.Context.IsEmpty() {
		return "", evalErrorf("%sthe string '%s' is not allowed to refer to a store path", s.posStr(pos), sv.V)
	}
	return sv.V, nil
}

// There is deliberately no "coerce, then reject a context" helper here.
//
// One existed, called forceStringNoCtx, and all 26 of its call sites were
// wrong in the same direction: the name said "force" and the body coerced, so
// every primop that reached for it accepted paths and __toString sets that the
// C++ function of that name rejects. Auditing the sites against primops.cc
// left it with no callers at all, which is the useful result — the combination
// it offered is not one the C++ evaluator actually uses anywhere.
//
// A primop that coerces (abort, throw, toString, toJSON, derivationStrict's
// ordinary attribute values) calls coerceToString and keeps the context it
// gets. A primop that needs a plain name calls forceStringNoContext. If a
// future site seems to want both, check the C++ first: last time, that
// impression was the bug.

// isDerivationAttrs returns true if b has type = "derivation".
// Mirrors C++ EvalState::isDerivation.
func (s *EvalState) isDerivationAttrs(b *Bindings) bool {
	typeSym := s.Symbols.Create("type")
	attr := b.Get(typeSym)
	if attr == nil {
		return false
	}
	v := attr.Value
	if err := s.forceValue(&v, NoPosIdx); err != nil {
		return false
	}
	sv, ok := v.(VString)
	return ok && sv.V == "derivation"
}

// forceAttrs forces v and asserts it is an attrset.
func (s *EvalState) forceAttrs(vp *Value, pos PosIdx, errorCtx string) (*Bindings, error) {
	if err := s.forceValue(vp, pos); err != nil {
		return nil, err
	}
	a, ok := (*vp).(VAttrs)
	if !ok {
		if errorCtx != "" {
			return nil, evalErrorf("%sexpected a set but found %s, %s", s.posStr(pos), valueType(*vp), errorCtx)
		}
		return nil, evalErrorf("%sexpected a set but found %s", s.posStr(pos), valueType(*vp))
	}
	return a.Bindings, nil
}

// forceBool forces v and asserts it is a boolean.
func (s *EvalState) forceBool(vp *Value, pos PosIdx) (bool, error) {
	if err := s.forceValue(vp, pos); err != nil {
		return false, err
	}
	b, ok := (*vp).(VBool)
	if !ok {
		return false, evalErrorf("%sexpected a Boolean but found %s", s.posStr(pos), valueType(*vp))
	}
	return b.V, nil
}

// forceList forces v and asserts it is a list.
func (s *EvalState) forceList(vp *Value, pos PosIdx, errorCtx string) ([]Value, error) {
	if err := s.forceValue(vp, pos); err != nil {
		return nil, err
	}
	l, ok := (*vp).((*VList))
	if !ok {
		if errorCtx != "" {
			return nil, evalErrorf("%sexpected a list but found %s, %s", s.posStr(pos), valueType(*vp), errorCtx)
		}
		return nil, evalErrorf("%sexpected a list but found %s", s.posStr(pos), valueType(*vp))
	}
	return l.Elems, nil
}

// forceFunction forces v and asserts it is callable, mirroring C++
// EvalState::forceFunction (eval.cc:1526).
//
// "Callable" is wider than "is a lambda": C++ tests `type() != nFunction &&
// !isFunctor(v)`, so an attrset carrying a __functor attribute passes, and
// callFunction below knows how to apply it. Rejecting sets outright here
// would make `operator = { __functor = self: x: [...]; }` fail in
// genericClosure, which C++ accepts.
//
// The check does not validate that __functor holds something callable; C++
// does not either, and that error surfaces from the eventual call.
func (s *EvalState) forceFunction(vp *Value, pos PosIdx, errorCtx string) error {
	if err := s.forceValue(vp, pos); err != nil {
		return err
	}
	switch v := (*vp).(type) {
	case *VLambda, VPrimOp, VPrimOpApp:
		return nil
	case VAttrs:
		if v.Bindings.Get(s.Symbols.Create("__functor")) != nil {
			return nil
		}
	}
	if errorCtx != "" {
		return evalErrorf("%sexpected a function but found %s, %s", s.posStr(pos), valueType(*vp), errorCtx)
	}
	return evalErrorf("%sexpected a function but found %s", s.posStr(pos), valueType(*vp))
}

// forceInt forces v and asserts it is an integer.
func (s *EvalState) forceInt(vp *Value, pos PosIdx) (int64, error) {
	if err := s.forceValue(vp, pos); err != nil {
		return 0, err
	}
	switch n := (*vp).(type) {
	case VInt:
		return n.V, nil
	}
	return 0, evalErrorf("%sexpected an integer but found %s", s.posStr(pos), valueType(*vp))
}

// lookupVar resolves a variable reference in an environment chain.
func (s *EvalState) lookupVar(env *Env, level, displ uint32, fromWith bool) (*Value, error) {
	// Walk up `level` frames.
	for i := uint32(0); i < level; i++ {
		if env.Up == nil {
			return nil, evalErrorf("environment chain too short (level=%d)", level)
		}
		env = env.Up
	}
	if !fromWith {
		if int(displ) >= len(env.Values) {
			return nil, evalErrorf("displacement %d out of range (env size %d)", displ, len(env.Values))
		}
		return &env.Values[displ], nil
	}
	// `with` lookup: env.Values[0] holds the attrset; search up the with-chain.
	for {
		withVal := env.Values[0]
		if err := s.forceValue(&withVal, NoPosIdx); err != nil {
			return nil, err
		}
		attrs, ok := withVal.(VAttrs)
		if !ok {
			return nil, evalErrorf("with expression is not an attrset")
		}
		// We need the symbol for the variable but don't have the name here;
		// the caller (ExprVar.eval) will do the attrs lookup.
		// Return env[0] (the with attrset) so the caller can look it up.
		_ = attrs
		// Actually: return a sentinel so ExprVar.eval knows to do attr lookup.
		// We use displ=0 to signal "look in env.Values[0]".
		return &env.Values[0], nil
	}
}

// callFunction calls fun with the given arguments.
// This is the central dispatch: handles lambdas, primops, partial primop apps,
// and functors (__functor attribute).
// pos is the call-site position, used in error messages.
//
// The depth bookkeeping lives here and the dispatch in callFunctionInner so
// that the decrement needs no defer. It used to be `defer func() {
// s.callDepth-- }()` at the top of one function, and the compiler could not
// open-code that defer: callFunction has too many return statements, so the
// defer was stack-allocated and run through the runtime's panic-unwinding
// machinery (_panic.nextDefer, popDefer) on every exit. Over a NixOS system
// evaluation that was ~0.5s of serial time for 6.36M calls — more than any
// function the interpreter itself spends time in.
//
// Dropping the defer is sound only because nothing recovers a panic raised
// during evaluation. The only recover() in eval is the parser's, around its
// own token limit; the evaluator's panics are internal invariant failures that
// kill the process, so a callDepth that fails to unwind is never observed.
// Errors are ordinary return values and pass through the decrement below. If
// evaluation ever starts recovering panics (e.g. to implement tryEval that
// way), this must go back to a defer.
func (s *EvalState) callFunction(fun Value, args []Value, pos PosIdx) (Value, error) {
	if s.callDepth >= s.MaxDepth {
		return nil, evalErrorf("%sstack overflow; max-call-depth exceeded", s.posStr(pos))
	}
	s.callDepth++
	v, err := s.callFunctionInner(fun, args, pos)
	s.callDepth--
	return v, err
}

func (s *EvalState) callFunctionInner(fun Value, args []Value, pos PosIdx) (Value, error) {
	if err := s.forceValue(&fun, pos); err != nil {
		return nil, err
	}

	for len(args) > 0 {
		switch f := fun.(type) {
		case *VLambda:
			lam := f.Fun

			var env *Env
			if inner, ok := curryPair(lam, args); ok {
				// The two frames of a saturated `a: b: body` applied as
				// `f x y`, in one allocation rather than two. See curryEnv2
				// for why this is safe and the elision below for what makes
				// it so.
				ce := &curryEnv2{}
				ce.outer.initOne(s, f.Env, args[0])
				ce.inner.initOne(s, &ce.outer, args[1])
				env = &ce.inner
				lam = inner
				args = args[2:]
				// Two, not one. C++ bumps nrFunctionCalls once per
				// pattern->match (eval.cc:1155) and reaches this shape as two
				// separate calls; the fusion performs both bindings in one
				// iteration. Counting it once would silently undercount by the
				// 1.98M calls the fusion elides, which is 31% of the total —
				// and would make the number look *better* than C++'s while
				// describing the same work.
				s.Stats.NrFunctionCalls += 2
			} else {
				s.Stats.NrFunctionCalls++
				var err error
				env, err = lam.Pattern.match(s, f.Env, args[0], lam.Pos)
				if err != nil {
					return nil, err
				}
				args = args[1:]
			}

			// A curried lambda applied to all its arguments at once --
			// `a: b: body` called as `f x y` -- used to evaluate the inner
			// `b: body` into a VLambda that the very next iteration of this
			// loop immediately destructured. That value is born and consumed
			// inside this function and can never be observed, so match the
			// inner pattern directly against the frame we just built and skip
			// it. Measured over a NixOS system evaluation: 1.98M of 6.36M
			// lambda calls take this path.
			//
			// Tracking the current lambda as an *ExprLambda rather than
			// rebinding a *VLambda is the entire point: a VLambda here is
			// precisely the object being elided.
			//
			// This computes what the outer loop would have: `fun =
			// inner.eval(...)` followed by another iteration differs from this
			// only in allocating that box, because (*ExprLambda).eval does
			// nothing but pair (Env, Fun).
			for len(args) > 0 {
				inner, ok := lam.Body.(*ExprLambda)
				if !ok {
					break
				}
				// Every iteration binds one more argument, which is one more
				// lambda call as C++ counts them — this loop is the third
				// pattern->match site in this function, and the easiest to
				// miss precisely because the call it represents was elided.
				s.Stats.NrFunctionCalls++
				next, err := inner.Pattern.match(s, env, args[0], inner.Pos)
				if err != nil {
					return nil, err
				}
				env = next
				args = args[1:]
				lam = inner
			}

			v, err := lam.Body.eval(s, env)
			if err != nil {
				return nil, err
			}
			fun = v

		case VPrimOp:
			arity := f.Impl.arity()
			if len(args) < arity {
				// Partial application: wrap in VPrimOpApp chain.
				result := Value(VPrimOpApp{PrimOp: fun, Arg: args[0]})
				for _, a := range args[1:] {
					result = VPrimOpApp{PrimOp: result, Arg: a}
				}
				return result, nil
			}
			// Counted here rather than at the top of the case, because C++
			// increments after its makeAppChain() early return too
			// (eval.cc:1186): a partial application is not a primop call, and
			// counting one would overcount by every `builtins.map f` that Nix
			// code passes around as a value.
			s.Stats.NrPrimOpCalls++
			v, err := applyPrimOp(s, f.Impl, args)
			if err != nil {
				return nil, err
			}
			fun = v
			args = args[arity:]

		case VPrimOpApp:
			// Collect all accumulated args plus new ones, into an array on
			// this frame: a primop takes at most three arguments, so the
			// whole saturated call always fits.
			var buf [3]Value
			n, primop, ok := collectPrimOpArgs(f, &buf)
			if !ok {
				return nil, evalErrorf("internal: VPrimOpApp chain longer than any primop's arity")
			}
			po, ok := primop.(VPrimOp)
			if !ok {
				return nil, evalErrorf("internal: VPrimOpApp target is not VPrimOp")
			}
			needed := po.Impl.arity() - n
			if len(args) < needed {
				// Still partial.
				result := Value(fun)
				for _, a := range args {
					result = VPrimOpApp{PrimOp: result, Arg: a}
				}
				return result, nil
			}
			// buf is this frame's own, so filling it cannot alias the
			// caller's args. n + needed == arity <= 3 == len(buf).
			copy(buf[n:], args[:needed])
			allArgs := buf[:n+needed]
			// C++ counts this path separately but identically (eval.cc:1241):
			// one increment per saturated call, however many partial
			// applications it took to get there.
			s.Stats.NrPrimOpCalls++
			v, err := applyPrimOp(s, po.Impl, allArgs)
			if err != nil {
				return nil, err
			}
			fun = v
			args = args[needed:]

		case VAttrs:
			// Check for __functor
			sym := s.Symbols.Create("__functor")
			attr := f.Bindings.Get(sym)
			if attr == nil {
				return nil, evalErrorf("%sattempt to call a set (no __functor attribute)", s.posStr(pos))
			}
			// Call __functor with the set itself and the arg.
			funktorArgs := []Value{fun, args[0]}
			v, err := s.callFunction(attr.Value, funktorArgs, pos)
			if err != nil {
				return nil, err
			}
			fun = v
			args = args[1:]

		default:
			// fun may be a thunk — force it and retry if it changed.
			prevType := valueType(fun)
			if err := s.forceValue(&fun, pos); err != nil {
				return nil, err
			}
			// If the type didn't change after forcing, it will never become
			// callable — error out now. We compare types rather than values
			// because some Value types (VString) contain maps and are not
			// comparable with ==.
			if valueType(fun) == prevType {
				return nil, evalErrorf("%sattempt to call a %s",
					s.posStr(pos), valueType(fun).String())
			}
			// Type changed (was a thunk, now forced) — loop again.
			continue
		}

		// Force the result before the next iteration.
		if len(args) > 0 {
			if err := s.forceValue(&fun, pos); err != nil {
				return nil, err
			}
		}
	}

	return fun, nil
}

// applyPrimOp calls impl with the first arity() elements of args.
//
// The type switch is what keeps the caller's argument slice off the heap. Each
// case passes Values *out* of the slice as ordinary parameters, so the slice
// itself is never handed to an opaque callee and escape analysis can see that
// nothing retains it. The old single `Fun(s, args[:arity])` could not: an
// indirect call through a func field is a black box, so the slice — and with
// it every caller's slice — had to be heap-allocated.

func applyPrimOp(s *EvalState, impl PrimOpN, args []Value) (Value, error) {
	switch fn := impl.(type) {
	case PrimOp1:
		return fn(s, args[0])
	case PrimOp2:
		return fn(s, args[0], args[1])
	case PrimOp3:
		return fn(s, args[0], args[1], args[2])
	default:
		return nil, evalErrorf("internal: unknown primop implementation %T", impl)
	}
}

// collectPrimOpArgs unwraps a VPrimOpApp chain into buf, in application order,
// and returns how many it wrote and the base the chain was built on.
//
// The chain is built outermost-last — the most recently supplied argument is
// on top — so it is walked twice: once to count, once to fill buf from the
// back. That is what lets the caller keep the arguments in an array on its own
// frame. The previous version prepended with append([]Value{a.Arg}, args...),
// which allocated on every step and was 311K objects per system evaluation.
//
// ok is false if the chain does not fit, which cannot happen for a well-formed
// chain: callFunction only builds one while fewer than arity arguments are
// supplied, so it holds at most arity-1 <= 2.
func collectPrimOpArgs(app VPrimOpApp, buf *[3]Value) (n int, base Value, ok bool) {
	var cur Value = app
	for {
		a, isApp := cur.(VPrimOpApp)
		if !isApp {
			break
		}
		n++
		cur = a.PrimOp
	}
	if n > len(buf) {
		return 0, nil, false
	}
	cur = app
	for i := n - 1; i >= 0; i-- {
		a := cur.(VPrimOpApp)
		buf[i] = a.Arg
		cur = a.PrimOp
	}
	return n, cur, true
}

// mkPos converts a PosIdx into the Nix value { file, line, column }.
//
// Returns null unless the position points into a real source file. This is a
// literal port of C++ mkPos (lix/libexpr/eval.cc:855-867), which builds the
// attrset only when originOf(p) holds a CheckedSourcePath and returns
// Value::VNULL for string, stdin, hidden and absent origins. An expression
// given with --expr has no file, so `builtins.unsafeGetAttrPos "x" args` on it
// must be null, not a location in a synthetic "<cmdline>" file.
//
// Nix code branches on this — see the PosOrigin doc comment for how a spurious
// location changes NixOS module ordering and thus derivation hashes.
func (s *EvalState) mkPos(pos PosIdx) Value {
	if !pos.Valid() || s.Pos.OriginOf(pos) != OriginPath {
		return VNullSingleton
	}
	file, line, col := s.Pos.Resolve(pos)
	symFile := s.Symbols.Create("file")
	symLine := s.Symbols.Create("line")
	symCol := s.Symbols.Create("column")
	b := newBindingsOf(s,
		Attr{Name: symFile, Value: VString{V: file}},
		Attr{Name: symLine, Value: VInt{V: int64(line)}},
		Attr{Name: symCol, Value: VInt{V: int64(col)}},
	)
	b.Sort()
	return VAttrs{Bindings: b}
}

// maybeThunk creates a thunk for expr in env, but avoids allocating one for
// trivially cheap expressions (literals), for variables whose env slot is
// already populated, and for the empty list. This matches C++ maybeThunk,
// which has specializations for exactly those three: ExprVar, ExprLiteral and
// ExprList.
//
// The ExprList case was missing for a long time while this comment claimed it
// was here, and the divergence was found by comparing nrThunks against Lix
// rather than by reading either side — 517471 thunks per system evaluation,
// which is 5.18% of the total. Worth noting how it stayed hidden: it is not a
// wrong answer, only a slower one, so no test could have failed on it.
//
// NrAvoided / NrThunks correspond exactly to C++'s counters of the same names:
// ExprLiteral::maybeThunk and the hit branch of ExprVar::maybeThunk bump
// nrAvoided (eval-expr.cc:35,43), everything else reaches makeThunk and bumps
// nrThunks (eval-expr.cc:16). Keeping the correspondence exact is the point —
// a counter that is "morally" the same but placed differently invites a
// comparison that looks meaningful and is not.
//
// Beyond those three, and unlike C++, anything peek can already answer gets
// no thunk either. That happens *after* NrThunks is counted, because C++
// would have called makeThunk; NrThunksElided records the difference.
//
// slot is the AST field holding the expression, not the expression: a thunk
// keeps the pointer (see VThunk.Expr), so it must point at storage that
// outlives the thunk and never changes. Every caller passes an element of a
// finalized AST node — `&e.Args[i]`, `&ad.Expr` on e.Attrs[i], … — never the
// address of a local copy, which would be shared by every iteration of the
// loop that made it.
func (s *EvalState) maybeThunk(slot *Expr, env *Env) Value {
	expr := *slot
	switch e := expr.(type) {
	case *ExprInt:
		s.Stats.NrAvoided++
		return e.val
	case *ExprFloat:
		s.Stats.NrAvoided++
		return e.val
	case *ExprString:
		s.Stats.NrAvoided++
		return e.val
	case *ExprPath:
		s.Stats.NrAvoided++
		return e.val
	case *ExprList:
		// C++ ExprList::maybeThunk returns the shared Value::EMPTY_LIST for
		// `[]` and allocates nothing (eval-expr.cc:47). Returning the same
		// singleton `ExprList.eval` already returns makes this invisible: the
		// thunk removed here, once forced, produced this exact pointer, so no
		// consumer that keys on list identity — deepForce's seenLists, the
		// printer's seenList, eqValues' short-circuit — can tell the
		// difference. A *fresh* empty VList per call would not be invisible,
		// and would not be a saving either.
		//
		// Deliberately bumps *neither* counter, which looks wrong and is not.
		// C++ has exactly three increment sites — makeThunk (nrThunks),
		// the ExprVar hit and ExprLiteral (nrAvoided, eval-expr.cc:35,43) —
		// and this branch is none of them: it returns before reaching
		// Expr::maybeThunk. Counting it as avoided would move nrAvoided from
		// +0.02% to +6.3% against Lix, trading a closed gap for a new one.
		if len(e.Elems) == 0 {
			return EmptyList
		}
		// Non-empty lists fall through to a thunk, as C++ does.

	case *ExprVar:
		// Match C++ ExprVar::maybeThunk: if the variable is not from a `with`
		// scope and its env slot is already populated, return the slot value
		// directly instead of wrapping it in a thunk. This avoids creating
		// thunk chains (thunk → thunk) that would require multi-step forcing.
		if !e.FromWith {
			if v := slotAt(env, e.Level, e.Displ); v != nil {
				s.Stats.NrAvoided++
				return v
			}
		}
		// fromWith vars or uninitialised slots: fall through to thunk creation.
	}
	// Not in C++: expressions whose value is already determined need no
	// thunk either. See peek.
	s.Stats.NrThunks++
	if v, ok := s.peek(expr, env); ok {
		s.Stats.NrThunksElided++
		return v
	}
	return &VThunk{Env: env, Expr: slot}
}

// peek returns what evaluating expr in env would return, when that is already
// determined by a lookup: no forcing, no computing, no way to fail. Otherwise
// it returns false and has done nothing but read.
//
// The returned value is a legal stand-in for a thunk of expr: either the value
// itself or a Value that forces to it (a slot's or an attr's own thunk, exactly
// as maybeThunk's ExprVar case returns a slot).
//
// It is deliberately limited to lookups. A version that also answered `!`,
// `&&`, `||`, `->`, `==`, `!=`, `if` and `assert` over evaluated operands
// elided 0.47 M more thunks on a NixOS system evaluation and measured
// +0.31 s slower: those cases are seldom answerable when the thunk is built,
// and checking them on every maybeThunk call cost more than the thunks saved.
// See OPTIMIZATION.md before widening this again.
//
// Every case returns true only where eval could not have failed or forced
// anything; a missing attr without `or`, a non-set, an unforced step and a
// dynamic name all keep their thunk, so errors stay exactly as lazy as they
// were.
func (s *EvalState) peek(expr Expr, env *Env) (Value, bool) {
	switch e := expr.(type) {
	case *ExprLambda:
		// Evaluating a lambda cannot fail, diverge or have effects; it only
		// captures env. A thunk costs 48 bytes plus this 16-byte VLambda once
		// forced, so building the closure now wins even when it is never
		// used. Identity is unchanged: a forced thunk also yields exactly one
		// closure, which is all eqValues' pointer compare sees.
		return &VLambda{Env: env, Fun: e}, true
	case *ExprSelect:
		return s.peekSelect(e, env)
	case *ExprOpHasAttr:
		v, ok := s.peekBase(e.E, env)
		if !ok {
			return nil, false
		}
		for i, an := range e.AttrPath {
			if an.Symbol == 0 {
				return nil, false
			}
			if i > 0 {
				if v = forcedOrNil(v); v == nil {
					return nil, false
				}
			}
			attrs, ok := v.(VAttrs)
			if !ok {
				return VFalseSingleton, true // as eval: `?` on a non-set is false
			}
			a := attrs.Bindings.Get(an.Symbol)
			if a == nil {
				return VFalseSingleton, true
			}
			v = a.Value
		}
		return VTrueSingleton, true
	}
	return nil, false
}

// peekSelect is peek for `base.a.b` and `base.a.b or def`. Every step must be
// already evaluated; the leaf is returned as is, forced or not. A step that is
// missing or not a set means the default if there is one and it needs no
// evaluation (see peekConst), exactly as ExprSelect.eval takes it — and a
// bail-out otherwise, since that is an error or a computation.
func (s *EvalState) peekSelect(e *ExprSelect, env *Env) (Value, bool) {
	v, ok := s.peekBase(e.E, env)
	if !ok {
		return nil, false
	}
	for i, an := range e.AttrPath {
		if an.Symbol == 0 {
			return nil, false
		}
		if i > 0 {
			if v = forcedOrNil(v); v == nil {
				return nil, false
			}
		}
		attrs, ok := v.(VAttrs)
		if !ok {
			return peekConst(e.Def, env)
		}
		a := attrs.Bindings.Get(an.Symbol)
		if a == nil {
			return peekConst(e.Def, env)
		}
		v = a.Value
	}
	return v, true
}

// peekBase returns the already-evaluated value of a select's base, which must
// be a non-`with` variable: a slot holding a value or a forced thunk.
func (s *EvalState) peekBase(base Expr, env *Env) (Value, bool) {
	ev, ok := base.(*ExprVar)
	if !ok || ev.FromWith {
		return nil, false
	}
	v := forcedOrNil(slotAt(env, ev.Level, ev.Displ))
	return v, v != nil
}

// peekConst returns the value of an `or` default that needs no evaluation: a
// literal, `[]`, a non-`rec` `{}`, or a non-`with` variable whose slot is
// filled — which covers `or null`, `or true` and `or false`, since those are
// variables bound to the builtins' singletons. Each is what eval would return,
// or (for a slot) a stand-in that forces to it exactly as maybeThunk's ExprVar
// case returns one, so identity is unchanged. A nil def (no `or`) is none.
func peekConst(def Expr, env *Env) (Value, bool) {
	switch e := def.(type) {
	case *ExprInt:
		return e.val, true
	case *ExprFloat:
		return e.val, true
	case *ExprString:
		return e.val, true
	case *ExprPath:
		return e.val, true
	case *ExprList:
		if len(e.Elems) == 0 {
			return EmptyList, true
		}
	case *ExprSet:
		// Not `rec {}`, which allocates (and counts) a frame.
		if !e.Recursive && len(e.Attrs) == 0 && len(e.DynamicAttrs) == 0 && len(e.InheritFrom) == 0 {
			return VAttrs{Bindings: EmptyBindings}, true
		}
	case *ExprVar:
		if !e.FromWith {
			if v := slotAt(env, e.Level, e.Displ); v != nil {
				return v, true
			}
		}
	}
	return nil, false
}

// slotAt returns env slot (level, displ), or nil if the chain is too short or
// the slot is not yet filled.
func slotAt(env *Env, level, displ uint32) Value {
	cur := env
	for i := uint32(0); i < level; i++ {
		if cur == nil {
			return nil
		}
		cur = cur.Up
	}
	if cur == nil || int(displ) >= len(cur.Values) {
		return nil
	}
	return cur.Values[displ]
}

// forcedOrNil follows a chain of already-forced thunks and returns the value
// at its end, or nil if the chain ends in an unforced or in-progress thunk.
func forcedOrNil(v Value) Value {
	for {
		t, ok := v.(*VThunk)
		if !ok {
			return v
		}
		if t.Result == nil || t.Result == blackHoleValue {
			return nil
		}
		v = t.Result
	}
}

// curryPair reports whether lam applied to args is the shape curryEnv2 can
// hold: `a: b: body` with at least two arguments supplied, both patterns
// simple. It returns the inner lambda so the caller need not re-assert it.
//
// Both patterns must be SimplePattern because curryEnv2's frames are fixed at
// one slot each. An AttrsPattern frame is as wide as the lambda has formals,
// and its match does real work — forcing the argument, filling defaults,
// diagnosing missing and unexpected attributes — none of which can be replaced
// by writing a value into a slot.
//
// Instrumented over a NixOS system evaluation, this accepts 1.98M of 6.36M
// lambda calls. Requiring both patterns simple costs only 2.5% against
// requiring neither (2.03M), so the restriction is nearly free here.
func curryPair(lam *ExprLambda, args []Value) (*ExprLambda, bool) {
	if len(args) < 2 {
		return nil, false
	}
	if _, ok := lam.Pattern.(SimplePattern); !ok {
		return nil, false
	}
	inner, ok := lam.Body.(*ExprLambda)
	if !ok {
		return nil, false
	}
	if _, ok := inner.Pattern.(SimplePattern); !ok {
		return nil, false
	}
	return inner, true
}