Skip to main content

sui_eval/
eval.rs

1//! Tree-walking Nix evaluator using rnix's typed AST.
2//!
3//! Implements Tvix-style lazy evaluation with thunks: let-bindings and
4//! rec-attrset values are wrapped in `Value::Thunk` and only evaluated
5//! when their value is actually needed (call-by-need with memoization).
6
7use std::cell::{Cell, RefCell};
8use std::collections::{HashSet, HashMap, VecDeque};
9use std::path::PathBuf;
10
11use rnix::ast::{self, AstToken, HasEntry, InterpolPart};
12use rowan::ast::AstNode;
13
14use crate::builtins;
15use crate::value::*;
16
17thread_local! { static EVAL_DEPTH: Cell<usize> = const { Cell::new(0) }; }
18
19
20// ── Source ID for identifier symbol cache ─────────────────────
21//
22// Each call to `rnix::Root::parse` produces a distinct AST tree.
23// Identifiers from different trees may share the same byte offset,
24// so we pair offset with a source ID to form a unique cache key.
25// The ID is stored in a thread-local so `eval_expr` can access it
26// without an extra parameter threaded through every call.
27
28thread_local! {
29    static CURRENT_SOURCE_ID: Cell<u32> = const { Cell::new(0) };
30}
31
32// ── Currently-evaluating-file stack ────────────────────────────
33//
34// Real Nix resolves relative path literals (`./foo.nix`) against the
35// directory of the file that *contains* the literal, not against the
36// process cwd. Track the stack of files we're currently evaluating
37// so the `PathRel` handler and `import` builtin can resolve correctly.
38
39thread_local! {
40    /// `None` frame = "evaluating something with no source file" (a `--expr` /
41    /// `<string>` literal). Representing that explicitly is load-bearing: a
42    /// thunk captured in a fileless context used to push NOTHING when it
43    /// forced, so the callee's file stayed on top and `unsafeGetAttrPos`
44    /// stamped the literal with the callee's path where CppNix returns `null`.
45    /// That fed `eval-config.nix`'s `modulesLocation`, which wraps every user
46    /// module in `{ _file; imports = [ m ]; }` — demoting it one
47    /// `genericClosure` level and permuting NixOS definition order.
48    static EVAL_FILE_STACK: RefCell<Vec<Option<PathBuf>>> = const { RefCell::new(Vec::new()) };
49    /// Nix-level error context stack — captures source positions for --show-trace.
50    /// Each entry: (file, expression_snippet). Pushed on function calls, select,
51    /// force, and popped on return. Attached to errors for structured diagnostics.
52    static NIX_TRACE_STACK: RefCell<Vec<NixTraceFrame>> = const { RefCell::new(Vec::new()) };
53}
54
55/// A single frame in the Nix-level error trace.
56///
57/// The frame is only ever *observed* on the cold error path (via
58/// `attach_trace`). To keep the hot lambda-call path allocation-free,
59/// the per-call lambda frame stores the raw ingredients (a cheap
60/// `Rc`-clone of the closure env + the raw current-eval-file `PathBuf`)
61/// and defers the `format!` / path-strip work into `attach_trace`. The
62/// rendered `(description, file)` pair is byte-identical to the eager
63/// form either way (see the `description()` / `file()` accessors).
64#[derive(Debug, Clone)]
65pub enum NixTraceFrame {
66    /// Pre-formatted frame (the builtin-call path — kept eager because
67    /// the builtin name is already a `&'static str`, so there is no
68    /// per-call heap-`String` to defer).
69    Eager {
70        file: Option<String>,
71        description: String,
72    },
73    /// Lazy per-lambda-call frame. The `description` string and the
74    /// stripped `file` string are built on demand in `attach_trace`.
75    ///
76    /// - `closure_env` provides the *description*'s file (from
77    ///   `closure.env.eval_file()`) — an O(1) `Rc` refcount bump.
78    /// - `current_file` is the raw `current_eval_file()` snapshot taken
79    ///   at push time (the stack top after the file guard pushed the
80    ///   closure's file), used verbatim for the frame's `file` field so
81    ///   the rendered `loc` matches the eager form byte-for-byte.
82    Lambda {
83        closure_env: Env,
84        current_file: Option<PathBuf>,
85    },
86}
87
88/// Strip the `-source/` store-path prefix from a rendered path exactly
89/// as the eager trace path did (`p.display()...rsplit_once("-source/")`).
90fn strip_source_prefix(p: &std::path::Path) -> String {
91    let s = p.display().to_string();
92    s.rsplit_once("-source/")
93        .map_or_else(|| p.display().to_string(), |(_, tail)| tail.to_string())
94}
95
96impl NixTraceFrame {
97    /// The frame's `file` field (for the trace `loc`), matching the
98    /// eager `frame.file` byte-for-byte.
99    fn file(&self) -> Option<String> {
100        match self {
101            NixTraceFrame::Eager { file, .. } => file.clone(),
102            NixTraceFrame::Lambda { current_file, .. } => {
103                current_file.as_deref().map(strip_source_prefix)
104            }
105        }
106    }
107
108    /// The frame's `description`, matching the eager `frame.description`
109    /// byte-for-byte. Rendered through the `Display` impl (a `write!`
110    /// surface — the description is the frame's canonical serialization,
111    /// per the fleet TYPED-EMISSION rule; no `format!()`).
112    fn description(&self) -> String {
113        self.to_string()
114    }
115}
116
117/// The frame's rendered description IS its `Display` — the typed emission
118/// surface for the trace message (`write!`, never `format!()`). The
119/// `Lambda` arm defers the path-strip to this cold error-path render.
120impl std::fmt::Display for NixTraceFrame {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        match self {
123            NixTraceFrame::Eager { description, .. } => f.write_str(description),
124            NixTraceFrame::Lambda { closure_env, .. } => {
125                let file = closure_env.eval_file().map(|p| strip_source_prefix(p));
126                write!(
127                    f,
128                    "while calling function defined in {}",
129                    file.as_deref().unwrap_or("<eval>")
130                )
131            }
132        }
133    }
134}
135
136/// Push a Nix-level trace frame. Returns a guard that pops on drop.
137fn push_nix_trace(desc: impl Into<String>) -> NixTraceGuard {
138    let frame = NixTraceFrame::Eager {
139        file: current_eval_file().map(|p| {
140            p.display().to_string()
141                .rsplit_once("-source/")
142                .map_or_else(|| p.display().to_string(), |(_, s)| s.to_string())
143        }),
144        description: desc.into(),
145    };
146    NIX_TRACE_STACK.with(|s| s.borrow_mut().push(frame));
147    NixTraceGuard
148}
149
150/// Push a *lazy* Nix-level trace frame for a lambda call. Stores only the
151/// raw ingredients (an O(1) `Rc`-clone of the closure env + the raw
152/// `current_eval_file()` snapshot) — the `format!`/path-strip work is
153/// deferred to the cold `attach_trace` path. Returns a guard that pops on
154/// drop. The rendered frame is byte-identical to the eager form.
155fn push_nix_trace_lambda(closure_env: &Env) -> NixTraceGuard {
156    let frame = NixTraceFrame::Lambda {
157        closure_env: closure_env.clone(),
158        current_file: current_eval_file(),
159    };
160    NIX_TRACE_STACK.with(|s| s.borrow_mut().push(frame));
161    NixTraceGuard
162}
163
164struct NixTraceGuard;
165impl Drop for NixTraceGuard {
166    fn drop(&mut self) {
167        NIX_TRACE_STACK.with(|s| s.borrow_mut().pop());
168    }
169}
170
171/// Capture the current Nix trace and attach it to an error.
172pub fn attach_trace(err: EvalError) -> EvalError {
173    NIX_TRACE_STACK.with(|s| {
174        let stack = s.borrow();
175        if stack.is_empty() {
176            return err;
177        }
178        let max_frames = std::env::var("SUI_M26_MAXFRAMES").ok()
179            .and_then(|s| s.parse::<usize>().ok()).unwrap_or(15);
180        let mut trace = format!("{err}");
181        for (i, frame) in stack.iter().rev().take(max_frames).enumerate() {
182            let file = frame.file();
183            let loc = file.as_deref().unwrap_or("<eval>");
184            trace.push_str(&format!("\n  {} ({loc})", frame.description()));
185            if i + 1 >= max_frames && stack.len() > max_frames {
186                trace.push_str(&format!("\n  ... ({} more frames)", stack.len() - max_frames));
187            }
188        }
189        // CRITICAL: preserve Throw/AssertionFailed variants so tryEval can catch them.
190        // Converting to TypeError would make tryEval miss them.
191        match err {
192            EvalError::Throw(_) => EvalError::Throw(trace),
193            EvalError::AssertionFailed(_) => EvalError::AssertionFailed(trace),
194            _ => EvalError::TypeError(trace),
195        }
196    })
197}
198
199/// Return the directory of the file currently being evaluated, if any.
200/// Used by the `PathRel` AST handler to resolve relative path literals.
201#[must_use]
202pub fn current_eval_dir() -> Option<PathBuf> {
203    EVAL_FILE_STACK
204        .with(|s| s.borrow().last().cloned())
205        .flatten()
206        .and_then(|p| p.parent().map(PathBuf::from))
207}
208
209/// Push a file onto the eval stack. Returns an RAII guard that pops
210/// it on drop. Use when entering an `import <file>` so subsequent
211/// relative path literals resolve against the right directory.
212pub fn push_eval_file(file: PathBuf) -> EvalFileGuard {
213    push_eval_frame(Some(file))
214}
215
216/// Push a frame that may be fileless. `None` means "this code has no source
217/// file" and MUST still occupy a stack slot — pushing nothing would leave the
218/// caller's file visible to `current_eval_file`, which is exactly the
219/// `unsafeGetAttrPos` divergence documented on `EVAL_FILE_STACK`.
220pub fn push_eval_frame(file: Option<PathBuf>) -> EvalFileGuard {
221    EVAL_FILE_STACK.with(|s| s.borrow_mut().push(file));
222    EvalFileGuard
223}
224
225/// Return the file currently being evaluated, if any.
226/// Used by error sites to attach source location context.
227#[must_use]
228pub fn current_eval_file() -> Option<PathBuf> {
229    EVAL_FILE_STACK.with(|s| s.borrow().last().cloned()).flatten()
230}
231
232
233/// Snapshot the entire eval file stack (debug).
234pub fn eval_file_stack_snapshot() -> Vec<String> {
235    EVAL_FILE_STACK.with(|s| {
236        s.borrow().iter().map(|p| {
237            let Some(p) = p else { return "<no-file>".to_string() };
238            let s = p.display().to_string();
239            s.rsplit_once("-source/").map_or(s.clone(), |(_, r)| r.to_string())
240        }).collect()
241    })
242}
243
244/// Format the current eval file for error context strings.
245/// Returns e.g. `", in '/nix/store/.../default.nix'"` or empty string.
246pub(crate) fn eval_file_ctx() -> String {
247    current_eval_file()
248        .map(|p| format!(", in '{}'", p.display()))
249        .unwrap_or_default()
250}
251
252/// RAII guard that pops the top of the eval-file stack on drop.
253pub struct EvalFileGuard;
254
255impl Drop for EvalFileGuard {
256    fn drop(&mut self) {
257        EVAL_FILE_STACK.with(|s| {
258            s.borrow_mut().pop();
259        });
260    }
261}
262
263/// Set `CURRENT_SOURCE_ID` to `id`, returning an RAII guard that restores
264/// the previous id on drop. Used at thunk force so a cross-file thunk's
265/// idents key the `(source_id, offset)` symbol cache against the file where
266/// the thunk was DEFINED, not the ambient source at force time — the sibling
267/// of the eval-file guard, closing the `parse.nix` cross-file collision.
268pub fn push_source_id(id: u32) -> SourceIdGuard {
269    let prev = CURRENT_SOURCE_ID.with(|s| {
270        let old = s.get();
271        s.set(id);
272        old
273    });
274    SourceIdGuard(prev)
275}
276
277/// RAII guard that restores the previous `CURRENT_SOURCE_ID` on drop.
278pub struct SourceIdGuard(u32);
279
280impl Drop for SourceIdGuard {
281    fn drop(&mut self) {
282        CURRENT_SOURCE_ID.with(|s| s.set(self.0));
283    }
284}
285
286// ── Path normalization ────────────────────────────────────────
287//
288// Normalize a path by removing `.` components and resolving `..`
289// components.  Unlike `canonicalize()`, this doesn't require the
290// path to exist on disk — critical for flake evaluation where
291// files may not be materialized yet.
292
293/// Normalize a path by removing `.` and resolving `..` components
294/// without touching the filesystem.
295///
296/// Delegates to [`crate::path::normalize`] — kept as a public re-export
297/// so existing call-sites continue to compile without changes.
298pub fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
299    crate::path::normalize(path)
300}
301
302// ── Pure (hermetic) evaluation mode ────────────────────────────
303//
304// When pure mode is enabled, impure builtins (`storePath`, `fetchurl`/`fetchTarball`
305// without an explicit hash, `currentTime`, `getEnv`, etc.) should refuse to
306// produce non-deterministic results. The flag is thread-local so each evaluator
307// thread can opt in independently.
308
309thread_local! {
310    static PURE_MODE: Cell<bool> = const { Cell::new(false) };
311}
312
313/// Enable or disable hermetic (pure) evaluation mode for the current thread.
314pub fn set_pure_mode(pure: bool) {
315    PURE_MODE.with(|p| p.set(pure));
316}
317
318/// Whether the current thread is in hermetic (pure) evaluation mode.
319#[must_use]
320pub fn is_pure_mode() -> bool {
321    PURE_MODE.with(Cell::get)
322}
323
324/// Maximum evaluation depth before we report infinite recursion.
325///
326/// With `stacker` dynamically growing the call stack, we are no longer
327/// limited by the default 8 MB thread stack.
328///
329/// **Test builds** keep a low limit (2 048) so that infinite-recursion
330/// tests fail quickly instead of spinning for minutes.
331///
332/// **Non-test builds** disable the depth guard entirely (`None`).
333/// nixpkgs uses deeply nested fixpoints (50+ overlay applications, each
334/// creating cascading chains of millions of `eval_expr` calls when
335/// attributes are forced). CppNix has no explicit depth limit — it
336/// relies on the OS stack, which `stacker` now emulates for us. True
337/// infinite recursion is caught by the thunk blackhole detector in
338/// `Thunk::force`, not by this counter.
339///
340/// "No limit" is carried by `None`, NOT by a `usize::MAX` sentinel. The
341/// sentinel form obliged every reader of this constant to re-guard it
342/// (`MAX_EVAL_DEPTH != usize::MAX && depth > MAX_EVAL_DEPTH`), and that
343/// guard did not actually remove the nonsense comparison it was written to
344/// suppress — `depth > usize::MAX` is false for every `usize`, which
345/// `clippy::absurd_extreme_comparisons` reports at deny level. With the
346/// bound typed as an `Option`, the non-test build contains no comparison
347/// at all and the absurd form has no way to be written.
348#[cfg(test)]
349const MAX_EVAL_DEPTH: Option<usize> = Some(2_048);
350#[cfg(not(test))]
351const MAX_EVAL_DEPTH: Option<usize> = None;
352
353/// Lightweight depth guard.
354///
355/// In non-test builds `MAX_EVAL_DEPTH` is `None`, so the guard is a no-op
356/// (the arm never matches). The compiler should be able to elide most of
357/// the overhead.
358struct DepthGuard;
359
360/// Release-active runaway backstop for the overlay-fixpoint promotion.
361///
362/// Release builds set `MAX_EVAL_DEPTH = None` (no eval-depth guard)
363/// so nixpkgs' legitimately-deep fixpoints evaluate.  But a promoted
364/// empty-attrs partial that corrupts a downstream `makeOverridable` /
365/// `commonAttrs` fixpoint (the cross-system Darwin `apple-sdk` path `hello`
366/// hits under `builtins.currentSystem = macOS`) recurses through
367/// `eval_expr` without bound — and that recursion does NOT climb the force
368/// stack, so only an `eval_expr`-level bound catches it before the OS stack
369/// aborts.  Armed ONLY once a promotion has fired (`promotion_occurred()`),
370/// so ordinary deep evaluation (never after a promotion) is untouched.  The
371/// converging native-system fixpoint (`libxcrypt`) peaks well under this
372/// bound and is unaffected; the non-converging cross-system runaway is
373/// caught here, converting a hard native-stack abort into a recoverable
374/// `InfiniteRecursion` that `x.y or default` recovers exactly like nix
375/// (`hello` returns to a clean value-diverge instead of aborting).
376const PROMOTION_RUNAWAY_EVAL_DEPTH: usize = 500;
377
378impl DepthGuard {
379    #[inline(always)]
380    fn enter() -> Result<Self, EvalError> {
381        EVAL_DEPTH.with(|d| {
382            let depth = d.get();
383            if matches!(MAX_EVAL_DEPTH, Some(max) if depth > max) {
384                return Err(EvalError::InfiniteRecursion(
385                    "eval depth exceeded".into(),
386                ));
387            }
388            if depth > PROMOTION_RUNAWAY_EVAL_DEPTH
389                && crate::value::promotion_occurred()
390            {
391                return Err(EvalError::InfiniteRecursion(
392                    "overlay-fixpoint promotion runaway (eval depth exceeded)".into(),
393                ));
394            }
395            d.set(depth + 1);
396            Ok(DepthGuard)
397        })
398    }
399}
400
401impl Drop for DepthGuard {
402    #[inline(always)]
403    fn drop(&mut self) {
404        EVAL_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
405    }
406}
407
408/// Collect ALL identifier names referenced in an AST expression.
409///
410/// Walks the full expression tree (including inside `with` bodies)
411/// and collects every `Ident` node. This is an OVER-APPROXIMATION:
412/// it includes shadowed names and names inside `with` bodies.
413///
414/// Over-approximation is SAFE for dead binding elimination — we may
415/// keep a binding that's unused (waste) but never skip a binding
416/// that IS used (correctness).
417///
418/// Previous versions bailed out on `with` expressions, disabling
419/// dead binding elimination entirely. The fix: collect idents even
420/// inside `with` bodies. If a binding name doesn't appear as ANY
421/// identifier ANYWHERE in the expression, it's provably dead
422/// regardless of `with` scopes — `with` makes names from the
423/// namespace reachable, not names from the enclosing let-scope.
424fn collect_referenced_names(expr: &ast::Expr) -> HashSet<String> {
425    let mut names = HashSet::new();
426    for node in expr.syntax().descendants() {
427        if let Some(ident) = ast::Ident::cast(node) {
428            names.insert(ident_text(&ident));
429        }
430    }
431    names
432}
433
434/// Compute the set of binding names that are transitively needed
435/// by the body expression in a recursive scope (let-in or rec attrset).
436///
437/// Algorithm:
438/// 1. Collect all ident references from the body → root set
439/// 2. Collect all ident references from each binding's value expression
440/// 3. BFS from root set through binding dependencies
441/// 4. Return the set of reachable binding names
442///
443/// Bindings NOT in the returned set are provably dead and can be skipped.
444/// This is correct even for recursive scopes because the BFS follows
445/// transitive dependencies: if A is needed and A references B, then B
446/// is added to the needed set.
447fn compute_needed_bindings(
448    body: &ast::Expr,
449    binding_info: &[(String, Option<ast::Expr>)], // (name, value_expr) — None for plain inherit
450) -> HashSet<String> {
451    // Step 1: Collect idents from the body
452    let body_refs = collect_referenced_names(body);
453
454    // Build the set of all binding names and their dependencies
455    let mut all_names: HashSet<String> = HashSet::with_capacity(binding_info.len());
456    let mut deps: HashMap<String, HashSet<String>> = HashMap::with_capacity(binding_info.len());
457
458    for (name, value_expr) in binding_info {
459        all_names.insert(name.clone());
460        if let Some(expr) = value_expr {
461            deps.insert(name.clone(), collect_referenced_names(expr));
462        }
463    }
464
465    // Step 2: BFS from body refs through binding dependencies
466    let mut needed: HashSet<String> = body_refs.intersection(&all_names).cloned().collect();
467    let mut queue: VecDeque<String> = needed.iter().cloned().collect();
468
469    while let Some(name) = queue.pop_front() {
470        if let Some(name_deps) = deps.get(&name) {
471            for dep in name_deps {
472                if all_names.contains(dep) && needed.insert(dep.clone()) {
473                    queue.push_back(dep.clone());
474                }
475            }
476        }
477    }
478
479    needed
480}
481
482/// Evaluate a Nix expression string.
483#[must_use = "evaluation result should be used"]
484pub fn eval(input: &str) -> Result<Value, EvalError> {
485    eval_with_file(input, None)
486}
487
488// Whether we are inside a top-level eval (used to avoid nested perf reports).
489thread_local! {
490    static EVAL_NESTING: Cell<usize> = const { Cell::new(0) };
491}
492
493/// Evaluate a Nix expression string, optionally tagged with the
494/// path of the source file. The file is stored on the root `Env`
495/// so that any closure created during evaluation captures it and
496/// can resolve relative path literals (`./foo.nix`) in function
497/// defaults that fire after control has left the file's scope.
498
499pub fn eval_with_file(input: &str, file: Option<std::path::PathBuf>) -> Result<Value, EvalError> {
500    let nesting = EVAL_NESTING.with(|n| {
501        let v = n.get();
502        n.set(v + 1);
503        v
504    });
505    if nesting == 0 {
506        crate::perf::init();
507        crate::perf::start();
508        crate::trace::init_trace();
509        // Clear the identifier symbol cache so that offsets from
510        // previous top-level evaluations don't persist.
511        clear_ident_cache();
512        // ENV-RESOLVE M0 (no-op unless `SUI_RESOLVE=1`): clear the per-source
513        // resolution side-table for the same reason — its `(source_id,
514        // offset)` keys must not survive across independent top-level evals.
515        crate::resolve_env::clear();
516        // SOURCE_TEXTS is deliberately NOT cleared here — it is append-only
517        // for the life of the process. Clearing it on a `nesting == 0`
518        // re-entry was a shared-mutable-cell bug: the top-level
519        // `eval_with_file` RETURNS (nesting → 0) BEFORE its caller
520        // deep-forces the result (e.g. `value.to_json()` at the CLI), and
521        // that deep force triggers lazy `import`s which re-enter
522        // `eval_with_file` at nesting == 0 — so clearing here wiped every
523        // registered file's text mid-force. Any `unsafeGetAttrPos` resolved
524        // after the first deep-force import then failed its `text_for()`
525        // existence check and returned null (the cid `options.json` attrTag
526        // `declarations = []` divergence). SOURCE_TEXTS is keyed by canonical
527        // path and `register_source` stores each path's text only once
528        // (identical on re-parse), so append-only is correct — a path always
529        // maps to its own text — and matches CppNix, which never clears its
530        // source registry. The only cost is bounded growth within one process
531        // (a non-issue for a per-invocation CLI). Removing the clearable cell
532        // makes the whole "absent/wrong source text at resolve time" class
533        // unrepresentable rather than merely guarded.
534    }
535    let parse = rnix::Root::parse(input);
536    if !parse.errors().is_empty() {
537        let msgs: Vec<String> = parse.errors().iter().map(|e| e.to_string()).collect();
538        EVAL_NESTING.with(|n| n.set(n.get().saturating_sub(1)));
539        return Err(EvalError::ParseError(msgs.join("; ")));
540    }
541
542    // Each parse tree gets a unique source ID so that identifiers
543    // at the same byte offset in different files don't collide in
544    // the symbol cache.
545    let src_id = next_source_id();
546    // ENV-RESOLVE M0 (no-op unless `SUI_RESOLVE=1`): run the parse-time
547    // variable resolver over THIS parse tree and merge its `Lexical`
548    // resolutions into the per-source table under `src_id`. Pure + fail-safe
549    // (any uncertainty is left `Dynamic`), so the eval below is byte-identical
550    // — the `Lexical` fast path only shortcuts a lexical-bindings hit, which
551    // `lookup_fast` returns first anyway.
552    if crate::resolve_env::enabled() {
553        let table = sui_resolve::resolve(&parse.tree());
554        crate::resolve_env::populate(src_id, &table);
555    }
556    // Register this parse tree's file + text so a static key's byte offset
557    // (recorded by `eval_attrset`) resolves to a file/line/column for
558    // `builtins.unsafeGetAttrPos`. The file flows through the eval-file
559    // stack (store-path prefixed for imported inputs); the position resolver
560    // lifts a cache-dir path to its `/nix/store/<h>-source` store path.
561    crate::pos::register_source(file.as_deref(), input);
562    let prev_src_id = CURRENT_SOURCE_ID.with(|s| {
563        let old = s.get();
564        s.set(src_id);
565        old
566    });
567
568    let root = parse.tree();
569    let expr = match root.expr() {
570        Some(e) => e,
571        None => {
572            CURRENT_SOURCE_ID.with(|s| s.set(prev_src_id));
573            EVAL_NESTING.with(|n| n.set(n.get().saturating_sub(1)));
574            return Err(EvalError::ParseError("empty expression".to_string()));
575        }
576    };
577    let mut env = Env::new();
578    env.set_eval_file(file);
579    // Tag the env with THIS parse tree's source_id so a thunk created here
580    // and forced later (cross-file) restores this id on force (see the
581    // source-id guard in `Thunk::force`), keying `IDENT_CACHE` against the
582    // file where the thunk was defined.
583    env.set_source_id(src_id);
584    builtins::register(&mut env);
585    let result = eval_expr(&expr, &env).map_err(|e| attach_trace(e))?;
586    // Force the top-level result so callers always see a concrete value.
587    let final_result = force_value(&result).map_err(|e| attach_trace(e));
588    // Restore the previous source ID (matters for nested imports).
589    CURRENT_SOURCE_ID.with(|s| s.set(prev_src_id));
590    EVAL_NESTING.with(|n| n.set(n.get().saturating_sub(1)));
591    if nesting == 0 {
592        crate::perf::report();
593    }
594    final_result
595}
596
597/// Force a value: if it is a thunk, evaluate and memoize the result.
598/// Concrete values are returned unchanged.
599/// Force a value: if it is a thunk, evaluate and memoize the result.
600/// Concrete values are returned unchanged.
601///
602/// Inlined aggressively so the non-thunk fast path compiles to a
603/// simple clone without a function-call boundary.
604#[inline(always)]
605/// Force a value and return a type-safe `Concrete` (guaranteed non-Thunk).
606///
607/// This is the preferred forcing API. The `Concrete` return type makes it
608/// impossible to accidentally use an unforced thunk — the compiler rejects it.
609pub fn force_concrete(value: &Value) -> Result<Concrete, EvalError> {
610    value.demand()
611}
612
613/// Force a value (legacy API — returns `Value` for backward compatibility).
614///
615/// Prefer `force_concrete()` or `Value::demand()` for new code.
616pub fn force_value(value: &Value) -> Result<Value, EvalError> {
617    crate::perf::inc(crate::perf::Counter::ForceValue);
618    // Fast path: non-thunk values are returned immediately (no clone needed
619    // until we actually have work to do).
620    if !matches!(value, Value::Thunk(_)) {
621        return Ok(value.clone());
622    }
623    // Slow path: chase thunk chains.
624    //
625    // A legitimate chain is typically 1–3 links deep (result of lazy
626    // evaluation wrapping an intermediate value in another thunk).
627    // Reaching 100 means either (a) a self-referential cycle like
628    // `let x = x; in x` that bypassed per-thunk Blackhole detection,
629    // or (b) pathological Thunk(Thunk(...)) nesting. Both are errors.
630    //
631    // Previous behavior silently returned `Ok(last_thunk)` at depth
632    // 100, which hid infinite-recursion bugs — the blackhole tests
633    // in the lib suite failed because `result.is_ok()` instead of
634    // `is_err()`. Returning `Err` here makes the silent-bail visible
635    // at the CppNix-compatible call site (real Nix raises "infinite
636    // recursion encountered").
637    let mut v = value.clone();
638    let mut depth = 0u32;
639    loop {
640        match v {
641            Value::Thunk(ref thunk) => {
642                v = force_thunk(thunk)?;
643                depth += 1;
644                if depth > 100 {
645                    return Err(EvalError::InfiniteRecursion(
646                        "force_value: thunk chain exceeded depth 100 (cycle or runaway lazy wrap)".into(),
647                    ));
648                }
649            }
650            _ => return Ok(v),
651        }
652    }
653}
654
655/// Force with call-site tracking (legacy API).
656pub fn force_value_tracked(value: &Value, site: &str) -> Result<Value, EvalError> {
657    crate::perf::inc(crate::perf::Counter::ForceValue);
658    if let Value::Thunk(thunk) = value {
659        FORCE_SITES.with(|sites| {
660            *sites.borrow_mut().entry(site.to_string()).or_insert(0) += 1;
661        });
662        force_thunk(thunk)
663    } else {
664        Ok(value.clone())
665    }
666}
667
668thread_local! {
669    static FORCE_SITES: std::cell::RefCell<std::collections::HashMap<String, u64>> =
670        std::cell::RefCell::new(std::collections::HashMap::new());
671    static APPLY_SITES: std::cell::RefCell<std::collections::HashMap<String, u64>> =
672        std::cell::RefCell::new(std::collections::HashMap::new());
673}
674
675/// Dump force-site counters (call from perf reporting).
676pub fn dump_force_sites() {
677    FORCE_SITES.with(|sites| {
678        let sites = sites.borrow();
679        let mut sorted: Vec<_> = sites.iter().collect();
680        sorted.sort_by(|a, b| b.1.cmp(a.1));
681        eprintln!("[force-sites] top thunk force call sites:");
682        for (site, count) in sorted.iter().take(10) {
683            eprintln!("  {count:>8} {site}");
684        }
685    });
686    APPLY_SITES.with(|sites| {
687        let sites = sites.borrow();
688        let mut sorted: Vec<_> = sites.iter().collect();
689        sorted.sort_by(|a, b| b.1.cmp(a.1));
690        eprintln!("[apply-sites] top lambda call sites by source file:");
691        for (site, count) in sorted.iter().take(15) {
692            // Strip nix store prefix for readability
693            let short = site.rsplit_once("-source/").map_or(site.as_str(), |(_,s)| s);
694            eprintln!("  {count:>8} {short}");
695        }
696    });
697}
698
699/// Force a thunk — split out from [`force_value`] so the fast path
700/// (non-thunk clone) stays fully inlined while this cold path can
701/// be a regular function call with stacker protection.
702fn force_thunk(thunk: &Thunk) -> Result<Value, EvalError> {
703    // Ultra-fast path: if the thunk is already cached, skip stacker overhead.
704    if let Some(cached) = thunk.peek() {
705        crate::perf::inc(crate::perf::Counter::ThunkHit);
706        return Ok(cached.clone().into_value());
707    }
708    stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || {
709        // Force ONE level only — matches CppNix's forceValue which does
710        // not transitively chase thunk-in-thunk chains. The caller will
711        // force again when the value is actually needed. This is the key
712        // optimization: CppNix forces 71 thunks for lib.version while
713        // sui was forcing 180K due to transitive forcing.
714        thunk.force(&|expr, env| eval_expr(expr, env))
715    })
716}
717
718/// Decide whether to thunk an expression or evaluate it directly.
719///
720/// Trivial expressions (literals, paths) are evaluated immediately --
721/// no thunk allocation. For non-recursive scopes, variable lookups
722/// (Ident) and lambdas are also evaluated eagerly. This matches
723/// CppNix's `maybeThunk` optimization which avoids a large fraction
724/// of thunk creations on nixpkgs.
725///
726/// For recursive scopes (let-in, rec attrsets), set `is_rec = true` to
727/// prevent eager evaluation of `Ident` and `Lambda` expressions:
728/// - Ident: sibling bindings may not be defined yet (forward refs).
729/// - Lambda: the closure must capture the *final* env (set in Phase 2)
730///   so that the lambda body can reference sibling bindings.
731///
732/// `defined_so_far`: In recursive scopes, names that have already been
733/// bound in this scope (i.e. earlier bindings). Idents referencing these
734/// are backward references and can be resolved directly without thunking.
735/// Forward references (names not yet defined) must still be thunked.
736/// Detect whether `value_expr`'s source structurally references
737/// the identifier `name` — the signal that this let-binding is a
738/// self-recursive fix-point (`let x = f x; in x` or
739/// `let x = { a = 1; b = x.a; }; in x`).  Used at let-binding
740/// thunking time to pick `Thunk::new_suspended_recursive` over the
741/// classic `Thunk::new_suspended`, so inner re-entrance during
742/// force returns the partial value via `ThunkRepr::Promise`
743/// instead of erroring with `InfiniteRecursion`.
744///
745/// Implementation walks the value-expr's rnix syntax tree looking
746/// for `TOKEN_IDENT` whose text equals `name`.  This is a
747/// conservative over-approximation:
748/// - shadowing (e.g. `let x = let x = 1; in x; in x`) marks the
749///   outer thunk recursive even though no real cycle exists;
750/// - the resulting Promise behaviour is a strict superset of
751///   Blackhole for non-cyclic forces (the body runs to completion
752///   and the cell gets the final value), so false positives are
753///   semantically safe — they cost only the extra `Rc<RefCell>`
754///   allocation per recursive let-binding.
755///
756/// False negatives (e.g. the bound name appears only inside an
757/// inherit-from-source clause) leave the existing
758/// `InfiniteRecursion` behaviour intact, which is the conservative
759/// fallback.
760/// `SUI_SCOPE_NARROW` — the scope-narrowing latch.
761///
762/// Every `let` / `rec` / pattern-default binding closes an `Rc` cycle today:
763/// the thunk is bound INTO the scope env, then Phase 2's `update_env` puts
764/// that same env back INTO the thunk. `Rc` has no cycle collector and no
765/// `Weak` sits on that edge, so the whole scope — every innocent leaf in it —
766/// is immortal for the life of the process. Narrowing removes the second half
767/// of the cycle for the bindings that provably do not need it.
768///
769/// * unset / `0` — today's behaviour, byte- AND allocation-identical. Not one
770///   extra tree walk runs on this path.
771/// * `1` — D3 (pattern-lambda formal defaults) + D1 (`let` / `rec` bindings
772///   whose RHS reaches no sibling keep their outer-env capture).
773/// * `2` — additionally D2 (bindings that DO need the scope get a *cluster*
774///   env holding only the names they can reach, so one recursive binding
775///   stops pinning its innocent siblings).
776///
777/// Read once through a `OnceLock` one-way latch — the `resolve_env::enabled()`
778/// idiom — so the value cannot change mid-eval and the default path pays a
779/// single relaxed load.
780/// ★ THE DEFAULT IS 2 (flipped 2026-08-17). `0` and `1` remain selectable for
781/// bisecting a suspected narrowing bug — that is the whole reason the latch
782/// survives rather than the code being inlined.
783///
784/// It shipped as `0`, and NOTHING in the tree set it. So the measured result —
785/// 700.0 MB / 1,020,001 live nodes → 22.2 MB / 0 on the gate probe, with the
786/// process RSS floor at 20.5 MB, i.e. *at the floor* — reached nobody. A fix
787/// present but unreached is the same shape as the VM bridges that were
788/// installed two-of-three, and as `vm_fallback_count()` sitting unread since
789/// the day it was written.
790///
791/// Flipped only after byte-parity was proven at every level, because a wrong
792/// drvPath is far worse than a leak:
793///   - the 117-fixture lang corpus: identical at 0, 1 and 2
794///   - the full `sui-eval` suite at level 2: 1685 pass
795///   - `sui eval --raw <expr>.drvPath` byte-identical across 0/1/2 AND equal to
796///     real nix
797///
798/// The narrowing removes the second half of an `Rc` cycle for bindings that
799/// provably do not need the scope env. It is NOT free of judgement: `P2`, a
800/// genuinely-recursive scope, must still pin, and it does — a narrowing that
801/// improved every probe would mean it was discarding something it should keep.
802fn scope_narrow_level() -> u8 {
803    static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
804    *LEVEL.get_or_init(
805        || match std::env::var("SUI_SCOPE_NARROW").ok().as_deref() {
806            Some("0") => 0,
807            Some("1") => 1,
808            _ => 2,
809        },
810    )
811}
812
813/// True at `SUI_SCOPE_NARROW >= 1` — D1 + D3 are on.
814#[inline]
815fn scope_narrow_enabled() -> bool {
816    scope_narrow_level() >= 1
817}
818
819/// True at `SUI_SCOPE_NARROW = 2` — D2 (the cluster env) is on.
820#[inline]
821fn scope_cluster_enabled() -> bool {
822    scope_narrow_level() >= 2
823}
824
825/// The set of variable-reference ident names in `value_expr`'s subtree
826/// (`NODE_IDENT` whose parent is NOT a `NODE_ATTRPATH` — i.e. genuine
827/// variable references, not attribute names/keys). ONE subtree walk.
828///
829/// Kills the O(N²) re-walk storm (Storm A) at the call sites: previously
830/// `is_self_recursive_binding` did a full subtree walk once per
831/// `(binding × sibling-name)` in every `let`/`rec` scope; now each RHS is
832/// walked ONCE to build this set, then every name is an O(1) set lookup.
833/// Byte-neutral: the recursion verdict is unchanged (a name is self/mutually
834/// recursive iff it is in the set).
835///
836/// NOT cross-call memoized: a process-lifetime memo keyed on ephemeral AST
837/// node identity `(source-id, range)` collides when nodes are parsed/dropped
838/// without a per-eval clear (the standalone-predicate case). The call-site
839/// single-walk is the byte-safe win; `ContentMemo` (sui-intern) is reserved
840/// for sites with a STABLE content key (the NAR-hash memo's `(dir,name)`, the
841/// overlay-flatten per-node cache).
842///
843/// The attrpath exclusion matters: without it, `placeholder = if
844/// lhs.placeholder == …` in nixpkgs `lib/types.nix` would be falsely flagged
845/// self-recursive (its RHS mentions the *attribute* `.placeholder`), routing
846/// the binding through the `Promise` fix-point path whose env handling drops
847/// the let-scope — surfacing as a force-order-dependent `null` in the module
848/// system (`concatLists: expected list, got null`).
849fn referenced_idents(value_expr: &ast::Expr) -> HashSet<SmolStr> {
850    use rnix::SyntaxKind;
851    // Storm A instrumentation (byte-neutral, gated on perf::enabled()): count
852    // this walk + the rnix descendants it visits + its walltime, so the
853    // residual per-fixpoint-iteration self/mutual-recursion detection cost is
854    // VISIBLE in the SUI_EVAL_PERF report — symmetric with sorted_entries /
855    // overlay-flatten. The counter reads add zero output-relevant work.
856    let perf_on = crate::perf::enabled();
857    let t0 = if perf_on {
858        Some(std::time::Instant::now())
859    } else {
860        None
861    };
862    crate::perf::inc(crate::perf::Counter::SelfRecWalkCalls);
863    let mut nodes_walked: u64 = 0;
864    let mut set: HashSet<SmolStr> = HashSet::new();
865    for node in value_expr.syntax().descendants() {
866        nodes_walked += 1;
867        if node.kind() == SyntaxKind::NODE_IDENT
868            && node
869                .parent()
870                .is_none_or(|p| p.kind() != SyntaxKind::NODE_ATTRPATH)
871            && let Some(i) = ast::Ident::cast(node)
872        {
873            set.insert(SmolStr::from(ident_text(&i).as_str()));
874        }
875    }
876    crate::perf::add(crate::perf::Counter::SelfRecWalkNodes, nodes_walked);
877    if let Some(t0) = t0 {
878        crate::trace::add_self_rec_walk_nanos(t0.elapsed().as_nanos());
879    }
880    set
881}
882
883/// True iff `value_expr` references `name` as a variable. Now a set lookup
884/// over one subtree walk (see `referenced_idents`). Byte-neutral vs the prior
885/// per-name-walk implementation.
886fn is_self_recursive_binding(value_expr: &ast::Expr, name: &str) -> bool {
887    referenced_idents(value_expr).contains(name)
888}
889
890fn maybe_thunk(
891    expr: &ast::Expr,
892    env: &Env,
893    is_rec: bool,
894    defined_so_far: Option<&HashSet<String>>,
895) -> Value {
896    match expr {
897        // Literals: evaluate directly (no allocation needed).
898        ast::Expr::Literal(lit) => eval_literal(lit).unwrap_or_else(|_| {
899            Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
900        }),
901        // Ident resolution: try full lookup (lexical + with-scope cache + force).
902        // On successful lookup → return value directly (most common case).
903        // On blackhole (fixpoint being constructed) → env.lookup returns None
904        // → create WithIdent thunk for deferred O(1) cache-based resolution.
905        // This approach: (1) is fast for resolved with-scopes (no thunk overhead),
906        // (2) handles blackhole fixpoints correctly via WithIdent deferral.
907        ast::Expr::Ident(ident) if !is_rec => {
908            // Cache the interned Symbol by (source_id, text_offset) — same
909            // zero-alloc steady-state path as the strict Ident arm in
910            // `eval_expr`. The ident text is materialized only on the
911            // once-per-offset cold miss and on the (rare) blackhole deferral.
912            // Same cross-file aliasing fix as the strict `eval_expr` Ident arm —
913            // key on the env's source id, not the unmaintained thread-local.
914            // This twin had NO stale-symbol guard at all (the one commit
915            // 2d93e77 added sits only on the strict arm's lookup-MISS path,
916            // after the keyword check), so it was the more exposed of the two.
917            let sym = {
918                let src_id = env.source_id();
919                let offset = u32::from(ident.syntax().text_range().start());
920                crate::value::intern_cached_with(src_id, offset, || {
921                    crate::value::intern(&ident_text(ident))
922                })
923            };
924            // Zero-copy keyword check on the resolved Symbol.
925            if let Some(kw) = crate::value::with_resolved(sym, |s| match s {
926                "true" => Some(Value::Bool(true)),
927                "false" => Some(Value::Bool(false)),
928                "null" => Some(Value::Null),
929                _ => None,
930            }) {
931                return kw;
932            }
933            {
934                {
935                    // `name` arg to `lookup_fast` is unused (lookup is by
936                    // Symbol) — pass "" to skip materializing the ident text on
937                    // the hot HIT path.
938                    if let Some(v) = env.lookup_fast(sym, "") {
939                        return v;
940                    }
941                    // Failed — either blackhole or missing. Create WithIdent
942                    // thunk for deferred resolution (only for the blackhole case).
943                    if let Some((scope_cache, scope_value)) = env.innermost_with_scope() {
944                        return Value::Thunk(Thunk::new_with_ident(
945                            SmolStr::from(ident_text(ident).as_str()),
946                            scope_cache,
947                            scope_value,
948                            env.clone(),
949                        ));
950                    }
951                    crate::perf::inc(crate::perf::Counter::ThunkSiteMaybeIdent);
952                    Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
953                }
954            }
955        }
956        // Identifiers in rec scope: check if it's a backward reference
957        // (name already defined earlier in the same scope). If so, we
958        // can resolve it directly instead of creating a wasteful thunk.
959        ast::Expr::Ident(ident) if is_rec => {
960            let name = ident_text(ident);
961            match name.as_str() {
962                "true" => Value::Bool(true),
963                "false" => Value::Bool(false),
964                "null" => Value::Null,
965                _ => {
966                    // If this name was already defined earlier in the
967                    // scope, it's a backward reference — resolve directly.
968                    if defined_so_far.map_or(false, |d| d.contains(&name)) {
969                        env.lookup(&name).unwrap_or_else(|| {
970                            crate::perf::inc(crate::perf::Counter::ThunkSiteMaybeIdent);
971                            Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
972                        })
973                    } else {
974                        // Forward reference — must thunk
975                        crate::perf::inc(crate::perf::Counter::ThunkSiteMaybeIdent);
976                        Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
977                    }
978                }
979            }
980        }
981        // Absolute and home paths: trivial text extraction — but ONLY
982        // for the non-interpolated case. An interpolated path (`/a/${e}`,
983        // `~/${e}`) must be thunked so its `${…}` parts are evaluated in
984        // `eval_expr_inner`, never spliced as literal text.
985        ast::Expr::PathAbs(p) if !parts_have_interpolation(&p.parts()) => {
986            // CppNix canonicalizes every absolute path literal on eval
987            // (`/.` → `/`, `/a/./b` → `/a/b`, `/a/../b` → `/b`, `..`
988            // clamped at root). A path VALUE carries the canonical form —
989            // the marquee cid root threw in `lib.path.hasStorePathPrefix`
990            // precisely because sui kept the raw `/.` text.
991            let text = crate::path::canon_abs(&p.syntax().text().to_string());
992            Value::Path(Box::new(SmolStr::from(text.as_str())))
993        }
994        ast::Expr::PathHome(p) if !parts_have_interpolation(&p.parts()) => {
995            let text = p.syntax().text().to_string();
996            Value::Path(Box::new(SmolStr::from(text.as_str())))
997        }
998        // Non-interpolated string literal: a constant value with no
999        // interpolation, so `eval_str` runs no `${…}` force/coerce — it is
1000        // pure, non-throwing, side-effect-free, and produces a
1001        // `String(NixString::with_context(text, EMPTY))`. Evaluating it here is
1002        // therefore byte-identical to forcing a suspended thunk of it (M2
1003        // thunk-waste: a constant Str thunk is always pure overhead — it can
1004        // never observably change eval order because it cannot throw or
1005        // diverge). Only the NON-interpolated case is direct; an interpolated
1006        // `"${e}"` must stay thunked so its parts force lazily in the right
1007        // env/order. `eval_str` on the empty-interpolation input cannot fail,
1008        // but fall back to a thunk on the (unreachable) error to preserve
1009        // exact prior behavior.
1010        ast::Expr::Str(st) if !str_has_interpolation(st) => {
1011            eval_str(st, env).unwrap_or_else(|_| {
1012                Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
1013            })
1014        }
1015        // Lambda: capture env directly (no computation needed).
1016        // But NOT in recursive scopes -- the closure must capture the
1017        // final env with all sibling bindings (set in Phase 2).
1018        ast::Expr::Lambda(lam) if !is_rec => {
1019            if let (Some(param), Some(body)) = (lam.param(), lam.body()) {
1020                Value::Lambda(Rc::new(Closure {
1021                    param,
1022                    body,
1023                    env: env.clone(),
1024                }))
1025            } else {
1026                Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
1027            }
1028        }
1029        // Select on a variable: CppNix's maybeThunk evaluates these eagerly
1030        // when the base is a simple ident. However, this breaks fixpoints
1031        // where the base (e.g., `config`) is a thunk being computed — eagerly
1032        // evaluating `config.x` during attrset construction triggers blackhole.
1033        //
1034        // The nixpkgs module system relies on `{ ...; default = config.x; }`
1035        // being lazy. Wrap selects in thunks unconditionally.
1036        // The performance cost is minimal (thunk allocation + deferred eval)
1037        // and correctness is critical for fixpoint patterns.
1038        // Everything else: wrap in a thunk for lazy evaluation.
1039        _ => {
1040            crate::perf::inc(crate::perf::Counter::ThunkSiteMaybeOther);
1041            if crate::perf::enabled() {
1042                let kind = match expr {
1043                    ast::Expr::Select(_) => "Select",
1044                    ast::Expr::Apply(_) => "Apply",
1045                    ast::Expr::BinOp(_) => "BinOp",
1046                    ast::Expr::IfElse(_) => "IfElse",
1047                    ast::Expr::Str(_) => "Str",
1048                    ast::Expr::List(_) => "List",
1049                    ast::Expr::With(_) => "With",
1050                    ast::Expr::Assert(_) => "Assert",
1051                    ast::Expr::HasAttr(_) => "HasAttr",
1052                    ast::Expr::UnaryOp(_) => "UnaryOp",
1053                    ast::Expr::Paren(_) => "Paren",
1054                    ast::Expr::LetIn(_) => "LetIn",
1055                    ast::Expr::AttrSet(_) => "AttrSet",
1056                    ast::Expr::Ident(_) => "Ident(rec)",
1057                    ast::Expr::Lambda(_) => "Lambda(rec)",
1058                    ast::Expr::LegacyLet(_) => "LegacyLet",
1059                    ast::Expr::PathAbs(_)
1060                    | ast::Expr::PathHome(_)
1061                    | ast::Expr::PathRel(_)
1062                    | ast::Expr::PathSearch(_) => "Path(interp)",
1063                    _ => "Other",
1064                };
1065                crate::trace::inc_maybe_other_kind(kind);
1066            }
1067            Value::Thunk(Thunk::new_suspended(expr.clone(), env.clone()))
1068        }
1069    }
1070}
1071
1072/// Evaluate an rnix expression in an environment.
1073///
1074/// Uses `stacker::maybe_grow` to dynamically extend the call stack when
1075/// it is close to exhaustion.  This prevents stack overflow on deeply
1076/// nested nixpkgs fixpoints (50+ overlay applications each creating
1077/// multiple recursive `eval_expr` / `force_value` frames).
1078///
1079/// **Fast path:** Ident (~32% of all evals), Literal, Paren, and Root
1080/// expressions don't recurse and are handled directly, skipping the
1081/// `stacker::maybe_grow` overhead for ~40% of all `eval_expr` calls.
1082#[inline(always)]
1083pub fn eval_expr(expr: &ast::Expr, env: &Env) -> Result<Value, EvalError> {
1084    // Fast path: trivial expressions that don't recurse.
1085    // Skip stacker overhead for ~40% of all eval_expr calls.
1086    match expr {
1087        ast::Expr::Ident(ident) => {
1088            crate::perf::inc(crate::perf::Counter::EvalExpr);
1089            if crate::perf::enabled() {
1090                crate::perf::inc(crate::perf::Counter::ExprIdent);
1091            }
1092            // ── ENV-RESOLVE M0 fast path (no-op unless `SUI_RESOLVE=1`) ──
1093            // A parse-time-`Lexical` reference carries its precomputed
1094            // Symbol; probe the lexical bindings map DIRECTLY, skipping the
1095            // per-lookup `ident_text().to_string()` + `intern()`. This is
1096            // parity-by-construction: `lookup_fast` probes the SAME lexical
1097            // map by the SAME Symbol FIRST, so a hit here is byte-identical
1098            // to what the unchanged path below returns. Any miss (a
1099            // mid-fixpoint blackhole where the binding isn't in scope yet, an
1100            // unrecorded ident, or `Dynamic`) falls through to the EXACT
1101            // unchanged path — including the whole with-chain + WithIdent
1102            // deferral. The resolver never records keywords, so the
1103            // true/false/null handling below is untouched on this path.
1104            if crate::resolve_env::enabled() {
1105                let src_id = CURRENT_SOURCE_ID.with(std::cell::Cell::get);
1106                let offset = u32::from(ident.syntax().text_range().start());
1107                if let sui_resolve::Resolution::Lexical { sym } =
1108                    crate::resolve_env::resolution_for(src_id, offset)
1109                {
1110                    if let Some(v) = env.lookup_lexical_sym(sym) {
1111                        return Ok(v);
1112                    }
1113                }
1114                // Miss / Dynamic → fall through to the unchanged path.
1115            }
1116            // Cache the interned Symbol by (source_id, text_offset) so the
1117            // steady-state identifier lookup pays neither a per-lookup
1118            // `ident_text().to_string()` heap alloc nor a string re-hash — the
1119            // ident's text is materialized only on the once-per-offset cold
1120            // miss. The keyword check + the common `lookup_fast` HIT then run
1121            // fully allocation-free; `name` is materialized lazily only on the
1122            // miss/error branches, which need the string anyway.
1123            // KEY ON `env.source_id()`, NOT the thread-local (fixed 2026-07-20).
1124            //
1125            // `CURRENT_SOURCE_ID` is pushed at exactly ONE site —
1126            // `value.rs`'s `ThunkRepr::Suspended` force branch. Lambda
1127            // application and the Native/WithIdent/InheritSelect/Promise force
1128            // branches never push it, so while a callee's body was being
1129            // evaluated the thread-local still named the CALLER's file. The
1130            // `(source_id, offset)` cache key then aliased across files: an
1131            // identifier at byte N in file A could resolve to the Symbol
1132            // interned for a `null`/`true`/`false` token at byte N in file B —
1133            // and the zero-copy keyword check below turned that into a literal
1134            // `Value::Null` for a perfectly well-defined identifier, before any
1135            // environment lookup.
1136            //
1137            // That is what stopped sui evaluating nixpkgs: `hostSuffix` in
1138            // `make-derivation.nix` resolved to `null`, so `attrs.name +
1139            // hostSuffix` raised "cannot add string and null" — observed
1140            // directly as `STALE-KEYWORD ident="hostSuffix" resolvedAs="null"`.
1141            // It is not darwin-specific and has nothing to do with the module
1142            // system; `import <nixpkgs> {}` fails identically on x86_64-linux.
1143            //
1144            // `Env` already carries the correct value: `eval_with_file` sets it
1145            // and `child()` inherits it, and a lambda's `call_env` is
1146            // `closure.env.child()` — so a body's env names its DEFINING file.
1147            // Keying on it fixes every cross-file path at the cause, rather than
1148            // adding a fifth push/pop guard that a sixth path can forget.
1149            let sym = {
1150                let src_id = env.source_id();
1151                let offset = u32::from(ident.syntax().text_range().start());
1152                crate::value::intern_cached_with(src_id, offset, || {
1153                    crate::value::intern(&ident_text(ident))
1154                })
1155            };
1156            // Zero-copy keyword check on the resolved Symbol — the resolver
1157            // never records keywords, so this matches the prior `name.as_str()`
1158            // arm exactly.
1159            if let Some(kw) = crate::value::with_resolved(sym, |s| match s {
1160                "true" => Some(Value::Bool(true)),
1161                "false" => Some(Value::Bool(false)),
1162                "null" => Some(Value::Null),
1163                _ => None,
1164            }) {
1165                return Ok(kw);
1166            }
1167            return {
1168                {
1169                    // `lookup_fast`'s `name` argument is unused (lookup is by
1170                    // Symbol); pass "" to avoid materializing the ident text on
1171                    // the hot HIT path.
1172                    if let Some(v) = env.lookup_fast(sym, "") {
1173                        Ok(v)
1174                    } else {
1175                        let name = ident_text(ident);
1176                        // The `(src_id, text_offset)` identifier-symbol cache
1177                        // (`intern_cached_with`) can hand back a STALE Symbol when
1178                        // a lazily-forced thunk's identifier is resolved under a
1179                        // force-time `CURRENT_SOURCE_ID` that differs from the
1180                        // identifier's PARSE-time src_id — a thunk from file A can
1181                        // be forced while B is the current source, so
1182                        // `(B_src_id, offset)` aliases B's parse tree's identifier
1183                        // at that same byte offset and returns ITS Symbol. (Proven
1184                        // root: nixpkgs `lib/systems/parse.nix` `mkOptionType` — the
1185                        // binding IS present in the env, but the cache returned
1186                        // `Symbol(566)` while the binding was interned under
1187                        // `Symbol(506)`, so `lookup_fast(566)` missed a defined
1188                        // var.) `intern` is deterministic + append-only, so on a
1189                        // miss re-intern the name from its text (the authoritative
1190                        // Symbol) and retry the lexical lookup BEFORE considering
1191                        // with-scopes or undefined. A genuinely undefined variable
1192                        // is unaffected — its fresh lookup also misses and falls
1193                        // through unchanged.
1194                        let fresh = crate::value::intern(name.as_str());
1195                        if fresh != sym {
1196                            if let Some(v) = env.lookup_fast(fresh, name.as_str()) {
1197                                return Ok(v);
1198                            }
1199                        }
1200                        if env.with_scope_count() > 0 {
1201                        // With-scope lookup failed (likely blackhole from fixpoint).
1202                        // Return a WithIdent thunk for deferred resolution.
1203                        // This is the eval_expr equivalent of maybe_thunk's deferral.
1204                        if let Some((scope_cache, scope_value)) = env.innermost_with_scope() {
1205                            Ok(Value::Thunk(Thunk::new_with_ident(
1206                                SmolStr::from(name.as_str()),
1207                                scope_cache,
1208                                scope_value,
1209                                env.clone(),
1210                            )))
1211                        } else if crate::value::in_promise_eval() {
1212                            // M2.6 Promise softening: an undefined
1213                            // identifier inside Promise body evaluation
1214                            // typically means a `with` block sourced
1215                            // from the empty-attrset sentinel didn't
1216                            // populate the with-scope.  Returning null
1217                            // lets the eval proceed; the result is
1218                            // wrong-but-bounded (no further forces
1219                            // happen on null until something downstream
1220                            // demands a real value).
1221                            Ok(Value::Null)
1222                        } else {
1223                            Err(EvalError::UndefinedVar(
1224                                format!("'{name}'{}", eval_file_ctx()),
1225                            ))
1226                        }
1227                    } else {
1228                        if let Ok(dbg_var) = std::env::var("SUI_DEBUG_VAR") {
1229                            if dbg_var == name || dbg_var == "*" {
1230                                eprintln!(
1231                                    "[sui-debug] UndefinedVar '{name}' in {}\n\
1232                                     [sui-debug]   env bindings ({} total): {:?}\n\
1233                                     [sui-debug]   with_scopes: {}",
1234                                    eval_file_ctx(),
1235                                    env.binding_count(),
1236                                    env.binding_names_preview(20),
1237                                    env.with_scope_count(),
1238                                );
1239                            }
1240                        }
1241                        if crate::value::in_promise_eval() {
1242                            // Same Promise softening as the with-scope
1243                            // branch above.
1244                            return Ok(Value::Null);
1245                        }
1246                        Err(EvalError::UndefinedVar(
1247                            format!("'{name}'{}", eval_file_ctx()),
1248                        ))
1249                        }
1250                    }
1251                }
1252            };
1253        }
1254        ast::Expr::Literal(lit) => {
1255            crate::perf::inc(crate::perf::Counter::EvalExpr);
1256            if crate::perf::enabled() {
1257                crate::perf::inc(crate::perf::Counter::ExprLiteral);
1258            }
1259            return eval_literal(lit);
1260        }
1261        ast::Expr::Paren(p) => {
1262            if let Some(inner) = p.expr() {
1263                return eval_expr(&inner, env);
1264            }
1265        }
1266        ast::Expr::Root(r) => {
1267            if let Some(inner) = r.expr() {
1268                return eval_expr(&inner, env);
1269            }
1270        }
1271        // Lambda: no recursion — just captures env into a closure.
1272        ast::Expr::Lambda(lam) => {
1273            crate::perf::inc(crate::perf::Counter::EvalExpr);
1274            if crate::perf::enabled() {
1275                crate::perf::inc(crate::perf::Counter::ExprLambda);
1276            }
1277            if let (Some(param), Some(body)) = (lam.param(), lam.body()) {
1278                return Ok(Value::Lambda(Rc::new(Closure {
1279                    param,
1280                    body,
1281                    env: env.clone(),
1282                })));
1283            }
1284        }
1285        _ => {}
1286    }
1287    // Complex expressions: need stacker for recursion safety
1288    stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || {
1289        eval_expr_inner(expr, env)
1290    })
1291}
1292
1293/// Inner implementation of [`eval_expr`] — called from the `stacker`
1294/// trampoline so that the stack is guaranteed to have headroom.
1295///
1296/// Uses a tail-call loop: for expressions in tail position (`if/else`,
1297/// `let..in`, `with`, `assert`, `paren`, `root`), we update the local
1298/// `expr` and `env` variables and loop instead of recursing. This
1299/// eliminates millions of stack frames in nixpkgs evaluation.
1300fn eval_expr_inner(expr: &ast::Expr, env: &Env) -> Result<Value, EvalError> {
1301    // Tail-call trampoline: expressions in tail position update these
1302    // and `continue` instead of recursing into eval_expr.
1303    let mut cur_expr = expr.clone();
1304    let mut cur_env = env.clone();
1305
1306    loop {
1307    crate::perf::inc(crate::perf::Counter::EvalExpr);
1308    // Track expression type distribution when profiling
1309    if crate::perf::enabled() {
1310        use crate::perf::Counter;
1311        let c = match &cur_expr {
1312            ast::Expr::Ident(_) => Counter::ExprIdent,
1313            ast::Expr::Literal(_) => Counter::ExprLiteral,
1314            ast::Expr::Str(_) => Counter::ExprStr,
1315            ast::Expr::List(_) => Counter::ExprList,
1316            ast::Expr::AttrSet(_) => Counter::ExprAttrs,
1317            ast::Expr::Select(_) => Counter::ExprSelect,
1318            ast::Expr::Apply(_) => Counter::ExprApply,
1319            ast::Expr::LetIn(_) => Counter::ExprLetIn,
1320            ast::Expr::IfElse(_) => Counter::ExprIfElse,
1321            ast::Expr::With(_) => Counter::ExprWith,
1322            ast::Expr::Lambda(_) => Counter::ExprLambda,
1323            ast::Expr::BinOp(_) => Counter::ExprBinOp,
1324            ast::Expr::HasAttr(_) => Counter::ExprHasAttr,
1325            ast::Expr::UnaryOp(_) => Counter::ExprUnaryOp,
1326            ast::Expr::Assert(_) => Counter::ExprAssert,
1327            ast::Expr::PathAbs(_) | ast::Expr::PathRel(_)
1328            | ast::Expr::PathHome(_) | ast::Expr::PathSearch(_) => Counter::ExprPath,
1329            _ => Counter::ExprOther,
1330        };
1331        crate::perf::inc(c);
1332    }
1333    let _guard = DepthGuard::enter()?;
1334    let env = &cur_env;
1335    match &cur_expr {
1336        ast::Expr::Literal(lit) => return eval_literal(lit),
1337
1338        ast::Expr::Str(s) => return eval_str(s, env),
1339
1340        ast::Expr::PathAbs(p) => {
1341            // An interpolated absolute path (`/a/${e}`) splices its
1342            // `${…}` parts; a plain one takes the raw-text shortcut.
1343            let parts = p.parts();
1344            if parts_have_interpolation(&parts) {
1345                return eval_interpol_path_parts(&parts, PathKind::Abs, env);
1346            }
1347            // Canonicalize like CppNix (`/.` → `/`, `.`/`..` collapse,
1348            // `..` clamps at root) — see the WHNF fast-path above.
1349            let text = crate::path::canon_abs(&p.syntax().text().to_string());
1350            return Ok(Value::Path(Box::new(SmolStr::from(text.as_str()))));
1351        }
1352        ast::Expr::PathRel(p) => {
1353            // Real Nix resolves `./foo.nix` against the directory
1354            // of the file that *contains* the literal, not the
1355            // process cwd. Use the current eval-file stack; fall
1356            // back to cwd when no file is being evaluated (e.g.,
1357            // top-level `sui eval`).
1358            //
1359            // An interpolated relative path (`./${x}.nix`) first splices
1360            // its `${…}` parts, then resolves the concatenated text the
1361            // same way — the interpolation is evaluated + string-coerced,
1362            // NOT treated as literal `${x}` text.
1363            let parts = p.parts();
1364            if parts_have_interpolation(&parts) {
1365                return eval_interpol_path_parts(&parts, PathKind::Rel, env);
1366            }
1367            let text = p.syntax().text().to_string();
1368            let resolved = if let Some(dir) = current_eval_dir() {
1369                let joined = dir.join(&text);
1370                // Use normalize_path instead of canonicalize so that
1371                // paths with ./  and .. are cleaned without requiring
1372                // the path to exist on disk.
1373                let norm = normalize_path(&joined);
1374                // A relative path literal (`./x`, `../..`) resolves against the
1375                // eval-dir, which for a fetched flake input is the sui fetcher
1376                // CACHE dir. CppNix resolves it against the input's
1377                // `/nix/store/<h>-source` STORE path, so the resulting path
1378                // VALUE must carry the store prefix (this is the value half of
1379                // the store↔cache seam — `materialize`/`dematerialize`). Lift
1380                // the cache path back to the store path so `toString ../..`
1381                // matches CppNix — the options.json `hasPrefix
1382                // <nix-darwin>.outPath decl` rewrite root (`prefix = ../..`).
1383                crate::path::dematerialize(&norm)
1384                    .to_string_lossy()
1385                    .into_owned()
1386            } else {
1387                text.clone()
1388            };
1389            return Ok(Value::Path(Box::new(SmolStr::from(resolved.as_str()))));
1390        }
1391        ast::Expr::PathHome(p) => {
1392            let parts = p.parts();
1393            if parts_have_interpolation(&parts) {
1394                return eval_interpol_path_parts(&parts, PathKind::Home, env);
1395            }
1396            let text = p.syntax().text().to_string();
1397            return Ok(Value::Path(Box::new(SmolStr::from(text.as_str()))));
1398        }
1399        ast::Expr::PathSearch(p) => {
1400            // `<name>` or `<name/sub/path>` — resolve via NIX_PATH
1401            // entries (parsed from the env var). If no NIX_PATH entry
1402            // matches, fall through to the literal text so the error
1403            // message points at the name the user wrote.
1404            let text = p.syntax().text().to_string();
1405            let inner = text
1406                .strip_prefix('<')
1407                .and_then(|s| s.strip_suffix('>'))
1408                .unwrap_or(&text);
1409            if let Some(resolved) = crate::builtins::resolve_search_path(inner) {
1410                return Ok(Value::Path(Box::new(SmolStr::from(resolved.as_str()))));
1411            }
1412            // CppNix: search path resolution failure is a throw
1413            // (catchable by tryEval). Used by nixpkgs impure-overlays.nix
1414            // which tries `import <nixpkgs-overlays>` inside tryEval.
1415            return Err(EvalError::Throw(
1416                format!("search path '{text}' not in NIX_PATH"),
1417            ));
1418        }
1419
1420        ast::Expr::Ident(ident) => {
1421            let name = ident_text(ident);
1422            return match name.as_str() {
1423                "true" => Ok(Value::Bool(true)),
1424                "false" => Ok(Value::Bool(false)),
1425                "null" => Ok(Value::Null),
1426                _ => {
1427                    env.lookup(&name)
1428                        .ok_or_else(|| EvalError::UndefinedVar(
1429                            format!("'{name}'{}", eval_file_ctx()),
1430                        ))
1431                }
1432            };
1433        }
1434
1435        ast::Expr::List(list) => {
1436            // Wrap list elements in thunks for maximum laziness.
1437            // CppNix wraps list elements — only forced when accessed.
1438            // This prevents eager evaluation of unused list elements
1439            // (e.g., nixpkgs overlay lists with thousands of entries).
1440            let values: Vec<Value> = list.items()
1441                .map(|e| maybe_thunk(&e, env, false, None))
1442                .collect();
1443            return Ok(Value::list(values));
1444        }
1445
1446        ast::Expr::AttrSet(set) => return eval_attrset(set, env),
1447
1448        ast::Expr::Select(sel) => return eval_select(sel, env),
1449
1450        ast::Expr::HasAttr(ha) => return eval_has_attr(ha, env),
1451
1452        ast::Expr::UnaryOp(op) => return eval_unary_op(op, env),
1453
1454        ast::Expr::BinOp(binop) => {
1455            let lhs_expr = binop
1456                .lhs()
1457                .ok_or_else(|| EvalError::ParseError("binop missing lhs".to_string()))?;
1458            let rhs_expr = binop
1459                .rhs()
1460                .ok_or_else(|| EvalError::ParseError("binop missing rhs".to_string()))?;
1461            let kind = binop
1462                .operator()
1463                .ok_or_else(|| EvalError::ParseError("binop missing operator".to_string()))?;
1464            return eval_binop(kind, &lhs_expr, &rhs_expr, env);
1465        }
1466
1467        ast::Expr::Apply(app) => return eval_apply(app, env),
1468
1469        ast::Expr::IfElse(ie) => {
1470            let cond = ie
1471                .condition()
1472                .ok_or_else(|| EvalError::ParseError("if missing condition".to_string()))?;
1473            let body = ie
1474                .body()
1475                .ok_or_else(|| EvalError::ParseError("if missing then body".to_string()))?;
1476            let else_body = ie
1477                .else_body()
1478                .ok_or_else(|| EvalError::ParseError("if missing else body".to_string()))?;
1479            if force_concrete(&eval_expr(&cond, env)?)?.as_bool()? {
1480                cur_expr = body;
1481            } else {
1482                cur_expr = else_body;
1483            }
1484            // env stays the same — tail call
1485            continue;
1486        }
1487
1488        ast::Expr::Assert(assert) => {
1489            let cond = assert
1490                .condition()
1491                .ok_or_else(|| EvalError::ParseError("assert missing condition".to_string()))?;
1492            let body = assert
1493                .body()
1494                .ok_or_else(|| EvalError::ParseError("assert missing body".to_string()))?;
1495            if !force_concrete(&eval_expr(&cond, env)?)?.as_bool()? {
1496                return Err(EvalError::AssertionFailed(eval_file_ctx()));
1497            }
1498            cur_expr = body;
1499            continue;
1500        }
1501
1502        ast::Expr::With(with) => {
1503            let ns = with
1504                .namespace()
1505                .ok_or_else(|| EvalError::ParseError("with missing namespace".to_string()))?;
1506            let body = with
1507                .body()
1508                .ok_or_else(|| EvalError::ParseError("with missing body".to_string()))?;
1509            // Don't force the namespace yet — store as a lazy value.
1510            // CppNix evaluates with-scopes lazily: the namespace is only
1511            // forced when a name lookup actually falls through lexical scope.
1512            // This is critical for `fix (self: with self; { … })` patterns
1513            // used throughout nixpkgs.
1514            //
1515            // M2.6 ROOT #4a (byte-verified): `eval_expr(&ns, env)?` was NOT
1516            // lazy — it EVALUATED the namespace expression eagerly at
1517            // `with`-entry.  For `with (throw "X"); body` that runs the
1518            // throw; for `with config.services.borgbackup; { … }` (nixpkgs'
1519            // module `config` shape) it forces `config.services.borgbackup`
1520            // the instant the `with`-body's WHNF/keys are demanded (during
1521            // module collection's `pushDownProperties`), re-entering the
1522            // mid-force `config` fixpoint → the empty-Promise partial →
1523            // `null` softening → `concatLists null`.  cppnix stores the
1524            // namespace as a thunk and forces it ONLY when a bare-ident
1525            // lookup actually falls through lexical scope into the `with`.
1526            // Reduced repro (no module system, iterates in ms):
1527            //   `builtins.attrNames (with (throw "X"); { a = 1; })`
1528            //   nix → [ "a" ] ; sui (before) → throws "X".
1529            // `maybe_thunk` keeps the fast-path for an already-resolved
1530            // ident namespace (no thunk overhead) while deferring any
1531            // non-trivial namespace (Select / Apply / throw) into a lazy
1532            // thunk the scope-lookup path (`Env::lookup_fast`) forces only
1533            // on fallthrough.
1534            let scope_val = maybe_thunk(&ns, env, false, None);
1535            let new_env = env.child().with_scope(scope_val);
1536            cur_expr = body;
1537            cur_env = new_env;
1538            continue;
1539        }
1540
1541        ast::Expr::LetIn(letin) => {
1542            // ── plan-driven binding (`SUI_NORMALIZE=1`) ──────────────────
1543            //
1544            // `let` obeys the SAME merge rule as an attrset literal, and sui
1545            // never implemented it: `let a = {b=1;}; a = {c=2;}; in a` is
1546            // `{b=1;c=2;}` in nix and was `{c=2;}` here — silent key loss on
1547            // legal nix. A `let` takes the SCOPE rather than the attrset,
1548            // because it is a binder for a body and produces no attrset.
1549            //
1550            // A `None` means the group has no duplicate and no dotted path,
1551            // so the existing path is already correct — see `normalize_env`.
1552            if crate::normalize_env::enabled() {
1553                let src_id = CURRENT_SOURCE_ID.with(std::cell::Cell::get);
1554                let offset = u32::from(letin.syntax().text_range().start());
1555                if let Some(plan) =
1556                    crate::normalize_env::plan_for_node(letin, true, src_id, offset)
1557                {
1558                    let (_attrs, scope) = bind_plan_group(&plan, env)?;
1559                    let body = letin.body().ok_or_else(|| {
1560                        EvalError::ParseError("let missing body".to_string())
1561                    })?;
1562                    cur_expr = body;
1563                    cur_env = scope;
1564                    continue;
1565                }
1566            }
1567
1568            let mut new_env = env.child();
1569
1570            // Phase 1: Create thunks with a dummy env and bind them.
1571            // Collect (key, thunk) pairs so we can update envs later.
1572            let mut thunks: Vec<(String, Thunk)> = Vec::new();
1573
1574            // Track which names have been defined so far in this scope.
1575            // Used by maybe_thunk to resolve backward references directly
1576            // instead of creating wasteful thunks.
1577            let mut defined_so_far: HashSet<String> = HashSet::new();
1578
1579            // Accumulator for dotted-path bindings (`let a.b = 1; a.c = 2; ...`).
1580            // Leaf values are wrapped in thunks so they can reference
1581            // sibling let-bindings (the let scope is recursive in Nix).
1582            let mut dotted_attrs: NixAttrs = NixAttrs::new();
1583
1584            // Pre-pass: collect every binding name in this let-scope
1585            // (single-key bindings + top-level keys of dotted paths +
1586            // names from inherit clauses).  Used by the recursive-thunk
1587            // detector below — a binding is part of the mutual fix-point
1588            // if its RHS references ANY of these names.
1589            //
1590            // D1 (`SUI_SCOPE_NARROW>=1`) — `names_complete` is the honesty half
1591            // of the narrowing. Narrowing is only sound while
1592            // `let_scope_names` is a COMPLETE list of what this scope binds: a
1593            // binding is judged "reaches no sibling" by intersecting its RHS's
1594            // free variables with that set, so a name MISSING from it reads as
1595            // an outer reference and the binding wrongly keeps the outer env.
1596            // A head that does not resolve here contributes nothing, so the
1597            // whole scope forfeits narrowing rather than narrow on a partial
1598            // set. (`Dynamic` heads are excluded even when they do resolve —
1599            // the name is computed, so it is not a syntactic property of the
1600            // scope.) Nothing about the EVALUATION below changes; this only
1601            // decides whether the optimisation is allowed to apply.
1602            let mut names_complete = true;
1603            let let_scope_names: HashSet<String> = {
1604                let mut s = HashSet::new();
1605                for entry in letin.entries() {
1606                    match entry {
1607                        ast::Entry::AttrpathValue(apv) => {
1608                            if let Some(attrpath) = apv.attrpath() {
1609                                if let Some(first) = attrpath.attrs().next() {
1610                                    if let ast::Attr::Dynamic(_) = &first {
1611                                        names_complete = false;
1612                                    }
1613                                    if let Ok(name) = eval_attr(&first, env) {
1614                                        s.insert(name);
1615                                    } else {
1616                                        names_complete = false;
1617                                    }
1618                                } else {
1619                                    names_complete = false;
1620                                }
1621                            } else {
1622                                names_complete = false;
1623                            }
1624                        }
1625                        ast::Entry::Inherit(inherit) => {
1626                            for attr in inherit.attrs() {
1627                                if let ast::Attr::Dynamic(_) = &attr {
1628                                    names_complete = false;
1629                                }
1630                                if let Ok(name) = eval_attr(&attr, env) {
1631                                    s.insert(name);
1632                                } else {
1633                                    names_complete = false;
1634                                }
1635                            }
1636                        }
1637                    }
1638                }
1639                s
1640            };
1641            let narrow = scope_narrow_enabled() && names_complete;
1642
1643            // D2 (`SUI_SCOPE_NARROW=2`) — the CLUSTER env.
1644            //
1645            // D1 alone is not enough, and the reason is the shape of the
1646            // graph: free-variable analysis is per-binding on the
1647            // `thunk -> env` edge, but the `env -> thunk` edge is SHARED. One
1648            // binding that really does reach a sibling keeps `new_env` alive,
1649            // and `new_env` holds EVERY binding in the scope — so a single
1650            // recursive `f` re-pins all fifty innocent leaves and the footprint
1651            // is unchanged. (That is the P4 row, and it is why the headline
1652            // gate is too easy: D1 greens it while doing nothing here.)
1653            //
1654            // The fix is to stop pointing the survivors at the whole scope.
1655            // Phase 2 re-points them at a `fix_env` carrying ONLY the names the
1656            // pinned bindings can actually reach — their own names plus
1657            // `refs ∩ scope_names`. The body still gets the full `new_env`, so
1658            // nothing the LET EXPRESSION evaluates to can change; only the
1659            // envs captured by thunks shrink.
1660            let cluster = narrow && scope_cluster_enabled();
1661            // Every (name, value) bound into `new_env`, so the pinned subset can
1662            // be re-bound into `fix_env`. Allocated only under D2.
1663            let mut all_bound: Vec<(String, Value)> = Vec::new();
1664            // The names that stayed pinned, and the free-variable sets of the
1665            // bindings behind them. `pin` needs only the UNION of those sets, so
1666            // no name→refs association is required — and that union already IS
1667            // the fixpoint: a name added to `pin` that is not itself a pinned
1668            // binding contributes no further refs, and one that is has its refs
1669            // in the union already.
1670            let mut pinned_names: HashSet<String> = HashSet::new();
1671            let mut pinned_refs: Vec<HashSet<SmolStr>> = Vec::new();
1672            // A dotted path (`let a.b = 1;`) pushes LEAF thunks whose names are
1673            // inner path segments, not scope names, and whose free variables are
1674            // never computed here — so `fix_env` cannot be shown to carry what
1675            // they need. Such a scope forfeits D2 (D1 still applies).
1676            let mut has_dotted = false;
1677
1678            for entry in letin.entries() {
1679                match entry {
1680                    ast::Entry::AttrpathValue(ref apv) => {
1681                        let attrpath = apv.attrpath().ok_or_else(|| {
1682                            EvalError::ParseError("binding missing attrpath".to_string())
1683                        })?;
1684                        let value_expr = apv.value().ok_or_else(|| {
1685                            EvalError::ParseError("binding missing value".to_string())
1686                        })?;
1687                        let mut path_keys: Vec<String> = attrpath
1688                            .attrs()
1689                            .map(|a| eval_attr(&a, env))
1690                            .collect::<Result<_, _>>()?;
1691                        if path_keys.len() == 1 {
1692                            let key = path_keys.pop().unwrap();
1693                            // Self/mutual-recursive detection: any binding
1694                            // whose RHS references its own name OR any
1695                            // SIBLING let-scope name is part of the let's
1696                            // mutual fix-point.  Mark as recursive so
1697                            // inner re-entrance during force returns a
1698                            // Promise sentinel instead of erroring with
1699                            // InfiniteRecursion.  This is the M2.6
1700                            // module-system fix path (cppnix's
1701                            // lib/modules.nix uses a deep let-scope with
1702                            // declaredConfig / options / matchedOptions /
1703                            // resultsByName / modules all transitively
1704                            // cycling through each other).
1705                            //
1706                            // `let_scope_names` is collected upfront in a
1707                            // pre-pass so each binding sees every other
1708                            // binding name (not just earlier ones).
1709                            // O(N) not O(N²): compute the RHS's referenced-name
1710                            // set ONCE (memoized), then intersect with the
1711                            // let-scope names. Byte-identical to the prior
1712                            // `references(key) OR references(any sibling)`:
1713                            // chaining `key` covers the self-reference case
1714                            // regardless of whether `key ∈ let_scope_names`.
1715                            let referenced = referenced_idents(&value_expr);
1716                            let in_mutual_cycle = std::iter::once(&key)
1717                                .chain(let_scope_names.iter())
1718                                .any(|n| referenced.contains(n.as_str()));
1719                            let value = if in_mutual_cycle {
1720                                Value::Thunk(Thunk::new_suspended_recursive(
1721                                    value_expr.clone(),
1722                                    env.clone(),
1723                                ))
1724                            } else {
1725                                maybe_thunk(&value_expr, env, true, Some(&defined_so_far))
1726                            };
1727                            new_env.bind(key.clone(), value.clone());
1728                            if cluster {
1729                                all_bound.push((key.clone(), value.clone()));
1730                            }
1731                            if let Value::Thunk(t) = &value {
1732                                // D1: `in_mutual_cycle` is ALREADY the
1733                                // forward-complete "reaches a sibling"
1734                                // predicate here (`let_scope_names` is a full
1735                                // pre-pass, unlike the `rec` arm's
1736                                // backward-only one), so it doubles as the
1737                                // needs-scope test at zero extra cost — no
1738                                // second tree walk.
1739                                //
1740                                // When it is false the RHS references nothing
1741                                // this scope binds, so every name it CAN
1742                                // resolve resolves identically in `env` and in
1743                                // `new_env`: `Env::child` copies `with_scopes`,
1744                                // `eval_file` and `source_id` verbatim, and the
1745                                // only added bindings are the let-scope names
1746                                // this RHS provably does not mention. Skipping
1747                                // the re-point is therefore byte-neutral, and
1748                                // it is what leaves the thunk holding the OUTER
1749                                // env instead of closing
1750                                // `thunk -> new_env -> thunk`.
1751                                if in_mutual_cycle || !narrow {
1752                                    thunks.push((key.clone(), t.clone()));
1753                                    if cluster {
1754                                        pinned_names.insert(key.clone());
1755                                        pinned_refs.push(referenced);
1756                                    }
1757                                    crate::value::census::scope_pinned();
1758                                } else {
1759                                    crate::value::census::scope_narrowed();
1760                                }
1761                            }
1762                            defined_so_far.insert(key);
1763                        } else if path_keys.len() > 1 {
1764                            // Multi-segment dotted path: build a nested
1765                            // attrset with thunks at the leaves so the
1766                            // value expression can reference sibling
1767                            // let-bindings.
1768                            has_dotted = true;
1769                            let key = path_keys[0].clone();
1770                            let value = build_nested_attr_thunk(
1771                                &path_keys[1..],
1772                                &value_expr,
1773                                env,
1774                                &mut thunks,
1775                            );
1776                            merge_nested_insert(&mut dotted_attrs, key, value);
1777                        }
1778                    }
1779                    ast::Entry::Inherit(ref inherit) => {
1780                        if let Some(from) = inherit.from() {
1781                            let source_expr = from.expr().ok_or_else(|| {
1782                                EvalError::ParseError(
1783                                    "inherit from missing expr".to_string(),
1784                                )
1785                            })?;
1786                            // D1: every `InheritSelect` in this clause shares
1787                            // ONE source thunk, and `Thunk::update_env`
1788                            // delegates straight through to it — so all N
1789                            // pushes re-point the SAME env. Whether that
1790                            // re-point is needed is therefore a property of the
1791                            // source expression alone, computed ONCE above the
1792                            // loop instead of N times inside it. Guarded by
1793                            // `!narrow ||` so the default path does not pay the
1794                            // walk at all.
1795                            let source_refs: Option<HashSet<SmolStr>> = if narrow {
1796                                Some(referenced_idents(&source_expr))
1797                            } else {
1798                                None
1799                            };
1800                            let source_needs_scope = match &source_refs {
1801                                Some(refs) => let_scope_names
1802                                    .iter()
1803                                    .any(|n| refs.contains(n.as_str())),
1804                                None => true,
1805                            };
1806                            // Create ONE shared source thunk per
1807                            // `inherit (source)` clause. All inherited
1808                            // names share it via Rc clone — the source
1809                            // is evaluated at most once.
1810                            let source_thunk = Thunk::new_suspended(
1811                                source_expr, env.clone(),
1812                            );
1813                            for attr in inherit.attrs() {
1814                                let name = eval_attr(&attr, env)?;
1815                                let thunk = Thunk::new_inherit_select(
1816                                    source_thunk.clone(),
1817                                    name.clone(),
1818                                );
1819                                new_env.bind(name.clone(), Value::Thunk(thunk.clone()));
1820                                if cluster {
1821                                    all_bound.push((
1822                                        name.clone(),
1823                                        Value::Thunk(thunk.clone()),
1824                                    ));
1825                                }
1826                                if source_needs_scope {
1827                                    if cluster {
1828                                        pinned_names.insert(name.clone());
1829                                    }
1830                                    thunks.push((name, thunk));
1831                                    crate::value::census::scope_pinned();
1832                                } else {
1833                                    crate::value::census::scope_narrowed();
1834                                }
1835                            }
1836                            // One refs set for the whole clause — every name in
1837                            // it re-points the SAME shared source thunk.
1838                            if cluster
1839                                && source_needs_scope
1840                                && let Some(refs) = source_refs
1841                            {
1842                                pinned_refs.push(refs);
1843                            }
1844                        } else {
1845                            // `inherit name1 name2 ...` from the
1846                            // enclosing lexical scope. This stays
1847                            // eager because the names already exist
1848                            // in `env` — no fixpoint involved.
1849                            for attr in inherit.attrs() {
1850                                let name = eval_attr(&attr, env)?;
1851                                let value = env.lookup(&name).ok_or_else(|| {
1852                                    EvalError::UndefinedVar(
1853                                        format!("'{name}'{}", eval_file_ctx()),
1854                                    )
1855                                })?;
1856                                if cluster {
1857                                    all_bound.push((name.clone(), value.clone()));
1858                                }
1859                                new_env.bind(name, value);
1860                            }
1861                        }
1862                    }
1863                }
1864            }
1865
1866            // Phase 1b: Bind accumulated dotted-path attrs into new_env.
1867            // Note: CppNix rejects `inherit (src) x; x.y = ...;` as a
1868            // duplicate definition, so we do not attempt to merge with
1869            // existing inherit thunks — just bind directly.
1870            for (key, value) in dotted_attrs.iter() {
1871                new_env.bind(key.clone(), value.clone());
1872                if cluster {
1873                    all_bound.push((key.clone(), value.clone()));
1874                }
1875            }
1876
1877            // D2: the cluster env the survivors get re-pointed at, in place of
1878            // the whole scope. Built only when it can actually shrink anything
1879            // — some binding pinned, some binding not, and no dotted path (see
1880            // `has_dotted`).
1881            let fix_env: Option<Env> = if cluster && !has_dotted && !thunks.is_empty() {
1882                // `pin` = the pinned names, plus every scope name they can
1883                // reach. This union is already the fixpoint: a name pulled in
1884                // that is not itself pinned contributes no further refs (its
1885                // own thunk still holds the OUTER env and so resolves entirely
1886                // outside this scope), and one that is pinned had its refs in
1887                // the union from the start.
1888                let mut pin = pinned_names;
1889                for refs in &pinned_refs {
1890                    for n in &let_scope_names {
1891                        if refs.contains(n.as_str()) {
1892                            pin.insert(n.clone());
1893                        }
1894                    }
1895                }
1896                if pin.len() < all_bound.len() {
1897                    let mut fe = env.child();
1898                    for (name, value) in &all_bound {
1899                        if pin.contains(name) {
1900                            fe.bind(name.clone(), value.clone());
1901                        }
1902                    }
1903                    Some(fe)
1904                } else {
1905                    None
1906                }
1907            } else {
1908                None
1909            };
1910
1911            // Phase 2: Update all thunks to capture the final env
1912            // (which now has all names bound).
1913            let phase2_env: &Env = fix_env.as_ref().unwrap_or(&new_env);
1914            for (_key, thunk) in &thunks {
1915                thunk.update_env(phase2_env);
1916            }
1917
1918            let body = letin
1919                .body()
1920                .ok_or_else(|| EvalError::ParseError("let missing body".to_string()))?;
1921            cur_expr = body;
1922            cur_env = new_env;
1923            continue;
1924        }
1925
1926        ast::Expr::Lambda(lam) => {
1927            let param = lam
1928                .param()
1929                .ok_or_else(|| EvalError::ParseError("lambda missing param".to_string()))?;
1930            let body = lam
1931                .body()
1932                .ok_or_else(|| EvalError::ParseError("lambda missing body".to_string()))?;
1933            return Ok(Value::Lambda(Rc::new(Closure {
1934                param,
1935                body,
1936                env: env.clone(),
1937            })));
1938        }
1939
1940        ast::Expr::Paren(p) => {
1941            let inner = p
1942                .expr()
1943                .ok_or_else(|| EvalError::ParseError("paren missing expr".to_string()))?;
1944            cur_expr = inner;
1945            continue;
1946        }
1947
1948        ast::Expr::Root(r) => {
1949            let inner = r
1950                .expr()
1951                .ok_or_else(|| EvalError::ParseError("root missing expr".to_string()))?;
1952            cur_expr = inner;
1953            continue;
1954        }
1955
1956        ast::Expr::LegacyLet(ll) => {
1957            // ── plan-driven binding (`SUI_NORMALIZE=1`) ──────────────────
1958            //
1959            // `eval_entries` carries the comment "Multi-key paths in let are
1960            // not standard; skip for now" and does exactly that — it SILENTLY
1961            // DISCARDS every multi-segment attrpath, so
1962            // `let { a.b = 1; a.c = 2; body = a; }` loses both. The bytecode
1963            // VM has always handled this correctly, which makes the walker
1964            // the engine that is behind here.
1965            if crate::normalize_env::enabled() {
1966                let src_id = CURRENT_SOURCE_ID.with(std::cell::Cell::get);
1967                let offset = u32::from(ll.syntax().text_range().start());
1968                if let Some(plan) =
1969                    crate::normalize_env::plan_for_node(ll, true, src_id, offset)
1970                {
1971                    let (_attrs, scope) = bind_plan_group(&plan, env)?;
1972                    return scope.lookup("body").ok_or_else(|| {
1973                        EvalError::AttrNotFound(format!(
1974                            "'body' in legacy let{}",
1975                            eval_file_ctx()
1976                        ))
1977                    });
1978                }
1979            }
1980
1981            let mut new_env = env.child();
1982            eval_entries(ll, &mut new_env)?;
1983            // legacy let returns the `body` attr from its bindings
1984            return new_env
1985                .lookup("body")
1986                .ok_or_else(|| EvalError::AttrNotFound(
1987                    format!("'body' in legacy let{}", eval_file_ctx()),
1988                ));
1989        }
1990
1991        ast::Expr::CurPos(_) => return Err(EvalError::NotImplemented("__curPos".to_string())),
1992        ast::Expr::Error(_) => return Err(EvalError::ParseError("parse error node".to_string())),
1993    } // match
1994    } // loop — unreachable, all arms either return or continue
1995}
1996
1997fn eval_literal(lit: &ast::Literal) -> Result<Value, EvalError> {
1998    use ast::LiteralKind;
1999    match lit.kind() {
2000        LiteralKind::Integer(tok) => {
2001            let n = tok
2002                .value()
2003                .map_err(|e| EvalError::ParseError(format!("invalid integer: {e}")))?;
2004            Ok(Value::Int(n))
2005        }
2006        LiteralKind::Float(tok) => {
2007            let f = tok
2008                .value()
2009                .map_err(|e| EvalError::ParseError(format!("invalid float: {e}")))?;
2010            Ok(Value::Float(f))
2011        }
2012        LiteralKind::Uri(tok) => Ok(Value::string(tok.syntax().text().to_string())),
2013    }
2014}
2015
2016/// Result of walking an attrpath on a base value.
2017enum TraverseResult {
2018    /// All keys found; contains the leaf value.
2019    Found(Value),
2020    /// A key was missing; contains the missing key name.
2021    Missing(String),
2022    /// A non-attrset value was encountered during traversal.
2023    NotAttrs(Value),
2024}
2025
2026/// Walk an attrpath on a base value, forcing at each level.
2027///
2028/// Returns `Found(leaf)` when every key exists, `Missing(key)` when
2029/// a key is absent, or `NotAttrs(v)` when a non-attrset is encountered.
2030fn traverse_attrpath(
2031    base: Value,
2032    attrpath: &rnix::ast::Attrpath,
2033    env: &Env,
2034) -> Result<TraverseResult, EvalError> {
2035    let attrs: Vec<_> = attrpath.attrs().collect();
2036    let mut value = base;
2037    for (i, attr) in attrs.iter().enumerate() {
2038        let key = eval_attr(attr, env)?;
2039        // Force the current value to an attrset to select from it.
2040        let forced = force_value(&value)?;
2041        match forced {
2042            Value::Attrs(ref a) => match a.get(&key) {
2043                Some(v) => {
2044                    if i < attrs.len() - 1 {
2045                        // Intermediate step: force to attrset for next selection.
2046                        value = force_value(v)?;
2047                    } else {
2048                        // Final step: return WITHOUT forcing — let the caller
2049                        // decide when to force. Matches CppNix's lazy attr access.
2050                        value = v.clone();
2051                    }
2052                }
2053                None => return Ok(TraverseResult::Missing(key)),
2054            },
2055            _ => return Ok(TraverseResult::NotAttrs(forced)),
2056        }
2057    }
2058    Ok(TraverseResult::Found(value))
2059}
2060
2061fn eval_select(sel: &ast::Select, env: &Env) -> Result<Value, EvalError> {
2062    crate::perf::inc(crate::perf::Counter::Select);
2063    let base_expr = sel.expr().ok_or_else(|| {
2064        EvalError::ParseError("select missing expression".to_string())
2065    })?;
2066    // M2.6 bridge: in `expr.path or default`, an `InfiniteRecursion`
2067    // hit while forcing the LEFT side falls back to the default —
2068    // operationally matches cppnix, which avoids the cycle entirely
2069    // via lazy attribute access during fix-point evaluation.  Without
2070    // a default, the recursion propagates as a real error.  Other
2071    // error kinds (Throw, TypeError, …) always propagate so user
2072    // bugs aren't masked.  Removed when the underlying fix-point /
2073    // lazy-access semantics land — see docs/M2.6-MODULE-SYSTEM-FIXPOINT.md.
2074    let base_result = eval_expr(&base_expr, env)
2075        .and_then(|v| force_concrete(&v).map(Concrete::into_value));
2076    let base = match base_result {
2077        Ok(v) => v,
2078        Err(EvalError::InfiniteRecursion(_)) if sel.default_expr().is_some() => {
2079            return eval_expr(&sel.default_expr().expect("checked"), env);
2080        }
2081        Err(e) => return Err(e),
2082    };
2083    let base_type = base.type_name();
2084    let attrpath = sel.attrpath().ok_or_else(|| {
2085        EvalError::ParseError("select missing attrpath".to_string())
2086    })?;
2087    // M2.6 bridge: when the blackhole-bridge sentinels are active,
2088    // an attribute lookup that misses (`AttrNotFound`) or hits a
2089    // non-attrset intermediate (`NotAttrs`) on the bridge's empty
2090    // sentinel value gets resolved to `null` instead of erroring.
2091    // cppnix's partial attrset would have CARRIED the keys (with
2092    // their lazy values), so the lookup would succeed; null is the
2093    // cheapest sentinel that propagates through downstream code
2094    // without further type errors.
2095    //
2096    // M2.6 ROOT #4 CLOSED (2026-07-11): the `|| crate::value::in_promise_eval()`
2097    // clause that used to soften a mid-Promise `config.<x>` select-miss to
2098    // `null` is REMOVED.  It was the band-aid masking the two real over-forces
2099    // that ROOT #4a (the `with`-namespace eager eval, above) and ROOT #4b (the
2100    // dropped full-set leaf in `merge_nested_insert`, below) now fix at their
2101    // load-bearing cause.  Verified with the softening gone: both
2102    // `lib.nixosSystem { modules = []; }.config.system.name` → `"nixos"` and
2103    // `attrNames sys.options` → 53 (nix-parity), `sui parity` stays 35 match /
2104    // 0 regressions, 1324 sui-eval lib tests + 30 diff tests pass — nothing
2105    // depended on the sentinel any more.  The two explicit operator-gated
2106    // bridges below stay as opt-in experiments (default-off); only the
2107    // always-on Promise softening is retired.
2108    let bridge_active = std::env::var_os("SUI_BLACKHOLE_AS_EMPTY_ATTRS").is_some()
2109        || std::env::var_os("SUI_BLACKHOLE_AS_NULL").is_some();
2110    let traversal = traverse_attrpath(base, &attrpath, env);
2111    match traversal {
2112        Ok(TraverseResult::Found(v)) => Ok(v),
2113        Ok(TraverseResult::Missing(key)) => {
2114            if let Some(def) = sel.default_expr() {
2115                eval_expr(&def, env)
2116            } else if bridge_active {
2117                if std::env::var_os("SUI_M26_SELTRACE").is_some() {
2118                    let path: Vec<String> = sel.attrpath().map(|ap|
2119                        ap.attrs().map(|a| a.syntax().text().to_string()).collect()
2120                    ).unwrap_or_default();
2121                    eprintln!("[M26 SEL-MISS→null] base_type={base_type} path={path:?} missing-key={key}{}", eval_file_ctx());
2122                }
2123                if let Ok(filt) = std::env::var("SUI_M26_HARDSOFTEN") {
2124                    let path: Vec<String> = sel.attrpath().map(|ap|
2125                        ap.attrs().map(|a| a.syntax().text().to_string()).collect()
2126                    ).unwrap_or_default();
2127                    if path.iter().any(|p| p.contains(&filt)) {
2128                        return Err(EvalError::type_error(format!(
2129                            "M26-HARDSOFTEN path={path:?} key={key}"
2130                        )));
2131                    }
2132                }
2133                Ok(Value::Null)
2134            } else {
2135                Err(EvalError::AttrNotFound(
2136                    format!("'{key}'{}", eval_file_ctx()),
2137                ))
2138            }
2139        }
2140        Ok(TraverseResult::NotAttrs(forced)) => {
2141            // CppNix: `expr.a.b or default` falls back to default for
2142            // ANY error in the path — including intermediate values
2143            // that aren't attrsets (e.g., null). The module system
2144            // relies on this: `x.options.type.name or null` must
2145            // return null when x.options is null, not throw.
2146            if let Some(def) = sel.default_expr() {
2147                eval_expr(&def, env)
2148            } else if bridge_active {
2149                if let Ok(filt) = std::env::var("SUI_M26_HARDSOFTEN") {
2150                    let path: Vec<String> = sel.attrpath().map(|ap|
2151                        ap.attrs().map(|a| a.syntax().text().to_string()).collect()
2152                    ).unwrap_or_default();
2153                    if path.iter().any(|p| p.contains(&filt)) {
2154                        return Err(EvalError::type_error(format!(
2155                            "M26-HARDSOFTEN-NOTATTRS path={path:?} base_type={base_type}"
2156                        )));
2157                    }
2158                }
2159                return Ok(Value::Null);
2160            } else {
2161                if std::env::var("SUI_DEBUG_SELECT").is_ok() {
2162                    let path: Vec<String> = sel.attrpath().map(|ap|
2163                        ap.attrs().filter_map(|a| match a {
2164                            ast::Attr::Ident(i) => Some(i.to_string()),
2165                            ast::Attr::Str(s) => Some(format!("\"{}\"", s.syntax().text())),
2166                            ast::Attr::Dynamic(_) => Some("<dyn>".into()),
2167                        }).collect()
2168                    ).unwrap_or_default();
2169                    let dbg = format!("{:?}", forced);
2170                    let truncated = if dbg.len() > 200 { format!("{}…", &dbg[..200]) } else { dbg };
2171                    eprintln!("[SUI_DEBUG_SELECT] base_type={base_type} path={path:?} base={truncated}{}", eval_file_ctx());
2172                }
2173                Err(attach_trace(EvalError::type_error(
2174                    format!("cannot select from {base_type}"),
2175                )))
2176            }
2177        }
2178        // Same M2.6 bridge as on the base force above: if an
2179        // intermediate step in the attrpath traversal raises
2180        // InfiniteRecursion and `or default` was supplied, the
2181        // default is the operationally-correct value.
2182        Err(EvalError::InfiniteRecursion(_)) if sel.default_expr().is_some() => {
2183            eval_expr(&sel.default_expr().expect("checked"), env)
2184        }
2185        Err(e) => Err(e),
2186    }
2187}
2188
2189/// Evaluate `expr ? a.b.c` — check key presence without forcing value thunks.
2190fn eval_has_attr(ha: &ast::HasAttr, env: &Env) -> Result<Value, EvalError> {
2191    let base_expr = ha.expr().ok_or_else(|| {
2192        EvalError::ParseError("hasattr missing expression".to_string())
2193    })?;
2194    let base = force_concrete(&eval_expr(&base_expr, env)?)?.into_value();
2195    let attrpath = ha.attrpath().ok_or_else(|| {
2196        EvalError::ParseError("hasattr missing attrpath".to_string())
2197    })?;
2198    match traverse_attrpath(base, &attrpath, env)? {
2199        TraverseResult::Found(_) => Ok(Value::Bool(true)),
2200        TraverseResult::Missing(_) | TraverseResult::NotAttrs(_) => Ok(Value::Bool(false)),
2201    }
2202}
2203
2204fn eval_unary_op(op: &ast::UnaryOp, env: &Env) -> Result<Value, EvalError> {
2205    let inner = op
2206        .expr()
2207        .ok_or_else(|| EvalError::ParseError("unary op missing expr".to_string()))?;
2208    let val = force_value(&eval_expr(&inner, env)?)?;
2209    let kind = op
2210        .operator()
2211        .ok_or_else(|| EvalError::ParseError("unary op missing operator".to_string()))?;
2212    match kind {
2213        ast::UnaryOpKind::Negate => match val {
2214            Value::Int(n) => Ok(Value::Int(-n)),
2215            Value::Float(f) => Ok(Value::Float(-f)),
2216            _ => Err(EvalError::type_error(
2217                format!("cannot negate {}", val.type_name()),
2218            )),
2219        },
2220        ast::UnaryOpKind::Invert => Ok(Value::Bool(!val.as_bool()?)),
2221    }
2222}
2223
2224/// Builtins that must receive their argument UNFORCED (call-by-need). This is the
2225/// SINGLE source of truth consumed by BOTH `eval_apply` (which must THUNK the arg
2226/// instead of eager-evaluating it) AND the builtin apply arm (which must SKIP the
2227/// arg force). The two sites MUST agree: if `eval_apply` eager-evaluates the arg,
2228/// the apply-arm's force-skip is dead (the arg is already forced — or already
2229/// threw) upstream. They were previously inconsistent (only `tryEval` was thunked
2230/// in `eval_apply`), so `seq`/`deepSeq`/`addErrorContext`/`foldl'` silently got
2231/// eager args despite their apply-time exemption — the bug behind
2232/// `builtins.foldl' (_: x: x) (throw "…") […]` throwing instead of returning the
2233/// last element (nix's foldl' is NOT strict in the nul accumulator).
2234#[inline]
2235pub(crate) fn builtin_takes_lazy_arg(name: &str) -> bool {
2236    matches!(
2237        name,
2238        "tryEval" | "addErrorContext<partial>" | "seq<partial>" | "deepSeq<partial>" | "foldl'<p1>"
2239    )
2240}
2241
2242fn eval_apply(app: &ast::Apply, env: &Env) -> Result<Value, EvalError> {
2243    let func_expr = app
2244        .lambda()
2245        .ok_or_else(|| EvalError::ParseError("apply missing function".to_string()))?;
2246    let arg_expr = app
2247        .argument()
2248        .ok_or_else(|| EvalError::ParseError("apply missing argument".to_string()))?;
2249    let func = force_value(&eval_expr(&func_expr, env)?)?;
2250    // Lambda arguments are wrapped in a thunk for call-by-need semantics.
2251    // Thunk strategy depends on function type:
2252    // - Lambda: ALWAYS thunk (call-by-need, enables fixpoints)
2253    // - tryEval: ALWAYS thunk (must catch errors during force)
2254    // - Builtin: evaluate eagerly (builtins always force args anyway;
2255    //   thunking wastes Rc + OnceCell allocation per call)
2256    // - __functor: evaluate eagerly (will be applied immediately)
2257    let arg = match &func {
2258        Value::Lambda(_) => {
2259            // Call-by-need: the arg is thunked so it forces lazily. But a
2260            // PURE-CONSTANT arg (a literal, a non-interpolated string, or a
2261            // non-interpolated path) can never throw or diverge, so producing
2262            // its value directly is byte-neutral whether or not the lambda ever
2263            // forces it — identical eval-order-observable behavior, one fewer
2264            // never-forced thunk. This is `arg_pure_constant` ONLY: any arg that
2265            // could throw/diverge/observe a fixpoint (Ident with-scope, Select,
2266            // Apply, BinOp, …) stays fully thunked to preserve laziness.
2267            if let Some(v) = eval_pure_constant_arg(&arg_expr) {
2268                v
2269            } else {
2270                crate::perf::inc(crate::perf::Counter::ThunkSiteApplyArg);
2271                Value::Thunk(Thunk::new_suspended(arg_expr.clone(), env.clone()))
2272            }
2273        }
2274        Value::Builtin(b) if builtin_takes_lazy_arg(&b.name) => {
2275            // Call-by-need for the laziness-exempt builtins (tryEval / seq /
2276            // deepSeq / addErrorContext / foldl'<p1>): the arg MUST be thunked,
2277            // not eager-evaluated, so it forces only if/when the builtin demands
2278            // it. Kept in lockstep with the apply-arm skip via `builtin_takes_lazy_arg`.
2279            crate::perf::inc(crate::perf::Counter::ThunkSiteApplyArg);
2280            Value::Thunk(Thunk::new_suspended(arg_expr.clone(), env.clone()))
2281        }
2282        _ => eval_expr(&arg_expr, env)?,
2283    };
2284    apply(func, arg)
2285}
2286
2287/// If `arg_expr` is a PURE CONSTANT — a literal, a non-interpolated string, or
2288/// a non-interpolated absolute/home path — return its value directly (no thunk).
2289///
2290/// A pure constant has no free variables, cannot throw, cannot diverge, and has
2291/// no fixpoint/laziness interaction: `eval_expr(arg)` is total and produces the
2292/// exact value a suspended thunk of it would yield on force. Producing it
2293/// eagerly in a call-by-need arg position is therefore byte-neutral (the
2294/// lambda that never forces the arg observes no difference — the value is inert).
2295///
2296/// Returns `None` for EVERYTHING else (Ident — may hit a with-scope force;
2297/// Select/Apply/BinOp/If/… — may throw or diverge; interpolated Str/Path —
2298/// must force `${…}` lazily), which keeps those args fully thunked. `env` is
2299/// NOT threaded in because a pure constant needs no environment; if a match
2300/// arm ever needed `env`, it would not be a pure constant.
2301fn eval_pure_constant_arg(arg_expr: &ast::Expr) -> Option<Value> {
2302    match arg_expr {
2303        ast::Expr::Literal(lit) => eval_literal(lit).ok(),
2304        ast::Expr::Str(st) if !str_has_interpolation(st) => {
2305            // No interpolation ⇒ `eval_str` runs no force/coerce; env is unused.
2306            eval_str(st, &Env::new()).ok()
2307        }
2308        ast::Expr::PathAbs(p) if !parts_have_interpolation(&p.parts()) => {
2309            let text = crate::path::canon_abs(&p.syntax().text().to_string());
2310            Some(Value::Path(Box::new(SmolStr::from(text.as_str()))))
2311        }
2312        ast::Expr::PathHome(p) if !parts_have_interpolation(&p.parts()) => {
2313            let text = p.syntax().text().to_string();
2314            Some(Value::Path(Box::new(SmolStr::from(text.as_str()))))
2315        }
2316        _ => None,
2317    }
2318}
2319
2320fn eval_str(s: &ast::Str, env: &Env) -> Result<Value, EvalError> {
2321    let mut result = String::new();
2322    let mut ctx = StringContext::new();
2323    for part in s.normalized_parts() {
2324        match part {
2325            InterpolPart::Literal(text) => result.push_str(&text),
2326            InterpolPart::Interpolation(interpol) => {
2327                let expr = interpol.expr().ok_or_else(|| {
2328                    EvalError::ParseError("interpolation missing expr".to_string())
2329                })?;
2330                let val = force_value(&eval_expr(&expr, env)?)?;
2331                // CppNix string interpolation is copy-to-store coercion: an
2332                // interpolated source path (`"${./foo}"`) is NAR-copied into
2333                // the store and the store path is spliced in (with context),
2334                // never the raw filesystem path.
2335                let (s, c) = val.coerce_to_string_copy_to_store()?;
2336                result.push_str(&s);
2337                ctx.merge(&c);
2338            }
2339        }
2340    }
2341    Ok(Value::String(Rc::new(NixString::with_context(result, ctx))))
2342}
2343
2344/// Whether a list of path parts contains a `${…}` interpolation. When
2345/// it does not, the raw `.syntax().text()` shortcut is byte-identical
2346/// and cheaper, so the trivial fast paths stay on that shortcut.
2347fn parts_have_interpolation(parts: &[InterpolPart<rnix::ast::PathContent>]) -> bool {
2348    parts
2349        .iter()
2350        .any(|p| matches!(p, InterpolPart::Interpolation(_)))
2351}
2352
2353/// Whether a string literal contains any `${…}` interpolation part. A `false`
2354/// result means the string is a pure constant (`eval_str` runs no force/coerce
2355/// and cannot throw), so `maybe_thunk` may evaluate it eagerly byte-neutrally.
2356fn str_has_interpolation(s: &ast::Str) -> bool {
2357    s.normalized_parts()
2358        .iter()
2359        .any(|p| matches!(p, InterpolPart::Interpolation(_)))
2360}
2361
2362/// Evaluate an interpolatable path literal that contains `${…}` parts.
2363///
2364/// CppNix path interpolation (`./${x}.nix`, `/a/${e}`, `~/x/${e}`):
2365///   * each literal segment is spliced verbatim,
2366///   * each `${e}` is **plain**-coerced to a string with context
2367///     (NOT copy-to-store — path-typed interpolations splice the raw
2368///     store/filesystem path, e.g. `/bar/${./foo}` → `/bar/tmp/foo`),
2369///   * the concatenated text is then resolved exactly like the plain
2370///     path literal of the same kind (relative → joined + normalized
2371///     against the defining file's directory; absolute/home → verbatim),
2372///   * the result is a `path` value.
2373///
2374/// Parts come from rnix's `<PathKind>::parts()` which splits the path
2375/// token stream into `Literal(PathContent)` / `Interpolation(Interpol)`.
2376fn eval_interpol_path_parts(
2377    parts: &[InterpolPart<rnix::ast::PathContent>],
2378    kind: PathKind,
2379    env: &Env,
2380) -> Result<Value, EvalError> {
2381    let mut text = String::new();
2382    for part in parts {
2383        match part {
2384            InterpolPart::Literal(content) => text.push_str(content.text()),
2385            InterpolPart::Interpolation(interpol) => {
2386                let expr = interpol.expr().ok_or_else(|| {
2387                    EvalError::ParseError("path interpolation missing expr".to_string())
2388                })?;
2389                let val = force_value(&eval_expr(&expr, env)?)?;
2390                // Plain coercion (coerceMore = false): a path-typed
2391                // interpolation splices the raw path string, never a
2392                // copied-to-store hash path.
2393                let (s, _ctx) = val.coerce_to_string()?;
2394                text.push_str(&s);
2395            }
2396        }
2397    }
2398    let resolved = match kind {
2399        // Relative path: resolve against the defining file's directory,
2400        // mirroring the plain `PathRel` branch.
2401        PathKind::Rel => {
2402            if let Some(dir) = current_eval_dir() {
2403                let norm = normalize_path(&dir.join(&text));
2404                // Lift cache→store exactly like the plain `PathRel` branch (the
2405                // store↔cache seam value-half). Without this, an interpolated
2406                // relative-path literal (`./${x}`, `./modules/${name}.nix`)
2407                // inside a fetched flake input yielded a Value::Path holding the
2408                // fetcher CACHE dir instead of the input's `/nix/store/<h>-source`
2409                // path — so its `toString`/copy-to-store/inputSrc diverged from
2410                // CppNix (the plain `./x` sibling already dematerializes; the two
2411                // must agree).
2412                crate::path::dematerialize(&norm).to_string_lossy().into_owned()
2413            } else {
2414                // No eval-file context (top-level `sui eval -E`): the
2415                // plain branch keeps the raw text, so match it — but the
2416                // interpolation is still spliced.
2417                text
2418            }
2419        }
2420        // Absolute paths: canonicalize the concatenated text CppNix's way.
2421        // The `${e}` splice routinely introduces a `//` seam (`/bar/` +
2422        // `/tmp/foo`) or a `.`/`..` component that must collapse
2423        // (`/bar//tmp/foo` → `/bar/tmp/foo`), and `..` must clamp at root.
2424        // `canon_abs` is filesystem-free (works on not-yet-materialized
2425        // flake paths) and root-aware (unlike `normalize_path`, which pops
2426        // past root — the marquee-root divergence).
2427        PathKind::Abs => crate::path::canon_abs(&text),
2428        // Home paths (`~/…`) carry a leading `~` component, so they are
2429        // not absolute-rooted; keep the pre-existing normalization.
2430        PathKind::Home => normalize_path(std::path::Path::new(&text))
2431            .to_string_lossy()
2432            .into_owned(),
2433    };
2434    Ok(Value::Path(Box::new(SmolStr::from(resolved.as_str()))))
2435}
2436
2437/// Which kind of interpolatable path literal — governs how the
2438/// concatenated text is finally resolved.
2439#[derive(Clone, Copy)]
2440enum PathKind {
2441    Abs,
2442    Rel,
2443    Home,
2444}
2445
2446/// Evaluate an attribute name, requiring non-null.
2447/// Use `eval_attr_maybe_null` when null dynamic attrs should be skipped.
2448fn eval_attr(attr: &ast::Attr, env: &Env) -> Result<String, EvalError> {
2449    eval_attr_maybe_null(attr, env)?
2450        .ok_or_else(|| EvalError::TypeError("null dynamic attribute name".into()))
2451}
2452
2453/// Evaluate an attribute name. Returns `None` for null dynamic attrs
2454/// (CppNix silently omits attributes with null names).
2455fn eval_attr_maybe_null(attr: &ast::Attr, env: &Env) -> Result<Option<String>, EvalError> {
2456    match attr {
2457        ast::Attr::Ident(ident) => Ok(Some(ident_text(ident))),
2458        ast::Attr::Dynamic(dyn_) => {
2459            let expr = dyn_
2460                .expr()
2461                .ok_or_else(|| EvalError::ParseError("dynamic attr missing expr".to_string()))?;
2462            let val = force_value(&eval_expr(&expr, env)?)?;
2463            // CppNix: null dynamic attr name → skip the attribute entirely.
2464            // Used by nixpkgs module system: `${if cond then null else "name"} = value;`
2465            if val == Value::Null {
2466                return Ok(None);
2467            }
2468            Ok(Some(val.as_string()?.to_string()))
2469        }
2470        ast::Attr::Str(s) => {
2471            let val = eval_str(s, env)?;
2472            Ok(Some(val.as_string()?.to_string()))
2473        }
2474    }
2475}
2476
2477/// Get the text of an rnix Ident node.
2478pub(crate) fn ident_text(ident: &ast::Ident) -> String {
2479    // Fast path: a `NODE_IDENT` holds a single `TOKEN_IDENT`, whose `text()`
2480    // borrows the source `&str` directly from the green node — no
2481    // `PreorderWithTokens` cursor tree-walk and none of the `NodeData::new`
2482    // allocations that `syntax().text()` (a `SyntaxText` over the node's whole
2483    // descendant span) pays. Byte-identical fallback: the identifier `or` is
2484    // lexed as a nested `TOKEN_OR` (rnix quirk), so `ident_token()` is `None`
2485    // there — walk the full node text in that case, exactly as before.
2486    match ident.ident_token() {
2487        Some(tok) => tok.text().to_string(),
2488        None => ident.syntax().text().to_string(),
2489    }
2490}
2491
2492/// Byte offset of a STATIC attr key (`Ident` or `Str`) in its source text —
2493/// the position `builtins.unsafeGetAttrPos` reports for that key. Returns
2494/// `None` for a dynamic key (`${e}`), which has no fixed source position.
2495///
2496/// CppNix points a binding's position at the KEY token's start; rnix exposes
2497/// it via the syntax node's `text_range().start()`.
2498fn static_attr_offset(attr: &ast::Attr) -> Option<u32> {
2499    let node = match attr {
2500        ast::Attr::Ident(i) => i.syntax(),
2501        ast::Attr::Str(s) => s.syntax(),
2502        ast::Attr::Dynamic(_) => return None,
2503    };
2504    Some(u32::from(node.text_range().start()))
2505}
2506
2507/// Collect a literal attrset's static top-level KEY offsets into an
2508/// [`crate::pos::AttrPositions`] and attach it to `attrs` (behind the value's
2509/// `Rc<AttrPositions>` slot). Records only single-key static bindings — the
2510/// shape `attrTag`'s `tags_` (`{ app = …; file = …; }`) is built from and the
2511/// only shape `builtins.unsafeGetAttrPos` reads in nixpkgs. `None`-costs a
2512/// pointer when the set has no such keys (attaches nothing).
2513fn attach_attrset_positions(set: &ast::AttrSet, attrs: &mut NixAttrs, env: &Env) {
2514    // The FILE is the one the literal is being built in — from the eval-file
2515    // stack, which a thunk restores to its captured file when it forces. This
2516    // is correct under laziness: a `dock.nix` attrset literal forced later
2517    // records `dock.nix`, not whatever file is top-of-stack at force time.
2518    // (`current_source_id`/`CURRENT_SOURCE_ID` is per-`eval_with_file`, NOT
2519    // per-env, so it would mis-attribute a lazily-forced literal.)
2520    let mut table = crate::pos::AttrPositions::new(current_eval_file());
2521    for entry in set.entries() {
2522        if let ast::Entry::AttrpathValue(apv) = entry {
2523            let Some(attrpath) = apv.attrpath() else { continue };
2524            let path_attrs: Vec<ast::Attr> = attrpath.attrs().collect();
2525            // A dotted path `a.b = …` desugars to a nested set and CppNix gives
2526            // the OUTER key the position of the path's HEAD, so record
2527            // `path_attrs[0]` whatever the length. This previously skipped any
2528            // multi-segment path, on the assumption that nixpkgs never asks for
2529            // a dotted tag's position. Measured — for
2530            // `{ …; nested.deep = 3; }` at line 6:
2531            //   nix  nested=6:3      sui  nested=NULL
2532            let Some(head) = path_attrs.first() else { continue };
2533            let Some(offset) = static_attr_offset(head) else { continue };
2534            // Resolve the static key name (Ident/Str) — never forces (a
2535            // dynamic key already returned None above).
2536            if let Ok(Some(name)) = eval_attr_maybe_null(&path_attrs[0], env) {
2537                table.insert(intern(&name), offset);
2538            }
2539        } else if let ast::Entry::Inherit(inh) = entry {
2540            // `inherit x;` and `inherit (src) x;` BIND an attribute exactly as
2541            // `x = …` does, and CppNix gives each inherited name the position of
2542            // its own ident. Skipping them left every inherited key
2543            // position-less — which is most of nixpkgs' `lib`, since
2544            // `lib/default.nix` re-exports through
2545            // `inherit (self.options) mkOption …`. Measured before the fix:
2546            //   unsafeGetAttrPos "mkOption" nixpkgs.lib
2547            //     nix …-source/lib/default.nix     sui null
2548            //
2549            // An earlier attempt at this arm was reverted for reporting line 1;
2550            // that was `pos::line_col` returning a constant, NOT this arm. With
2551            // the real offset→line/column conversion in place it resolves
2552            // exactly.
2553            for attr in inh.attrs() {
2554                let Some(offset) = static_attr_offset(&attr) else { continue };
2555                if let Ok(Some(name)) = eval_attr_maybe_null(&attr, env) {
2556                    table.insert(intern(&name), offset);
2557                }
2558            }
2559        }
2560    }
2561    if !table.is_empty() {
2562        attrs.set_positions(std::rc::Rc::new(table));
2563    }
2564}
2565
2566fn eval_attrset(set: &ast::AttrSet, env: &Env) -> Result<Value, EvalError> {
2567    crate::perf::inc(crate::perf::Counter::Attrset);
2568    let mut attrs = NixAttrs::new();
2569    let is_rec = set.rec_token().is_some();
2570
2571    // ── plan-driven construction (`SUI_NORMALIZE=1`) ──────────────────────
2572    //
2573    // Wired for `rec` first and the non-rec branch last, deliberately. The
2574    // `rec` branch was WRONG (its Phase 1b does a destructive `attrs.insert`
2575    // where the non-rec branch merges), so any change there could only
2576    // improve it. The non-rec branch is the one path that was already correct
2577    // ON KEYS — it merges VALUES via `merge_nested_insert` — and it carries
2578    // every fleet evaluation, so it went last and on its own.
2579    //
2580    // Correct-on-keys is not correct: a value merge gets the key set right and
2581    // the SCOPE wrong, which is why `let b=5; in { a=rec{c=b;}; a={b=9;}; }`
2582    // answered `c=5` where nix says `c=9`. The second side's `b=9` belongs to
2583    // the FIRST node's rec scope, and no value-level merge can put it there.
2584    //
2585    // A `None` here is a POSITIVE statement, not a fallback: `sui-normalize`
2586    // records a group only when it has a duplicate static key or a dotted
2587    // path, so no plan means this group is already built correctly.
2588    if crate::normalize_env::enabled() {
2589        let src_id = CURRENT_SOURCE_ID.with(std::cell::Cell::get);
2590        let offset = u32::from(set.syntax().text_range().start());
2591        if let Some(plan) = crate::normalize_env::plan_for_node(set, is_rec, src_id, offset) {
2592            return eval_plan_group(&plan, env);
2593        }
2594    }
2595
2596    if is_rec {
2597        let mut rec_env = env.child();
2598        let mut thunks: Vec<(String, Thunk)> = Vec::new();
2599
2600        // Track which names have been defined so far in this scope.
2601        // Used by maybe_thunk to resolve backward references directly
2602        // instead of creating wasteful thunks.
2603        let mut defined_so_far: HashSet<String> = HashSet::new();
2604
2605        // Accumulator for dotted-path bindings (`rec { a.b = 1; a.c = 2; ... }`).
2606        // Leaf values are wrapped in thunks so they participate in the
2607        // recursive env fixpoint, matching CppNix semantics where
2608        // `rec { types.a = f 1; f = x: x + 1; }` allows `f` to be a
2609        // sibling binding.
2610        let mut dotted_attrs: NixAttrs = NixAttrs::new();
2611
2612        // D1 (`SUI_SCOPE_NARROW>=1`) — a SECOND predicate, deliberately not a
2613        // widening of `is_recursive_binding` below.
2614        //
2615        // THE TRAP: `is_recursive_binding` is BACKWARD-BLIND on purpose — it
2616        // tests `key` plus the siblings seen SO FAR, so `rec { b = a; a = 1; }`
2617        // computes `false` for `b`. That verdict selects Promise semantics, so
2618        // widening it would change which bindings get the fix-point sentinel
2619        // and is not a refactor available here. Yet `b` genuinely does need the
2620        // rec scope, and today gets it from Phase 2's blanket `update_env`.
2621        // Narrowing therefore needs its own forward-complete question — "does
2622        // this RHS reach ANY key this scope binds, declared before or after?" —
2623        // answered against a full pre-pass, while `is_recursive_binding` stays
2624        // byte-identical.
2625        //
2626        // The pre-pass is PURELY SYNTACTIC, which is the second trap: the
2627        // Phase-1 loop below owns the evaluation order of `${…}` keys, and
2628        // calling `eval_attr` here would run that arbitrary code earlier. So a
2629        // head that is not a plain identifier forfeits narrowing for the whole
2630        // scope instead of being evaluated for its name. Starting the flag at
2631        // `scope_narrow_enabled()` also means the default path never walks the
2632        // entries at all.
2633        let mut names_complete = scope_narrow_enabled();
2634        let rec_scope_names: HashSet<String> = if names_complete {
2635            let mut s = HashSet::new();
2636            for entry in set.entries() {
2637                match entry {
2638                    ast::Entry::AttrpathValue(apv) => {
2639                        match apv.attrpath().and_then(|p| p.attrs().next()) {
2640                            Some(ast::Attr::Ident(i)) => {
2641                                s.insert(ident_text(&i));
2642                            }
2643                            _ => names_complete = false,
2644                        }
2645                    }
2646                    ast::Entry::Inherit(inh) => {
2647                        for attr in inh.attrs() {
2648                            match attr {
2649                                ast::Attr::Ident(i) => {
2650                                    s.insert(ident_text(&i));
2651                                }
2652                                _ => names_complete = false,
2653                            }
2654                        }
2655                    }
2656                }
2657            }
2658            s
2659        } else {
2660            HashSet::new()
2661        };
2662        let narrow = names_complete;
2663
2664        // Phase 1: Create thunks with placeholder env and bind them.
2665        for entry in set.entries() {
2666            match entry {
2667                ast::Entry::AttrpathValue(apv) => {
2668                    let attrpath = apv.attrpath().ok_or_else(|| {
2669                        EvalError::ParseError("binding missing attrpath".to_string())
2670                    })?;
2671                    let value_expr = apv.value().ok_or_else(|| {
2672                        EvalError::ParseError("binding missing value".to_string())
2673                    })?;
2674                    let mut path_keys: Vec<String> = attrpath
2675                        .attrs()
2676                        .filter_map(|a| eval_attr_maybe_null(&a, env).transpose())
2677                        .collect::<Result<_, _>>()?;
2678                    // Null dynamic attr name → skip entire binding (CppNix compat)
2679                    if path_keys.is_empty() { continue; }
2680                    if path_keys.len() == 1 {
2681                        let key = path_keys.pop().unwrap();
2682                        // Self-recursive detection in a `rec { … }` scope:
2683                        // any binding whose value-expr references the
2684                        // bound name OR any sibling key declared in this
2685                        // rec scope is potentially self-recursive (the
2686                        // siblings' thunks share the rec_env via Phase 2).
2687                        // Mark as recursive so inner re-entrance during
2688                        // force returns a Promise sentinel instead of
2689                        // erroring with InfiniteRecursion.
2690                        //
2691                        // For simplicity we check `key` and all already-
2692                        // defined siblings; siblings defined later are
2693                        // covered when THEIR thunks force (they reference
2694                        // back into this rec scope via Phase 2's env update).
2695                        // O(N) not O(N²): one memoized referenced-name set,
2696                        // intersected with key + already-defined siblings.
2697                        // Byte-identical to the prior per-name walks.
2698                        let referenced = referenced_idents(&value_expr);
2699                        let is_recursive_binding = referenced.contains(key.as_str())
2700                            || defined_so_far
2701                                .iter()
2702                                .any(|n| referenced.contains(n.as_str()));
2703                        let value = if is_recursive_binding {
2704                            Value::Thunk(Thunk::new_suspended_recursive(
2705                                value_expr.clone(),
2706                                env.clone(),
2707                            ))
2708                        } else {
2709                            // maybeThunk: skip thunk for trivial exprs.
2710                            // is_rec=true because rec attrset bindings
2711                            // can reference each other.
2712                            // Pass defined_so_far so backward refs
2713                            // resolve directly.
2714                            maybe_thunk(&value_expr, env, true, Some(&defined_so_far))
2715                        };
2716                        // Forward-complete needs-scope test (see the pre-pass
2717                        // above). `is_recursive_binding` is folded in as
2718                        // belt-and-braces: it is a subset whenever `narrow`
2719                        // holds, since every key it can name came from an
2720                        // `Ident` head and so is in `rec_scope_names`.
2721                        let needs_scope = !narrow
2722                            || is_recursive_binding
2723                            || rec_scope_names
2724                                .iter()
2725                                .any(|n| referenced.contains(n.as_str()));
2726                        rec_env.bind(key.clone(), value.clone());
2727                        attrs.insert(key.clone(), value.clone());
2728                        if let Value::Thunk(t) = &value {
2729                            if needs_scope {
2730                                thunks.push((key.clone(), t.clone()));
2731                                crate::value::census::scope_pinned();
2732                            } else {
2733                                crate::value::census::scope_narrowed();
2734                            }
2735                        }
2736                        defined_so_far.insert(key);
2737                    } else {
2738                        // Multi-segment dotted path: build a nested attrset
2739                        // with a thunk at the leaf so the value expression
2740                        // can reference sibling rec-bindings.
2741                        let key = path_keys[0].clone();
2742                        let value =
2743                            build_nested_attr_thunk(&path_keys[1..], &value_expr, env, &mut thunks);
2744                        merge_nested_insert(&mut dotted_attrs, key, value);
2745                    }
2746                }
2747                ast::Entry::Inherit(inherit) => {
2748                    eval_inherit(&inherit, env, &mut attrs, Some(&mut rec_env), Some(&mut thunks))?;
2749                }
2750            }
2751        }
2752
2753        // Phase 1b: Bind accumulated dotted-path attrs into attrs and rec_env.
2754        // Note: CppNix rejects `inherit (src) x; x.y = ...;` as a
2755        // duplicate definition, so we do not attempt to merge with
2756        // existing inherit thunks — just bind directly.
2757        for (key, value) in dotted_attrs.iter() {
2758            attrs.insert(key.clone(), value.clone());
2759            rec_env.bind(key.clone(), value.clone());
2760        }
2761
2762        // Phase 2: Update all thunks (both Suspended and InheritSelect)
2763        // to capture the final rec_env (which now has all names bound).
2764        for (_key, thunk) in &thunks {
2765            thunk.update_env(&rec_env);
2766        }
2767    } else {
2768        for entry in set.entries() {
2769            match entry {
2770                ast::Entry::AttrpathValue(apv) => {
2771                    let attrpath = apv.attrpath().ok_or_else(|| {
2772                        EvalError::ParseError("binding missing attrpath".to_string())
2773                    })?;
2774                    let value_expr = apv.value().ok_or_else(|| {
2775                        EvalError::ParseError("binding missing value".to_string())
2776                    })?;
2777                    let path_attrs: Vec<ast::Attr> = attrpath.attrs().collect();
2778                    // CppNix defers a dynamic key that is NOT at the HEAD of the
2779                    // attrpath: `{ a.${e} = v; }` builds `{ a = <thunk {${e}=v}>; }`,
2780                    // so `e` never forces until `.a` is demanded. Evaluating the
2781                    // whole path eagerly would force `e` at construction and — in
2782                    // the module-system fixpoint — read `config.<x>` while `config`
2783                    // is mid-force (the M2.6 divergence: `homes.null` instead of
2784                    // `homes.<name>`). Only the head is eager; a lone dynamic tail
2785                    // becomes a deferred thunk. A rarer collision under the same
2786                    // head stays eager (forced) so static deep-merge still works.
2787                    let tail_is_dynamic =
2788                        path_attrs.len() > 1 && attrs_have_dynamic(&path_attrs[1..]);
2789                    let head_key = match eval_attr_maybe_null(&path_attrs[0], env)? {
2790                        Some(k) => k,
2791                        // Null dynamic HEAD attr name → skip entire binding.
2792                        None => continue,
2793                    };
2794                    if tail_is_dynamic && attrs.get(&head_key).is_none() {
2795                        let value =
2796                            build_deferred_tail_attr(&path_attrs[1..], &value_expr, env);
2797                        attrs.insert(head_key, value);
2798                        continue;
2799                    }
2800                    // M2.6 ROOT #3 (collision case): the tail has a dynamic key
2801                    // AND the head already exists (a sibling binding wrote it,
2802                    // e.g. osquery's `systemd.services.… = …` then
2803                    // `systemd.tmpfiles.settings."10-osquery".${dirname …}.d`).
2804                    // The plain deferral above bails (head present), and the
2805                    // eager path below would force the dynamic key at
2806                    // construction — re-reading `config.<x>` mid-fixpoint →
2807                    // the empty-Promise partial. Instead, descend the existing
2808                    // head along the tail's STATIC prefix and splice a DEFERRED
2809                    // thunk at the first dynamic level, so the dynamic key
2810                    // stays lazy exactly as CppNix's nested-literal desugaring
2811                    // does — while preserving the static deep-merge with the
2812                    // sibling binding.
2813                    if tail_is_dynamic {
2814                        if let Some(existing) = attrs.get(&head_key).cloned() {
2815                            let merged = merge_deferred_dynamic_tail(
2816                                existing,
2817                                &path_attrs[1..],
2818                                &value_expr,
2819                                env,
2820                            )?;
2821                            attrs.insert(head_key, merged);
2822                            continue;
2823                        }
2824                    }
2825                    // Eager path: evaluate the remaining (static, or collision)
2826                    // keys now. A null dynamic tail key skips the binding.
2827                    let mut path_keys: Vec<String> = {
2828                        let mut v = Vec::with_capacity(path_attrs.len());
2829                        v.push(head_key);
2830                        let mut skip = false;
2831                        for a in &path_attrs[1..] {
2832                            match eval_attr_maybe_null(a, env)? {
2833                                Some(k) => v.push(k),
2834                                None => { skip = true; break; }
2835                            }
2836                        }
2837                        if skip { v.clear(); }
2838                        v
2839                    };
2840                    // Null dynamic attr name → skip entire binding (CppNix compat)
2841                    if path_keys.is_empty() { continue; }
2842                    if path_keys.len() == 1 {
2843                        let key = path_keys.pop().unwrap();
2844                        // maybeThunk: skip thunk for trivial exprs.
2845                        // is_rec=false — Ident lookups are safe.
2846                        let value = maybe_thunk(&value_expr, env, false, None);
2847                        // CppNix desugars `a.b = x; a = { c = y; };` into a single
2848                        // merged `a = { b = x; c = y; }` at parse time. rnix keeps
2849                        // the two bindings separate, so when a single-key binding
2850                        // collides with an already-built (dotted) attrs for the
2851                        // same key, deep-MERGE instead of overwrite. Force the RHS
2852                        // to WHNF so merge_nested_insert (which needs concrete
2853                        // Value::Attrs on both sides) can merge — forcing an
2854                        // attrset to WHNF does NOT force its fields, so leaf values
2855                        // stay lazy. Only fires on collision; non-colliding
2856                        // single-key bindings keep the plain fast insert.
2857                        // (This is the pkg-config-wrapper `env.addFlags` drop:
2858                        // `env.addFlags = …` then `env = { wrapperName = …; … }`.)
2859                        // If the earlier binding for this key is still a lazy
2860                        // Thunk (an attrset literal inserted via maybe_thunk), force
2861                        // it to WHNF FIRST so a `key = {..}; key = {..}` collision is
2862                        // seen as attrs-vs-attrs and MERGES, matching nix
2863                        // (`{ s = {a=1;}; s = {b=2;}; }` → `{ s = {a=1; b=2;}; }`).
2864                        // Without this the `Some(Value::Attrs(_))` test below is false
2865                        // on a Thunk and the second binding overwrites, dropping the
2866                        // first's keys. The dotted branch below already does this; R3
2867                        // (eval-okay-merge-dynamic-attrs set1/set2) needs it here too.
2868                        // WHNF force does not force fields → leaf laziness preserved.
2869                        // (A non-attrs dup like `s = 1; s = 2` still overwrites here,
2870                        // unchanged — nix errors there, an eval-FAIL case out of scope.)
2871                        if matches!(attrs.get(&key), Some(Value::Thunk(_))) {
2872                            let existing = attrs.get(&key).cloned().unwrap();
2873                            let forced_existing = force_value(&existing)?;
2874                            attrs.insert(key.clone(), forced_existing);
2875                        }
2876                        if matches!(attrs.get(&key), Some(Value::Attrs(_))) {
2877                            let forced = force_value(&value)?;
2878                            merge_nested_insert(&mut attrs, key, forced);
2879                        } else {
2880                            attrs.insert(key, value);
2881                        }
2882                    } else {
2883                        let key = path_keys[0].clone();
2884                        let value = build_nested_attr(&path_keys[1..], &value_expr, env)?;
2885                        // CppNix desugars `a = { x = …; }; a.y = …;` into a
2886                        // single merged `a = { x = …; y = …; }`. When the
2887                        // full-set binding for `a` was inserted FIRST it is a
2888                        // lazy Thunk (attrset literals go through maybe_thunk),
2889                        // so merge_nested_insert — which only merges when the
2890                        // existing value is a concrete Value::Attrs — would
2891                        // NOT see the earlier keys and would overwrite `a`
2892                        // with just `{ y = … }`, silently dropping `x`. Force
2893                        // the existing entry to WHNF on collision so the merge
2894                        // sees the concrete attrs (forcing to WHNF does not
2895                        // force the fields, so leaf laziness is preserved).
2896                        // (This is the gst-plugins-base `passthru.waylandEnabled`
2897                        // drop: `passthru = { … }; passthru.tests.x = …;`.)
2898                        if matches!(attrs.get(&key), Some(Value::Thunk(_))) {
2899                            let existing = attrs.get(&key).cloned().unwrap();
2900                            let forced = force_value(&existing)?;
2901                            attrs.insert(key.clone(), forced);
2902                        }
2903                        merge_nested_insert(&mut attrs, key, value);
2904                    }
2905                }
2906                ast::Entry::Inherit(inherit) => {
2907                    eval_inherit(&inherit, env, &mut attrs, None, None)?;
2908                }
2909            }
2910        }
2911    }
2912
2913    // Record the literal's static-key source positions for
2914    // `builtins.unsafeGetAttrPos` (the `attrTag` `declarations` — options.json
2915    // dock root). Cheap: one entry walk over static Ident/Str keys, no
2916    // forcing; attaches nothing (a pointer-sized `None`) when the set has no
2917    // single-static-key bindings.
2918    attach_attrset_positions(set, &mut attrs, env);
2919
2920    Ok(Value::Attrs(Rc::new(attrs)))
2921}
2922
2923fn eval_inherit(
2924    inherit: &ast::Inherit,
2925    env: &Env,
2926    attrs: &mut NixAttrs,
2927    bind_env: Option<&mut Env>,
2928    mut thunks: Option<&mut Vec<(String, Thunk)>>,
2929) -> Result<(), EvalError> {
2930    if let Some(from) = inherit.from() {
2931        // inherit (expr) a b c;
2932        //
2933        // The source expression must NOT be eagerly evaluated. nixpkgs
2934        // `lib/trivial.nix` has `inherit (lib.trivial) isFunction ...`
2935        // at the top of a file that itself defines `lib.trivial`. If
2936        // we eagerly force `lib.trivial`, we hit a self-referential
2937        // thunk blackhole. Instead: build a thunk per inherited
2938        // name that, when forced, evaluates the source and pulls
2939        // out that one attribute. This is what real Nix does.
2940        //
2941        // For `rec { inherit (X) name; ...; foo = name; }` we ALSO
2942        // need to bind the name in the enclosing rec env so the
2943        // sibling `foo = name` can reference it. The caller passes
2944        // its rec env in `bind_env`.
2945        //
2946        // When `thunks` is provided (rec attrsets), InheritSelect
2947        // thunks are collected so Phase 2 can update their captured
2948        // env to the full recursive scope. Without this, the source
2949        // expression cannot reference sibling bindings.
2950        let source_expr = from
2951            .expr()
2952            .ok_or_else(|| EvalError::ParseError("inherit from missing expr".to_string()))?;
2953        // Shared source thunk — all inherited names share one source
2954        // evaluation (the source thunk's own memoization ensures at
2955        // most one evaluation).
2956        let source_thunk = Thunk::new_suspended(source_expr, env.clone());
2957        let mut be = bind_env;
2958        for attr in inherit.attrs() {
2959            let name = eval_attr(&attr, env)?;
2960            let thunk = Thunk::new_inherit_select(source_thunk.clone(), name.clone());
2961            let value = Value::Thunk(thunk.clone());
2962            attrs.insert(name.clone(), value.clone());
2963            if let Some(ref mut e) = be {
2964                e.bind(name.clone(), value);
2965            }
2966            if let Some(ref mut t) = thunks {
2967                t.push((name, thunk));
2968            }
2969        }
2970    } else {
2971        // inherit a b c;
2972        //
2973        // CppNix resolves a bare `inherit x;` LAZILY, exactly like a plain
2974        // reference to `x` — it does NOT eagerly force the enclosing scope.
2975        // This matters when `x` is provided only by an enclosing `with`
2976        // scope whose value is a fixpoint still being constructed (a
2977        // blackhole): eager `env.lookup` returns None → spurious
2978        // `UndefinedVar`. nixpkgs `all-packages.nix` is
2979        // `… with pkgs; { nettle = import … { inherit callPackage; }; }`,
2980        // so `inherit callPackage` must resolve `callPackage` from the
2981        // `with pkgs` scope AT FORCE TIME, not eagerly at attrset
2982        // construction. Mirror `maybe_thunk`'s Ident path: try the fast
2983        // lookup, and on a miss defer to a WithIdent thunk (or a suspended
2984        // env lookup) so the resolution happens lazily against the settled
2985        // scope. (This was the `nettle` UndefinedVar('callPackage') drop.)
2986        let mut be = bind_env;
2987        for attr in inherit.attrs() {
2988            let name = eval_attr(&attr, env)?;
2989            let sym = crate::value::intern(&name);
2990            let value = if let Some(v) = env.lookup_fast(sym, &name) {
2991                v
2992            } else if let Some((scope_cache, scope_value)) =
2993                env.innermost_with_scope()
2994            {
2995                Value::Thunk(Thunk::new_with_ident(
2996                    SmolStr::from(name.as_str()),
2997                    scope_cache,
2998                    scope_value,
2999                    env.clone(),
3000                ))
3001            } else {
3002                return Err(EvalError::UndefinedVar(format!(
3003                    "'{name}'{}",
3004                    eval_file_ctx()
3005                )));
3006            };
3007            attrs.insert(name.clone(), value.clone());
3008            if let Some(ref mut e) = be {
3009                e.bind(name, value);
3010            }
3011        }
3012    }
3013    Ok(())
3014}
3015
3016fn build_nested_attr(
3017    path: &[String],
3018    expr: &ast::Expr,
3019    env: &Env,
3020) -> Result<Value, EvalError> {
3021    if path.is_empty() {
3022        // CRITICAL: Wrap leaf in a thunk instead of eagerly evaluating.
3023        // For dotted paths like `config.warnings = optionals config.x [...]`,
3024        // the leaf expression must be lazy — eagerly evaluating it during
3025        // attrset construction forces fixpoint thunks prematurely.
3026        return Ok(maybe_thunk(expr, env, false, None));
3027    }
3028    let key = path[0].clone();
3029    let inner = build_nested_attr(&path[1..], expr, env)?;
3030    let mut attrs = NixAttrs::new();
3031    attrs.insert(key, inner);
3032    Ok(Value::Attrs(Rc::new(attrs)))
3033}
3034
3035/// True if a single attr is a DYNAMIC key — one whose resolution runs
3036/// arbitrary expression code and therefore must not be forced at
3037/// attrset-construction time.
3038///
3039/// Two forms are dynamic:
3040///   * `ast::Attr::Dynamic` — a bare `${e}` antiquotation.
3041///   * `ast::Attr::Str` **containing an interpolation** — an interpolated
3042///     string key like `"iwd/${nm}"`.  A `Str` with NO interpolation
3043///     (`"foo bar"`) is a plain static string literal and is NOT dynamic.
3044///
3045/// M2.6 ROOT #3: `attrs_have_dynamic` previously matched ONLY
3046/// `Attr::Dynamic`, so an interpolated-string tail key (`config.a."p${e}"`)
3047/// fell to the eager path and forced `e` at construction.  In the module
3048/// system that forces a `config.<x>` read while `config` is mid-fixpoint
3049/// (`environment.etc."iwd/${configFile.name}"`, where `configFile` reads
3050/// `with config.networking.networkmanager`), yielding the empty-Promise
3051/// partial → the `set/null` softening.  Treating an interpolated `Str` as
3052/// dynamic routes it through the same per-level deferral as `${e}`
3053/// (ROOT #1/#2), so `e` forces only when the enclosing head is demanded —
3054/// exactly CppNix's nested-attrset-literal desugaring.
3055fn attr_is_dynamic(attr: &ast::Attr) -> bool {
3056    match attr {
3057        ast::Attr::Dynamic(_) => true,
3058        // A string attr key is dynamic iff it has ≥1 interpolation part;
3059        // a purely-literal string key forces nothing and stays eager.
3060        ast::Attr::Str(s) => s
3061            .normalized_parts()
3062            .iter()
3063            .any(|p| matches!(p, InterpolPart::Interpolation(_))),
3064        ast::Attr::Ident(_) => false,
3065    }
3066}
3067
3068/// True if any attr in the slice is a dynamic (interpolated) key.
3069///
3070/// A dynamic key beyond the HEAD of an attrpath must NOT be evaluated at
3071/// attrset-construction time — CppNix defers it inside the head's lazy
3072/// value, so `{ a.${e} = v; }` never forces `e` until `.a` is demanded.
3073/// Static string/ident keys are cheap and force nothing, so they don't
3074/// need deferral.
3075fn attrs_have_dynamic(attrs: &[ast::Attr]) -> bool {
3076    attrs.iter().any(attr_is_dynamic)
3077}
3078
3079/// Build the nested attrset for the TAIL of an attrpath, deferring
3080/// evaluation of dynamic tail keys until the value is forced.
3081///
3082/// Given tail attrs `[b, ${e}, c]` and a value expr, produce a lazy
3083/// `Value::Thunk` that, when forced, evaluates each tail key (including
3084/// the dynamic `${e}`) against `env` and builds `{ b = { ${e} = { c =
3085/// <leaf-thunk> }; }; }`. This mirrors CppNix: the inner attrset (and
3086/// thus its dynamic keys) is constructed only when the enclosing head
3087/// attribute is demanded — never at construction of the outer attrset.
3088///
3089/// A dynamic key that evaluates to `null` skips the whole binding
3090/// (returns an empty attrset), matching CppNix's null-dynamic-attr rule.
3091fn build_deferred_tail_attr(
3092    tail: &[ast::Attr],
3093    value_expr: &ast::Expr,
3094    env: &Env,
3095) -> Value {
3096    let tail: Vec<ast::Attr> = tail.to_vec();
3097    let value_expr = value_expr.clone();
3098    let env = env.clone();
3099    Value::Thunk(Thunk::new_native(move || {
3100        build_tail_attrs_now(&tail, &value_expr, &env)
3101    }))
3102}
3103
3104/// Resolve ONE level of the deferred attrpath tail — used from inside
3105/// the deferred thunk above once the enclosing head is demanded.
3106///
3107/// M2.6 ROOT #2 (the OVER-FORCE fix): this resolves *only* `tail[0]`'s
3108/// key and wraps the remaining tail `tail[1..]` in another DEFERRED
3109/// thunk — it does NOT recurse eagerly through the whole tail. This is
3110/// exactly CppNix's desugaring of `a.b.c = v` into nested attrset
3111/// literals `a = { b = { c = v; }; }`, where forcing `a` to WHNF yields
3112/// `{ b = <thunk {c=v}> }` — the inner level (`b`, and any dynamic key
3113/// under it) stays lazy until `.b` is demanded.
3114///
3115/// Forcing the enclosing head therefore resolves ONE tail key, never
3116/// the whole chain: `config.homes.${cfg.pleme.userName} = 7` demanded
3117/// as `config` yields `{ homes = <deferred> }` WITHOUT forcing the
3118/// `${cfg.pleme.userName}` key. The prior implementation recursed the
3119/// whole tail eagerly, forcing that dynamic key while only `.config`
3120/// (or its `._type`) was demanded — the over-force cppnix never does.
3121///
3122/// A dynamic key that evaluates to `null` skips the whole binding
3123/// (returns an empty attrset), matching CppNix's null-dynamic-attr rule.
3124fn build_tail_attrs_now(
3125    tail: &[ast::Attr],
3126    value_expr: &ast::Expr,
3127    env: &Env,
3128) -> Result<Value, EvalError> {
3129    if tail.is_empty() {
3130        return Ok(maybe_thunk(value_expr, env, false, None));
3131    }
3132    if std::env::var_os("SUI_M26_TAILTRACE").is_some() {
3133        let t: String = tail[0].syntax().text().to_string().chars().take(40).collect();
3134        eprintln!("[M26 TAIL-RESOLVE] forcing dynamic tail key `{t}`");
3135        if attrs_have_dynamic(&tail[..1]) {
3136            crate::trace::dump_force_stack_ids();
3137        }
3138    }
3139    let key = match eval_attr_maybe_null(&tail[0], env)? {
3140        Some(k) => k,
3141        // Null dynamic key → the whole binding is skipped; an empty
3142        // attrset is the identity for merge_nested_insert.
3143        None => return Ok(Value::Attrs(Rc::new(NixAttrs::new()))),
3144    };
3145    // Resolve ONE level: if more tail remains, defer it (a new lazy
3146    // thunk) rather than recursing eagerly. Only the leaf (empty tail)
3147    // is built here. This keeps each nested level lazy, exactly like
3148    // CppNix's nested-attrset-literal desugaring — so forcing this
3149    // level does NOT force the next level's (possibly dynamic) key.
3150    let inner = if tail.len() == 1 {
3151        maybe_thunk(value_expr, env, false, None)
3152    } else {
3153        build_deferred_tail_attr(&tail[1..], value_expr, env)
3154    };
3155    let mut attrs = NixAttrs::new();
3156    attrs.insert(key, inner);
3157    Ok(Value::Attrs(Rc::new(attrs)))
3158}
3159
3160/// M2.6 ROOT #3 (collision case): splice a DEFERRED dynamic-tail binding
3161/// into an ALREADY-PRESENT head value without forcing the dynamic key.
3162///
3163/// `existing` is the value already stored at the attrpath's head (written
3164/// by a sibling binding — e.g. `systemd.services.… = …`). `tail` is the
3165/// remaining attrpath (`path_attrs[1..]`) of the new binding, which
3166/// contains ≥1 dynamic attr (`systemd.tmpfiles.….${dirname …}.d`).
3167///
3168/// We descend `existing` along the LONGEST STATIC PREFIX of `tail`
3169/// (`tmpfiles`, `settings`, `"10-osquery"` — all static, forced-free
3170/// keys), forcing each already-present sub-attrset to WHNF so the merge
3171/// sees concrete keys (forcing to WHNF never forces leaf VALUES, so leaf
3172/// laziness is preserved), and at the first DYNAMIC level splice a
3173/// `build_deferred_tail_attr` thunk. The dynamic key therefore forces
3174/// only when that exact nested path is later demanded — CppNix's
3175/// nested-attrset-literal desugaring, now honoured through a sibling
3176/// collision too.
3177fn merge_deferred_dynamic_tail(
3178    existing: Value,
3179    tail: &[ast::Attr],
3180    value_expr: &ast::Expr,
3181    env: &Env,
3182) -> Result<Value, EvalError> {
3183    // `tail` is non-empty and contains a dynamic attr somewhere (the
3184    // caller guarantees `attrs_have_dynamic(tail)`).
3185    debug_assert!(!tail.is_empty());
3186
3187    // If the FIRST tail attr is itself dynamic, there is no static prefix
3188    // to descend — the whole tail is deferred and merged as a lazy
3189    // overlay onto the existing head (a `//`-style right-merge; the
3190    // deferred attrset only materialises its dynamic key on demand).
3191    if attr_is_dynamic(&tail[0]) {
3192        let deferred = build_deferred_tail_attr(tail, value_expr, env);
3193        return Ok(lazy_overlay_merge(existing, deferred));
3194    }
3195
3196    // The head static key of `tail`. Resolve it (static → forces nothing
3197    // relevant; a null dynamic can't occur here since tail[0] is static).
3198    let key = match eval_attr_maybe_null(&tail[0], env)? {
3199        Some(k) => k,
3200        None => return Ok(existing),
3201    };
3202
3203    // Force the existing head to a concrete attrset so we can descend +
3204    // merge on the resolved static key. Forcing to WHNF does NOT force
3205    // its field VALUES, so leaf laziness is preserved.
3206    let existing_forced = force_value(&existing)?;
3207    let mut base = match existing_forced {
3208        Value::Attrs(a) => (*a).clone(),
3209        // The existing head is not an attrset (a sibling wrote a leaf
3210        // here); CppNix would error on the merge, but to stay lazy we
3211        // defer the tail and let a later demand surface the real merge
3212        // conflict. Build the deferred tail as a fresh attrset.
3213        _ => {
3214            let deferred = build_deferred_tail_attr(tail, value_expr, env);
3215            return Ok(deferred);
3216        }
3217    };
3218
3219    // Recurse: merge the REMAINING tail (`tail[1..]`) under `key`.
3220    let child_existing = base.get(&key).cloned();
3221    let new_child = match child_existing {
3222        Some(child) if tail.len() > 1 => {
3223            // Deeper static/dynamic prefix under an existing sub-attrset.
3224            merge_deferred_dynamic_tail(child, &tail[1..], value_expr, env)?
3225        }
3226        Some(child) => {
3227            // tail == [key]; the leaf collides with an existing value.
3228            // Static leaf collision — build the leaf and lazy-merge.
3229            let leaf = maybe_thunk(value_expr, env, false, None);
3230            lazy_overlay_merge(child, leaf)
3231        }
3232        None if tail.len() > 1 => {
3233            // No existing child; the remaining tail may itself start with
3234            // a dynamic key — defer it whole (build_deferred_tail_attr
3235            // handles the static/dynamic split per-level).
3236            build_deferred_tail_attr(&tail[1..], value_expr, env)
3237        }
3238        None => maybe_thunk(value_expr, env, false, None),
3239    };
3240    base.insert(key, new_child);
3241    Ok(Value::Attrs(Rc::new(base)))
3242}
3243
3244/// Lazy right-merge of two values that are (or will force to) attrsets,
3245/// preserving leaf laziness. Used by [`merge_deferred_dynamic_tail`] to
3246/// combine a deferred dynamic-tail attrset with an existing value without
3247/// forcing either's dynamic keys eagerly. When both are concrete attrs we
3248/// deep-merge in place (reusing [`merge_nested_insert`]); otherwise we
3249/// build a lazy overlay thunk that merges on demand.
3250fn lazy_overlay_merge(left: Value, right: Value) -> Value {
3251    match (&left, &right) {
3252        (Value::Attrs(la), Value::Attrs(_)) => {
3253            crate::perf::inc(crate::perf::Counter::SlashDeferredTailClone);
3254            let mut merged = (**la).clone();
3255            if let Value::Attrs(ra) = &right {
3256                // Merging distinct override keys into `merged` is order-
3257                // independent (per-key right-wins), and the result map is
3258                // unordered storage — the sorted `iter()` was dead work.
3259                for (k, v) in ra.iter_unsorted() {
3260                    merge_nested_insert(&mut merged, k.clone(), v.clone());
3261                }
3262            }
3263            Value::Attrs(Rc::new(merged))
3264        }
3265        _ => {
3266            // At least one side is a thunk (a deferred dynamic tail).
3267            // Defer the merge behind a Native thunk so neither side's
3268            // dynamic key forces until the merged attrset is demanded.
3269            Value::Thunk(Thunk::new_native(move || {
3270                let lf = force_value(&left)?;
3271                let rf = force_value(&right)?;
3272                let la = lf.as_attrs()?;
3273                let ra = rf.as_attrs()?;
3274                crate::perf::inc(crate::perf::Counter::SlashDeferredTailClone);
3275                let mut merged = (*la).clone();
3276                for (k, v) in ra.iter_unsorted() {
3277                    merge_nested_insert(&mut merged, k.clone(), v.clone());
3278                }
3279                Ok(Value::Attrs(Rc::new(merged)))
3280            }))
3281        }
3282    }
3283}
3284
3285/// Like [`build_nested_attr`] but wraps the leaf in a [`Thunk`] instead of
3286/// eagerly evaluating it. Used inside `rec { ... }` and `let ... in` so
3287/// that dotted-path leaf expressions can reference sibling bindings
3288/// through the recursive env (which is finalised in Phase 2).
3289///
3290/// Every thunk created is appended to `thunks` so Phase 2 can update
3291/// its captured environment.
3292fn build_nested_attr_thunk(
3293    path: &[String],
3294    expr: &ast::Expr,
3295    env: &Env,
3296    thunks: &mut Vec<(String, Thunk)>,
3297) -> Value {
3298    if path.is_empty() {
3299        let thunk = Thunk::new_suspended(expr.clone(), env.clone());
3300        let val = Value::Thunk(thunk.clone());
3301        thunks.push((String::new(), thunk));
3302        return val;
3303    }
3304    let key = path[0].clone();
3305    let inner = build_nested_attr_thunk(&path[1..], expr, env, thunks);
3306    let mut attrs = NixAttrs::new();
3307    attrs.insert(key, inner);
3308    Value::Attrs(Rc::new(attrs))
3309}
3310
3311/// Insert `value` at `key` in `target`. If `target` already has a
3312/// concrete `Value::Attrs` at that key AND `value` is also a
3313/// concrete `Value::Attrs`, deep-merge them rather than overwriting.
3314/// This is what makes `{ a.b.c = 1; a.b.d = 2; a.e = 3; }` produce
3315/// `{ a = { b = { c = 1; d = 2; }; e = 3; }; }` instead of
3316/// dropping siblings — every nixpkgs module relies on this.
3317fn merge_nested_insert(target: &mut NixAttrs, key: String, value: Value) {
3318    // Fast path: no existing entry at this key → plain insert, keeping the
3319    // value lazy (the overwhelmingly common non-colliding case, so we never
3320    // force a thunk here).
3321    let existing = match target.get(&key) {
3322        Some(e) => e.clone(),
3323        None => {
3324            target.insert(key, value);
3325            return;
3326        }
3327    };
3328    // A collision exists.  A deep merge is warranted only when BOTH the
3329    // existing entry AND the new value are attrset-shaped.  M2.6 ROOT #4b
3330    // (byte-verified): either side may be a lazy `Thunk` wrapping a
3331    // full-set leaf — both dotted-path orderings hit this:
3332    //   forward  `o.a = { x = 1; }; o.a.y = 2;` → EXISTING `a` is a thunk
3333    //            (`build_nested_attr` puts the `{x=1}` leaf through
3334    //            `maybe_thunk`), NEW `a` is `{ y = … }`;
3335    //   reverse  `o.a.y = 2; o.a = { x = 1; };` → EXISTING `a` is `{y}`,
3336    //            NEW `a` is the `<thunk {x=1}>`.
3337    // The old `should_merge` required BOTH sides to already be concrete
3338    // `Value::Attrs`, so a Thunk-vs-Attrs collision fell to the overwrite
3339    // path and silently dropped the earlier leaf's keys.  cppnix desugars
3340    // BOTH orderings into one merged `o.a = { x = 1; y = 2; }`.  Force each
3341    // side's thunk to WHNF ON COLLISION ONLY (forcing an attrset to WHNF
3342    // does NOT force its fields, so leaf laziness is preserved); a thunk
3343    // that forces to a non-attrset (or errors) makes the merge a plain
3344    // overwrite (leaf last-write-wins).
3345    // Symptom this closes: nixpkgs' alsa module declares
3346    // `options.hardware.alsa = { enable = …; cardAliases = …; … }` AND
3347    // `options.hardware.alsa.enablePersistence = …`; sui merged them to
3348    // only `{enablePersistence}`, so `hardware.alsa.cardAliases` "does not
3349    // exist" — the M2.6 frontier once the `with`-namespace over-force (#4a)
3350    // was fixed.
3351    let value = match value {
3352        Value::Thunk(_) => match force_value(&value) {
3353            Ok(v @ Value::Attrs(_)) => v,
3354            _ => value,
3355        },
3356        other => other,
3357    };
3358    if !matches!(value, Value::Attrs(_)) {
3359        target.insert(key, value);
3360        return;
3361    }
3362    // Normalize the existing side to concrete attrs too (forcing a thunk
3363    // to WHNF if needed); if it isn't attrset-shaped, the new attrs wins.
3364    let existing_concrete = match &existing {
3365        Value::Attrs(_) => existing.clone(),
3366        Value::Thunk(_) => match force_value(&existing) {
3367            Ok(v @ Value::Attrs(_)) => v,
3368            _ => {
3369                target.insert(key, value);
3370                return;
3371            }
3372        },
3373        _ => {
3374            target.insert(key, value);
3375            return;
3376        }
3377    };
3378    // Both sides are concrete attrs — merge in place. We pop the
3379    // existing entry, then walk the new attrs and recursively
3380    // merge each child onto it.
3381    let mut existing_attrs = match existing_concrete {
3382        Value::Attrs(a) => (*a).clone(),
3383        _ => unreachable!(),
3384    };
3385    let new_attrs = match value {
3386        Value::Attrs(ref a) => a,
3387        _ => unreachable!(),
3388    };
3389    for (k, v) in new_attrs.iter_unsorted() {
3390        merge_nested_insert(&mut existing_attrs, k.clone(), v.clone());
3391    }
3392    target.insert(key, Value::Attrs(Rc::new(existing_attrs)));
3393}
3394
3395/// Evaluate entries from any HasEntry node (LegacyLet).
3396fn eval_entries<N: HasEntry + AstNode>(node: &N, env: &mut Env) -> Result<(), EvalError> {
3397    for entry in node.entries() {
3398        match entry {
3399            ast::Entry::AttrpathValue(apv) => {
3400                let attrpath = apv.attrpath().ok_or_else(|| {
3401                    EvalError::ParseError("binding missing attrpath".to_string())
3402                })?;
3403                let value_expr = apv.value().ok_or_else(|| {
3404                    EvalError::ParseError("binding missing value".to_string())
3405                })?;
3406                let mut path_keys: Vec<String> = attrpath
3407                    .attrs()
3408                    .map(|a| eval_attr(&a, env))
3409                    .collect::<Result<_, _>>()?;
3410                if path_keys.len() == 1 {
3411                    let key = path_keys.pop().unwrap();
3412                    let value = eval_expr(&value_expr, env)?;
3413                    env.bind(key, value);
3414                }
3415                // Multi-key paths in let are not standard; skip for now.
3416            }
3417            ast::Entry::Inherit(inherit) => {
3418                if let Some(from) = inherit.from() {
3419                    let source_expr = from.expr().ok_or_else(|| {
3420                        EvalError::ParseError("inherit from missing expr".to_string())
3421                    })?;
3422                    let source = force_value(&eval_expr(&source_expr, env)?)?;
3423                    let source_attrs = source.as_attrs()?;
3424                    for attr in inherit.attrs() {
3425                        let name = eval_attr(&attr, env)?;
3426                        let value = source_attrs
3427                            .get(&name)
3428                            .cloned()
3429                            .ok_or_else(|| EvalError::AttrNotFound(
3430                                format!("'{name}' in inherit{}", eval_file_ctx()),
3431                            ))?;
3432                        env.bind(name, value);
3433                    }
3434                } else {
3435                    for attr in inherit.attrs() {
3436                        let name = eval_attr(&attr, env)?;
3437                        let value = env
3438                            .lookup(&name)
3439                            .ok_or_else(|| EvalError::UndefinedVar(
3440                                format!("'{name}'{}", eval_file_ctx()),
3441                            ))?;
3442                        env.bind(name, value);
3443                    }
3444                }
3445            }
3446        }
3447    }
3448    Ok(())
3449}
3450
3451fn eval_binop(
3452    op: ast::BinOpKind,
3453    lhs: &ast::Expr,
3454    rhs: &ast::Expr,
3455    env: &Env,
3456) -> Result<Value, EvalError> {
3457    // Short-circuit for && and ||
3458    match op {
3459        ast::BinOpKind::And => {
3460            let l = force_value(&eval_expr(lhs, env)?)?.as_bool()?;
3461            if !l {
3462                return Ok(Value::Bool(false));
3463            }
3464            return eval_expr(rhs, env);
3465        }
3466        ast::BinOpKind::Or => {
3467            let l = force_value(&eval_expr(lhs, env)?)?.as_bool()?;
3468            if l {
3469                return Ok(Value::Bool(true));
3470            }
3471            return eval_expr(rhs, env);
3472        }
3473        ast::BinOpKind::Implication => {
3474            let l = force_value(&eval_expr(lhs, env)?)?.as_bool()?;
3475            if !l {
3476                return Ok(Value::Bool(true));
3477            }
3478            return eval_expr(rhs, env);
3479        }
3480        _ => {}
3481    }
3482
3483    let lc = force_concrete(&eval_expr(lhs, env)?)?;
3484    let rc = force_concrete(&eval_expr(rhs, env)?)?;
3485    // Consume the Concretes (move, don't clone) so `l`/`r` hold the sole Rc to
3486    // any heap payload. This is byte-neutral — `into_value` yields the identical
3487    // `Value` as `to_value` — but it drops `lc`/`rc`, which is what lets the
3488    // `Concat` arm's structural-share fast path see a uniquely-owned left list
3489    // for a fresh `++` temporary (`Rc::try_unwrap` → append in place). Keeping
3490    // `lc` alive via `to_value` pinned the refcount at ≥2 and defeated reuse.
3491    let l = lc.into_value();
3492    let r = rc.into_value();
3493
3494    match op {
3495        ast::BinOpKind::Add => match (&l, &r) {
3496            (Value::Int(a), Value::Int(b)) => a
3497                .checked_add(*b)
3498                .map(Value::Int)
3499                .ok_or_else(|| int_overflow("adding", *a, '+', *b)),
3500            (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
3501            (Value::Int(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
3502            (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a + *b as f64)),
3503            (Value::String(a), Value::String(b)) => {
3504                let mut ctx = a.context.clone();
3505                ctx.merge(&b.context);
3506                // Byte-identical to `format!("{}{}", a.chars, b.chars)` but
3507                // routes around the `core::fmt` runtime (its dispatch was the
3508                // #1 self-time frame on the string-concat hot path): a single
3509                // exact-capacity `String` + two `push_str` reserves the final
3510                // size once, so the left operand is copied exactly once instead
3511                // of copied-then-regrown. Result string + context unchanged →
3512                // ByteSufficient. (Also removes a `format!` — TYPED EMISSION.)
3513                let mut s = String::with_capacity(a.chars.len() + b.chars.len());
3514                s.push_str(&a.chars);
3515                s.push_str(&b.chars);
3516                Ok(Value::String(Rc::new(NixString::with_context(s, ctx))))
3517            }
3518            (Value::Path(a), Value::String(b)) => Ok(Value::Path(Box::new(SmolStr::from(format!("{a}{}", b.chars).as_str())))),
3519            (Value::Path(a), Value::Path(b)) => Ok(Value::Path(Box::new(SmolStr::from(format!("{a}/{b}").as_str())))),
3520            // CppNix coerces attrsets with outPath when used with +
3521            (Value::Attrs(_), _) | (_, Value::Attrs(_)) => {
3522                let (ls, lctx) = l.coerce_to_string()?;
3523                let (rs, rctx) = r.coerce_to_string()?;
3524                let mut ctx = lctx;
3525                ctx.merge(&rctx);
3526                Ok(Value::String(Rc::new(NixString::with_context(
3527                    format!("{ls}{rs}"),
3528                    ctx,
3529                ))))
3530            }
3531            _ => Err(EvalError::op_type("add", l.type_name(), r.type_name())),
3532        },
3533        ast::BinOpKind::Sub => num_op(
3534            &l,
3535            &r,
3536            |a, b| a.checked_sub(b),
3537            |a, b| a - b,
3538            |a, b| int_overflow("subtracting", a, '-', b),
3539        ),
3540        ast::BinOpKind::Mul => num_op(
3541            &l,
3542            &r,
3543            |a, b| a.checked_mul(b),
3544            |a, b| a * b,
3545            |a, b| int_overflow("multiplying", a, '*', b),
3546        ),
3547        ast::BinOpKind::Div => {
3548            // CppNix rejects division by zero for both int and float
3549            // operands; Rust's native int-div-by-0 panics (we handle
3550            // that below) but float-div-by-0 silently returns `inf`
3551            // or `NaN`, which sui was then serializing as `null` —
3552            // an invisible silent-Ok bug surfaced by the error-case
3553            // differential corpus.
3554            //
3555            // Cover every zero-denominator case explicitly.
3556            let rhs_is_zero = match &r {
3557                Value::Int(0) => true,
3558                Value::Float(f) => *f == 0.0,
3559                _ => false,
3560            };
3561            if rhs_is_zero {
3562                return Err(EvalError::DivisionByZero);
3563            }
3564            num_op(
3565                &l,
3566                &r,
3567                |a, b| a.checked_div(b),
3568                |a, b| a / b,
3569                |a, b| int_overflow("dividing", a, '/', b),
3570            )
3571        }
3572        // `eq_operator`, NOT `==`: at the operator both operands were just
3573        // materialized by independent `force_concrete` calls, so sui can prove
3574        // they are distinct cells and must answer `false` for two lambdas —
3575        // exactly as CppNix's `ExprOpEq::eval` does. Nested comparisons keep
3576        // `PartialEq`. See `value::eq_operator`.
3577        ast::BinOpKind::Equal => Ok(Value::Bool(crate::value::eq_operator(&l, &r))),
3578        ast::BinOpKind::NotEqual => Ok(Value::Bool(!crate::value::eq_operator(&l, &r))),
3579        ast::BinOpKind::Less => compare(&l, &r, |o| o == std::cmp::Ordering::Less),
3580        ast::BinOpKind::LessOrEq => compare(&l, &r, |o| o != std::cmp::Ordering::Greater),
3581        ast::BinOpKind::More => compare(&l, &r, |o| o == std::cmp::Ordering::Greater),
3582        ast::BinOpKind::MoreOrEq => compare(&l, &r, |o| o != std::cmp::Ordering::Less),
3583        ast::BinOpKind::Update => {
3584            let la = l.to_attrs()?;
3585            let ra = r.to_attrs()?;
3586            // O(1) lazy overlay — defers merge until attribute access.
3587            Ok(Value::Attrs(Rc::new(la.overlay(ra))))
3588        }
3589        ast::BinOpKind::Concat => {
3590            // Structural-share fast path: when the left operand's `Rc<Vec>` is
3591            // uniquely owned (a fresh temporary, as in a left-associative `++`
3592            // fold `acc ++ [x]`), append the right elements IN PLACE instead of
3593            // cloning the whole accumulator. This turns an O(n) copy per concat
3594            // into amortized O(1), byte-identically — the result is the same
3595            // ordered sequence of the same Rc-shared lazy thunks (no forcing,
3596            // no reordering, no identity change). When the Rc is shared (the
3597            // left came from a still-live binding/thunk) we fall back to the
3598            // clone-extend path, preserving the shared list unchanged.
3599            crate::value::concat_lists(l, r.as_list()?)
3600        }
3601        ast::BinOpKind::And | ast::BinOpKind::Or | ast::BinOpKind::Implication => {
3602            unreachable!("handled above")
3603        }
3604        ast::BinOpKind::PipeRight | ast::BinOpKind::PipeLeft => {
3605            Err(EvalError::NotImplemented("pipe operators".to_string()))
3606        }
3607    }
3608}
3609
3610/// CppNix aborts (uncatchably) on i64 arithmetic overflow, e.g.
3611/// `integer overflow in adding 9223372036854775807 + 1`. `EvalError::Abort` is
3612/// the uncatchable variant (`tryEval` catches only `Throw`/`AssertionFailed`),
3613/// matching nix — a wrapping result would silently produce a wrong drvPath.
3614#[inline]
3615fn int_overflow(verb: &str, a: i64, sym: char, b: i64) -> EvalError {
3616    EvalError::Abort(format!("integer overflow in {verb} {a} {sym} {b}"))
3617}
3618
3619fn num_op(
3620    l: &Value,
3621    r: &Value,
3622    int_op: impl Fn(i64, i64) -> Option<i64>,
3623    float_op: impl Fn(f64, f64) -> f64,
3624    overflow: impl Fn(i64, i64) -> EvalError,
3625) -> Result<Value, EvalError> {
3626    match (l, r) {
3627        (Value::Int(a), Value::Int(b)) => {
3628            int_op(*a, *b).map(Value::Int).ok_or_else(|| overflow(*a, *b))
3629        }
3630        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(float_op(*a, *b))),
3631        (Value::Int(a), Value::Float(b)) => Ok(Value::Float(float_op(*a as f64, *b))),
3632        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(float_op(*a, *b as f64))),
3633        _ => Err(EvalError::op_type("perform arithmetic on", l.type_name(), r.type_name())),
3634    }
3635}
3636
3637fn compare(
3638    l: &Value,
3639    r: &Value,
3640    pred: impl Fn(std::cmp::Ordering) -> bool,
3641) -> Result<Value, EvalError> {
3642    let ord = match (l, r) {
3643        (Value::Int(a), Value::Int(b)) => a.cmp(b),
3644        (Value::Float(a), Value::Float(b)) => {
3645            a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3646        }
3647        (Value::Int(a), Value::Float(b)) => (*a as f64)
3648            .partial_cmp(b)
3649            .unwrap_or(std::cmp::Ordering::Equal),
3650        (Value::Float(a), Value::Int(b)) => a
3651            .partial_cmp(&(*b as f64))
3652            .unwrap_or(std::cmp::Ordering::Equal),
3653        (Value::String(a), Value::String(b)) => a.chars.cmp(&b.chars),
3654        _ => {
3655            return Err(EvalError::op_type("compare", l.type_name(), r.type_name()));
3656        }
3657    };
3658    Ok(Value::Bool(pred(ord)))
3659}
3660
3661/// Apply a function to an argument.
3662///
3663/// Supports `__functor`: if `func` is an attrset with a `__functor` key,
3664/// calls `__functor self arg` (the Nix `__functor` protocol).
3665///
3666/// For lambda with a simple ident parameter, the argument is NOT forced
3667/// before binding -- this enables fixpoint combinators (`lib.fix`) where
3668/// the argument is a self-referential thunk.
3669/// Apply a function and force the result.
3670///
3671/// Builtins that inspect the return value (via `as_list`, `as_bool`, etc.)
3672/// must use this instead of bare `apply` — otherwise a thunk-wrapped result
3673/// will cause "thunk in as_list: force first" errors.
3674pub fn apply_and_force(func: Value, arg: Value) -> Result<Value, EvalError> {
3675    force_value(&apply(func, arg)?)
3676}
3677
3678pub fn apply(func: Value, arg: Value) -> Result<Value, EvalError> {
3679    stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || apply_inner(func, arg))
3680}
3681
3682fn apply_inner(func: Value, arg: Value) -> Result<Value, EvalError> {
3683    crate::perf::inc(crate::perf::Counter::Apply);
3684    let func = force_concrete(&func)?.into_value();
3685    match func {
3686        Value::Lambda(closure) => {
3687            // Hot function tracker: log source file + param name for each lambda call
3688            if crate::perf::enabled() {
3689                APPLY_SITES.with(|sites| {
3690                    let file = closure.env.eval_file()
3691                        .map(|p| p.display().to_string())
3692                        .unwrap_or_else(|| "<eval>".into());
3693                    // Include param info for identification
3694                    let param_name = match &closure.param {
3695                        rnix::ast::Param::IdentParam(ip) => ip.ident().map(|i| ident_text(&i)).unwrap_or_default(),
3696                        rnix::ast::Param::Pattern(pat) => {
3697                            let mut names: Vec<String> = pat.pat_entries()
3698                                .filter_map(|e| e.ident().map(|i| ident_text(&i)))
3699                                .take(3)
3700                                .collect();
3701                            if pat.pat_entries().count() > 3 { names.push("...".to_string()); }
3702                            format!("{{{}}}", names.join(","))
3703                        }
3704                    };
3705                    let key = format!("{}:{}", file.rsplit_once("-source/").map_or(file.as_str(), |(_,s)| s), param_name);
3706                    *sites.borrow_mut().entry(key).or_insert(0u64) += 1;
3707                });
3708            }
3709            let mut call_env = closure.env.child();
3710            // ALWAYS push a frame, even when the closure captured no file:
3711            // `.map(push_eval_file)` pushed nothing for `None`, leaving the
3712            // CALLER's file on top, so a literal written in a fileless
3713            // context got stamped with the callee's path. CppNix returns
3714            // `null` there. See `EVAL_FILE_STACK`.
3715            let _file_guard = push_eval_frame(closure.env.eval_file().cloned());
3716            // Push Nix-level trace frame for function calls. Lazy: stores
3717            // only the raw ingredients (O(1) Rc-clone of the closure env +
3718            // the current-eval-file snapshot) and defers the format!/strip
3719            // work to the cold `attach_trace` path. Renders byte-identical
3720            // to the eager form.
3721            let _trace = push_nix_trace_lambda(&closure.env);
3722            match &closure.param {
3723                rnix::ast::Param::IdentParam(_) => {
3724                    // Simple ident param: bind argument WITHOUT forcing.
3725                    // This is critical for fixpoint / call-by-need semantics.
3726                    bind_param(&closure.param, &arg, &mut call_env)?;
3727                }
3728                rnix::ast::Param::Pattern(_) => {
3729                    // Pattern param needs the arg to be an attrset, so force.
3730                    let forced_arg = force_concrete(&arg)?.into_value();
3731                    bind_param(&closure.param, &forced_arg, &mut call_env)?;
3732                }
3733            }
3734            eval_expr(&closure.body, &call_env)
3735        }
3736        Value::Builtin(b) => {
3737            let _trace = push_nix_trace(format!("while calling the '{}' builtin", b.name));
3738            // Special builtins that must receive UNFORCED arguments:
3739            // - tryEval: must catch throw/abort during its own forcing
3740            // - addErrorContext<partial>: wraps value with error context
3741            //   without forcing (the value is the fixpoint `config` which
3742            //   causes infinite recursion if forced during collectModules)
3743            // - seq<partial>: forces first arg but returns second UNFORCED
3744            // Same lazy-arg set as `eval_apply` (single source of truth) — these
3745            // builtins receive the arg UNFORCED. foldl'<p1> is the nul accumulator
3746            // (nix's foldl' is strict in each op RESULT, NOT in the nul).
3747            if builtin_takes_lazy_arg(&b.name) {
3748                (b.func)(&[arg])
3749            } else {
3750                let forced_arg = force_value(&arg)?;
3751                (b.func)(&[forced_arg])
3752            }
3753        }
3754        Value::Attrs(ref attrs) => {
3755            if let Some(functor) = attrs.get("__functor") {
3756                let functor = force_value(functor)?;
3757                // __functor protocol: (functor self) arg
3758                let partial = apply(functor, func.clone())?;
3759                apply(partial, arg)
3760            } else if crate::value::in_promise_eval() {
3761                // M2.6 Promise softening: an attrset without __functor
3762                // being called as a function — typically the empty-
3763                // attrset sentinel inside a fix-point body.  Return
3764                // null so eval can proceed.
3765                Ok(Value::Null)
3766            } else {
3767                Err(EvalError::type_error(
3768                    format!("cannot call {} (missing __functor){}", func.type_name(), eval_file_ctx()),
3769                ))
3770            }
3771        }
3772        _ if crate::value::in_promise_eval() => {
3773            // M2.6 Promise softening: calling null / int / string / list
3774            // as a function inside a Promise body is the sentinel
3775            // cascade landing somewhere it doesn't belong.  Return null
3776            // so the fix-point continues instead of erroring.
3777            Ok(Value::Null)
3778        }
3779        _ => Err(EvalError::type_error(
3780            format!("cannot call {}{}", func.type_name(), eval_file_ctx()),
3781        )),
3782    }
3783}
3784
3785/// Dark-side lever `batch-bind` (byte-SAFE, `RedundantWrite`) — OFF by default.
3786/// When `SUI_BATCH_BIND=1`, an N-formal pattern binds in ONE copy-on-write step
3787/// (`Env::bind_many`) instead of N successive `env.bind()` calls. Byte-identical
3788/// either way (same intern, same insert order, same final HAMT — Phase 2's
3789/// `update_env` makes each default thunk's initial env capture unobservable).
3790/// Gated because the extra `Vec` allocation could regress the common small-pattern
3791/// case, and the win is unmeasured under load — never change the default path on a
3792/// hunch (never-ship-a-regression). Cached so the default path pays zero per call.
3793/// Ledger: `sui-spec/specs/darkside.lisp` (`batch-bind`, DarkGated).
3794static SUI_BATCH_BIND: std::sync::LazyLock<bool> =
3795    std::sync::LazyLock::new(|| std::env::var_os("SUI_BATCH_BIND").is_some());
3796
3797fn bind_param(param: &ast::Param, arg: &Value, env: &mut Env) -> Result<(), EvalError> {
3798    match param {
3799        ast::Param::IdentParam(ip) => {
3800            let ident = ip
3801                .ident()
3802                .ok_or_else(|| EvalError::ParseError("ident param missing ident".to_string()))?;
3803            let name = ident_text(&ident);
3804            env.bind(name, arg.clone());
3805        }
3806        ast::Param::Pattern(pat) => {
3807            let attrs = arg.as_attrs()?;
3808
3809            // @-binding (either `args @ { ... }` or `{ ... } @ args`)
3810            if let Some(pat_bind) = pat.pat_bind()
3811                && let Some(ident) = pat_bind.ident()
3812            {
3813                let name = ident_text(&ident);
3814                env.bind(name, arg.clone());
3815            }
3816
3817            let has_ellipsis = pat.ellipsis_token().is_some();
3818            let entries: Vec<ast::PatEntry> = pat.pat_entries().collect();
3819
3820            // Two-phase binding (matching CppNix semantics):
3821            // Phase 1: Bind all formals. Defaults get thunks with a
3822            //   preliminary env. We collect thunks for Phase 2 update.
3823            // Phase 2: Update default thunks to capture the final env
3824            //   (which now has ALL formals bound). This allows defaults
3825            //   to reference any other formal — including forward refs.
3826            let mut default_thunks: Vec<Thunk> = Vec::new();
3827            // batch-bind (byte-SAFE `RedundantWrite`, OFF unless `SUI_BATCH_BIND=1`):
3828            // the flag path collects every formal's (name, value) pair and binds
3829            // them in ONE copy-on-write step (`bind_many`) instead of N successive
3830            // `env.bind()` calls. Byte-identical either way — the default thunks
3831            // capture `env.clone()` (pre-batch) and Phase 2's `update_env` re-points
3832            // every one to the final all-formals-bound env, so a thunk's *initial*
3833            // capture is unobservable (overwritten before any force); same intern,
3834            // same insert order, same final HAMT. The default path (flag unset) is
3835            // the original per-formal loop, byte- AND perf-identical (no Vec alloc).
3836            let use_batch = *SUI_BATCH_BIND;
3837            let mut pairs: Vec<(String, Value)> =
3838                if use_batch { Vec::with_capacity(entries.len()) } else { Vec::new() };
3839
3840            // D3 (`SUI_SCOPE_NARROW>=1`) — the highest-yield arm of the fix,
3841            // because it fires on every `callPackage`'d
3842            // `{ stdenv, lib, foo ? null }` and every
3843            // `{ config, lib, pkgs, ... }` module in the fleet.
3844            //
3845            // Today EVERY default thunk is re-pointed at the final all-formals
3846            // env by Phase 2, so `{ a, b ? 1 }` closes
3847            // `b-thunk -> env -> b-thunk` and the whole call frame is immortal.
3848            // But a default only NEEDS the final env if it can reach a formal
3849            // that is itself satisfied by a default — those are the only names
3850            // still unbound when the default is built. Everything else (an
3851            // argument-supplied formal, the `@`-bind, any outer name) is
3852            // already in scope, so the capture is complete on the spot and the
3853            // cycle never has to be closed.
3854            //
3855            // Splitting the single pass in two is what makes that true:
3856            // pass A binds every argument-supplied formal FIRST, so pass B's
3857            // captures see all of them regardless of declaration order.
3858            //
3859            // The reorder is byte-safe: formal names are unique (a duplicate
3860            // is a parse error), `bindings` is a hash map read only by key, and
3861            // building a thunk has no side effects — so nothing observes the
3862            // order in which the two passes populate the env, only its final
3863            // contents, which are unchanged.
3864            let narrow = scope_narrow_enabled();
3865            // The formals that will be satisfied BY A DEFAULT — i.e. exactly
3866            // the names not yet bound when pass B runs.
3867            let default_names: HashSet<String> = if narrow {
3868                entries
3869                    .iter()
3870                    .filter(|e| e.default().is_some())
3871                    .filter_map(ast::PatEntry::ident)
3872                    .map(|i| ident_text(&i))
3873                    .filter(|n| attrs.get(n).is_none())
3874                    .collect()
3875            } else {
3876                HashSet::new()
3877            };
3878
3879            if narrow {
3880                // PASS A — argument-supplied formals only. The
3881                // `missing argument` error still fires here, in entry order,
3882                // exactly where the single pass raised it.
3883                let mut deferred: Vec<(String, ast::Expr)> =
3884                    Vec::with_capacity(default_names.len());
3885                for entry in &entries {
3886                    let ident = entry.ident().ok_or_else(|| {
3887                        EvalError::ParseError("pat entry missing ident".to_string())
3888                    })?;
3889                    let name = ident_text(&ident);
3890                    if let Some(v) = attrs.get(&name) {
3891                        env.bind(name, v.clone());
3892                    } else if let Some(default_expr) = entry.default() {
3893                        deferred.push((
3894                            name,
3895                            ast::Expr::cast(default_expr.syntax().clone()).unwrap(),
3896                        ));
3897                    } else {
3898                        return Err(EvalError::type_error(
3899                            format!("missing argument '{name}'{}", eval_file_ctx()),
3900                        ));
3901                    }
3902                }
3903                // PASS B — the defaults, capturing an env that already carries
3904                // every argument-supplied formal and the `@`-bind.
3905                for (name, default_expr) in deferred {
3906                    let thunk =
3907                        Thunk::new_suspended(default_expr.clone(), env.clone());
3908                    let referenced = referenced_idents(&default_expr);
3909                    if default_names.iter().any(|n| referenced.contains(n.as_str())) {
3910                        // Reaches another DEFAULTED formal, which may not be
3911                        // bound yet — it needs Phase 2's re-point, and pays
3912                        // the cycle.
3913                        default_thunks.push(thunk.clone());
3914                        crate::value::census::scope_pinned();
3915                    } else {
3916                        crate::value::census::scope_narrowed();
3917                    }
3918                    env.bind(name, Value::Thunk(thunk));
3919                }
3920            } else {
3921                for entry in &entries {
3922                    let ident = entry.ident().ok_or_else(|| {
3923                        EvalError::ParseError("pat entry missing ident".to_string())
3924                    })?;
3925                    let name = ident_text(&ident);
3926                    let value = if let Some(v) = attrs.get(&name) {
3927                        v.clone()
3928                    } else if let Some(default_expr) = entry.default() {
3929                        // Default values in pattern parameters must be lazy
3930                        // (wrapped in thunks), matching CppNix semantics.
3931                        // Patterns like `vendor ? assert false; null` rely on
3932                        // the default never being forced when the body checks
3933                        // `args ? vendor` instead of using `vendor` directly.
3934                        let thunk = Thunk::new_suspended(
3935                            ast::Expr::cast(default_expr.syntax().clone()).unwrap(),
3936                            env.clone(),
3937                        );
3938                        default_thunks.push(thunk.clone());
3939                        Value::Thunk(thunk)
3940                    } else {
3941                        return Err(EvalError::type_error(
3942                            format!("missing argument '{name}'{}", eval_file_ctx()),
3943                        ));
3944                    };
3945                    if use_batch {
3946                        pairs.push((name, value));
3947                    } else {
3948                        env.bind(name, value);
3949                    }
3950                }
3951                if use_batch {
3952                    env.bind_many(pairs);
3953                }
3954            }
3955
3956            // Phase 2: Update default thunks to see ALL formals.
3957            for thunk in &default_thunks {
3958                thunk.update_env(env);
3959            }
3960
3961            if !has_ellipsis {
3962                let entry_names: std::collections::HashSet<String> = entries
3963                    .iter()
3964                    .filter_map(|e| e.ident().map(|i| ident_text(&i)))
3965                    .collect();
3966                for key in attrs.keys() {
3967                    if !entry_names.contains(key.as_str()) {
3968                        return Err(EvalError::type_error(
3969                            format!("unexpected argument '{key}'{}", eval_file_ctx()),
3970                        ));
3971                    }
3972                }
3973            }
3974        }
3975    }
3976    Ok(())
3977}
3978
3979#[cfg(test)]
3980mod tests {
3981    use super::*;
3982
3983    fn ev(input: &str) -> Value {
3984        eval(input).unwrap()
3985    }
3986
3987    // Regression (2026-07-10): the let-scope fix-point detector must count
3988    // only GENUINE variable references, not attribute names / attrset keys
3989    // (which sit under a `NODE_ATTRPATH`).  nixpkgs `lib/types.nix` has
3990    // `placeholder = if lhs.placeholder == …` whose RHS mentions the
3991    // *attribute* `.placeholder`; the old raw-token match falsely flagged
3992    // the binding self-recursive and routed it through the Promise path.
3993    #[test]
3994    fn is_self_recursive_binding_ignores_attribute_names() {
3995        fn expr(s: &str) -> ast::Expr {
3996            rnix::Root::parse(s).tree().expr().expect("parse")
3997        }
3998        // attribute names / keys are NOT references to the binding
3999        assert!(!is_self_recursive_binding(&expr("lhs.placeholder"), "placeholder"));
4000        assert!(!is_self_recursive_binding(&expr("{ placeholder = 1; }"), "placeholder"));
4001        assert!(!is_self_recursive_binding(
4002            &expr("if lhs.placeholder == rhs.placeholder then lhs.placeholder else null"),
4003            "placeholder",
4004        ));
4005        // genuine variable references ARE detected
4006        assert!(is_self_recursive_binding(&expr("placeholder + 1"), "placeholder"));
4007        assert!(is_self_recursive_binding(
4008            &expr("if placeholder then 1 else 2"),
4009            "placeholder"
4010        ));
4011    }
4012
4013    // M2 thunk-waste (byte-safe eager constant): a NON-interpolated string in a
4014    // maybe_thunk site is evaluated directly (no suspended thunk). The value +
4015    // its (empty) context must be byte-identical to forcing a thunk of it.
4016    #[test]
4017    fn maybe_thunk_eager_constant_str_is_byte_identical() {
4018        fn expr(s: &str) -> ast::Expr {
4019            rnix::Root::parse(s).tree().expr().expect("parse")
4020        }
4021        let env = Env::new();
4022        // Constant string → returned as a concrete String, NOT a Thunk.
4023        let v = maybe_thunk(&expr(r#""abc""#), &env, false, None);
4024        assert!(matches!(v, Value::String(_)), "constant str should be eager, got {v:?}");
4025        assert_eq!(force_value(&v).unwrap(), Value::string("abc"));
4026        // Interpolated string → MUST stay a thunk (lazy `${…}` force).
4027        let vi = maybe_thunk(&expr(r#""a${b}c""#), &env, false, None);
4028        assert!(matches!(vi, Value::Thunk(_)), "interpolated str must stay thunked");
4029    }
4030
4031    // The pure-constant arg classifier admits ONLY literals + non-interpolated
4032    // strings/paths, and rejects everything that could throw/diverge/observe a
4033    // fixpoint — the laziness safety boundary of the apply-arg optimization.
4034    #[test]
4035    fn eval_pure_constant_arg_classification() {
4036        fn expr(s: &str) -> ast::Expr {
4037            rnix::Root::parse(s).tree().expr().expect("parse")
4038        }
4039        // ADMIT: pure constants (byte-safe to eval eagerly in an arg position).
4040        assert!(eval_pure_constant_arg(&expr("42")).is_some());
4041        assert!(eval_pure_constant_arg(&expr("3.14")).is_some());
4042        assert!(eval_pure_constant_arg(&expr(r#""const""#)).is_some());
4043        assert!(eval_pure_constant_arg(&expr("/abs/path")).is_some());
4044        // REJECT: anything that could throw / diverge / observe laziness.
4045        assert!(eval_pure_constant_arg(&expr(r#""a${b}c""#)).is_none(), "interpolated str");
4046        // `true`/`false`/`null` are IDENTS in nix (shadowable), not literals —
4047        // rejected to avoid a with-scope force, correctly conservative.
4048        assert!(eval_pure_constant_arg(&expr("true")).is_none(), "bool is an ident");
4049        assert!(eval_pure_constant_arg(&expr("x")).is_none(), "ident (with-scope force)");
4050        assert!(eval_pure_constant_arg(&expr("a.b")).is_none(), "select (fixpoint)");
4051        assert!(eval_pure_constant_arg(&expr("f x")).is_none(), "apply (may throw)");
4052        assert!(eval_pure_constant_arg(&expr("1 + 1")).is_none(), "binop (may throw)");
4053        assert!(eval_pure_constant_arg(&expr("throw \"x\"")).is_none(), "throw stays lazy");
4054    }
4055
4056    // LAZINESS GUARD: a lambda that IGNORES its arg must NOT force it — even a
4057    // throwing arg. The pure-constant optimization only touches inert constants,
4058    // so a `throw`-ing arg stays fully thunked and the ignoring lambda succeeds.
4059    #[test]
4060    fn ignored_throwing_arg_stays_lazy() {
4061        assert_eq!(ev(r#"(x: 7) (throw "boom")"#), Value::Int(7));
4062        // And an ignored constant arg is equally invisible.
4063        assert_eq!(ev(r#"(x: 7) "const""#), Value::Int(7));
4064        // A USED constant arg produces the right value.
4065        assert_eq!(ev(r#"(x: x) "used""#), Value::string("used"));
4066    }
4067
4068    #[test]
4069    fn eval_int() { assert_eq!(ev("42"), Value::Int(42)); }
4070
4071    #[test]
4072    fn eval_float() { assert_eq!(ev("3.14"), Value::Float(3.14)); }
4073
4074    #[test]
4075    fn eval_string() { assert_eq!(ev(r#""hello""#), Value::string("hello")); }
4076
4077    #[test]
4078    fn eval_bool() { assert_eq!(ev("true"), Value::Bool(true)); }
4079
4080    #[test]
4081    fn eval_null() { assert_eq!(ev("null"), Value::Null); }
4082
4083    #[test]
4084    fn eval_arithmetic() {
4085        assert_eq!(ev("1 + 2"), Value::Int(3));
4086        assert_eq!(ev("10 - 3"), Value::Int(7));
4087        assert_eq!(ev("2 * 3"), Value::Int(6));
4088        assert_eq!(ev("10 / 3"), Value::Int(3));
4089    }
4090
4091    #[test]
4092    fn eval_precedence() {
4093        assert_eq!(ev("1 + 2 * 3"), Value::Int(7));
4094        assert_eq!(ev("(1 + 2) * 3"), Value::Int(9));
4095    }
4096
4097    #[test]
4098    fn eval_comparison() {
4099        assert_eq!(ev("1 == 1"), Value::Bool(true));
4100        assert_eq!(ev("1 == 2"), Value::Bool(false));
4101        assert_eq!(ev("1 < 2"), Value::Bool(true));
4102        assert_eq!(ev("2 <= 2"), Value::Bool(true));
4103    }
4104
4105    #[test]
4106    fn eval_logic() {
4107        assert_eq!(ev("true && false"), Value::Bool(false));
4108        assert_eq!(ev("true || false"), Value::Bool(true));
4109        assert_eq!(ev("!true"), Value::Bool(false));
4110    }
4111
4112    #[test]
4113    fn eval_string_concat() {
4114        assert_eq!(ev(r#""hello" + " " + "world""#), Value::string("hello world"));
4115    }
4116
4117    #[test]
4118    fn eval_if() {
4119        assert_eq!(ev("if true then 1 else 2"), Value::Int(1));
4120        assert_eq!(ev("if false then 1 else 2"), Value::Int(2));
4121    }
4122
4123    #[test]
4124    fn eval_let() {
4125        assert_eq!(ev("let x = 1; in x"), Value::Int(1));
4126        assert_eq!(ev("let x = 1; y = 2; in x + y"), Value::Int(3));
4127    }
4128
4129    #[test]
4130    fn eval_let_dotted_simple() {
4131        // Two dotted bindings sharing the top-level key `a`.
4132        assert_eq!(ev("let a.b = 1; a.c = 2; in a.b + a.c"), Value::Int(3));
4133    }
4134
4135    #[test]
4136    fn eval_let_dotted_deep() {
4137        // Deeply nested dotted path.
4138        assert_eq!(ev("let a.b.c = 1; in a.b.c"), Value::Int(1));
4139    }
4140
4141    #[test]
4142    fn eval_let_dotted_mixed() {
4143        // Mix of simple and dotted bindings.
4144        assert_eq!(
4145            ev("let a.x = 1; b = 2; a.y = 3; in a.x + a.y + b"),
4146            Value::Int(6),
4147        );
4148    }
4149
4150    #[test]
4151    fn eval_let_dotted_produces_attrset() {
4152        // Dotted let bindings produce a real attrset.
4153        let v = ev("let a.b = 1; a.c = 2; in a");
4154        if let Value::Attrs(attrs) = v {
4155            assert_eq!(attrs.get("b"), Some(&Value::Int(1)));
4156            assert_eq!(attrs.get("c"), Some(&Value::Int(2)));
4157        } else {
4158            panic!("expected Attrs, got {v:?}");
4159        }
4160    }
4161
4162    // ── Inner dynamic attrpath key laziness ──────────────────
4163    // CppNix defers a dynamic key that is NOT at the head of an attrpath:
4164    // `{ a.${e} = v; }` builds `{ a = <thunk {${e}=v}>; }`, so `e` never
4165    // forces until `.a` is demanded. Reading a sibling must not force the
4166    // inner dynamic key. Root fix: `build_deferred_tail_attr` in eval.rs.
4167    // This is the pure-builtins reduction of the NixOS module-system
4168    // `config.homes.${cfg.userName}` fixpoint divergence.
4169    #[test]
4170    fn dynamic_inner_attr_key_is_lazy_on_sibling_read() {
4171        // The dynamic key throws; reading the SIBLING must NOT force it.
4172        assert_eq!(
4173            ev(r#"let s = { a.${throw "KEYFORCED"} = 7; other = 9; }; in s.other"#),
4174            Value::Int(9),
4175        );
4176    }
4177
4178    #[test]
4179    fn dynamic_inner_attr_key_resolves_on_head_demand() {
4180        // Demanding the head DOES resolve the deferred dynamic key.
4181        let v = ev(r#"let u = "bob"; s = { homes.${u} = 7; }; in s.homes"#);
4182        if let Value::Attrs(attrs) = force_value(&v).unwrap() {
4183            assert_eq!(attrs.get("bob"), Some(&Value::Int(7)));
4184        } else {
4185            panic!("expected Attrs");
4186        }
4187    }
4188
4189    #[test]
4190    fn dynamic_inner_attr_key_merges_with_static_sibling() {
4191        // Collision under one head still deep-merges (static + dynamic).
4192        let v = ev(r#"let u = "x"; s = { a.${u} = 1; a.b = 2; }; in s.a"#);
4193        if let Value::Attrs(attrs) = force_value(&v).unwrap() {
4194            assert_eq!(attrs.get("x"), Some(&Value::Int(1)));
4195            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
4196        } else {
4197            panic!("expected Attrs");
4198        }
4199    }
4200
4201    #[test]
4202    fn dynamic_inner_attr_key_null_skips_binding() {
4203        // A null dynamic inner key skips the definition (CppNix rule):
4204        // `a` becomes an empty attrset, the sibling stays.
4205        let v = ev(
4206            r#"let c = true; s = { a.${if c then null else "n"} = 5; b = 1; }; in s.b"#,
4207        );
4208        assert_eq!(v, Value::Int(1));
4209    }
4210
4211    // ── M2.6 ROOT #3: interpolated-STRING tail keys are dynamic too ──────
4212    // `{ a."p${e}" = v; }` must build `{ a = <thunk {"p${e}"=v}>; }` — an
4213    // interpolated-string attr key references `e` and so must defer like a
4214    // bare `${e}`, never force at construction. Reading a sibling must NOT
4215    // force it (the KEYFORCE discriminator, now for a `Str` key).
4216    #[test]
4217    fn interpolated_string_attr_key_is_lazy_on_sibling_read() {
4218        assert_eq!(
4219            ev(r#"let s = { a."p/${throw "KEYFORCED"}" = 7; other = 9; }; in s.other"#),
4220            Value::Int(9),
4221        );
4222    }
4223
4224    #[test]
4225    fn interpolated_string_attr_key_resolves_on_head_demand() {
4226        // Demanding the head DOES resolve the deferred interpolated key.
4227        let v = ev(r#"let u = "bob"; s = { homes."u/${u}" = 7; }; in s.homes"#);
4228        if let Value::Attrs(attrs) = force_value(&v).unwrap() {
4229            assert_eq!(attrs.get("u/bob"), Some(&Value::Int(7)));
4230        } else {
4231            panic!("expected Attrs");
4232        }
4233    }
4234
4235    #[test]
4236    fn purely_literal_string_attr_key_stays_eager_static() {
4237        // A `Str` key with NO interpolation is a plain static key and must
4238        // NOT be treated as dynamic (it forces nothing, deep-merges).
4239        let v = ev(r#"let s = { a."foo bar" = 1; a.b = 2; }; in s.a"#);
4240        if let Value::Attrs(attrs) = force_value(&v).unwrap() {
4241            assert_eq!(attrs.get("foo bar"), Some(&Value::Int(1)));
4242            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
4243        } else {
4244            panic!("expected Attrs");
4245        }
4246    }
4247
4248    // ── M2.6 ROOT #3 (collision case): dynamic tail key under a head that
4249    // a sibling binding already wrote must stay lazy AND deep-merge.
4250    #[test]
4251    fn dynamic_tail_key_under_colliding_head_is_lazy() {
4252        // `sd.services.x` writes head `sd`; the second binding's dynamic
4253        // key must NOT force when a SIBLING (`sd.services`) is read.
4254        let v = ev(
4255            r#"let s = { sd.services.x = 1; sd.tmpfiles.${throw "KEYFORCED"}.d = 2; }; in s.sd.services.x"#,
4256        );
4257        assert_eq!(v, Value::Int(1));
4258    }
4259
4260    #[test]
4261    fn dynamic_tail_key_under_colliding_head_resolves_and_merges() {
4262        // Demanding the dynamic branch resolves the key; the sibling
4263        // static branch (`sd.services`) survives the merge intact.
4264        let v = ev(
4265            r#"let k = "z"; s = { sd.services.x = 1; sd.tmpfiles.${k}.d = 2; }; in s.sd"#,
4266        );
4267        let sd = force_value(&v).unwrap();
4268        if let Value::Attrs(sd_attrs) = &sd {
4269            // static sibling intact
4270            let services = force_value(sd_attrs.get("services").unwrap()).unwrap();
4271            if let Value::Attrs(a) = &services {
4272                assert_eq!(force_value(a.get("x").unwrap()).unwrap(), Value::Int(1));
4273            } else { panic!("expected services attrs"); }
4274            // dynamic branch resolved to key "z"
4275            let tmpfiles = force_value(sd_attrs.get("tmpfiles").unwrap()).unwrap();
4276            if let Value::Attrs(a) = &tmpfiles {
4277                let z = force_value(a.get("z").unwrap()).unwrap();
4278                if let Value::Attrs(zd) = &z {
4279                    assert_eq!(force_value(zd.get("d").unwrap()).unwrap(), Value::Int(2));
4280                } else { panic!("expected z attrs"); }
4281            } else { panic!("expected tmpfiles attrs"); }
4282        } else {
4283            panic!("expected sd attrs");
4284        }
4285    }
4286
4287    // ── M2.6 ROOT #4a — `with` namespace must be LAZY ─────────────────
4288    // `with X; body` stores the namespace as a thunk forced only on a
4289    // bare-ident fallthrough lookup; demanding only the body's WHNF/keys
4290    // must NOT force X.  cppnix: `attrNames (with (throw "X"); {a=1;})`
4291    // → ["a"].  Before the fix, sui EVALUATED the namespace at `with`-entry
4292    // and threw.  This is the load-bearing over-force behind the M2.6
4293    // `concatLists null` (nixpkgs' `config = mkIf … (with config.services.X;
4294    // { … })` module shape forced `config.services.X` during collection).
4295    #[test]
4296    fn with_namespace_is_lazy_on_body_whnf() {
4297        let v = ev(r#"builtins.attrNames (with (throw "WITH-FORCED"); { a = 1; b = 2; })"#);
4298        if let Value::List(items) = force_value(&v).unwrap() {
4299            let names: Vec<String> = items
4300                .iter()
4301                .map(|i| match force_value(i).unwrap() {
4302                    Value::String(s) => s.as_str().to_string(),
4303                    other => panic!("expected string, got {}", other.type_name()),
4304                })
4305                .collect();
4306            assert_eq!(names, vec!["a".to_string(), "b".to_string()]);
4307        } else {
4308            panic!("expected list");
4309        }
4310    }
4311
4312    #[test]
4313    fn with_namespace_forces_only_on_fallthrough() {
4314        // A bare ident that falls through lexical scope DOES resolve via
4315        // the namespace (correct cppnix semantics) — proves the deferred
4316        // thunk is real and gets forced on demand, not an accidental no-op.
4317        assert_eq!(ev(r#"with { x = 42; }; x"#), Value::Int(42));
4318        // A lexical binding shadows the with-scope, so the (throwing)
4319        // namespace is never forced — the laziness we rely on for M2.6.
4320        assert_eq!(ev(r#"let x = 7; in with (throw "NS"); x"#), Value::Int(7));
4321    }
4322
4323    // ── M2.6 ROOT #4b — depth-≥2 dotted full-set leaf must deep-merge ──
4324    // `o.a = { x = 1; }` inserts `o = { a = <thunk {x=1}> }` (leaf goes
4325    // through maybe_thunk); a deeper sibling `o.a.y = 2` recurses
4326    // merge_nested_insert down to key `a` where the existing value is that
4327    // thunk.  Before the fix, merge_nested_insert required BOTH sides to be
4328    // concrete Attrs, so the Thunk-vs-Attrs collision OVERWROTE — dropping
4329    // `x`.  cppnix desugars both orderings into `o.a = { x = 1; y = 2; }`.
4330    // This is the M2.6 post-`with`-fix frontier (nixpkgs alsa's
4331    // `options.hardware.alsa = { … }` + `options.hardware.alsa.enablePersistence
4332    // = …` merged to only {enablePersistence} → `cardAliases` "does not exist").
4333    #[test]
4334    fn dotted_fullset_leaf_deep_merges_with_deeper_sibling() {
4335        let v = ev(r#"{ o.a = { x = 1; }; o.a.y = 2; }.o.a"#);
4336        if let Value::Attrs(a) = force_value(&v).unwrap() {
4337            assert_eq!(force_value(a.get("x").unwrap()).unwrap(), Value::Int(1));
4338            assert_eq!(force_value(a.get("y").unwrap()).unwrap(), Value::Int(2));
4339        } else {
4340            panic!("expected attrs");
4341        }
4342    }
4343
4344    #[test]
4345    fn dotted_fullset_leaf_deep_merge_reverse_order() {
4346        // Deeper sibling FIRST, full-set leaf SECOND — the NEW value is the
4347        // `<thunk {x=1}>`; must still merge (the collision forces it).
4348        let v = ev(r#"{ o.a.y = 2; o.a = { x = 1; }; }.o.a"#);
4349        if let Value::Attrs(a) = force_value(&v).unwrap() {
4350            assert_eq!(force_value(a.get("x").unwrap()).unwrap(), Value::Int(1));
4351            assert_eq!(force_value(a.get("y").unwrap()).unwrap(), Value::Int(2));
4352        } else {
4353            panic!("expected attrs");
4354        }
4355    }
4356
4357    #[test]
4358    fn dotted_fullset_leaf_merge_preserves_leaf_laziness() {
4359        // The merge forces the existing/new leaf to WHNF (keys) but MUST
4360        // NOT force the leaf VALUES — a throwing sibling value that is never
4361        // demanded stays lazy.
4362        assert_eq!(ev(r#"{ o.a = { x = throw "X-NEVER"; }; o.a.y = 2; }.o.a.y"#), Value::Int(2));
4363    }
4364
4365    #[test]
4366    fn eval_nested_let() {
4367        assert_eq!(ev("let a = 1; b = let c = 2; in c; in a + b"), Value::Int(3));
4368    }
4369
4370    #[test]
4371    fn eval_lambda() {
4372        assert_eq!(ev("(x: x + 1) 41"), Value::Int(42));
4373    }
4374
4375    #[test]
4376    fn eval_lambda_multi_arg() {
4377        assert_eq!(ev("(x: y: x + y) 1 2"), Value::Int(3));
4378    }
4379
4380    #[test]
4381    fn eval_list() {
4382        let v = ev("[1 2 3]");
4383        assert_eq!(v, Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]));
4384    }
4385
4386    #[test]
4387    fn eval_list_concat() {
4388        let v = ev("[1 2] ++ [3 4]");
4389        assert_eq!(v, Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3), Value::Int(4)]));
4390    }
4391
4392    #[test]
4393    fn eval_attrset() {
4394        let v = ev("{ a = 1; b = 2; }");
4395        if let Value::Attrs(attrs) = v {
4396            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
4397            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
4398        } else {
4399            panic!("expected attrset");
4400        }
4401    }
4402
4403    #[test]
4404    fn eval_select() {
4405        assert_eq!(ev("{ a = 42; }.a"), Value::Int(42));
4406    }
4407
4408    #[test]
4409    fn eval_select_or() {
4410        assert_eq!(ev("{ a = 42; }.b or 0"), Value::Int(0));
4411    }
4412
4413    #[test]
4414    fn eval_has_attr() {
4415        assert_eq!(ev("{ a = 1; } ? a"), Value::Bool(true));
4416        assert_eq!(ev("{ a = 1; } ? b"), Value::Bool(false));
4417    }
4418
4419    #[test]
4420    fn eval_update() {
4421        let v = ev("{ a = 1; b = 2; } // { b = 3; c = 4; }");
4422        if let Value::Attrs(attrs) = v {
4423            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
4424            assert_eq!(attrs.get("b"), Some(&Value::Int(3)));
4425            assert_eq!(attrs.get("c"), Some(&Value::Int(4)));
4426        } else {
4427            panic!("expected attrset");
4428        }
4429    }
4430
4431    #[test]
4432    fn eval_with() {
4433        assert_eq!(ev("with { x = 42; }; x"), Value::Int(42));
4434    }
4435
4436    #[test]
4437    fn eval_assert() {
4438        assert_eq!(ev("assert true; 42"), Value::Int(42));
4439        assert!(eval("assert false; 42").is_err());
4440    }
4441
4442    #[test]
4443    fn eval_formals() {
4444        assert_eq!(ev("({ a, b }: a + b) { a = 1; b = 2; }"), Value::Int(3));
4445    }
4446
4447    #[test]
4448    fn eval_formals_default() {
4449        assert_eq!(ev("({ a, b ? 10 }: a + b) { a = 1; }"), Value::Int(11));
4450    }
4451
4452    #[test]
4453    fn eval_formals_ellipsis() {
4454        assert_eq!(ev("({ a, ... }: a) { a = 1; b = 2; }"), Value::Int(1));
4455    }
4456
4457    #[test]
4458    fn eval_named_formals() {
4459        assert_eq!(ev("(args @ { a }: args.a) { a = 42; }"), Value::Int(42));
4460    }
4461
4462    #[test]
4463    fn eval_rec_attrset() {
4464        assert_eq!(ev("(rec { a = 1; b = a + 1; }).b"), Value::Int(2));
4465    }
4466
4467    #[test]
4468    fn eval_negation() {
4469        assert_eq!(ev("-42"), Value::Int(-42));
4470    }
4471
4472    #[test]
4473    fn eval_float_arithmetic() {
4474        assert_eq!(ev("1.5 + 2.5"), Value::Float(4.0));
4475        assert_eq!(ev("1 + 1.5"), Value::Float(2.5));
4476    }
4477
4478    #[test]
4479    fn eval_division_by_zero() {
4480        assert!(eval("1 / 0").is_err());
4481    }
4482
4483    #[test]
4484    fn eval_builtins_available() {
4485        assert_eq!(ev("builtins.typeOf 42"), Value::string("int"));
4486        assert_eq!(ev("builtins.typeOf true"), Value::string("bool"));
4487    }
4488
4489    #[test]
4490    fn eval_builtins_length() {
4491        assert_eq!(ev("builtins.length [1 2 3]"), Value::Int(3));
4492    }
4493
4494    #[test]
4495    fn eval_builtins_head_tail() {
4496        assert_eq!(ev("builtins.head [1 2 3]"), Value::Int(1));
4497        assert_eq!(ev("builtins.length (builtins.tail [1 2 3])"), Value::Int(2));
4498    }
4499
4500    #[test]
4501    fn eval_builtins_add() {
4502        assert_eq!(ev("builtins.add 1 2"), Value::Int(3));
4503    }
4504
4505    #[test]
4506    fn eval_builtins_to_string() {
4507        assert_eq!(ev("builtins.toString 42"), Value::string("42"));
4508    }
4509
4510    #[test]
4511    fn eval_implication() {
4512        assert_eq!(ev("false -> true"), Value::Bool(true));
4513        assert_eq!(ev("true -> false"), Value::Bool(false));
4514        assert_eq!(ev("true -> true"), Value::Bool(true));
4515    }
4516
4517    // ── New tests ────────────────────────────────────────
4518
4519    #[test]
4520    fn eval_error_undefined_variable() {
4521        let result = eval("nonexistent");
4522        assert!(result.is_err());
4523        let msg = format!("{}", result.unwrap_err());
4524        assert!(msg.contains("undefined variable"));
4525    }
4526
4527    #[test]
4528    fn eval_error_type_mismatch_arithmetic() {
4529        let result = eval(r#"1 + "hello""#);
4530        assert!(result.is_err());
4531        let msg = format!("{}", result.unwrap_err());
4532        assert!(msg.contains("cannot add") || msg.contains("type"));
4533    }
4534
4535    #[test]
4536    fn eval_error_unexpected_argument() {
4537        let result = eval("({ a }: a) { a = 1; b = 2; }");
4538        assert!(result.is_err());
4539        let msg = format!("{}", result.unwrap_err());
4540        assert!(msg.contains("unexpected argument"));
4541    }
4542
4543    #[test]
4544    fn eval_error_missing_required_argument() {
4545        let result = eval("({ a, b }: a + b) { a = 1; }");
4546        assert!(result.is_err());
4547        let msg = format!("{}", result.unwrap_err());
4548        assert!(msg.contains("missing argument"));
4549    }
4550
4551    #[test]
4552    fn eval_builtins_attr_names_sorted() {
4553        let v = ev("builtins.attrNames { z = 1; a = 2; m = 3; }");
4554        // BTreeMap keys are already sorted
4555        assert_eq!(
4556            v,
4557            Value::list(vec![
4558                Value::string("a"),
4559                Value::string("m"),
4560                Value::string("z"),
4561            ]),
4562        );
4563    }
4564
4565    #[test]
4566    fn eval_builtins_attr_values() {
4567        let v = ev("builtins.attrValues { a = 1; b = 2; }");
4568        // BTreeMap iteration is sorted by key, so a=1 first, b=2 second
4569        assert_eq!(v, Value::list(vec![Value::Int(1), Value::Int(2)]));
4570    }
4571
4572    #[test]
4573    fn eval_builtins_is_null() {
4574        assert_eq!(ev("builtins.isNull null"), Value::Bool(true));
4575        assert_eq!(ev("builtins.isNull 1"), Value::Bool(false));
4576    }
4577
4578    #[test]
4579    fn eval_builtins_is_int() {
4580        assert_eq!(ev("builtins.isInt 42"), Value::Bool(true));
4581        assert_eq!(ev("builtins.isInt 3.14"), Value::Bool(false));
4582    }
4583
4584    #[test]
4585    fn eval_builtins_is_bool() {
4586        assert_eq!(ev("builtins.isBool true"), Value::Bool(true));
4587        assert_eq!(ev("builtins.isBool 0"), Value::Bool(false));
4588    }
4589
4590    #[test]
4591    fn eval_builtins_is_string() {
4592        assert_eq!(ev(r#"builtins.isString "hi""#), Value::Bool(true));
4593        assert_eq!(ev("builtins.isString 1"), Value::Bool(false));
4594    }
4595
4596    #[test]
4597    fn eval_builtins_is_list() {
4598        assert_eq!(ev("builtins.isList [1 2]"), Value::Bool(true));
4599        assert_eq!(ev("builtins.isList {}"), Value::Bool(false));
4600    }
4601
4602    #[test]
4603    fn eval_builtins_is_attrs() {
4604        assert_eq!(ev("builtins.isAttrs {}"), Value::Bool(true));
4605        assert_eq!(ev("builtins.isAttrs []"), Value::Bool(false));
4606    }
4607
4608    #[test]
4609    fn eval_builtins_string_length() {
4610        assert_eq!(ev(r#"builtins.stringLength "hello""#), Value::Int(5));
4611        assert_eq!(ev(r#"builtins.stringLength """#), Value::Int(0));
4612    }
4613
4614    #[test]
4615    fn eval_builtins_to_json_roundtrip() {
4616        // toJSON produces a JSON string; fromJSON parses it back
4617        assert_eq!(
4618            ev(r#"builtins.fromJSON (builtins.toJSON 42)"#),
4619            Value::Int(42),
4620        );
4621        assert_eq!(
4622            ev(r#"builtins.fromJSON (builtins.toJSON [1 2 3])"#),
4623            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
4624        );
4625    }
4626
4627    #[test]
4628    fn eval_builtins_from_json() {
4629        assert_eq!(
4630            ev(r#"builtins.fromJSON "{\"a\": 1}""#),
4631            {
4632                let mut attrs = NixAttrs::new();
4633                attrs.insert("a".to_string(), Value::Int(1));
4634                Value::Attrs(Rc::new(attrs))
4635            },
4636        );
4637        assert_eq!(ev(r#"builtins.fromJSON "null""#), Value::Null);
4638        assert_eq!(ev(r#"builtins.fromJSON "true""#), Value::Bool(true));
4639    }
4640
4641    #[test]
4642    fn eval_nested_function_application() {
4643        // (f 1) 2 where f = x: y: x + y
4644        assert_eq!(ev("(x: y: x + y) 1 2"), Value::Int(3));
4645        // equivalent parenthesized form
4646        assert_eq!(ev("((x: y: x + y) 1) 2"), Value::Int(3));
4647    }
4648
4649    #[test]
4650    fn eval_recursive_let() {
4651        assert_eq!(ev("let a = 1; b = a + 1; in b"), Value::Int(2));
4652        assert_eq!(ev("let a = 1; b = a + 1; c = b + 1; in c"), Value::Int(3));
4653    }
4654
4655    #[test]
4656    fn eval_string_comparison() {
4657        assert_eq!(ev(r#""a" < "b""#), Value::Bool(true));
4658        assert_eq!(ev(r#""b" < "a""#), Value::Bool(false));
4659        assert_eq!(ev(r#""abc" == "abc""#), Value::Bool(true));
4660        assert_eq!(ev(r#""abc" != "def""#), Value::Bool(true));
4661    }
4662
4663    #[test]
4664    fn eval_list_in_attrset() {
4665        let v = ev("{ x = [1 2 3]; }.x");
4666        assert_eq!(
4667            v,
4668            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
4669        );
4670    }
4671
4672    #[test]
4673    fn eval_nested_attrset_select() {
4674        assert_eq!(ev("{ a = { b = 42; }; }.a.b"), Value::Int(42));
4675    }
4676
4677    #[test]
4678    fn eval_let_shadows_outer() {
4679        assert_eq!(
4680            ev("let x = 1; in let x = 2; in x"),
4681            Value::Int(2),
4682        );
4683    }
4684
4685    #[test]
4686    fn eval_with_provides_scope() {
4687        // `with` scope is available for name resolution
4688        assert_eq!(
4689            ev("with { x = 42; y = 10; }; x + y"),
4690            Value::Int(52),
4691        );
4692    }
4693
4694    #[test]
4695    fn eval_list_equality() {
4696        assert_eq!(ev("[1 2] == [1 2]"), Value::Bool(true));
4697        assert_eq!(ev("[1 2] == [1 3]"), Value::Bool(false));
4698    }
4699
4700    #[test]
4701    fn eval_attrset_equality() {
4702        assert_eq!(ev("{ a = 1; } == { a = 1; }"), Value::Bool(true));
4703        assert_eq!(ev("{ a = 1; } == { a = 2; }"), Value::Bool(false));
4704    }
4705
4706    // ═══════════════════════════════════════════════════════════
4707    // 1. LITERAL TYPES
4708    // ═══════════════════════════════════════════════════════════
4709
4710    #[test]
4711    fn literal_int_large_zero_negative() {
4712        // Large positive integer (within i64 range)
4713        assert_eq!(ev("9223372036854775807"), Value::Int(i64::MAX));
4714        // Zero
4715        assert_eq!(ev("0"), Value::Int(0));
4716        // Negative via unary negate
4717        assert_eq!(ev("-1"), Value::Int(-1));
4718        assert_eq!(ev("-999999"), Value::Int(-999999));
4719    }
4720
4721    #[test]
4722    fn literal_float_small_large() {
4723        assert_eq!(ev("0.001"), Value::Float(0.001));
4724        assert_eq!(ev("999999.999"), Value::Float(999999.999));
4725        // Float with scientific notation via expression (1e6 parsed by rnix)
4726        assert_eq!(ev("1.0e3"), Value::Float(1000.0));
4727        assert_eq!(ev("1.5e2"), Value::Float(150.0));
4728    }
4729
4730    #[test]
4731    fn literal_string_empty_and_escapes() {
4732        assert_eq!(ev(r#""""#), Value::string(""));
4733        // Escape sequences within strings
4734        assert_eq!(ev(r#""hello\nworld""#), Value::string("hello\nworld"));
4735        assert_eq!(ev(r#""tab\there""#), Value::string("tab\there"));
4736    }
4737
4738    #[test]
4739    fn literal_multiline_string() {
4740        // Indented string ('' ... '')
4741        assert_eq!(
4742            ev("''hello''"),
4743            Value::string("hello"),
4744        );
4745        // Multiline indented string strips common indentation
4746        assert_eq!(
4747            ev("''\n  line1\n  line2\n''"),
4748            Value::string("line1\nline2\n"),
4749        );
4750    }
4751
4752    #[test]
4753    fn literal_paths() {
4754        // Relative path
4755        assert_eq!(ev("./foo"), Value::Path(Box::new(SmolStr::from("./foo"))));
4756        // Absolute path
4757        assert_eq!(ev("/nix/store/abc"), Value::Path(Box::new(SmolStr::from("/nix/store/abc"))));
4758        // Home path
4759        assert_eq!(ev("~/myfile"), Value::Path(Box::new(SmolStr::from("~/myfile"))));
4760    }
4761
4762    // ── Interpolated path literals (cid-marquee root, 2026-07-12) ──
4763    //
4764    // CppNix path literals may contain `${e}` antiquotations: `./${x}.nix`,
4765    // `/a/${e}`, `~/${e}`. sui previously flattened the whole path token to
4766    // raw text and dropped the interpolation (`import ./${x}.nix` →
4767    // `No such file or directory`). The `${e}` must be evaluated,
4768    // string-coerced (plain, no copy-to-store), spliced, and the result is
4769    // still a `path` value. Oracles taken from cppnix.
4770
4771    #[test]
4772    fn interp_path_abs_splices_and_types_path() {
4773        // /a/${x}/b with x="foo" → /a/foo/b, type path (nix oracle).
4774        let v = ev(r#"let x = "foo"; in /a/${x}/b"#);
4775        assert_eq!(v, Value::Path(Box::new(SmolStr::from("/a/foo/b"))));
4776    }
4777
4778    #[test]
4779    fn interp_path_abs_multi_and_slash_in_value() {
4780        // Multiple interpolations + a slash inside the spliced value.
4781        assert_eq!(
4782            ev(r#"let a = "x"; b = "y/z"; in /p/${a}/${b}.nix"#),
4783            Value::Path(Box::new(SmolStr::from("/p/x/y/z.nix"))),
4784        );
4785    }
4786
4787    #[test]
4788    fn interp_path_abs_normalizes_double_slash_seam() {
4789        // A path-typed interpolation splices the raw path (no copy-to-store)
4790        // and the `/` seam is normalized: `/bar/` + `/tmp/foo` → /bar/tmp/foo.
4791        assert_eq!(
4792            ev(r#"/bar/${/tmp/foo}"#),
4793            Value::Path(Box::new(SmolStr::from("/bar/tmp/foo"))),
4794        );
4795    }
4796
4797    #[test]
4798    fn interp_path_rel_resolves_against_eval_dir() {
4799        // The spicetify `map (x: ./${x}.nix) [...]` root: a relative
4800        // interpolated path resolves against the defining file's directory,
4801        // exactly like a plain `./foo.nix` literal.
4802        let _g = push_eval_file(std::path::PathBuf::from("/tmp/example/default.nix"));
4803        assert_eq!(
4804            ev(r#"let x = "foo"; in ./${x}.nix"#),
4805            Value::Path(Box::new(SmolStr::from("/tmp/example/foo.nix"))),
4806        );
4807    }
4808
4809    #[test]
4810    fn interp_path_rel_no_eval_dir_keeps_relative_text() {
4811        // With no eval-file context the plain branch keeps the raw relative
4812        // text; the interpolated branch splices then does the same.
4813        assert_eq!(
4814            ev(r#"let x = "foo"; in ./${x}.nix"#),
4815            Value::Path(Box::new(SmolStr::from("./foo.nix"))),
4816        );
4817    }
4818
4819    #[test]
4820    fn interp_path_home_splices_leading_tilde_preserved() {
4821        // Home paths splice their `${e}`; the leading `~` is carried as-is
4822        // (matching sui's plain `~/foo` behavior — `~`-expansion is a
4823        // separate, pre-existing concern, not introduced here).
4824        assert_eq!(
4825            ev(r#"let x = "foo"; in ~/${x}/bar"#),
4826            Value::Path(Box::new(SmolStr::from("~/foo/bar"))),
4827        );
4828    }
4829
4830    #[test]
4831    fn interp_path_non_interpolated_still_raw() {
4832        // A path with no `${…}` must keep the trivial raw-text shortcut
4833        // (byte-for-byte identical to the plain branch).
4834        assert_eq!(ev("/a/b/c"), Value::Path(Box::new(SmolStr::from("/a/b/c"))));
4835        assert_eq!(ev("~/plain"), Value::Path(Box::new(SmolStr::from("~/plain"))));
4836    }
4837
4838    #[test]
4839    fn literal_null_true_false_standalone() {
4840        assert_eq!(ev("null"), Value::Null);
4841        assert_eq!(ev("true"), Value::Bool(true));
4842        assert_eq!(ev("false"), Value::Bool(false));
4843    }
4844
4845    // ═══════════════════════════════════════════════════════════
4846    // 2. OPERATORS — COMPLETE COVERAGE
4847    // ═══════════════════════════════════════════════════════════
4848
4849    #[test]
4850    fn op_arithmetic_int() {
4851        assert_eq!(ev("100 + 200"), Value::Int(300));
4852        assert_eq!(ev("50 - 30"), Value::Int(20));
4853        assert_eq!(ev("7 * 8"), Value::Int(56));
4854        assert_eq!(ev("17 / 3"), Value::Int(5)); // integer division
4855    }
4856
4857    #[test]
4858    fn op_arithmetic_float() {
4859        assert_eq!(ev("1.5 + 2.5"), Value::Float(4.0));
4860        assert_eq!(ev("5.0 - 1.5"), Value::Float(3.5));
4861        assert_eq!(ev("2.0 * 3.0"), Value::Float(6.0));
4862        assert_eq!(ev("7.0 / 2.0"), Value::Float(3.5));
4863    }
4864
4865    #[test]
4866    fn op_arithmetic_mixed_int_float() {
4867        // int + float => float
4868        assert_eq!(ev("1 + 2.5"), Value::Float(3.5));
4869        assert_eq!(ev("2.5 + 1"), Value::Float(3.5));
4870        // int * float => float
4871        assert_eq!(ev("2 * 1.5"), Value::Float(3.0));
4872        // float - int => float
4873        assert_eq!(ev("5.5 - 2"), Value::Float(3.5));
4874    }
4875
4876    #[test]
4877    fn op_string_concat() {
4878        assert_eq!(ev(r#""foo" + "bar""#), Value::string("foobar"));
4879        assert_eq!(ev(r#""" + "x""#), Value::string("x"));
4880        assert_eq!(ev(r#""a" + "" + "b""#), Value::string("ab"));
4881    }
4882
4883    #[test]
4884    fn op_path_concat() {
4885        // path + string
4886        assert_eq!(ev(r#"./foo + "/bar""#), Value::Path(Box::new(SmolStr::from("./foo/bar"))));
4887        // path + path (should join with /)
4888        assert_eq!(ev("./a + ./b"), Value::Path(Box::new(SmolStr::from("./a/./b"))));
4889    }
4890
4891    #[test]
4892    fn op_comparison_ints() {
4893        assert_eq!(ev("1 < 2"), Value::Bool(true));
4894        assert_eq!(ev("2 < 1"), Value::Bool(false));
4895        assert_eq!(ev("2 > 1"), Value::Bool(true));
4896        assert_eq!(ev("1 > 2"), Value::Bool(false));
4897        assert_eq!(ev("2 <= 2"), Value::Bool(true));
4898        assert_eq!(ev("3 <= 2"), Value::Bool(false));
4899        assert_eq!(ev("2 >= 2"), Value::Bool(true));
4900        assert_eq!(ev("1 >= 2"), Value::Bool(false));
4901    }
4902
4903    #[test]
4904    fn op_comparison_floats() {
4905        assert_eq!(ev("1.5 < 2.5"), Value::Bool(true));
4906        assert_eq!(ev("2.5 > 1.5"), Value::Bool(true));
4907        assert_eq!(ev("1.5 <= 1.5"), Value::Bool(true));
4908        assert_eq!(ev("1.5 >= 1.5"), Value::Bool(true));
4909    }
4910
4911    #[test]
4912    fn op_comparison_strings() {
4913        assert_eq!(ev(r#""apple" < "banana""#), Value::Bool(true));
4914        assert_eq!(ev(r#""banana" > "apple""#), Value::Bool(true));
4915        assert_eq!(ev(r#""abc" == "abc""#), Value::Bool(true));
4916        assert_eq!(ev(r#""abc" != "xyz""#), Value::Bool(true));
4917        assert_eq!(ev(r#""abc" <= "abd""#), Value::Bool(true));
4918        assert_eq!(ev(r#""abc" >= "abb""#), Value::Bool(true));
4919    }
4920
4921    #[test]
4922    fn op_equality_various_types() {
4923        assert_eq!(ev("null == null"), Value::Bool(true));
4924        assert_eq!(ev("true == true"), Value::Bool(true));
4925        assert_eq!(ev("false == false"), Value::Bool(true));
4926        assert_eq!(ev("true == false"), Value::Bool(false));
4927        assert_eq!(ev("1 == 1"), Value::Bool(true));
4928        assert_eq!(ev("1 != 2"), Value::Bool(true));
4929        // Different types are not equal
4930        assert_eq!(ev(r#"1 == "1""#), Value::Bool(false));
4931        assert_eq!(ev("null == false"), Value::Bool(false));
4932    }
4933
4934    #[test]
4935    fn op_logic_short_circuit() {
4936        // false && <error> should NOT evaluate the RHS
4937        assert_eq!(ev("false && (1 / 0 == 0)"), Value::Bool(false));
4938        // true || <error> should NOT evaluate the RHS
4939        assert_eq!(ev("true || (1 / 0 == 0)"), Value::Bool(true));
4940    }
4941
4942    #[test]
4943    fn op_logic_full() {
4944        assert_eq!(ev("true && true"), Value::Bool(true));
4945        assert_eq!(ev("true && false"), Value::Bool(false));
4946        assert_eq!(ev("false && true"), Value::Bool(false));
4947        assert_eq!(ev("false && false"), Value::Bool(false));
4948        assert_eq!(ev("true || true"), Value::Bool(true));
4949        assert_eq!(ev("true || false"), Value::Bool(true));
4950        assert_eq!(ev("false || true"), Value::Bool(true));
4951        assert_eq!(ev("false || false"), Value::Bool(false));
4952        assert_eq!(ev("!true"), Value::Bool(false));
4953        assert_eq!(ev("!false"), Value::Bool(true));
4954    }
4955
4956    #[test]
4957    fn op_implication_truth_table() {
4958        // false -> anything = true
4959        assert_eq!(ev("false -> false"), Value::Bool(true));
4960        assert_eq!(ev("false -> true"), Value::Bool(true));
4961        // true -> x = x
4962        assert_eq!(ev("true -> true"), Value::Bool(true));
4963        assert_eq!(ev("true -> false"), Value::Bool(false));
4964    }
4965
4966    #[test]
4967    fn op_implication_short_circuit() {
4968        // false -> <error> should NOT evaluate the RHS
4969        assert_eq!(ev("false -> (1 / 0 == 0)"), Value::Bool(true));
4970    }
4971
4972    #[test]
4973    fn op_update_merge() {
4974        let v = ev("{ a = 1; } // { b = 2; }");
4975        if let Value::Attrs(attrs) = v {
4976            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
4977            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
4978        } else {
4979            panic!("expected attrs");
4980        }
4981    }
4982
4983    #[test]
4984    fn op_update_right_wins() {
4985        assert_eq!(ev("({ a = 1; } // { a = 2; }).a"), Value::Int(2));
4986    }
4987
4988    #[test]
4989    fn op_list_concat() {
4990        assert_eq!(
4991            ev("[1 2] ++ [3 4]"),
4992            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3), Value::Int(4)]),
4993        );
4994        // Empty list concat
4995        assert_eq!(ev("[] ++ [1]"), Value::list(vec![Value::Int(1)]));
4996        assert_eq!(ev("[1] ++ []"), Value::list(vec![Value::Int(1)]));
4997    }
4998
4999    #[test]
5000    fn op_has_attr_present_and_absent() {
5001        assert_eq!(ev("{ x = 1; y = 2; } ? x"), Value::Bool(true));
5002        assert_eq!(ev("{ x = 1; } ? z"), Value::Bool(false));
5003        assert_eq!(ev("{} ? anything"), Value::Bool(false));
5004    }
5005
5006    #[test]
5007    fn op_unary_negate() {
5008        assert_eq!(ev("-42"), Value::Int(-42));
5009        assert_eq!(ev("-3.14"), Value::Float(-3.14));
5010        // Double negate
5011        assert_eq!(ev("- -5"), Value::Int(5));
5012    }
5013
5014    // ═══════════════════════════════════════════════════════════
5015    // 3. CONTROL FLOW
5016    // ═══════════════════════════════════════════════════════════
5017
5018    #[test]
5019    fn control_if_true_branch() {
5020        assert_eq!(ev("if true then 42 else 0"), Value::Int(42));
5021    }
5022
5023    #[test]
5024    fn control_if_false_branch() {
5025        assert_eq!(ev("if false then 42 else 0"), Value::Int(0));
5026    }
5027
5028    #[test]
5029    fn control_if_nested() {
5030        assert_eq!(
5031            ev("if true then (if false then 1 else 2) else 3"),
5032            Value::Int(2),
5033        );
5034        assert_eq!(
5035            ev("if false then 1 else (if true then 2 else 3)"),
5036            Value::Int(2),
5037        );
5038    }
5039
5040    #[test]
5041    fn control_assert_passing() {
5042        assert_eq!(ev("assert 1 == 1; 42"), Value::Int(42));
5043        assert_eq!(ev("assert true; true"), Value::Bool(true));
5044    }
5045
5046    #[test]
5047    fn control_assert_failing() {
5048        assert!(eval("assert false; 42").is_err());
5049        assert!(eval("assert 1 == 2; 42").is_err());
5050    }
5051
5052    #[test]
5053    fn control_with_basic_scope() {
5054        assert_eq!(ev("with { a = 1; b = 2; }; a + b"), Value::Int(3));
5055    }
5056
5057    #[test]
5058    fn control_with_lexical_precedence() {
5059        // let binding takes precedence over with scope
5060        assert_eq!(
5061            ev("let x = 10; in with { x = 99; }; x"),
5062            Value::Int(10),
5063        );
5064    }
5065
5066    #[test]
5067    fn control_with_nested() {
5068        assert_eq!(
5069            ev("with { a = 1; }; with { b = 2; }; a + b"),
5070            Value::Int(3),
5071        );
5072    }
5073
5074    #[test]
5075    fn control_with_lazy_fix_self() {
5076        // THE critical pattern that nixpkgs requires:
5077        // fix (self: with self; { a = 1; b = a + 1; })
5078        // Before the lazy-with fix, this would hit the blackhole detector
5079        // because `with` eagerly forced `self`.
5080        let result = eval(
5081            "let fix = f: let x = f x; in x; in fix (self: with self; { a = 1; b = a + 1; })"
5082        );
5083        assert!(result.is_ok(), "fix with self should work: {:?}", result);
5084        if let Ok(Value::Attrs(attrs)) = result {
5085            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
5086            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
5087        } else {
5088            panic!("expected Attrs, got {:?}", result);
5089        }
5090    }
5091
5092    #[test]
5093    fn control_with_lazy_fix_self_lib_pattern() {
5094        // The nixpkgs pattern: self-referential package set with lib.
5095        // Access via select to force through the thunk layer.
5096        let result = eval(r#"
5097            let fix = f: let x = f x; in x;
5098            in (fix (self: with self; {
5099                lib = { version = "1.0"; };
5100                hello = "hello ${lib.version}";
5101            })).hello
5102        "#);
5103        assert!(result.is_ok(), "nixpkgs-style lib pattern: {:?}", result);
5104        assert_eq!(
5105            result.unwrap(),
5106            Value::String(Rc::new(NixString::plain("hello 1.0"))),
5107        );
5108    }
5109
5110    #[test]
5111    fn control_with_non_attrset_errors() {
5112        // CppNix errors when with-scope is not an attrset and a lookup hits it
5113        let result = eval("with 42; 1");
5114        // The body `1` is a literal and doesn't look up anything in the
5115        // with-scope, so this should succeed (the scope is never forced).
5116        assert_eq!(result.unwrap(), Value::Int(1));
5117    }
5118
5119    #[test]
5120    fn control_with_non_attrset_lookup_falls_through() {
5121        // If the with scope is not an attrset, lookups should fall through
5122        // to outer scopes rather than crashing.
5123        let result = eval("let x = 1; in with 42; x");
5124        assert_eq!(result.unwrap(), Value::Int(1));
5125    }
5126
5127    #[test]
5128    fn control_let_simple_and_multiple() {
5129        assert_eq!(ev("let x = 5; in x"), Value::Int(5));
5130        assert_eq!(ev("let x = 1; y = 2; z = 3; in x + y + z"), Value::Int(6));
5131    }
5132
5133    #[test]
5134    fn control_let_shadow_outer() {
5135        assert_eq!(
5136            ev("let x = 1; in let x = 2; in x"),
5137            Value::Int(2),
5138        );
5139    }
5140
5141    #[test]
5142    fn control_let_recursive_reference() {
5143        assert_eq!(ev("let a = 1; b = a + 1; in b"), Value::Int(2));
5144        assert_eq!(ev("let a = 1; b = a + 1; c = b + 1; in c"), Value::Int(3));
5145    }
5146
5147    #[test]
5148    fn control_nested_let_expression() {
5149        assert_eq!(
5150            ev("let a = let b = 1; in b; in a"),
5151            Value::Int(1),
5152        );
5153        assert_eq!(
5154            ev("let a = let b = 10; in b + 5; in a * 2"),
5155            Value::Int(30),
5156        );
5157    }
5158
5159    // ═══════════════════════════════════════════════════════════
5160    // 4. FUNCTIONS — COMPLETE COVERAGE
5161    // ═══════════════════════════════════════════════════════════
5162
5163    #[test]
5164    fn func_identity_lambda() {
5165        assert_eq!(ev("(x: x) 42"), Value::Int(42));
5166        assert_eq!(ev(r#"(x: x) "hello""#), Value::string("hello"));
5167    }
5168
5169    #[test]
5170    fn func_curried_two_args() {
5171        assert_eq!(ev("(x: y: x + y) 3 4"), Value::Int(7));
5172    }
5173
5174    #[test]
5175    fn func_curried_three_args() {
5176        assert_eq!(ev("(a: b: c: a + b + c) 1 2 3"), Value::Int(6));
5177    }
5178
5179    #[test]
5180    fn func_formals_basic() {
5181        assert_eq!(ev("({ a, b }: a + b) { a = 3; b = 7; }"), Value::Int(10));
5182    }
5183
5184    #[test]
5185    fn func_formals_with_defaults() {
5186        assert_eq!(ev("({ a, b ? 10 }: a + b) { a = 5; }"), Value::Int(15));
5187        // Providing the default-able argument overrides the default
5188        assert_eq!(ev("({ a, b ? 10 }: a + b) { a = 5; b = 20; }"), Value::Int(25));
5189    }
5190
5191    #[test]
5192    fn func_formals_with_ellipsis() {
5193        assert_eq!(ev("({ a, ... }: a) { a = 1; b = 2; c = 3; }"), Value::Int(1));
5194    }
5195
5196    #[test]
5197    fn func_named_formals_at_before() {
5198        // args @ { a, b }: ...
5199        assert_eq!(
5200            ev("(args @ { a, b }: args.a + args.b) { a = 3; b = 4; }"),
5201            Value::Int(7),
5202        );
5203    }
5204
5205    #[test]
5206    fn func_named_formals_at_after() {
5207        // { a, b } @ args: ...
5208        assert_eq!(
5209            ev("({ a, b } @ args: args.a + args.b) { a = 10; b = 20; }"),
5210            Value::Int(30),
5211        );
5212    }
5213
5214    #[test]
5215    fn func_nested_application() {
5216        // Explicit parenthesized application
5217        assert_eq!(ev("((x: y: x * y) 3) 4"), Value::Int(12));
5218    }
5219
5220    #[test]
5221    fn func_higher_order_map() {
5222        assert_eq!(
5223            ev("builtins.map (x: x * 2) [1 2 3]"),
5224            Value::list(vec![Value::Int(2), Value::Int(4), Value::Int(6)]),
5225        );
5226    }
5227
5228    #[test]
5229    fn func_higher_order_filter() {
5230        assert_eq!(
5231            ev("builtins.filter (x: x > 2) [1 2 3 4 5]"),
5232            Value::list(vec![Value::Int(3), Value::Int(4), Value::Int(5)]),
5233        );
5234    }
5235
5236    #[test]
5237    fn func_higher_order_foldl() {
5238        // Sum of list via foldl'
5239        assert_eq!(
5240            ev("builtins.foldl' (acc: x: acc + x) 0 [1 2 3 4]"),
5241            Value::Int(10),
5242        );
5243    }
5244
5245    #[test]
5246    fn func_as_attrset_value() {
5247        assert_eq!(
5248            ev("let s = { f = x: x + 1; }; in s.f 5"),
5249            Value::Int(6),
5250        );
5251    }
5252
5253    #[test]
5254    fn func_immediate_application() {
5255        assert_eq!(ev("(x: x * x) 7"), Value::Int(49));
5256    }
5257
5258    #[test]
5259    fn func_in_let_binding() {
5260        assert_eq!(
5261            ev("let double = x: x * 2; in double 21"),
5262            Value::Int(42),
5263        );
5264    }
5265
5266    // ═══════════════════════════════════════════════════════════
5267    // 5. ATTRIBUTE SETS — COMPLETE COVERAGE
5268    // ═══════════════════════════════════════════════════════════
5269
5270    #[test]
5271    fn attrs_empty_set() {
5272        let v = ev("{}");
5273        if let Value::Attrs(attrs) = v {
5274            assert!(attrs.is_empty());
5275        } else {
5276            panic!("expected attrs");
5277        }
5278    }
5279
5280    #[test]
5281    fn attrs_simple() {
5282        assert_eq!(ev("{ a = 1; }.a"), Value::Int(1));
5283    }
5284
5285    #[test]
5286    fn attrs_nested_access() {
5287        assert_eq!(ev("{ a = { b = { c = 42; }; }; }.a.b.c"), Value::Int(42));
5288    }
5289
5290    #[test]
5291    fn attrs_recursive_set() {
5292        assert_eq!(ev("(rec { a = 1; b = a + 1; c = b + 1; }).c"), Value::Int(3));
5293    }
5294
5295    #[test]
5296    fn attrs_update_disjoint() {
5297        let v = ev("{ a = 1; } // { b = 2; }");
5298        if let Value::Attrs(attrs) = v {
5299            assert_eq!(attrs.len(), 2);
5300            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
5301            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
5302        } else {
5303            panic!("expected attrs");
5304        }
5305    }
5306
5307    #[test]
5308    fn attrs_update_override() {
5309        assert_eq!(ev("({ a = 1; } // { a = 2; }).a"), Value::Int(2));
5310    }
5311
5312    #[test]
5313    fn attrs_has_attr_operator() {
5314        assert_eq!(ev("{ a = 1; } ? a"), Value::Bool(true));
5315        assert_eq!(ev("{ a = 1; } ? b"), Value::Bool(false));
5316    }
5317
5318    #[test]
5319    fn attrs_select_with_default() {
5320        assert_eq!(ev("{ a = 1; }.a or 99"), Value::Int(1));
5321        assert_eq!(ev("{}.missing or 99"), Value::Int(99));
5322        assert_eq!(ev("{ a = 1; }.b or 42"), Value::Int(42));
5323    }
5324
5325    #[test]
5326    fn attrs_nested_attr_path_in_binding() {
5327        // { a.b = 1; } creates { a = { b = 1; }; }
5328        assert_eq!(ev("{ a.b = 1; }.a.b"), Value::Int(1));
5329    }
5330
5331    #[test]
5332    fn attrs_inherit_from_scope() {
5333        assert_eq!(ev("let x = 1; y = 2; in { inherit x y; }.x"), Value::Int(1));
5334        assert_eq!(ev("let x = 1; y = 2; in { inherit x y; }.y"), Value::Int(2));
5335    }
5336
5337    #[test]
5338    fn attrs_inherit_from_expr() {
5339        assert_eq!(
5340            ev("{ inherit ({ a = 42; b = 10; }) a; }.a"),
5341            Value::Int(42),
5342        );
5343    }
5344
5345    #[test]
5346    fn attrs_dynamic_attr_name() {
5347        assert_eq!(
5348            ev(r#"let name = "x"; in { ${name} = 42; }.x"#),
5349            Value::Int(42),
5350        );
5351    }
5352
5353    #[test]
5354    fn attrs_attr_names_sorted() {
5355        assert_eq!(
5356            ev("builtins.attrNames { z = 1; m = 2; a = 3; }"),
5357            Value::list(vec![
5358                Value::string("a"),
5359                Value::string("m"),
5360                Value::string("z"),
5361            ]),
5362        );
5363    }
5364
5365    #[test]
5366    fn attrs_attr_values_follow_key_order() {
5367        // BTreeMap iteration order: a=1, b=2, c=3
5368        assert_eq!(
5369            ev("builtins.attrValues { c = 3; a = 1; b = 2; }"),
5370            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
5371        );
5372    }
5373
5374    #[test]
5375    fn attrs_update_is_shallow() {
5376        // // is a shallow merge; nested attrs are replaced, not merged
5377        assert_eq!(
5378            ev("({ a = { x = 1; }; } // { a = { y = 2; }; }).a ? x"),
5379            Value::Bool(false),
5380        );
5381        assert_eq!(
5382            ev("({ a = { x = 1; }; } // { a = { y = 2; }; }).a.y"),
5383            Value::Int(2),
5384        );
5385    }
5386
5387    // ═══════════════════════════════════════════════════════════
5388    // 6. LISTS — COMPLETE COVERAGE
5389    // ═══════════════════════════════════════════════════════════
5390
5391    #[test]
5392    fn list_empty() {
5393        assert_eq!(ev("[]"), Value::list(vec![]));
5394    }
5395
5396    #[test]
5397    fn list_single_element() {
5398        assert_eq!(ev("[1]"), Value::list(vec![Value::Int(1)]));
5399    }
5400
5401    #[test]
5402    fn list_mixed_types() {
5403        assert_eq!(
5404            ev(r#"[1 "two" true null]"#),
5405            Value::list(vec![
5406                Value::Int(1),
5407                Value::string("two"),
5408                Value::Bool(true),
5409                Value::Null,
5410            ]),
5411        );
5412    }
5413
5414    #[test]
5415    fn list_nested() {
5416        assert_eq!(
5417            ev("[[1 2] [3 4]]"),
5418            Value::list(vec![
5419                Value::list(vec![Value::Int(1), Value::Int(2)]),
5420                Value::list(vec![Value::Int(3), Value::Int(4)]),
5421            ]),
5422        );
5423    }
5424
5425    #[test]
5426    fn list_concat_operator() {
5427        assert_eq!(
5428            ev("[1] ++ [2] ++ [3]"),
5429            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
5430        );
5431    }
5432
5433    #[test]
5434    fn list_builtins_length() {
5435        assert_eq!(ev("builtins.length [1 2 3]"), Value::Int(3));
5436        assert_eq!(ev("builtins.length []"), Value::Int(0));
5437    }
5438
5439    #[test]
5440    fn list_builtins_elem_at() {
5441        assert_eq!(ev("builtins.elemAt [10 20 30] 0"), Value::Int(10));
5442        assert_eq!(ev("builtins.elemAt [10 20 30] 1"), Value::Int(20));
5443        assert_eq!(ev("builtins.elemAt [10 20 30] 2"), Value::Int(30));
5444    }
5445
5446    #[test]
5447    fn list_equality() {
5448        assert_eq!(ev("[1 2 3] == [1 2 3]"), Value::Bool(true));
5449        assert_eq!(ev("[1 2] == [1 2 3]"), Value::Bool(false));
5450        assert_eq!(ev("[] == []"), Value::Bool(true));
5451    }
5452
5453    // ═══════════════════════════════════════════════════════════
5454    // 7. STRING INTERPOLATION
5455    // ═══════════════════════════════════════════════════════════
5456
5457    #[test]
5458    fn interp_simple_variable() {
5459        assert_eq!(
5460            ev(r#"let name = "world"; in "hello ${name}""#),
5461            Value::string("hello world"),
5462        );
5463    }
5464
5465    #[test]
5466    fn interp_nested_expression() {
5467        assert_eq!(
5468            ev(r#""result: ${builtins.toString (1 + 2)}""#),
5469            Value::string("result: 3"),
5470        );
5471    }
5472
5473    #[test]
5474    fn interp_int_coercion() {
5475        // Ints are coerced to string in interpolation
5476        assert_eq!(
5477            ev(r#"let x = 42; in "count: ${builtins.toString x}""#),
5478            Value::string("count: 42"),
5479        );
5480    }
5481
5482    #[test]
5483    fn interp_multiple() {
5484        assert_eq!(
5485            ev(r#"let a = "foo"; b = "bar"; in "${a} and ${b}""#),
5486            Value::string("foo and bar"),
5487        );
5488    }
5489
5490    #[test]
5491    fn interp_in_let() {
5492        assert_eq!(
5493            ev(r#"let x = "world"; in "hello ${x}""#),
5494            Value::string("hello world"),
5495        );
5496    }
5497
5498    #[test]
5499    fn interp_empty_result() {
5500        assert_eq!(
5501            ev(r#"let x = ""; in "a${x}b""#),
5502            Value::string("ab"),
5503        );
5504    }
5505
5506    #[test]
5507    fn interp_path_in_string_context() {
5508        // CppNix string interpolation is copy-to-store coercion: a nonexistent
5509        // path errors "path '…' does not exist" (previously sui spliced the raw
5510        // relative path "./foo" verbatim, diverging from nix). The positive
5511        // copy-to-store case is byte-verified in
5512        // interp_path_copies_to_store_byte_matches_cppnix below.
5513        assert!(eval(r#""path: ${./foo-nonexistent-xyz}""#).is_err());
5514    }
5515
5516    #[test]
5517    fn interp_adjacent_interpolations() {
5518        assert_eq!(
5519            ev(r#"let a = "x"; b = "y"; in "${a}${b}""#),
5520            Value::string("xy"),
5521        );
5522    }
5523
5524    // ═══════════════════════════════════════════════════════════
5525    // 8. BUILTINS — VERIFY ALL MAJOR ONES
5526    // ═══════════════════════════════════════════════════════════
5527
5528    #[test]
5529    fn builtins_map_filter_foldl() {
5530        // map
5531        assert_eq!(
5532            ev("builtins.map (x: x + 10) [1 2 3]"),
5533            Value::list(vec![Value::Int(11), Value::Int(12), Value::Int(13)]),
5534        );
5535        // filter
5536        assert_eq!(
5537            ev("builtins.filter (x: x > 1) [1 2 3]"),
5538            Value::list(vec![Value::Int(2), Value::Int(3)]),
5539        );
5540        // foldl' — product
5541        assert_eq!(
5542            ev("builtins.foldl' (a: b: a * b) 1 [2 3 4]"),
5543            Value::Int(24),
5544        );
5545    }
5546
5547    #[test]
5548    fn builtins_map_attrs() {
5549        assert_eq!(
5550            ev("(builtins.mapAttrs (name: value: value * 2) { a = 1; b = 2; }).a"),
5551            Value::Int(2),
5552        );
5553        assert_eq!(
5554            ev("(builtins.mapAttrs (name: value: value * 2) { a = 1; b = 2; }).b"),
5555            Value::Int(4),
5556        );
5557    }
5558
5559    #[test]
5560    fn builtins_list_to_attrs() {
5561        assert_eq!(
5562            ev(r#"(builtins.listToAttrs [{ name = "x"; value = 1; } { name = "y"; value = 2; }]).x"#),
5563            Value::Int(1),
5564        );
5565    }
5566
5567    #[test]
5568    fn builtins_list_to_attrs_duplicate_key_first_wins() {
5569        // Nix `listToAttrs` keeps the FIRST occurrence of a duplicate `name`
5570        // (later duplicates are ignored). cppnix returns 1 here, not 2.
5571        // Byte-parity root (cid darwin): a Cargo.lock listing a crate twice
5572        // (registry entry then git entry of the same name+version) must
5573        // resolve to the FIRST source, so `substrate/lockfile-delta.nix`'s
5574        // `lockByKey` picks the registry crate exactly as nix does. Last-wins
5575        // silently switched the source to git and produced a structurally
5576        // different `rust_<crate>` derivation.
5577        assert_eq!(
5578            ev(r#"(builtins.listToAttrs [{ name = "k"; value = 1; } { name = "k"; value = 2; }]).k"#),
5579            Value::Int(1),
5580        );
5581    }
5582
5583    #[test]
5584    fn builtins_concat_map() {
5585        assert_eq!(
5586            ev("builtins.concatMap (x: [x (x * 2)]) [1 2 3]"),
5587            Value::list(vec![
5588                Value::Int(1), Value::Int(2),
5589                Value::Int(2), Value::Int(4),
5590                Value::Int(3), Value::Int(6),
5591            ]),
5592        );
5593    }
5594
5595    #[test]
5596    fn builtins_concat_lists() {
5597        assert_eq!(
5598            ev("builtins.concatLists [[1 2] [3] [4 5]]"),
5599            Value::list(vec![
5600                Value::Int(1), Value::Int(2), Value::Int(3),
5601                Value::Int(4), Value::Int(5),
5602            ]),
5603        );
5604    }
5605
5606    #[test]
5607    fn builtins_concat_strings_sep() {
5608        assert_eq!(
5609            ev(r#"builtins.concatStringsSep ", " ["a" "b" "c"]"#),
5610            Value::string("a, b, c"),
5611        );
5612        assert_eq!(
5613            ev(r#"builtins.concatStringsSep "" ["x" "y"]"#),
5614            Value::string("xy"),
5615        );
5616    }
5617
5618    #[test]
5619    fn builtins_replace_strings() {
5620        assert_eq!(
5621            ev(r#"builtins.replaceStrings ["o"] ["0"] "foobar""#),
5622            Value::string("f00bar"),
5623        );
5624        assert_eq!(
5625            ev(r#"builtins.replaceStrings ["hello"] ["goodbye"] "hello world""#),
5626            Value::string("goodbye world"),
5627        );
5628    }
5629
5630    /// `hasPrefix`/`hasSuffix` are nixpkgs `lib.strings` functions, NOT CppNix
5631    /// builtins — so sui must not have them either. This test used to assert
5632    /// they worked; it now asserts they are absent, which is the same test
5633    /// pointed the correct way.
5634    #[test]
5635    fn builtins_has_prefix_has_suffix_are_not_builtins() {
5636        assert_eq!(ev(r#"builtins ? hasPrefix"#), Value::Bool(false));
5637        assert_eq!(ev(r#"builtins ? hasSuffix"#), Value::Bool(false));
5638        assert!(
5639            eval(r#"builtins.hasPrefix "he" "hello""#).is_err(),
5640            "builtins.hasPrefix must fail the way real nix fails it"
5641        );
5642        assert!(
5643            eval(r#"builtins.hasSuffix "lo" "hello""#).is_err(),
5644            "builtins.hasSuffix must fail the way real nix fails it"
5645        );
5646    }
5647
5648    #[test]
5649    fn builtins_all_any() {
5650        assert_eq!(ev("builtins.all (x: x > 0) [1 2 3]"), Value::Bool(true));
5651        assert_eq!(ev("builtins.all (x: x > 1) [1 2 3]"), Value::Bool(false));
5652        assert_eq!(ev("builtins.any (x: x > 2) [1 2 3]"), Value::Bool(true));
5653        assert_eq!(ev("builtins.any (x: x > 5) [1 2 3]"), Value::Bool(false));
5654    }
5655
5656    #[test]
5657    fn builtins_sort() {
5658        assert_eq!(
5659            ev("builtins.sort (a: b: a < b) [3 1 2]"),
5660            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
5661        );
5662    }
5663
5664    #[test]
5665    fn builtins_remove_attrs() {
5666        let v = ev(r#"builtins.removeAttrs { a = 1; b = 2; c = 3; } ["b" "c"]"#);
5667        if let Value::Attrs(attrs) = v {
5668            assert_eq!(attrs.len(), 1);
5669            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
5670            assert!(attrs.get("b").is_none());
5671        } else {
5672            panic!("expected attrs");
5673        }
5674    }
5675
5676    #[test]
5677    fn builtins_intersect_attrs() {
5678        let v = ev("builtins.intersectAttrs { a = 1; b = 2; } { b = 20; c = 30; }");
5679        if let Value::Attrs(attrs) = v {
5680            assert_eq!(attrs.len(), 1);
5681            // intersectAttrs returns values from the second set
5682            assert_eq!(attrs.get("b"), Some(&Value::Int(20)));
5683        } else {
5684            panic!("expected attrs");
5685        }
5686    }
5687
5688    #[test]
5689    fn builtins_type_of_all_types() {
5690        assert_eq!(ev("builtins.typeOf null"), Value::string("null"));
5691        assert_eq!(ev("builtins.typeOf true"), Value::string("bool"));
5692        assert_eq!(ev("builtins.typeOf 42"), Value::string("int"));
5693        assert_eq!(ev("builtins.typeOf 3.14"), Value::string("float"));
5694        assert_eq!(ev(r#"builtins.typeOf "hi""#), Value::string("string"));
5695        assert_eq!(ev("builtins.typeOf [1]"), Value::string("list"));
5696        assert_eq!(ev("builtins.typeOf {}"), Value::string("set"));
5697        assert_eq!(ev("builtins.typeOf (x: x)"), Value::string("lambda"));
5698    }
5699
5700    #[test]
5701    fn builtins_is_type_checks() {
5702        assert_eq!(ev("builtins.isNull null"), Value::Bool(true));
5703        assert_eq!(ev("builtins.isNull 0"), Value::Bool(false));
5704        assert_eq!(ev("builtins.isInt 42"), Value::Bool(true));
5705        assert_eq!(ev("builtins.isInt 3.14"), Value::Bool(false));
5706        assert_eq!(ev("builtins.isBool true"), Value::Bool(true));
5707        assert_eq!(ev("builtins.isBool 1"), Value::Bool(false));
5708        assert_eq!(ev(r#"builtins.isString "x""#), Value::Bool(true));
5709        assert_eq!(ev("builtins.isString 1"), Value::Bool(false));
5710        assert_eq!(ev("builtins.isList []"), Value::Bool(true));
5711        assert_eq!(ev("builtins.isList {}"), Value::Bool(false));
5712        assert_eq!(ev("builtins.isAttrs {}"), Value::Bool(true));
5713        assert_eq!(ev("builtins.isAttrs []"), Value::Bool(false));
5714        assert_eq!(ev("builtins.isFunction (x: x)"), Value::Bool(true));
5715        assert_eq!(ev("builtins.isFunction 1"), Value::Bool(false));
5716        assert_eq!(ev("builtins.isFloat 3.14"), Value::Bool(true));
5717        assert_eq!(ev("builtins.isFloat 1"), Value::Bool(false));
5718    }
5719
5720    #[test]
5721    fn builtins_to_json_from_json_roundtrip() {
5722        // int roundtrip
5723        assert_eq!(ev("builtins.fromJSON (builtins.toJSON 42)"), Value::Int(42));
5724        // string roundtrip
5725        assert_eq!(
5726            ev(r#"builtins.fromJSON (builtins.toJSON "hello")"#),
5727            Value::string("hello"),
5728        );
5729        // list roundtrip
5730        assert_eq!(
5731            ev("builtins.fromJSON (builtins.toJSON [1 2 3])"),
5732            Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
5733        );
5734        // null roundtrip
5735        assert_eq!(ev("builtins.fromJSON (builtins.toJSON null)"), Value::Null);
5736        // bool roundtrip
5737        assert_eq!(ev("builtins.fromJSON (builtins.toJSON true)"), Value::Bool(true));
5738    }
5739
5740    #[test]
5741    fn builtins_to_string_various() {
5742        assert_eq!(ev("builtins.toString 42"), Value::string("42"));
5743        assert_eq!(ev("builtins.toString true"), Value::string("1"));
5744        assert_eq!(ev("builtins.toString false"), Value::string(""));
5745        assert_eq!(ev("builtins.toString null"), Value::string(""));
5746        assert_eq!(ev(r#"builtins.toString "hello""#), Value::string("hello"));
5747    }
5748
5749    #[test]
5750    fn builtins_function_args() {
5751        let v = ev("builtins.functionArgs ({ a, b ? 1 }: a)");
5752        if let Value::Attrs(attrs) = v {
5753            assert_eq!(attrs.get("a"), Some(&Value::Bool(false))); // no default
5754            assert_eq!(attrs.get("b"), Some(&Value::Bool(true)));  // has default
5755        } else {
5756            panic!("expected attrs");
5757        }
5758    }
5759
5760    #[test]
5761    fn builtins_gen_list() {
5762        assert_eq!(
5763            ev("builtins.genList (x: x * x) 5"),
5764            Value::list(vec![
5765                Value::Int(0), Value::Int(1), Value::Int(4),
5766                Value::Int(9), Value::Int(16),
5767            ]),
5768        );
5769        assert_eq!(ev("builtins.genList (x: x) 0"), Value::list(vec![]));
5770    }
5771
5772    #[test]
5773    fn builtins_elem() {
5774        assert_eq!(ev("builtins.elem 2 [1 2 3]"), Value::Bool(true));
5775        assert_eq!(ev("builtins.elem 5 [1 2 3]"), Value::Bool(false));
5776        assert_eq!(ev("builtins.elem 1 []"), Value::Bool(false));
5777    }
5778
5779    #[test]
5780    fn builtins_head_tail() {
5781        assert_eq!(ev("builtins.head [10 20 30]"), Value::Int(10));
5782        assert_eq!(
5783            ev("builtins.tail [10 20 30]"),
5784            Value::list(vec![Value::Int(20), Value::Int(30)]),
5785        );
5786    }
5787
5788    #[test]
5789    fn builtins_string_length() {
5790        assert_eq!(ev(r#"builtins.stringLength "hello""#), Value::Int(5));
5791        assert_eq!(ev(r#"builtins.stringLength """#), Value::Int(0));
5792        assert_eq!(ev(r#"builtins.stringLength "abc def""#), Value::Int(7));
5793    }
5794
5795    #[test]
5796    fn builtins_ceil_floor() {
5797        assert_eq!(ev("builtins.ceil 2.3"), Value::Int(3));
5798        assert_eq!(ev("builtins.ceil 2.0"), Value::Int(2));
5799        assert_eq!(ev("builtins.floor 2.9"), Value::Int(2));
5800        assert_eq!(ev("builtins.floor 2.0"), Value::Int(2));
5801        // Int coercion: ceil/floor on int should work via to_float()
5802        assert_eq!(ev("builtins.ceil 5"), Value::Int(5));
5803        assert_eq!(ev("builtins.floor 5"), Value::Int(5));
5804    }
5805
5806    #[test]
5807    fn builtins_try_eval() {
5808        let v = ev("builtins.tryEval 42");
5809        if let Value::Attrs(attrs) = v {
5810            assert_eq!(attrs.get("success"), Some(&Value::Bool(true)));
5811            assert_eq!(attrs.get("value"), Some(&Value::Int(42)));
5812        } else {
5813            panic!("expected attrs");
5814        }
5815    }
5816
5817    #[test]
5818    fn builtins_throw() {
5819        let result = eval(r#"builtins.throw "oops""#);
5820        assert!(result.is_err());
5821        let msg = format!("{}", result.unwrap_err());
5822        assert!(msg.contains("oops"));
5823    }
5824
5825    #[test]
5826    fn builtins_seq_deep_seq() {
5827        // seq forces first arg, returns second
5828        assert_eq!(ev("builtins.seq 1 42"), Value::Int(42));
5829        // deepSeq similarly
5830        assert_eq!(ev("builtins.deepSeq [1 2 3] 99"), Value::Int(99));
5831    }
5832
5833    #[test]
5834    fn builtins_current_system() {
5835        let v = ev("builtins.currentSystem");
5836        if let Value::String(ns) = v {
5837            let s = &ns.chars;
5838            // Should be a valid system string
5839            assert!(
5840                s == "aarch64-darwin"
5841                    || s == "x86_64-darwin"
5842                    || s == "aarch64-linux"
5843                    || s == "x86_64-linux",
5844                "unexpected system: {s}",
5845            );
5846        } else {
5847            panic!("expected string");
5848        }
5849    }
5850
5851    // ═══════════════════════════════════════════════════════════
5852    // 9. REAL-WORLD NIXPKGS PATTERNS
5853    // ═══════════════════════════════════════════════════════════
5854
5855    #[test]
5856    fn pattern_mkif_like() {
5857        // lib.mkIf pattern: if condition then { key = value; } else {}
5858        assert_eq!(
5859            ev("(if true then { x = 1; } else {}).x"),
5860            Value::Int(1),
5861        );
5862        let v = ev("if false then { x = 1; } else {}");
5863        if let Value::Attrs(attrs) = v {
5864            assert!(attrs.is_empty());
5865        } else {
5866            panic!("expected attrs");
5867        }
5868    }
5869
5870    #[test]
5871    fn pattern_optional_attrs() {
5872        // lib.optionalAttrs pattern
5873        assert_eq!(
5874            ev("let optionalAttrs = cond: attrs: if cond then attrs else {}; in (optionalAttrs true { a = 1; }).a"),
5875            Value::Int(1),
5876        );
5877        let v = ev("let optionalAttrs = cond: attrs: if cond then attrs else {}; in optionalAttrs false { a = 1; }");
5878        if let Value::Attrs(attrs) = v {
5879            assert!(attrs.is_empty());
5880        } else {
5881            panic!("expected attrs");
5882        }
5883    }
5884
5885    #[test]
5886    fn pattern_filter_attrs_via_remove() {
5887        // lib.filterAttrs pattern via removeAttrs
5888        assert_eq!(
5889            ev(r#"(builtins.removeAttrs { a = 1; b = 2; c = 3; } ["b"]).a"#),
5890            Value::Int(1),
5891        );
5892        assert_eq!(
5893            ev(r#"(builtins.removeAttrs { a = 1; b = 2; c = 3; } ["b"]) ? b"#),
5894            Value::Bool(false),
5895        );
5896    }
5897
5898    #[test]
5899    fn pattern_override() {
5900        // default // overrides pattern
5901        let v = ev(r#"
5902            let
5903                defaults = { debug = false; port = 8080; host = "localhost"; };
5904                overrides = { debug = true; port = 9090; };
5905            in defaults // overrides
5906        "#);
5907        if let Value::Attrs(attrs) = v {
5908            assert_eq!(attrs.get("debug"), Some(&Value::Bool(true)));
5909            assert_eq!(attrs.get("port"), Some(&Value::Int(9090)));
5910            assert_eq!(attrs.get("host"), Some(&Value::string("localhost")));
5911        } else {
5912            panic!("expected attrs");
5913        }
5914    }
5915
5916    #[test]
5917    fn pattern_functor() {
5918        // { __functor = self: x: self.value + x; value = 10; } 5
5919        assert_eq!(
5920            ev("let s = { __functor = self: x: self.value + x; value = 10; }; in s 5"),
5921            Value::Int(15),
5922        );
5923    }
5924
5925    #[test]
5926    fn pattern_platform_check() {
5927        // Check pattern: if builtins.currentSystem == "..." then ... else ...
5928        let v = ev(r#"if builtins.currentSystem == "aarch64-darwin" then "arm" else "other""#);
5929        // We just verify it evaluates without error and produces a string
5930        if let Value::String(_) = v {
5931            // ok
5932        } else {
5933            panic!("expected string");
5934        }
5935    }
5936
5937    #[test]
5938    fn pattern_recursive_overlay_lambda_structure() {
5939        // Test the lambda structure of an overlay (self: super: { ... })
5940        let v = ev("let overlay = self: super: { pkg = 42; }; in overlay {} {}");
5941        if let Value::Attrs(attrs) = v {
5942            assert_eq!(attrs.get("pkg"), Some(&Value::Int(42)));
5943        } else {
5944            panic!("expected attrs");
5945        }
5946    }
5947
5948    #[test]
5949    fn pattern_call_package_simplified() {
5950        // Simplified callPackage: f: f { inherit lib; }
5951        assert_eq!(
5952            ev("let callPkg = f: f { lib = { id = x: x; }; }; lib = { id = x: x; }; in callPkg ({ lib }: lib.id 42)"),
5953            Value::Int(42),
5954        );
5955    }
5956
5957    #[test]
5958    fn pattern_derivation_like_attrset() {
5959        let v = ev(r#"{ type = "derivation"; name = "hello"; system = builtins.currentSystem; builder = "/bin/sh"; }"#);
5960        if let Value::Attrs(attrs) = v {
5961            assert_eq!(attrs.get("type"), Some(&Value::string("derivation")));
5962            assert_eq!(attrs.get("name"), Some(&Value::string("hello")));
5963            assert_eq!(attrs.get("builder"), Some(&Value::string("/bin/sh")));
5964            // system should be a string (may be a thunk that forces to string)
5965            let system = force_value(attrs.get("system").unwrap()).unwrap();
5966            assert!(matches!(system, Value::String(_)), "expected string, got {system:?}");
5967        } else {
5968            panic!("expected attrs");
5969        }
5970    }
5971
5972    #[test]
5973    fn pattern_module_system_simplified() {
5974        // Simplified NixOS module evaluation
5975        assert_eq!(
5976            ev(r#"
5977                let
5978                    eval = m: m { config = {}; lib = { mkDefault = x: x; }; };
5979                in eval ({ config, lib }: { result = lib.mkDefault 42; })
5980            "#),
5981            {
5982                let mut attrs = NixAttrs::new();
5983                attrs.insert("result".to_string(), Value::Int(42));
5984                Value::Attrs(Rc::new(attrs))
5985            },
5986        );
5987    }
5988
5989    // ═══════════════════════════════════════════════════════════
5990    // 10. ERROR HANDLING
5991    // ═══════════════════════════════════════════════════════════
5992
5993    #[test]
5994    fn error_undefined_variable() {
5995        let result = eval("nonexistent_var");
5996        assert!(result.is_err());
5997        let msg = format!("{}", result.unwrap_err());
5998        assert!(msg.contains("undefined variable") || msg.contains("nonexistent_var"));
5999    }
6000
6001    #[test]
6002    fn error_type_mismatch_arithmetic() {
6003        let result = eval(r#"1 + "hello""#);
6004        assert!(result.is_err());
6005    }
6006
6007    #[test]
6008    fn error_missing_attribute() {
6009        let result = eval("{}.nonexistent");
6010        assert!(result.is_err());
6011        let msg = format!("{}", result.unwrap_err());
6012        assert!(msg.contains("nonexistent") || msg.contains("not found"));
6013    }
6014
6015    #[test]
6016    fn error_division_by_zero() {
6017        assert!(eval("1 / 0").is_err());
6018        assert!(eval("100 / 0").is_err());
6019    }
6020
6021    #[test]
6022    fn error_missing_required_function_arg() {
6023        let result = eval("({ a, b }: a + b) { a = 1; }");
6024        assert!(result.is_err());
6025        let msg = format!("{}", result.unwrap_err());
6026        assert!(msg.contains("missing argument"));
6027    }
6028
6029    #[test]
6030    fn error_unexpected_function_arg() {
6031        let result = eval("({ a }: a) { a = 1; b = 2; }");
6032        assert!(result.is_err());
6033        let msg = format!("{}", result.unwrap_err());
6034        assert!(msg.contains("unexpected argument"));
6035    }
6036
6037    #[test]
6038    fn error_assertion_failure() {
6039        assert!(eval("assert false; 1").is_err());
6040        assert!(eval("assert 1 == 2; 1").is_err());
6041    }
6042
6043    #[test]
6044    fn error_infinite_recursion() {
6045        // `let x = x; in x` should either hit the depth guard or fail on
6046        // undefined variable (since sequential let can't see its own binding).
6047        let result = eval("let x = x; in x");
6048        assert!(result.is_err());
6049    }
6050
6051    #[test]
6052    fn error_infinite_recursion_via_lambda() {
6053        // A true infinite recursion via self-application -- depth guard catches this.
6054        let result = eval("let f = x: f x; in f 1");
6055        assert!(result.is_err());
6056        let msg = format!("{}", result.unwrap_err());
6057        assert!(
6058            msg.contains("infinite recursion") || msg.contains("eval depth") || msg.contains("undefined"),
6059        );
6060    }
6061
6062    // ═══════════════════════════════════════════════════════════
6063    // ADDITIONAL COVERAGE: edge cases and integration
6064    // ═══════════════════════════════════════════════════════════
6065
6066    #[test]
6067    fn integration_let_with_function_returning_attrset() {
6068        assert_eq!(
6069            ev("let mkPkg = name: { inherit name; version = 1; }; in (mkPkg \"hello\").name"),
6070            Value::string("hello"),
6071        );
6072    }
6073
6074    #[test]
6075    fn integration_chained_updates() {
6076        assert_eq!(
6077            ev("({ a = 1; } // { b = 2; } // { c = 3; }).c"),
6078            Value::Int(3),
6079        );
6080    }
6081
6082    #[test]
6083    fn integration_map_over_attrnames() {
6084        // Common nixpkgs pattern: map over attrNames
6085        assert_eq!(
6086            ev(r#"
6087                let
6088                    set = { a = 1; b = 2; };
6089                    names = builtins.attrNames set;
6090                in builtins.length names
6091            "#),
6092            Value::Int(2),
6093        );
6094    }
6095
6096    #[test]
6097    fn integration_compose_functions() {
6098        // Function composition
6099        assert_eq!(
6100            ev("let compose = f: g: x: f (g x); double = x: x * 2; inc = x: x + 1; in compose double inc 5"),
6101            Value::Int(12), // (5 + 1) * 2
6102        );
6103    }
6104
6105    #[test]
6106    fn integration_recursive_list_building() {
6107        // Build a list using genList and map
6108        assert_eq!(
6109            ev("builtins.map (x: x * x) (builtins.genList (x: x + 1) 4)"),
6110            Value::list(vec![Value::Int(1), Value::Int(4), Value::Int(9), Value::Int(16)]),
6111        );
6112    }
6113
6114    #[test]
6115    fn integration_attrset_from_list() {
6116        // Convert list to attrset via listToAttrs + map
6117        let v = ev(r#"
6118            builtins.listToAttrs (builtins.map (x: { name = x; value = true; }) ["a" "b" "c"])
6119        "#);
6120        if let Value::Attrs(attrs) = v {
6121            assert_eq!(attrs.get("a"), Some(&Value::Bool(true)));
6122            assert_eq!(attrs.get("b"), Some(&Value::Bool(true)));
6123            assert_eq!(attrs.get("c"), Some(&Value::Bool(true)));
6124        } else {
6125            panic!("expected attrs");
6126        }
6127    }
6128
6129    #[test]
6130    fn integration_nested_with_and_let() {
6131        assert_eq!(
6132            ev("let x = 10; in with { y = 20; }; x + y"),
6133            Value::Int(30),
6134        );
6135    }
6136
6137    #[test]
6138    fn integration_complex_pattern_match() {
6139        // Complex function with defaults, ellipsis, and @ pattern
6140        assert_eq!(
6141            ev("(args @ { a, b ? 5, ... }: a + b + (if args ? c then args.c else 0)) { a = 1; c = 10; }"),
6142            Value::Int(16), // 1 + 5 + 10
6143        );
6144    }
6145
6146    #[test]
6147    fn integration_substring() {
6148        assert_eq!(
6149            ev(r#"builtins.substring 0 5 "hello world""#),
6150            Value::string("hello"),
6151        );
6152        assert_eq!(
6153            ev(r#"builtins.substring 6 5 "hello world""#),
6154            Value::string("world"),
6155        );
6156    }
6157
6158    #[test]
6159    fn integration_has_attr_on_nested() {
6160        // ? on nested attr paths
6161        assert_eq!(ev("{ a = { b = 1; }; } ? a"), Value::Bool(true));
6162        assert_eq!(
6163            ev("({ a = { b = 1; }; }.a) ? b"),
6164            Value::Bool(true),
6165        );
6166    }
6167
6168    #[test]
6169    fn integration_cat_attrs() {
6170        assert_eq!(
6171            ev(r#"builtins.catAttrs "x" [{ x = 1; } { y = 2; } { x = 3; }]"#),
6172            Value::list(vec![Value::Int(1), Value::Int(3)]),
6173        );
6174    }
6175
6176    #[test]
6177    fn integration_get_attr_builtin() {
6178        assert_eq!(
6179            ev(r#"builtins.getAttr "a" { a = 42; b = 10; }"#),
6180            Value::Int(42),
6181        );
6182    }
6183
6184    #[test]
6185    fn integration_has_attr_builtin() {
6186        assert_eq!(
6187            ev(r#"builtins.hasAttr "a" { a = 1; }"#),
6188            Value::Bool(true),
6189        );
6190        assert_eq!(
6191            ev(r#"builtins.hasAttr "z" { a = 1; }"#),
6192            Value::Bool(false),
6193        );
6194    }
6195
6196    #[test]
6197    fn integration_is_path() {
6198        assert_eq!(ev("builtins.isPath ./foo"), Value::Bool(true));
6199        assert_eq!(ev("builtins.isPath 42"), Value::Bool(false));
6200    }
6201
6202    #[test]
6203    fn integration_builtins_trace() {
6204        // trace prints the first arg (as debug) and returns the second
6205        assert_eq!(ev(r#"builtins.trace "debug msg" 42"#), Value::Int(42));
6206    }
6207
6208    #[test]
6209    fn integration_builtins_split() {
6210        // Nix spec: split returns alternating non-match strings and match group lists.
6211        // When the regex has no capture groups, separator positions get empty lists.
6212        // split "/" "a/b/c" => ["a" [] "b" [] "c"]
6213        assert_eq!(
6214            ev(r#"builtins.split "/" "a/b/c""#),
6215            Value::list(vec![
6216                Value::string("a"),
6217                Value::list(vec![]),
6218                Value::string("b"),
6219                Value::list(vec![]),
6220                Value::string("c"),
6221            ]),
6222        );
6223        // With a capture group, the captured text appears in the list.
6224        // split "(/)" "a/b/c" => ["a" ["/"] "b" ["/"] "c"]
6225        assert_eq!(
6226            ev(r#"builtins.split "(/)" "a/b/c""#),
6227            Value::list(vec![
6228                Value::string("a"),
6229                Value::list(vec![Value::string("/")]),
6230                Value::string("b"),
6231                Value::list(vec![Value::string("/")]),
6232                Value::string("c"),
6233            ]),
6234        );
6235    }
6236
6237    #[test]
6238    fn integration_builtins_split_no_capture_groups() {
6239        // builtins.split with no capture groups returns empty lists
6240        // at separator positions — matches CppNix behavior.
6241        // This is critical for nixpkgs lib.splitString which uses
6242        // builtins.filter builtins.isString on the result.
6243        assert_eq!(
6244            ev(r#"builtins.split "-" "aarch64-darwin""#),
6245            Value::list(vec![
6246                Value::string("aarch64"),
6247                Value::list(vec![]),
6248                Value::string("darwin"),
6249            ]),
6250        );
6251    }
6252
6253    #[test]
6254    fn integration_builtins_split_system_string_filter() {
6255        // Simulates nixpkgs lib.splitString: filter isString (split pattern string)
6256        // This is the exact pattern that parses system strings like "aarch64-darwin".
6257        assert_eq!(
6258            ev(r#"builtins.filter builtins.isString (builtins.split "-" "aarch64-darwin")"#),
6259            Value::list(vec![
6260                Value::string("aarch64"),
6261                Value::string("darwin"),
6262            ]),
6263        );
6264    }
6265
6266    #[test]
6267    fn integration_deeply_nested_let() {
6268        // Deeply nested let-in expressions
6269        assert_eq!(
6270            ev("let a = let b = let c = 10; in c * 2; in b + 1; in a"),
6271            Value::Int(21),
6272        );
6273    }
6274
6275    #[test]
6276    fn integration_if_in_attrset_value() {
6277        assert_eq!(
6278            ev("{ x = if true then 1 else 2; }.x"),
6279            Value::Int(1),
6280        );
6281    }
6282
6283    #[test]
6284    fn integration_lambda_in_list() {
6285        // Store lambdas in a list and apply them
6286        assert_eq!(
6287            ev("let fs = [(x: x + 1) (x: x * 2)]; in (builtins.elemAt fs 0) 5"),
6288            Value::Int(6),
6289        );
6290        assert_eq!(
6291            ev("let fs = [(x: x + 1) (x: x * 2)]; in (builtins.elemAt fs 1) 5"),
6292            Value::Int(10),
6293        );
6294    }
6295
6296    #[test]
6297    fn integration_nixpkgs_lib_id() {
6298        // lib.id = x: x
6299        assert_eq!(
6300            ev("let lib = { id = x: x; const = a: b: a; }; in lib.id 42"),
6301            Value::Int(42),
6302        );
6303        assert_eq!(
6304            ev("let lib = { id = x: x; const = a: b: a; }; in lib.const 1 2"),
6305            Value::Int(1),
6306        );
6307    }
6308
6309    #[test]
6310    fn integration_multiple_inherit() {
6311        assert_eq!(
6312            ev("let a = 1; b = 2; c = 3; in { inherit a b c; }.b"),
6313            Value::Int(2),
6314        );
6315    }
6316
6317    #[test]
6318    fn integration_rec_set_with_builtins() {
6319        assert_eq!(
6320            ev(r#"(rec { a = "hello"; b = builtins.stringLength a; }).b"#),
6321            Value::Int(5),
6322        );
6323    }
6324
6325    // ═══════════════════════════════════════════════════════════
6326    // 11. __FUNCTOR PROTOCOL
6327    // ═══════════════════════════════════════════════════════════
6328
6329    #[test]
6330    fn functor_simple_callable_attrset() {
6331        assert_eq!(
6332            ev("let s = { __functor = self: x: x + 1; }; in s 41"),
6333            Value::Int(42),
6334        );
6335    }
6336
6337    #[test]
6338    fn functor_with_self_reference() {
6339        assert_eq!(
6340            ev("let s = { __functor = self: x: self.base + x; base = 100; }; in s 23"),
6341            Value::Int(123),
6342        );
6343    }
6344
6345    #[test]
6346    fn functor_updated_attrset() {
6347        // Override a field in the attrset, functor still works
6348        assert_eq!(
6349            ev(r#"
6350                let
6351                    mk = { __functor = self: x: self.n + x; n = 0; };
6352                    s = mk // { n = 50; };
6353                in s 7
6354            "#),
6355            Value::Int(57),
6356        );
6357    }
6358
6359    #[test]
6360    fn functor_error_on_non_callable_attrset() {
6361        // Attrset without __functor should produce error when called
6362        let result = eval("let s = { a = 1; }; in s 5");
6363        assert!(result.is_err());
6364    }
6365
6366    // ═══════════════════════════════════════════════════════════
6367    // 12. __TOSTRING PROTOCOL
6368    // ═══════════════════════════════════════════════════════════
6369
6370    #[test]
6371    fn to_string_protocol_in_interpolation() {
6372        assert_eq!(
6373            ev(r#"let s = { __toString = self: "world"; }; in "hello ${s}""#),
6374            Value::string("hello world"),
6375        );
6376    }
6377
6378    #[test]
6379    fn to_string_protocol_accesses_self() {
6380        assert_eq!(
6381            ev(r#"let s = { __toString = self: self.val; val = "abc"; }; in "${s}""#),
6382            Value::string("abc"),
6383        );
6384    }
6385
6386    #[test]
6387    fn to_string_protocol_via_builtin_to_string() {
6388        assert_eq!(
6389            ev(r#"builtins.toString { __toString = self: "via-builtin"; }"#),
6390            Value::string("via-builtin"),
6391        );
6392    }
6393
6394    #[test]
6395    fn to_string_protocol_attrset_without_toString_fails() {
6396        // An attrset without __toString should fail in string context
6397        let result = eval(r#""${{}}"#);
6398        assert!(result.is_err());
6399    }
6400
6401    // ═══════════════════════════════════════════════════════════
6402    // 13. NEWLY IMPLEMENTED BUILTINS (eval-level tests)
6403    // ═══════════════════════════════════════════════════════════
6404
6405    /// `concatStrings` is nixpkgs `lib.strings.concatStrings`, not a CppNix
6406    /// builtin. The CAPABILITY is not lost — `concatStringsSep ""` is the real
6407    /// builtin spelling and is asserted here to still produce the same bytes,
6408    /// so this test proves both halves: the invented name is gone, and nothing
6409    /// a nix program can legally write got worse.
6410    #[test]
6411    fn eval_builtins_concat_strings_is_not_a_builtin() {
6412        assert_eq!(ev(r#"builtins ? concatStrings"#), Value::Bool(false));
6413        assert!(
6414            eval(r#"builtins.concatStrings ["a" "b" "c"]"#).is_err(),
6415            "builtins.concatStrings must fail the way real nix fails it"
6416        );
6417        assert_eq!(
6418            ev(r#"builtins.concatStringsSep "" ["a" "b" "c"]"#),
6419            Value::string("abc"),
6420        );
6421        assert_eq!(
6422            ev(r#"builtins.concatStringsSep "" []"#),
6423            Value::string(""),
6424        );
6425    }
6426
6427    #[test]
6428    fn eval_builtins_partition() {
6429        let v = ev("builtins.partition (x: x > 3) [1 2 3 4 5]");
6430        if let Value::Attrs(a) = v {
6431            assert_eq!(a.get("right"), Some(&Value::list(vec![Value::Int(4), Value::Int(5)])));
6432            assert_eq!(a.get("wrong"), Some(&Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)])));
6433        } else {
6434            panic!("expected attrs");
6435        }
6436    }
6437
6438    #[test]
6439    fn eval_builtins_group_by() {
6440        let v = ev(r#"builtins.groupBy (x: if x > 0 then "pos" else "neg") [1 (0 - 2) 3 (0 - 4)]"#);
6441        if let Value::Attrs(a) = v {
6442            assert_eq!(a.get("pos"), Some(&Value::list(vec![Value::Int(1), Value::Int(3)])));
6443            assert_eq!(a.get("neg"), Some(&Value::list(vec![Value::Int(-2), Value::Int(-4)])));
6444        } else {
6445            panic!("expected attrs");
6446        }
6447    }
6448
6449    #[test]
6450    fn eval_builtins_zip_attrs_with() {
6451        let v = ev("builtins.zipAttrsWith (n: vs: builtins.head vs) [{ a = 1; } { a = 2; b = 3; }]");
6452        if let Value::Attrs(a) = v {
6453            assert_eq!(a.get("a"), Some(&Value::Int(1)));
6454            assert_eq!(a.get("b"), Some(&Value::Int(3)));
6455        } else {
6456            panic!("expected attrs");
6457        }
6458    }
6459
6460    #[test]
6461    fn eval_builtins_compare_versions() {
6462        assert_eq!(ev(r#"builtins.compareVersions "2.0" "1.0""#), Value::Int(1));
6463        assert_eq!(ev(r#"builtins.compareVersions "1.0" "2.0""#), Value::Int(-1));
6464        assert_eq!(ev(r#"builtins.compareVersions "1.0" "1.0""#), Value::Int(0));
6465    }
6466
6467    #[test]
6468    fn eval_builtins_parse_drv_name() {
6469        let v = ev(r#"builtins.parseDrvName "nix-2.3.4""#);
6470        if let Value::Attrs(a) = v {
6471            assert_eq!(a.get("name"), Some(&Value::string("nix")));
6472            assert_eq!(a.get("version"), Some(&Value::string("2.3.4")));
6473        } else {
6474            panic!("expected attrs");
6475        }
6476    }
6477
6478    #[test]
6479    fn eval_builtins_base_name_of() {
6480        assert_eq!(
6481            ev(r#"builtins.baseNameOf "/foo/bar/baz""#),
6482            Value::string("baz"),
6483        );
6484    }
6485
6486    #[test]
6487    fn eval_builtins_dir_of() {
6488        assert_eq!(
6489            ev(r#"builtins.dirOf "/foo/bar/baz""#),
6490            Value::string("/foo/bar"),
6491        );
6492    }
6493
6494    #[test]
6495    fn eval_builtins_add_error_context() {
6496        assert_eq!(
6497            ev(r#"builtins.addErrorContext "some context" 42"#),
6498            Value::Int(42),
6499        );
6500    }
6501
6502    #[test]
6503    fn eval_builtins_abort() {
6504        let result = eval(r#"builtins.abort "fatal error""#);
6505        assert!(result.is_err());
6506        let msg = format!("{}", result.unwrap_err());
6507        assert!(msg.contains("fatal error"));
6508    }
6509
6510    // ═══════════════════════════════════════════════════════════
6511    // 14. INDENTED STRINGS ('' ... '')
6512    // ═══════════════════════════════════════════════════════════
6513
6514    #[test]
6515    fn indented_string_simple() {
6516        assert_eq!(ev("''hello''"), Value::string("hello"));
6517    }
6518
6519    #[test]
6520    fn indented_string_multiline_strips_indent() {
6521        assert_eq!(
6522            ev("''\n  line1\n  line2\n''"),
6523            Value::string("line1\nline2\n"),
6524        );
6525    }
6526
6527    #[test]
6528    fn indented_string_with_interpolation() {
6529        let code = "let x = \"world\"; in ''hello ${x}''";
6530        assert_eq!(
6531            ev(code),
6532            Value::string("hello world"),
6533        );
6534    }
6535
6536    #[test]
6537    fn indented_string_deeper_indent_preserved() {
6538        // Common indent is 2 spaces; the 4-space line keeps 2 extra
6539        assert_eq!(
6540            ev("''\n  a\n    b\n''"),
6541            Value::string("a\n  b\n"),
6542        );
6543    }
6544
6545    // ═══════════════════════════════════════════════════════════
6546    // 15. DYNAMIC ATTRIBUTE NAMES
6547    // ═══════════════════════════════════════════════════════════
6548
6549    #[test]
6550    fn dynamic_attr_name_in_set() {
6551        assert_eq!(
6552            ev(r#"let key = "mykey"; in { ${key} = 42; }.mykey"#),
6553            Value::Int(42),
6554        );
6555    }
6556
6557    #[test]
6558    fn dynamic_attr_name_with_expression() {
6559        assert_eq!(
6560            ev(r#"let prefix = "foo"; in { ${"${prefix}bar"} = 1; }.foobar"#),
6561            Value::Int(1),
6562        );
6563    }
6564
6565    // ═══════════════════════════════════════════════════════════
6566    // 16. IGNORED TESTS — features needing major infrastructure
6567    // ═══════════════════════════════════════════════════════════
6568
6569    #[test]
6570    fn eval_builtins_match() {
6571        assert_eq!(
6572            ev(r#"builtins.match "([0-9]+)" "42""#),
6573            Value::list(vec![Value::string("42")]),
6574        );
6575    }
6576
6577    #[test]
6578    fn eval_builtins_hash_string() {
6579        let v = ev(r#"builtins.hashString "sha256" "hello""#);
6580        if let Value::String(ns) = v {
6581            assert_eq!(ns.chars.len(), 64);
6582        } else {
6583            panic!("expected string");
6584        }
6585    }
6586
6587    #[test]
6588    fn eval_builtins_import() {
6589        let dir = std::env::temp_dir();
6590        let path = dir.join("sui_eval_test_import_eval.nix");
6591        std::fs::write(&path, "42").unwrap();
6592        let expr = format!(r#"import "{}""#, path.display());
6593        let v = eval(&expr).unwrap();
6594        assert_eq!(v, Value::Int(42));
6595        std::fs::remove_file(&path).ok();
6596    }
6597
6598    #[test]
6599    fn eval_builtins_derivation() {
6600        let v = eval(r#"builtins.derivation { name = "test"; system = "x86_64-linux"; builder = "/bin/sh"; }"#).unwrap();
6601        if let Value::Attrs(a) = v {
6602            assert_eq!(a.get("type"), Some(&Value::string("derivation")));
6603        } else {
6604            panic!("expected attrs");
6605        }
6606    }
6607
6608    #[test]
6609    fn eval_mutual_recursive_let() {
6610        // Multi-pass evaluation allows forward references in let bindings.
6611        // After 3 passes (placeholder + eval + re-eval), `a.x` resolves to
6612        // the value of `b` from the previous pass, and `a.x.y` is an attrset.
6613        // Full semantic equivalence with Nix (a.x.y == a) requires lazy
6614        // thunks, but the multi-pass approach is sufficient for common
6615        // patterns like mutual module references.
6616        let v = eval("let a = { x = b; }; b = { y = a; }; in a.x.y");
6617        assert!(v.is_ok(), "mutual recursive let should not error: {v:?}");
6618        // a.x.y should be an attrset (it's a's value from a prior pass)
6619        let val = v.unwrap();
6620        assert!(
6621            matches!(val, Value::Attrs(_)),
6622            "a.x.y should be an attrset, got: {val:?}",
6623        );
6624    }
6625
6626    #[test]
6627    fn eval_mutual_recursive_let_simple() {
6628        // Simpler case: forward reference in sequential let bindings
6629        let v = eval("let a = b; b = 42; in a");
6630        assert!(v.is_ok());
6631        // After multi-pass: pass 2 sets a=Null (b not yet bound), b=42
6632        // pass 3 sets a=42, b=42
6633        assert_eq!(v.unwrap(), Value::Int(42));
6634    }
6635
6636    #[test]
6637    fn eval_builtins_read_dir() {
6638        let dir = std::env::temp_dir().join("sui_eval_test_readdir_eval");
6639        let _ = std::fs::remove_dir_all(&dir);
6640        std::fs::create_dir_all(&dir).unwrap();
6641        std::fs::write(dir.join("a.txt"), "").unwrap();
6642        let expr = format!(r#"builtins.readDir "{}""#, dir.display());
6643        let v = eval(&expr).unwrap();
6644        if let Value::Attrs(a) = v {
6645            assert_eq!(a.get("a.txt"), Some(&Value::string("regular")));
6646        } else {
6647            panic!("expected attrs");
6648        }
6649        let _ = std::fs::remove_dir_all(&dir);
6650    }
6651
6652    // ═══════════════════════════════════════════════════════════
6653    // 17. THUNK / LAZY EVALUATION
6654    // ═══════════════════════════════════════════════════════════
6655
6656    #[test]
6657    fn thunk_basic_let() {
6658        // Simple let binding through thunk.
6659        assert_eq!(ev("let x = 1; in x"), Value::Int(1));
6660    }
6661
6662    #[test]
6663    fn thunk_forward_ref() {
6664        // Forward reference: `a` references `b` which is defined later.
6665        assert_eq!(ev("let a = b; b = 1; in a"), Value::Int(1));
6666    }
6667
6668    #[test]
6669    fn thunk_mutual_rec_attrset_in_let() {
6670        // Mutual recursion through attrsets in let bindings.
6671        assert_eq!(ev("let a = { x = b; }; b = { y = 1; }; in a.x.y"), Value::Int(1));
6672    }
6673
6674    #[test]
6675    fn thunk_rec_attrset() {
6676        // rec { a = b; b = 1; } -- forward ref within rec set.
6677        assert_eq!(ev("(rec { a = b; b = 1; }).a"), Value::Int(1));
6678    }
6679
6680    #[test]
6681    fn thunk_rec_attrset_chain() {
6682        // Longer chain: c depends on b depends on a.
6683        assert_eq!(ev("(rec { a = 1; b = a + 1; c = b + 1; }).c"), Value::Int(3));
6684    }
6685
6686    #[test]
6687    fn thunk_fixpoint() {
6688        // Classic fixpoint combinator -- the core of nixpkgs' `lib.fix`.
6689        assert_eq!(
6690            ev("let fix = f: let x = f x; in x; in (fix (self: { a = 1; b = self.a + 1; })).b"),
6691            Value::Int(2),
6692        );
6693    }
6694
6695    #[test]
6696    fn thunk_blackhole_self_reference() {
6697        // `let x = x; in x` is infinite recursion -- blackhole detection.
6698        let result = eval("let x = x; in x");
6699        assert!(result.is_err());
6700        let msg = format!("{}", result.unwrap_err());
6701        assert!(
6702            msg.contains("infinite recursion") || msg.contains("blackhole"),
6703            "expected blackhole error, got: {msg}",
6704        );
6705    }
6706
6707    #[test]
6708    fn thunk_mutual_blackhole() {
6709        // `let a = b; b = a; in a` -- mutual infinite recursion.
6710        let result = eval("let a = b; b = a; in a");
6711        assert!(result.is_err());
6712    }
6713
6714    #[test]
6715    fn thunk_let_body_forces_correctly() {
6716        // The let body should be able to use thunked bindings in arithmetic.
6717        assert_eq!(ev("let a = 10; b = 20; in a + b"), Value::Int(30));
6718    }
6719
6720    #[test]
6721    fn thunk_only_forced_when_needed() {
6722        // The binding `bad` would error if forced, but it is never used.
6723        assert_eq!(ev("let bad = 1 / 0; good = 42; in good"), Value::Int(42));
6724    }
6725
6726    #[test]
6727    fn thunk_forward_ref_in_function_body() {
6728        // Forward reference used inside a function body.
6729        assert_eq!(
6730            ev("let f = x: x + b; b = 10; in f 5"),
6731            Value::Int(15),
6732        );
6733    }
6734
6735    #[test]
6736    fn thunk_rec_set_self_ref_through_self() {
6737        // rec set where `b` references `a` which is in the same set.
6738        assert_eq!(
6739            ev(r#"(rec { a = "hello"; b = builtins.stringLength a; }).b"#),
6740            Value::Int(5),
6741        );
6742    }
6743
6744    #[test]
6745    fn thunk_nested_let_forward_ref() {
6746        // Forward reference in nested let.
6747        assert_eq!(
6748            ev("let a = b + 1; b = 2; in a"),
6749            Value::Int(3),
6750        );
6751    }
6752
6753    #[test]
6754    fn thunk_deep_chain() {
6755        // Chain of forward references: e -> d -> c -> b -> a.
6756        assert_eq!(
6757            ev("let a = 1; b = a; c = b; d = c; e = d; in e"),
6758            Value::Int(1),
6759        );
6760    }
6761
6762    #[test]
6763    fn thunk_rec_set_fixpoint() {
6764        // Fixpoint through rec set -- common nixpkgs pattern.
6765        assert_eq!(
6766            ev("let fix = f: let x = f x; in x; in (fix (self: { a = 1; b = self.a + 1; c = self.b + 1; })).c"),
6767            Value::Int(3),
6768        );
6769    }
6770
6771    #[test]
6772    fn thunk_let_with_inherit() {
6773        // Inherit in let should work alongside thunked bindings.
6774        assert_eq!(
6775            ev("let a = 1; in let inherit a; b = a + 1; in b"),
6776            Value::Int(2),
6777        );
6778    }
6779
6780    #[test]
6781    fn thunk_attrset_value_lazy() {
6782        // Values in non-rec attrsets are evaluated eagerly, but the test
6783        // verifies that thunked let bindings inside attrset values work.
6784        assert_eq!(
6785            ev("let x = 42; in { a = x; }.a"),
6786            Value::Int(42),
6787        );
6788    }
6789
6790    #[test]
6791    fn thunk_unused_error_not_forced() {
6792        // Multiple bindings, only `ok` is used. `bad` throws but is never forced.
6793        assert_eq!(
6794            ev(r#"let bad = builtins.throw "boom"; ok = 1; in ok"#),
6795            Value::Int(1),
6796        );
6797    }
6798
6799    #[test]
6800    fn thunk_rec_set_mutual_reference() {
6801        // Mutual reference within rec set.
6802        let v = ev("rec { a = { val = b.val + 1; }; b = { val = 10; }; }");
6803        if let Value::Attrs(attrs) = v {
6804            let a = attrs.get("a").unwrap();
6805            let a_forced = force_value(a).unwrap();
6806            if let Value::Attrs(a_attrs) = a_forced {
6807                assert_eq!(a_attrs.get("val"), Some(&Value::Int(11)));
6808            } else {
6809                panic!("expected attrs for a");
6810            }
6811        } else {
6812            panic!("expected attrs");
6813        }
6814    }
6815
6816    // ── let-rec self-reference corner cases ───────────────
6817
6818    #[test]
6819    fn let_rec_self_reference_simple() {
6820        assert_eq!(
6821            ev("let x = 1; y = x + 1; in y"),
6822            Value::Int(2),
6823        );
6824    }
6825
6826    #[test]
6827    fn let_rec_self_reference_chain() {
6828        assert_eq!(
6829            ev("let a = 1; b = a + 1; c = b + 1; in c"),
6830            Value::Int(3),
6831        );
6832    }
6833
6834    #[test]
6835    fn let_rec_self_reference_with_function() {
6836        assert_eq!(
6837            ev("let f = x: x + 1; y = f 10; in y"),
6838            Value::Int(11),
6839        );
6840    }
6841
6842    #[test]
6843    fn let_rec_mutual_recursion_via_if() {
6844        assert_eq!(
6845            ev("let isEven = n: if n == 0 then true else isOdd (n - 1); isOdd = n: if n == 0 then false else isEven (n - 1); in isEven 4"),
6846            Value::Bool(true),
6847        );
6848    }
6849
6850    #[test]
6851    fn let_rec_forward_ref_in_list() {
6852        assert_eq!(
6853            ev("let xs = [a b]; a = 1; b = 2; in builtins.length xs"),
6854            Value::Int(2),
6855        );
6856    }
6857
6858    // ── with-shadowing corner cases ───────────────────────
6859
6860    #[test]
6861    fn with_shadowing_let_wins_over_with() {
6862        assert_eq!(
6863            ev("let x = 1; in with { x = 2; }; x"),
6864            Value::Int(1),
6865        );
6866    }
6867
6868    #[test]
6869    fn with_shadowing_inner_with_wins() {
6870        assert_eq!(
6871            ev("with { x = 1; }; with { x = 2; }; x"),
6872            Value::Int(2),
6873        );
6874    }
6875
6876    #[test]
6877    fn with_shadowing_outer_provides_missing() {
6878        assert_eq!(
6879            ev("with { x = 1; y = 10; }; with { x = 2; }; x + y"),
6880            Value::Int(12),
6881        );
6882    }
6883
6884    #[test]
6885    fn with_shadowing_lambda_arg_wins() {
6886        assert_eq!(
6887            ev("(x: with { x = 99; }; x) 42"),
6888            Value::Int(42),
6889        );
6890    }
6891
6892    #[test]
6893    fn with_shadowing_nested_let_wins_over_with() {
6894        assert_eq!(
6895            ev("with { x = 1; }; let x = 2; in x"),
6896            Value::Int(2),
6897        );
6898    }
6899
6900    #[test]
6901    fn with_scope_dynamic_attrs() {
6902        assert_eq!(
6903            ev(r#"with { x = 1; y = 2; z = 3; }; x + y + z"#),
6904            Value::Int(6),
6905        );
6906    }
6907
6908    #[test]
6909    fn with_scope_over_lazy_thunk_chain_resolves() {
6910        // A `with`-head that resolves through a NESTED thunk chain
6911        // (`Thunk(Thunk(Attrs))`) must still be searched: the lookup
6912        // has to FULLY force the head (chase the chain), not take a
6913        // single force step. A single step leaves a `Value::Thunk`
6914        // that `type_name()` reports as "set" but the `Value::Attrs`
6915        // match rejects — the scope is skipped and a bare ident
6916        // through it fails with a spurious UndefinedVar. This corners
6917        // the nixpkgs `platforms = with lib.platforms; unix;` shape.
6918        assert_eq!(
6919            ev(r#"let outer = if true then (if true then { unix = 42; } else {}) else {};
6920                      # force a two-deep lazy wrap of the with-head
6921                      head = (x: x) ((y: y) outer);
6922                  in with head; unix"#),
6923            Value::Int(42),
6924        );
6925    }
6926
6927    #[test]
6928    fn with_scope_head_from_deep_select_resolves() {
6929        // `with a.b.c; key` where a.b.c is a lazily-selected attrset —
6930        // the bare-ident body must find `key` through the forced head.
6931        assert_eq!(
6932            ev(r#"let a = { b = { c = { key = 7; }; }; }; in with a.b.c; key"#),
6933            Value::Int(7),
6934        );
6935    }
6936
6937    // ── attrset deep merge ────────────────────────────────
6938
6939    #[test]
6940    fn attrset_deep_merge_simple() {
6941        let v = ev("{ a.b = 1; a.c = 2; }");
6942        if let Value::Attrs(attrs) = v {
6943            let a = force_value(attrs.get("a").unwrap()).unwrap();
6944            if let Value::Attrs(inner) = a {
6945                assert_eq!(force_value(inner.get("b").unwrap()).unwrap(), Value::Int(1));
6946                assert_eq!(force_value(inner.get("c").unwrap()).unwrap(), Value::Int(2));
6947            } else {
6948                panic!("expected nested attrs");
6949            }
6950        } else {
6951            panic!("expected attrs");
6952        }
6953    }
6954
6955    #[test]
6956    fn attrset_deep_merge_three_levels() {
6957        let v = ev("{ a.b.c = 1; a.b.d = 2; a.e = 3; }");
6958        if let Value::Attrs(attrs) = v {
6959            let a = force_value(attrs.get("a").unwrap()).unwrap();
6960            if let Value::Attrs(a_inner) = a {
6961                let e = force_value(a_inner.get("e").unwrap()).unwrap();
6962                assert_eq!(e, Value::Int(3));
6963                let b = force_value(a_inner.get("b").unwrap()).unwrap();
6964                if let Value::Attrs(b_inner) = b {
6965                    assert_eq!(force_value(b_inner.get("c").unwrap()).unwrap(), Value::Int(1));
6966                    assert_eq!(force_value(b_inner.get("d").unwrap()).unwrap(), Value::Int(2));
6967                } else {
6968                    panic!("expected nested attrs for b");
6969                }
6970            } else {
6971                panic!("expected nested attrs for a");
6972            }
6973        } else {
6974            panic!("expected attrs");
6975        }
6976    }
6977
6978    #[test]
6979    fn attrset_deep_merge_preserves_siblings() {
6980        assert_eq!(
6981            ev("{ a.x = 1; b = 2; a.y = 3; }.b"),
6982            Value::Int(2),
6983        );
6984    }
6985
6986    #[test]
6987    fn attrset_deep_merge_in_let() {
6988        let v = ev("let s = { a.b = 1; a.c = 2; }; in s.a.b + s.a.c");
6989        assert_eq!(v, Value::Int(3));
6990    }
6991
6992    #[test]
6993    fn attrset_deep_merge_fullset_then_dotted() {
6994        // General root (gst-plugins-base `passthru.waylandEnabled` drop):
6995        // `a = { x = 1; }; a.y = 2;` — the full-set binding is a lazy
6996        // Thunk (attrset literals go through maybe_thunk), so a naive
6997        // merge_nested_insert (which only merges concrete Value::Attrs)
6998        // overwrote `a` with `{ y = 2 }`, silently dropping `x`. The
6999        // collision must force the existing thunk to WHNF first.
7000        let v = ev("let s = { a = { x = 1; }; a.y = 2; }; in s.a.x + s.a.y");
7001        assert_eq!(v, Value::Int(3));
7002        // both keys must survive (not just their sum)
7003        let both = ev("let s = { a = { x = 1; }; a.y = 2; }; in [ s.a.x s.a.y ]");
7004        if let Value::List(items) = both {
7005            assert_eq!(force_value(&items[0]).unwrap(), Value::Int(1));
7006            assert_eq!(force_value(&items[1]).unwrap(), Value::Int(2));
7007        } else {
7008            panic!("expected list");
7009        }
7010    }
7011
7012    // ── inherit-from patterns ─────────────────────────────
7013
7014    #[test]
7015    fn inherit_from_basic() {
7016        assert_eq!(
7017            ev("let s = { x = 1; y = 2; }; in let inherit (s) x y; in x + y"),
7018            Value::Int(3),
7019        );
7020    }
7021
7022    #[test]
7023    fn inherit_from_with_shadowing() {
7024        assert_eq!(
7025            ev("let x = 10; in let inherit ({ x = 20; }) x; in x"),
7026            Value::Int(20),
7027        );
7028    }
7029
7030    #[test]
7031    fn inherit_from_in_attrset() {
7032        let v = ev(r#"let s = { a = 1; b = 2; }; in { inherit (s) a b; c = 3; }"#);
7033        if let Value::Attrs(attrs) = v {
7034            assert_eq!(force_value(attrs.get("a").unwrap()).unwrap(), Value::Int(1));
7035            assert_eq!(force_value(attrs.get("b").unwrap()).unwrap(), Value::Int(2));
7036            assert_eq!(force_value(attrs.get("c").unwrap()).unwrap(), Value::Int(3));
7037        } else {
7038            panic!("expected attrs");
7039        }
7040    }
7041
7042    #[test]
7043    fn inherit_from_rec_set() {
7044        assert_eq!(
7045            ev("rec { inherit ({ x = 42; }) x; y = x; }.y"),
7046            Value::Int(42),
7047        );
7048    }
7049
7050    #[test]
7051    fn inherit_plain_from_scope() {
7052        assert_eq!(
7053            ev("let x = 1; in { inherit x; }.x"),
7054            Value::Int(1),
7055        );
7056    }
7057
7058    // Regression (2026-07-11): a bare `inherit x;` must resolve LAZILY, like
7059    // a plain reference to `x` — not eagerly at attrset construction. When
7060    // `x` is provided only by an enclosing `with` scope whose value is a
7061    // fixpoint still being constructed, eager resolution spuriously threw
7062    // `UndefinedVar`. nixpkgs `all-packages.nix` is
7063    // `with pkgs; { nettle = import … { inherit callPackage; }; }`, so
7064    // `inherit callPackage` must resolve from the `with pkgs` scope at force
7065    // time. (This was the nettle UndefinedVar('callPackage') drop.)
7066    #[test]
7067    fn inherit_plain_from_with_scope_lazy() {
7068        // `inherit cp` reads `cp` from a `with self` fixpoint scope; the
7069        // attr forcing it (`a`) must resolve `cp` lazily against the settled
7070        // scope, not eagerly during attrset construction.
7071        assert_eq!(
7072            ev("let fix = f: let x = f x; in x;
7073                    self = fix (self: with self; {
7074                      a = use { inherit cp; };
7075                      use = { cp }: cp 5;
7076                      cp = x: x + 100;
7077                    });
7078                in self.a"),
7079            Value::Int(105),
7080        );
7081        // Simpler: bare inherit from a plain (non-blackhole) with scope.
7082        assert_eq!(
7083            ev("with { y = 7; }; { inherit y; }.y"),
7084            Value::Int(7),
7085        );
7086    }
7087
7088    #[test]
7089    fn inherit_multiple_from_expr() {
7090        assert_eq!(
7091            ev("let s = { a = 10; b = 20; c = 30; }; in let inherit (s) a b c; in a + b + c"),
7092            Value::Int(60),
7093        );
7094    }
7095
7096    // ── string interpolation edge cases ───────────────────
7097
7098    #[test]
7099    fn interp_nested_attrset_access() {
7100        assert_eq!(
7101            ev(r#"let x = { a = "hello"; }; in "${x.a} world""#),
7102            Value::string("hello world"),
7103        );
7104    }
7105
7106    #[test]
7107    fn interp_with_let_expression() {
7108        assert_eq!(
7109            ev(r#""${let x = "inner"; in x}""#),
7110            Value::string("inner"),
7111        );
7112    }
7113
7114    #[test]
7115    fn interp_float_coercion() {
7116        // CppNix %f-format: always 6 decimal places.
7117        assert_eq!(
7118            ev(r#""${toString 3.14}""#),
7119            Value::string("3.140000"),
7120        );
7121    }
7122
7123    // ── comparison edge cases ─────────────────────────────
7124
7125    #[test]
7126    fn compare_mixed_int_float() {
7127        assert_eq!(ev("1 < 1.5"), Value::Bool(true));
7128        assert_eq!(ev("1.5 > 1"), Value::Bool(true));
7129        assert_eq!(ev("2.0 == 2"), Value::Bool(true));
7130    }
7131
7132    #[test]
7133    fn compare_string_lexicographic() {
7134        assert_eq!(ev(r#""abc" < "abd""#), Value::Bool(true));
7135        assert_eq!(ev(r#""abc" < "abc""#), Value::Bool(false));
7136        assert_eq!(ev(r#""abc" <= "abc""#), Value::Bool(true));
7137    }
7138
7139    // ── update operator edge cases ────────────────────────
7140
7141    #[test]
7142    fn update_empty_sets() {
7143        let v = ev("{} // {}");
7144        if let Value::Attrs(a) = v { assert!(a.is_empty()); } else { panic!(); }
7145    }
7146
7147    #[test]
7148    fn update_right_overrides_completely() {
7149        assert_eq!(
7150            ev("{ a = 1; b = 2; } // { a = 10; c = 30; }"),
7151            ev("{ a = 10; b = 2; c = 30; }"),
7152        );
7153    }
7154
7155    #[test]
7156    fn update_chained() {
7157        assert_eq!(
7158            ev("{ a = 1; } // { b = 2; } // { c = 3; }"),
7159            ev("{ a = 1; b = 2; c = 3; }"),
7160        );
7161    }
7162
7163    // ── force_value edge cases ────────────────────────────
7164
7165    #[test]
7166    fn force_value_concrete_unchanged() {
7167        let v = Value::Int(42);
7168        assert_eq!(force_value(&v).unwrap(), Value::Int(42));
7169    }
7170
7171    #[test]
7172    fn force_value_null() {
7173        assert_eq!(force_value(&Value::Null).unwrap(), Value::Null);
7174    }
7175
7176    // ── eval_with_file ────────────────────────────────────
7177
7178    #[test]
7179    fn eval_with_file_none() {
7180        let result = eval_with_file("1 + 2", None).unwrap();
7181        assert_eq!(result, Value::Int(3));
7182    }
7183
7184    // ── error messages ────────────────────────────────────
7185
7186    #[test]
7187    fn error_type_mismatch_in_comparison() {
7188        let result = eval(r#"1 < "a""#);
7189        assert!(result.is_err());
7190    }
7191
7192    #[test]
7193    fn error_select_from_non_set() {
7194        let result = eval("42.x");
7195        assert!(result.is_err());
7196    }
7197
7198    #[test]
7199    fn error_call_non_function() {
7200        let result = eval("42 1");
7201        assert!(result.is_err());
7202    }
7203
7204    #[test]
7205    fn error_negate_string() {
7206        let result = eval(r#"-"hello""#);
7207        assert!(result.is_err());
7208    }
7209
7210    // ── multiline string edge cases ───────────────────────
7211
7212    #[test]
7213    fn multiline_string_empty() {
7214        assert_eq!(ev("''''"), Value::string(""));
7215    }
7216
7217    #[test]
7218    fn multiline_string_with_trailing_newline() {
7219        let v = ev("''\n  hello\n''");
7220        assert_eq!(v, Value::string("hello\n"));
7221    }
7222
7223    // ── list operations ───────────────────────────────────
7224
7225    #[test]
7226    fn list_concat_empty_left() {
7227        assert_eq!(ev("[] ++ [1 2]"), Value::list(vec![Value::Int(1), Value::Int(2)]));
7228    }
7229
7230    #[test]
7231    fn list_concat_empty_right() {
7232        assert_eq!(ev("[1 2] ++ []"), Value::list(vec![Value::Int(1), Value::Int(2)]));
7233    }
7234
7235    #[test]
7236    fn list_concat_both_empty() {
7237        assert_eq!(ev("[] ++ []"), Value::list(vec![]));
7238    }
7239
7240    // ── pattern matching / formals edge cases ─────────────
7241
7242    #[test]
7243    fn formals_at_pattern_accessible() {
7244        assert_eq!(
7245            ev("({ x, ... } @ args: builtins.length (builtins.attrNames args)) { x = 1; y = 2; z = 3; }"),
7246            Value::Int(3),
7247        );
7248    }
7249
7250    #[test]
7251    fn formals_default_uses_other_arg() {
7252        assert_eq!(
7253            ev("({ x, y ? x + 1 }: y) { x = 10; }"),
7254            Value::Int(11),
7255        );
7256    }
7257
7258    #[test]
7259    fn formals_default_lazy_assert_false() {
7260        // nixpkgs parse.nix pattern: default is `assert false; null` but
7261        // the body checks `args ? vendor` instead of using `vendor`
7262        // directly, so the default must never be forced.
7263        assert_eq!(
7264            ev("({ cpu, vendor ? assert false; null, kernel } @ args: if args ? vendor then vendor else \"inferred\") { cpu = \"x86_64\"; kernel = \"linux\"; }"),
7265            Value::String(Rc::new(NixString::plain("inferred"))),
7266        );
7267    }
7268
7269    #[test]
7270    fn formals_default_lazy_only_forced_when_accessed() {
7271        // When the default IS accessed, it should still evaluate correctly.
7272        assert_eq!(
7273            ev("({ a, b ? 42 }: b) { a = 1; }"),
7274            Value::Int(42),
7275        );
7276    }
7277
7278    #[test]
7279    fn formals_ellipsis_ignores_extra() {
7280        assert_eq!(
7281            ev("({ x, ... }: x) { x = 1; y = 2; z = 3; }"),
7282            Value::Int(1),
7283        );
7284    }
7285
7286    // ── pure mode ─────────────────────────────────────────
7287
7288    #[test]
7289    fn pure_mode_roundtrip() {
7290        let was_pure = is_pure_mode();
7291        set_pure_mode(true);
7292        assert!(is_pure_mode());
7293        set_pure_mode(false);
7294        assert!(!is_pure_mode());
7295        set_pure_mode(was_pure);
7296    }
7297
7298    // ── path operations ───────────────────────────────────
7299
7300    #[test]
7301    fn path_concat_with_string() {
7302        assert_eq!(
7303            ev(r#"/foo + "bar""#),
7304            Value::Path(Box::new(SmolStr::from("/foobar"))),
7305        );
7306    }
7307
7308    #[test]
7309    fn path_concat_with_path() {
7310        assert_eq!(
7311            ev("/foo + /bar"),
7312            Value::Path(Box::new(SmolStr::from("/foo//bar"))),
7313        );
7314    }
7315
7316    // ── EvalFileGuard / current_eval_dir ───────────────────
7317
7318    #[test]
7319    fn current_eval_dir_empty_when_no_file_pushed() {
7320        // Without a push, current_eval_dir should yield None.
7321        // (Note: this test is order-dependent; we accept whatever the
7322        // top of the stack happens to be when called.)
7323        let snapshot = current_eval_dir();
7324        // At minimum the API doesn't panic and returns Option.
7325        let _ = snapshot;
7326    }
7327
7328    #[test]
7329    fn push_eval_file_sets_current_dir() {
7330        let p = std::path::PathBuf::from("/tmp/example/file.nix");
7331        {
7332            let _g = push_eval_file(p.clone());
7333            assert_eq!(current_eval_dir(), Some(std::path::PathBuf::from("/tmp/example")));
7334        }
7335        // Guard dropped, stack popped — current dir is whatever was below.
7336        // We can't assert exact value without snapshotting first, but the
7337        // value before push should be restored.
7338    }
7339
7340    #[test]
7341    fn push_eval_file_nested_stack() {
7342        let outer = std::path::PathBuf::from("/a/x.nix");
7343        let inner = std::path::PathBuf::from("/b/y.nix");
7344        {
7345            let _g_outer = push_eval_file(outer.clone());
7346            assert_eq!(current_eval_dir(), Some(std::path::PathBuf::from("/a")));
7347            {
7348                let _g_inner = push_eval_file(inner.clone());
7349                assert_eq!(current_eval_dir(), Some(std::path::PathBuf::from("/b")));
7350            }
7351            // Inner dropped — outer is back on top.
7352            assert_eq!(current_eval_dir(), Some(std::path::PathBuf::from("/a")));
7353        }
7354    }
7355
7356    /// A fileless frame MASKS the parent's file rather than being skipped.
7357    ///
7358    /// Regression: the stack used to be `Vec<PathBuf>`, so a thunk captured in
7359    /// a `--expr` context pushed nothing when it forced and the callee's file
7360    /// stayed visible. `builtins.unsafeGetAttrPos` then reported the callee's
7361    /// path where CppNix reports `null`, which set `eval-config.nix`'s
7362    /// `modulesLocation` and permuted NixOS module definition order.
7363    #[test]
7364    fn fileless_frame_masks_parent_file() {
7365        let outer = std::path::PathBuf::from("/a/x.nix");
7366        let _g_outer = push_eval_file(outer.clone());
7367        assert_eq!(current_eval_file(), Some(outer.clone()));
7368        {
7369            let _g_none = push_eval_frame(None);
7370            // The whole point: NOT Some("/a/x.nix").
7371            assert_eq!(current_eval_file(), None);
7372            assert_eq!(current_eval_dir(), None);
7373            assert_eq!(eval_file_stack_snapshot().last().map(String::as_str), Some("<no-file>"));
7374        }
7375        // Popped — the parent is visible again.
7376        assert_eq!(current_eval_file(), Some(outer));
7377    }
7378
7379    // ── Source-mapped error context ────────────────────────
7380
7381    #[test]
7382    fn error_undefined_var_includes_file_context() {
7383        let p = std::path::PathBuf::from("/nix/store/abc-default.nix");
7384        let _g = push_eval_file(p);
7385        let result = eval("nonexistent_xyz");
7386        let msg = format!("{}", result.unwrap_err());
7387        assert!(msg.contains("undefined variable"), "msg: {msg}");
7388        assert!(msg.contains("nonexistent_xyz"), "msg: {msg}");
7389        assert!(msg.contains("abc-default.nix"), "msg: {msg}");
7390    }
7391
7392    #[test]
7393    fn error_attr_not_found_includes_file_context() {
7394        let p = std::path::PathBuf::from("/nix/store/xyz-module.nix");
7395        let _g = push_eval_file(p);
7396        let result = eval("{}.missing_key");
7397        let msg = format!("{}", result.unwrap_err());
7398        assert!(msg.contains("not found") || msg.contains("missing_key"), "msg: {msg}");
7399        assert!(msg.contains("xyz-module.nix"), "msg: {msg}");
7400    }
7401
7402    #[test]
7403    fn error_assertion_failed_includes_file_context() {
7404        let p = std::path::PathBuf::from("/nix/store/test-assert.nix");
7405        let _g = push_eval_file(p);
7406        let result = eval("assert false; 1");
7407        let msg = format!("{}", result.unwrap_err());
7408        assert!(msg.contains("assertion failed"), "msg: {msg}");
7409        assert!(msg.contains("test-assert.nix"), "msg: {msg}");
7410    }
7411
7412    /// `inherit` binds an attribute, so it carries a position.
7413    ///
7414    /// Regression: `attach_attrset_positions` matched only
7415    /// `Entry::AttrpathValue`, so every inherited key was position-less — most
7416    /// of nixpkgs' `lib`, which re-exports via `inherit (self.options) mkOption
7417    /// …`, and it fed a null into `eval-config.nix`'s `modulesLocation`.
7418    ///
7419    /// Shaped exactly like `unsafe_get_attr_pos_reports_file_and_offset_column`
7420    /// (ONE direct `eval`, no lambda, no second evaluation) because the
7421    /// in-process harness is fragile here: the source-text registry is a
7422    /// thread-local that `pos.rs`'s tests clear, so a multi-eval version passes
7423    /// standalone and fails in the full suite. The CLI path is not affected —
7424    /// verified against `nix eval` on both shapes, both engines agreeing on
7425    /// column 18.
7426    #[test]
7427    fn inherit_bindings_carry_positions() {
7428        let dir = tempfile::tempdir().unwrap();
7429        // A PLAIN attrset, no `let ... in` wrapper: with the wrapper the
7430        // result is built lazily AFTER `import` returns, and the in-process
7431        // harness then resolves it without the file on the eval stack. The CLI
7432        // handles both (measured), the harness only this one.
7433        let body = "{ inherit ({ x = 1; }) x; }\n";
7434        let f = dir.path().join("inh.nix");
7435        std::fs::write(&f, body).unwrap();
7436        let v = eval(&format!("builtins.unsafeGetAttrPos \"x\" (import {})", f.display())).unwrap();
7437        let attrs = match v {
7438            Value::Attrs(a) => a,
7439            Value::Null => panic!("null — the inherit binding carried no position"),
7440            o => panic!("expected attrs, got {o:?}"),
7441        };
7442        // Computed from the fixture, never hardcoded: a hardcoded expectation is
7443        // how `pos::line_col`'s own "verified" comment came to agree with the
7444        // bug it documented.
7445        let off = body.rfind("x; }").unwrap();
7446        let bol = body[..off].rfind('\n').map_or(0, |i| i + 1);
7447        assert_eq!(*attrs.get("line").unwrap(), Value::Int(1));
7448        assert_eq!(*attrs.get("column").unwrap(), Value::Int((off - bol) as i64 + 1));
7449    }
7450
7451    /// Corpus gate: every attribute-BINDING form carries a position.
7452    ///
7453    /// Seals the class the three position bugs came from, rather than the three
7454    /// instances: `//` dropping positions wholesale, `pos::line_col` returning a
7455    /// constant, and `inherit` never being recorded. Each was found only because
7456    /// a NixOS toplevel drvPath diverged — an expensive way to learn that an
7457    /// attribute lost its position.
7458    ///
7459    /// Expectations are DERIVED from the fixture, never written out, so the test
7460    /// cannot drift into agreeing with whatever the implementation emits. That
7461    /// is exactly how `line_col`'s own "verified against nix eval" comment came
7462    /// to document the bug it contained.
7463    ///
7464    /// Anti-vacuity: the row count is asserted, and any `NULL` fails. A change
7465    /// that stops attaching positions altogether makes every row `NULL` — which
7466    /// must be a failure, not an empty-set pass.
7467    #[test]
7468    fn every_binding_form_carries_a_position() {
7469        let dir = tempfile::tempdir().unwrap();
7470        // One line per key so the expected line number is its 1-based index.
7471        let body = concat!(
7472            "let src = { i = 1; j = 2; }; in {\n",
7473            "  plain = 1;\n",
7474            "  \"quoted\" = 2;\n",
7475            "  inherit (src) i;\n",
7476            "  inherit src;\n",
7477            "  nested.deep = 3;\n",
7478            "}\n",
7479        );
7480        let f = dir.path().join("forms.nix");
7481        std::fs::write(&f, body).unwrap();
7482
7483        // `nested` is the head of a dotted path; CppNix points at the head.
7484        let keys = ["plain", "quoted", "i", "src", "nested"];
7485        let probe = keys
7486            .iter()
7487            .map(|k| format!(
7488                "(let q = builtins.unsafeGetAttrPos \"{k}\" t; \
7489                 in if q == null then \"{k}=NULL\" \
7490                 else \"{k}=${{toString q.line}}:${{toString q.column}}\")"
7491            ))
7492            .collect::<Vec<_>>()
7493            .join(" + \" \" + ");
7494        let got = eval(&format!("let t = import {}; in {probe}", f.display()))
7495            .unwrap()
7496            .as_string()
7497            .unwrap()
7498            .to_string();
7499
7500        assert!(!got.contains("NULL"), "a binding form lost its position: {got}");
7501        let rows: Vec<&str> = got.split(' ').collect();
7502        assert_eq!(rows.len(), keys.len(), "corpus shrank — gate would be vacuous: {got}");
7503
7504        // Derive each expectation by locating the key token in the fixture.
7505        for (k, row) in keys.iter().zip(&rows) {
7506            let needle = match *k {
7507                "quoted" => "\"quoted\"".to_string(),
7508                "i" => "i;".to_string(),
7509                "src" => "src;".to_string(),
7510                // A dotted path's head is followed by `.`, not ` =` — CppNix
7511                // reports the HEAD token's position for the outer key.
7512                "nested" => "nested.".to_string(),
7513                other => format!("{other} ="),
7514            };
7515            let off = body.find(&needle).unwrap();
7516            let bol = body[..off].rfind('\n').map_or(0, |i| i + 1);
7517            let line = 1 + body[..off].matches('\n').count();
7518            let col = off - bol + 1;
7519            assert_eq!(*row, format!("{k}={line}:{col}"), "wrong position for `{k}` in:\n{body}");
7520        }
7521    }
7522
7523    /// A missing-argument error names the file the LAMBDA came from.
7524    ///
7525    /// Evaluated with `eval_with_file`, not `push_eval_file` + bare `eval`, and
7526    /// the difference is the point. Calling a closure now pushes the closure's
7527    /// OWN file — including a fileless frame when it has none — so a lambda
7528    /// defined in a fileless string no longer borrows whatever unrelated file
7529    /// happens to sit on the stack. That borrowing is what the old form
7530    /// asserted, and CppNix does not do it: an `--expr` lambda has no file.
7531    /// Associating the source with a file, as every real `import` does, keeps
7532    /// the original intent (errors carry file context) while testing the path
7533    /// production actually takes. Verified against CppNix: for a lambda in a
7534    /// real file both engines name that file.
7535    #[test]
7536    fn error_missing_argument_includes_file_context() {
7537        let p = std::path::PathBuf::from("/nix/store/func.nix");
7538        let result = eval_with_file("({ a, b }: a) { a = 1; }", Some(p));
7539        let msg = format!("{}", result.unwrap_err());
7540        assert!(msg.contains("missing argument"), "msg: {msg}");
7541        assert!(msg.contains("func.nix"), "msg: {msg}");
7542    }
7543
7544    #[test]
7545    fn error_cannot_call_includes_file_context() {
7546        let p = std::path::PathBuf::from("/nix/store/call.nix");
7547        let _g = push_eval_file(p);
7548        let result = eval("42 99");
7549        let msg = format!("{}", result.unwrap_err());
7550        assert!(msg.contains("cannot call"), "msg: {msg}");
7551        assert!(msg.contains("call.nix"), "msg: {msg}");
7552    }
7553
7554    #[test]
7555    fn error_without_file_has_no_in_prefix() {
7556        // When no file is on the eval stack, error messages should
7557        // not contain ", in" context.
7558        let result = eval("nonexistent_xyz");
7559        let msg = format!("{}", result.unwrap_err());
7560        assert!(msg.contains("undefined variable"), "msg: {msg}");
7561        assert!(!msg.contains(", in"), "msg should not contain file context: {msg}");
7562    }
7563
7564    // ── pure mode getter/setter independence ───────────────
7565
7566    #[test]
7567    fn pure_mode_set_get_independence() {
7568        let was = is_pure_mode();
7569        set_pure_mode(true);
7570        assert!(is_pure_mode());
7571        set_pure_mode(false);
7572        assert!(!is_pure_mode());
7573        set_pure_mode(was);
7574    }
7575
7576    // ── eval_with_file with file path ──────────────────────
7577
7578    #[test]
7579    fn eval_with_file_some_path_arithmetic() {
7580        let p = std::path::PathBuf::from("/tmp/imaginary.nix");
7581        let result = eval_with_file("1 + 2", Some(p)).unwrap();
7582        assert_eq!(result, Value::Int(3));
7583    }
7584
7585    // ── unsafeGetAttrPos — the options.json `attrTag` declarations root ──
7586    //
7587    // Seals the CppNix-matching behavior: for a literal attrset built in a
7588    // FILE, `builtins.unsafeGetAttrPos <key> <set>` returns
7589    // `{ file; line=1; column=<key byte offset>+1; }`; for a `<string>` eval
7590    // (no file) it returns `null`. Byte-verified against `nix eval`.
7591
7592    #[test]
7593    fn unsafe_get_attr_pos_reports_file_and_offset_column() {
7594        // The real `attrTag` path: a literal attrset built in an IMPORTED file.
7595        // `import` registers the file's source text + pushes it on the eval
7596        // stack, so `eval_attrset` captures the key positions against that file
7597        // and `unsafeGetAttrPos` resolves them. CppNix reports the file plus a
7598        // real newline-resolved line and BYTE column.
7599        //
7600        // Re-baselined: this used to assert line 1 and column = the key's
7601        // 1-based byte offset in the whole file, citing "verified against nix
7602        // eval". It was not — that was sui's own output taken as the oracle,
7603        // and the same false rule was pinned in pos.rs. Measured on nix 2.31.5:
7604        // for `{ a = 1;\n  b = 2; }` the `b` key is 2:3, not 1:12.
7605        let dir = tempfile::tempdir().unwrap();
7606        // The literal's `b` key sits at a known byte offset in this file.
7607        let file_body = "{ a = 1;\n  b = 2; }\n";
7608        let f = dir.path().join("lit.nix");
7609        std::fs::write(&f, file_body).unwrap();
7610        let src = format!("builtins.unsafeGetAttrPos \"b\" (import {})", f.display());
7611        let v = eval(&src).unwrap();
7612        let attrs = match v { Value::Attrs(a) => a, other => panic!("expected attrs, got {other:?}") };
7613        assert_eq!(
7614            attrs.get("file").unwrap().as_string().unwrap(),
7615            f.to_string_lossy(),
7616        );
7617        // `b` is on the SECOND line, at byte column 3.
7618        let off = file_body.find("b = 2").unwrap();
7619        let bol = file_body[..off].rfind('\n').map_or(0, |i| i + 1);
7620        let expected_line = 1 + file_body[..off].matches('\n').count() as i64;
7621        let expected_col = (off - bol) as i64 + 1;
7622        assert_eq!(expected_line, 2, "fixture must put `b` on line 2");
7623        assert_eq!(*attrs.get("line").unwrap(), Value::Int(expected_line));
7624        let col = match attrs.get("column").unwrap() { Value::Int(n) => *n, o => panic!("{o:?}") };
7625        assert_eq!(col, expected_col, "column must be the 1-based BYTE column");
7626    }
7627
7628    #[test]
7629    fn unsafe_get_attr_pos_null_for_string_origin() {
7630        // A `<string>`-eval'd literal (no file on the stack) has no position → null.
7631        let v = eval("builtins.unsafeGetAttrPos \"a\" { a = 1; }").unwrap();
7632        assert_eq!(v, Value::Null);
7633    }
7634
7635    #[test]
7636    fn unsafe_get_attr_pos_null_for_missing_key() {
7637        // A key absent from an imported set → null.
7638        let dir = tempfile::tempdir().unwrap();
7639        let f = dir.path().join("lit.nix");
7640        std::fs::write(&f, "{ a = 1; }\n").unwrap();
7641        let src = format!("builtins.unsafeGetAttrPos \"zzz\" (import {})", f.display());
7642        let v = eval(&src).unwrap();
7643        assert_eq!(v, Value::Null);
7644    }
7645
7646    // ── String interpolation primitive coercions ───────────
7647
7648    #[test]
7649    fn interp_int_into_string() {
7650        // Integer interpolated into a string is coerced to its decimal repr.
7651        assert_eq!(ev(r#""val=${toString 42}""#), Value::string("val=42"));
7652    }
7653
7654    #[test]
7655    fn interp_bool_true_becomes_one() {
7656        // Per eval_str: Bool(true) → "1", Bool(false) → "" (empty)
7657        let v = ev(r#"let x = true; in "${builtins.toString x}""#);
7658        assert_eq!(v, Value::string("1"));
7659    }
7660
7661    #[test]
7662    fn interp_null_becomes_empty() {
7663        // Null in interpolation is empty.
7664        let v = ev(r#"let x = null; in "${builtins.toString x}""#);
7665        assert_eq!(v, Value::string(""));
7666    }
7667
7668    #[test]
7669    fn interp_attrset_without_to_string_errors() {
7670        // An attrset interpolated without __toString is a type error.
7671        let result = eval(r#"let s = { x = 1; }; in "${s}""#);
7672        assert!(result.is_err());
7673    }
7674
7675    #[test]
7676    fn interp_attrset_with_to_string_protocol() {
7677        // __toString protocol returns a string when called with self.
7678        let v = ev(r#""${{ __toString = self: "ok"; }}""#);
7679        assert_eq!(v, Value::string("ok"));
7680    }
7681
7682    // ── Path PathRel / PathHome / PathAbs ─────────────────
7683
7684    #[test]
7685    fn eval_path_absolute_literal() {
7686        let v = ev("/tmp/foo");
7687        match v {
7688            Value::Path(p) => assert!(p.contains("/tmp/foo")),
7689            _ => panic!("expected Path"),
7690        }
7691    }
7692
7693    #[test]
7694    fn eval_path_home_literal() {
7695        let v = ev("~/foo.nix");
7696        match v {
7697            Value::Path(p) => assert!(p.contains("~/foo.nix") || p.ends_with("foo.nix")),
7698            _ => panic!("expected Path"),
7699        }
7700    }
7701
7702    // ── search path miss ──────────────────────────────────
7703
7704    #[test]
7705    fn path_search_unmatched_errors() {
7706        // Without NIX_PATH entries matching, <nonexistent> errors out.
7707        // We unset NIX_PATH locally to ensure no entries match.
7708        let saved = std::env::var("NIX_PATH").ok();
7709        // SAFETY: tests run sequentially in single-threaded mode by
7710        // default? The thread_local NIX_PATH is per-thread but std::env
7711        // is process-global. We restore it after.
7712        unsafe {
7713            std::env::remove_var("NIX_PATH");
7714        }
7715        let result = eval("<this_should_not_resolve>");
7716        if let Some(v) = saved {
7717            unsafe {
7718                std::env::set_var("NIX_PATH", v);
7719            }
7720        }
7721        assert!(result.is_err());
7722    }
7723
7724    // ── Unary operators ────────────────────────────────────
7725
7726    #[test]
7727    fn unary_negate_int() {
7728        assert_eq!(ev("-7"), Value::Int(-7));
7729    }
7730
7731    #[test]
7732    fn unary_negate_float() {
7733        assert_eq!(ev("-2.5"), Value::Float(-2.5));
7734    }
7735
7736    #[test]
7737    fn unary_invert_true() {
7738        assert_eq!(ev("!true"), Value::Bool(false));
7739    }
7740
7741    #[test]
7742    fn unary_invert_false() {
7743        assert_eq!(ev("!false"), Value::Bool(true));
7744    }
7745
7746    #[test]
7747    fn unary_negate_bool_errors() {
7748        let result = eval("-true");
7749        assert!(result.is_err());
7750    }
7751
7752    #[test]
7753    fn unary_invert_int_errors() {
7754        let result = eval("!42");
7755        assert!(result.is_err());
7756    }
7757
7758    // ── Binary op type errors ──────────────────────────────
7759
7760    #[test]
7761    fn binop_add_attrs_errors() {
7762        let result = eval("{a=1;} + {b=2;}");
7763        assert!(result.is_err());
7764    }
7765
7766    #[test]
7767    fn binop_sub_string_errors() {
7768        let result = eval(r#""a" - "b""#);
7769        assert!(result.is_err());
7770    }
7771
7772    #[test]
7773    fn binop_mul_string_errors() {
7774        let result = eval(r#""a" * "b""#);
7775        assert!(result.is_err());
7776    }
7777
7778    #[test]
7779    fn binop_div_string_errors() {
7780        let result = eval(r#""a" / "b""#);
7781        assert!(result.is_err());
7782    }
7783
7784    #[test]
7785    fn binop_compare_attrs_errors() {
7786        let result = eval("{a=1;} < {b=2;}");
7787        assert!(result.is_err());
7788    }
7789
7790    #[test]
7791    fn binop_div_float_by_zero_int() {
7792        // Float / int(0) is NOT a DivisionByZero error in this evaluator —
7793        // only int/int matches the DivisionByZero branch. This documents
7794        // that branch.
7795        let result = eval("1.0 / 0");
7796        // Either inf or error is acceptable; the documented branch is
7797        // the int/int(0) → DivisionByZero one.
7798        let _ = result;
7799    }
7800
7801    #[test]
7802    fn binop_int_div_zero_is_division_by_zero() {
7803        let result = eval("5 / 0");
7804        match result {
7805            Err(EvalError::DivisionByZero) => {}
7806            other => panic!("expected DivisionByZero, got {other:?}"),
7807        }
7808    }
7809
7810    // ── if/then/else laziness ──────────────────────────────
7811
7812    #[test]
7813    fn if_else_only_chosen_branch_evaluated_then() {
7814        // The else branch contains a divide-by-zero that would error
7815        // if eagerly evaluated. Choosing the then branch must skip it.
7816        assert_eq!(ev("if true then 42 else 1 / 0"), Value::Int(42));
7817    }
7818
7819    #[test]
7820    fn if_else_only_chosen_branch_evaluated_else() {
7821        assert_eq!(ev("if false then 1 / 0 else 99"), Value::Int(99));
7822    }
7823
7824    #[test]
7825    fn if_condition_must_be_bool() {
7826        let result = eval("if 1 then 1 else 2");
7827        assert!(result.is_err());
7828    }
7829
7830    #[test]
7831    fn if_condition_lazy_does_not_force_unused() {
7832        // Lazy `let` ensures that `bad` is only forced if the chosen
7833        // branch references it.
7834        assert_eq!(
7835            ev("let bad = 1 / 0; in if true then 42 else bad"),
7836            Value::Int(42),
7837        );
7838    }
7839
7840    // ── Logic short-circuit laziness ───────────────────────
7841
7842    #[test]
7843    fn and_short_circuits_on_false() {
7844        // RHS contains an error; should never run.
7845        assert_eq!(ev("false && (1 / 0 == 0)"), Value::Bool(false));
7846    }
7847
7848    #[test]
7849    fn or_short_circuits_on_true() {
7850        assert_eq!(ev("true || (1 / 0 == 0)"), Value::Bool(true));
7851    }
7852
7853    #[test]
7854    fn implication_short_circuits_on_false_lhs() {
7855        // false -> anything is true; RHS not evaluated.
7856        assert_eq!(ev("false -> (1 / 0 == 0)"), Value::Bool(true));
7857    }
7858
7859    // ── Lambda fixpoint via let ────────────────────────────
7860
7861    #[test]
7862    fn lambda_fix_combinator_returns_attrset() {
7863        // The classic `fix = f: let x = f x; in x` shape.
7864        let v = ev(
7865            "let fix = f: let x = f x; in x; in
7866              (fix (self: { val = 1; double = self.val * 2; })).double",
7867        );
7868        assert_eq!(v, Value::Int(2));
7869    }
7870
7871    // ── eval_attrset rec scope details ─────────────────────
7872
7873    #[test]
7874    fn rec_attrset_self_reference() {
7875        // rec set with simple forward reference.
7876        let v = ev("(rec { a = b; b = 1; }).a");
7877        assert_eq!(v, Value::Int(1));
7878    }
7879
7880    #[test]
7881    fn rec_attrset_inherit_from_uses_outer_scope() {
7882        // inherit-from in rec uses the OUTER (lexical) scope to evaluate
7883        // the source expression, not the rec scope. We bind `src` in
7884        // an outer let so the inherit can find it.
7885        let v = ev(
7886            "let src = { a = 10; }; in
7887              rec {
7888                inherit (src) a;
7889                b = a + 1;
7890              }",
7891        );
7892        if let Value::Attrs(attrs) = v {
7893            let b = attrs.get("b").unwrap();
7894            let b_forced = force_value(b).unwrap();
7895            assert_eq!(b_forced, Value::Int(11));
7896        } else {
7897            panic!("expected attrs");
7898        }
7899    }
7900
7901    #[test]
7902    fn nonrec_attrset_no_self_reference() {
7903        // In a non-rec set, a name doesn't see its sibling. The error
7904        // surfaces as an UndefinedVar when the thunk is forced.
7905        let result = eval("({ a = 1; b = a + 1; }).b");
7906        assert!(result.is_err());
7907    }
7908
7909    // ── eval_attrset deep merge edge cases ─────────────────
7910
7911    #[test]
7912    fn dotted_binding_three_segments_then_sibling() {
7913        let v = ev("{ a.b.c = 1; a.b.d = 2; a.e = 3; }");
7914        if let Value::Attrs(attrs) = v {
7915            let a = attrs.get("a").unwrap();
7916            let a_forced = force_value(a).unwrap();
7917            if let Value::Attrs(a_attrs) = a_forced {
7918                let b = a_attrs.get("b").unwrap();
7919                let b_forced = force_value(b).unwrap();
7920                if let Value::Attrs(b_attrs) = b_forced {
7921                    assert_eq!(force_value(b_attrs.get("c").unwrap()).unwrap(), Value::Int(1));
7922                    assert_eq!(force_value(b_attrs.get("d").unwrap()).unwrap(), Value::Int(2));
7923                } else {
7924                    panic!("expected b to be attrs");
7925                }
7926                assert_eq!(force_value(a_attrs.get("e").unwrap()).unwrap(), Value::Int(3));
7927            } else {
7928                panic!("expected a to be attrs");
7929            }
7930        } else {
7931            panic!("expected outer attrs");
7932        }
7933    }
7934
7935    // ── rec/let dotted bindings in recursive scope ────────
7936
7937    #[test]
7938    fn rec_dotted_bindings_visible_to_siblings() {
7939        // Dotted bindings in rec blocks must be visible to sibling
7940        // bindings -- this is the nixpkgs lib/systems/parse.nix pattern.
7941        let v = ev("rec { types.openSB = 1; types.openCpu = 2; foo = types.openSB; }.foo");
7942        assert_eq!(v, Value::Int(1));
7943    }
7944
7945    #[test]
7946    fn rec_dotted_leaf_uses_rec_scope() {
7947        // Leaf expressions in dotted bindings must see sibling
7948        // rec-bindings, not just the parent scope.
7949        let v = ev("rec { types.a = f 1; f = x: x + 1; }.types.a");
7950        assert_eq!(v, Value::Int(2));
7951    }
7952
7953    #[test]
7954    fn rec_dotted_multiple_keys_merge() {
7955        // Multiple dotted bindings sharing a top-level key must merge.
7956        let v = ev("rec { types.a = 1; types.b = 2; x = types; }.x");
7957        if let Value::Attrs(attrs) = v {
7958            assert_eq!(force_value(attrs.get("a").unwrap()).unwrap(), Value::Int(1));
7959            assert_eq!(force_value(attrs.get("b").unwrap()).unwrap(), Value::Int(2));
7960        } else {
7961            panic!("expected attrs");
7962        }
7963    }
7964
7965    #[test]
7966    fn rec_nixpkgs_parse_pattern() {
7967        // Simplified nixpkgs lib/systems/parse.nix pattern:
7968        // rec block with dotted types.xxx bindings that reference
7969        // each other through the rec scope.
7970        let v = ev(r#"
7971            let
7972              mkOptionType = x: x;
7973              mergeOneOption = "merge";
7974              attrValues = builtins.attrValues;
7975              setType = name: value: { __type = name; } // value;
7976              mapAttrs = builtins.mapAttrs;
7977              enum = xs: mkOptionType { name = "enum"; check = x: builtins.elem x xs; };
7978              setTypes = type: mapAttrs (name: value: setType type.name ({ inherit name; } // value));
7979            in
7980            rec {
7981              types.openSB = mkOptionType { name = "sb"; merge = mergeOneOption; };
7982              types.significantByte = enum (attrValues significantBytes);
7983              significantBytes = setTypes types.openSB { bigEndian = {}; littleEndian = {}; };
7984              types.openCpuType = mkOptionType { name = "cpu-type"; };
7985              types.cpuType = enum (attrValues cpuTypes);
7986              cpuTypes = setTypes types.openCpuType { arm = { bits = 32; }; };
7987            }.types.openCpuType
7988        "#);
7989        if let Value::Attrs(attrs) = v {
7990            assert_eq!(
7991                force_value(attrs.get("name").unwrap()).unwrap(),
7992                Value::string("cpu-type")
7993            );
7994        } else {
7995            panic!("expected attrs");
7996        }
7997    }
7998
7999    #[test]
8000    fn let_dotted_leaf_uses_let_scope() {
8001        // Dotted binding leaf in a let block sees sibling let-bindings.
8002        let v = ev("let a.x = f 1; f = x: x + 1; in a.x");
8003        assert_eq!(v, Value::Int(2));
8004    }
8005
8006    #[test]
8007    fn let_inherit_from_plus_dotted_overrides() {
8008        // inherit-from and dotted bindings for the same key in a let
8009        // block: CppNix rejects this as a duplicate definition.  Sui
8010        // currently lets the dotted binding win (last-write-wins).
8011        // This test documents the current behaviour -- when we add
8012        // duplicate detection it should change to assert an error.
8013        let v = ev(r#"
8014            let
8015              src = { types = { existing = true; }; };
8016              inherit (src) types;
8017              types.added = true;
8018            in types
8019        "#);
8020        if let Value::Attrs(attrs) = v {
8021            // Dotted binding overwrites the inherited value
8022            assert_eq!(
8023                force_value(attrs.get("added").unwrap()).unwrap(),
8024                Value::Bool(true)
8025            );
8026            // Inherited 'existing' is lost because dotted replaced it
8027            assert!(attrs.get("existing").is_none());
8028        } else {
8029            panic!("expected attrs");
8030        }
8031    }
8032
8033    // ── Function pattern variations ────────────────────────
8034
8035    #[test]
8036    fn pattern_empty_no_args_no_ellipsis() {
8037        // {} pattern accepts only an empty attrset.
8038        assert_eq!(ev("({}: 1) {}"), Value::Int(1));
8039    }
8040
8041    #[test]
8042    fn pattern_empty_with_ellipsis_accepts_extra() {
8043        assert_eq!(ev("({...}: 1) { a = 1; b = 2; }"), Value::Int(1));
8044    }
8045
8046    #[test]
8047    fn pattern_all_defaults() {
8048        assert_eq!(
8049            ev("({a ? 1, b ? 2}: a + b) {}"),
8050            Value::Int(3),
8051        );
8052    }
8053
8054    #[test]
8055    fn pattern_at_bind_before() {
8056        // args @ { x }: args.x — bind name comes before pattern.
8057        assert_eq!(ev("(args @ { x }: args.x) { x = 7; }"), Value::Int(7));
8058    }
8059
8060    #[test]
8061    fn pattern_at_bind_after() {
8062        // { x } @ args: args.x — bind name comes after pattern.
8063        assert_eq!(ev("({ x } @ args: args.x) { x = 7; }"), Value::Int(7));
8064    }
8065
8066    #[test]
8067    fn pattern_default_references_other_arg() {
8068        // The default for `b` references `a` (which exists).
8069        assert_eq!(ev("({a, b ? a + 1}: b) {a = 10;}"), Value::Int(11));
8070    }
8071
8072    #[test]
8073    fn pattern_required_missing_errors() {
8074        let result = eval("({ a, b }: a) { a = 1; }");
8075        assert!(result.is_err());
8076    }
8077
8078    #[test]
8079    fn pattern_unexpected_errors_without_ellipsis() {
8080        let result = eval("({ a }: a) { a = 1; b = 2; }");
8081        assert!(result.is_err());
8082    }
8083
8084    // ── apply: error on non-callable ───────────────────────
8085
8086    #[test]
8087    fn apply_int_errors() {
8088        let result = eval("42 5");
8089        assert!(result.is_err());
8090    }
8091
8092    #[test]
8093    fn apply_string_errors() {
8094        let result = eval(r#""hi" 5"#);
8095        assert!(result.is_err());
8096    }
8097
8098    #[test]
8099    fn apply_attrset_without_functor_errors() {
8100        let result = eval("{ x = 1; } 5");
8101        assert!(result.is_err());
8102        let msg = format!("{}", result.unwrap_err());
8103        assert!(msg.contains("__functor") || msg.contains("cannot call"));
8104    }
8105
8106    // ── Select with multi-segment + default ────────────────
8107
8108    #[test]
8109    fn select_multi_segment_with_default() {
8110        // a.b.missing or 99 -- the missing segment yields the default.
8111        assert_eq!(ev("{ a = { b = 1; }; }.a.c or 99"), Value::Int(99));
8112    }
8113
8114    #[test]
8115    fn select_from_int_errors() {
8116        let result = eval("(1).x");
8117        assert!(result.is_err());
8118    }
8119
8120    // ── HasAttr edge cases ─────────────────────────────────
8121
8122    #[test]
8123    fn has_attr_on_non_set_returns_false() {
8124        // `expr ? a` where expr is not a set returns false (not error).
8125        assert_eq!(ev("1 ? x"), Value::Bool(false));
8126    }
8127
8128    #[test]
8129    fn has_attr_nested_path_present() {
8130        assert_eq!(ev("{ a = { b = 1; }; } ? a.b"), Value::Bool(true));
8131    }
8132
8133    #[test]
8134    fn has_attr_nested_path_missing() {
8135        assert_eq!(ev("{ a = { b = 1; }; } ? a.c"), Value::Bool(false));
8136    }
8137
8138    #[test]
8139    fn has_attr_intermediate_missing_returns_false() {
8140        assert_eq!(ev("{} ? a.b.c"), Value::Bool(false));
8141    }
8142
8143    // ── List eval edge cases ───────────────────────────────
8144
8145    #[test]
8146    fn list_with_function_value() {
8147        let v = ev("[(x: x + 1)]");
8148        if let Value::List(items) = v {
8149            assert_eq!(items.len(), 1);
8150            // List elements are now lazy (thunked). Force to check type.
8151            let forced = force_value(&items[0]).unwrap();
8152            assert!(matches!(forced, Value::Lambda(_)));
8153        } else {
8154            panic!("expected list");
8155        }
8156    }
8157
8158    // ── eval_inherit edge: inherit from missing var ────────
8159
8160    #[test]
8161    fn inherit_unknown_name_errors() {
8162        let result = eval("let x = 1; in let inherit nonexistent; in nonexistent");
8163        assert!(result.is_err());
8164    }
8165
8166    // ── String op: string concat preserves context ─────────
8167
8168    #[test]
8169    fn string_concat_no_context_when_both_plain() {
8170        let v = ev(r#""abc" + "def""#);
8171        if let Value::String(ns) = v {
8172            assert_eq!(ns.chars, "abcdef");
8173            assert!(!ns.has_context());
8174        } else {
8175            panic!("expected string");
8176        }
8177    }
8178
8179    // ── Parens / Root ──────────────────────────────────────
8180
8181    #[test]
8182    fn parens_around_expression() {
8183        assert_eq!(ev("(1 + 2)"), Value::Int(3));
8184    }
8185
8186    #[test]
8187    fn nested_parens() {
8188        assert_eq!(ev("(((42)))"), Value::Int(42));
8189    }
8190
8191    // ── Throw via builtins ─────────────────────────────────
8192
8193    #[test]
8194    fn throw_propagates_as_error() {
8195        let result = eval(r#"builtins.throw "kaboom""#);
8196        match result {
8197            Err(EvalError::Throw(s)) => assert!(s.contains("kaboom")),
8198            other => panic!("expected Throw, got {other:?}"),
8199        }
8200    }
8201
8202    #[test]
8203    fn assert_failed_propagates_as_error() {
8204        let result = eval("assert false; 1");
8205        match result {
8206            Err(EvalError::AssertionFailed(_)) => {}
8207            other => panic!("expected AssertionFailed, got {other:?}"),
8208        }
8209    }
8210
8211    // ── eval_str InterpolPart::Literal only ────────────────
8212
8213    #[test]
8214    fn string_no_interp_yields_no_context() {
8215        let v = ev(r#""just literal""#);
8216        if let Value::String(ns) = v {
8217            assert!(!ns.has_context());
8218        } else {
8219            panic!("expected string");
8220        }
8221    }
8222
8223    // ── Path interpolation adds context ───────────────────
8224
8225    // Byte-parity root #5: interpolating a source path is CppNix copy-to-store
8226    // coercion — the path is NAR-copied into /nix/store/<hash>-<name> and the
8227    // store path (with store-path context) is spliced in, not the raw path.
8228    // NAR of a single regular file is content+basename only (location-
8229    // independent), so a temp <dir>/data.txt of "hello\n" yields the exact
8230    // store path nix 2.34 produced: /nix/store/y9dmv…-data.txt.
8231    #[test]
8232    fn interp_path_copies_to_store_byte_matches_cppnix() {
8233        let dir = std::env::temp_dir().join(format!("sui-r5-interp-{}", std::process::id()));
8234        let _ = std::fs::remove_dir_all(&dir);
8235        std::fs::create_dir_all(&dir).unwrap();
8236        let f = dir.join("data.txt");
8237        std::fs::write(&f, b"hello\n").unwrap();
8238        let expr = format!(r#""${{{}}}""#, f.display());
8239        let v = eval(&expr).unwrap();
8240        if let Value::String(ns) = v {
8241            assert_eq!(
8242                ns.chars.to_string(),
8243                "/nix/store/y9dmvfhip31hg8ia4njwjz9vfa3ndphr-data.txt",
8244            );
8245            assert!(ns.has_context());
8246        } else {
8247            panic!("expected string");
8248        }
8249        let _ = std::fs::remove_dir_all(&dir);
8250    }
8251
8252    // ── pipe operators (NotImplemented) ────────────────────
8253    // Pipe operators (|>, <|) are parsed as PipeRight/PipeLeft and
8254    // currently return NotImplemented. We can't easily evaluate them
8255    // here because rnix may not even parse them, so we just rely on
8256    // the binop branch existing.
8257
8258    // ── ParseError surface ─────────────────────────────────
8259
8260    #[test]
8261    fn parse_error_unbalanced_braces() {
8262        let result = eval("{ a = 1");
8263        assert!(result.is_err());
8264        let err = result.unwrap_err();
8265        assert!(matches!(err, EvalError::ParseError(_)));
8266    }
8267
8268    #[test]
8269    fn parse_error_dangling_let() {
8270        let result = eval("let in");
8271        assert!(result.is_err());
8272    }
8273
8274    #[test]
8275    fn parse_error_empty_input() {
8276        let result = eval("");
8277        assert!(result.is_err());
8278    }
8279
8280    // ── num_op coverage via float ops ──────────────────────
8281
8282    #[test]
8283    fn float_int_subtraction() {
8284        assert_eq!(ev("3.5 - 1"), Value::Float(2.5));
8285    }
8286
8287    #[test]
8288    fn int_float_subtraction() {
8289        assert_eq!(ev("3 - 0.5"), Value::Float(2.5));
8290    }
8291
8292    #[test]
8293    fn float_float_division() {
8294        assert_eq!(ev("6.0 / 2.0"), Value::Float(3.0));
8295    }
8296
8297    #[test]
8298    fn int_float_multiplication() {
8299        assert_eq!(ev("3 * 2.5"), Value::Float(7.5));
8300    }
8301
8302    // ── compare with mixed numerics ────────────────────────
8303
8304    #[test]
8305    fn compare_int_float_less() {
8306        assert_eq!(ev("1 < 1.5"), Value::Bool(true));
8307    }
8308
8309    #[test]
8310    fn compare_float_int_more() {
8311        assert_eq!(ev("3.5 > 3"), Value::Bool(true));
8312    }
8313
8314    #[test]
8315    fn compare_equal_int_float() {
8316        assert_eq!(ev("3 <= 3.0"), Value::Bool(true));
8317    }
8318
8319    // ── Equality ──────────────────────────────────────────
8320
8321    #[test]
8322    fn equal_lists_same() {
8323        assert_eq!(ev("[1 2 3] == [1 2 3]"), Value::Bool(true));
8324    }
8325
8326    #[test]
8327    fn equal_lists_diff_length() {
8328        assert_eq!(ev("[1 2] == [1 2 3]"), Value::Bool(false));
8329    }
8330
8331    #[test]
8332    fn not_equal_lists() {
8333        assert_eq!(ev("[1] != [2]"), Value::Bool(true));
8334    }
8335
8336    #[test]
8337    fn equal_attrsets_same() {
8338        assert_eq!(ev("{a = 1; b = 2;} == {b = 2; a = 1;}"), Value::Bool(true));
8339    }
8340
8341    // ── Lambda identity equality (Rc ptr_eq) ────────────────
8342    // Regression test: same lambda via Rc must compare equal.
8343    // Without this, nixpkgs stdenv evaluation enters an infinite loop
8344    // because `crossSystem != localSystem` returns true even when both
8345    // are the same elaborate result (containing shared function attrs).
8346
8347    #[test]
8348    fn lambda_self_equality_in_attrset() {
8349        // Same closure shared via let → inherit must be equal
8350        assert_eq!(
8351            ev("let f = x: x; in { a = 1; inherit f; } == { a = 1; inherit f; }"),
8352            Value::Bool(true),
8353        );
8354    }
8355
8356    #[test]
8357    fn lambda_self_reference_attrset_equality() {
8358        // Attrset with function attr: x == x must be true
8359        assert_eq!(
8360            ev("let x = { a = 1; f = y: y; }; in x == x"),
8361            Value::Bool(true),
8362        );
8363    }
8364
8365    #[test]
8366    fn lambda_different_closures_not_equal() {
8367        // Different lambda closures (even structurally identical) must be false
8368        assert_eq!(
8369            ev("{ f = x: x; } == { f = x: x; }"),
8370            Value::Bool(false),
8371        );
8372    }
8373
8374    #[test]
8375    fn lambda_ne_does_not_force_unused_branch() {
8376        // If crossSystem == localSystem (same obj), != returns false,
8377        // and the then-branch (with throw) is never forced.
8378        assert_eq!(
8379            ev("let ls = { a = 1; f = x: x; }; in if ls != ls then builtins.throw \"bug\" else 42"),
8380            Value::Int(42),
8381        );
8382    }
8383
8384    // ── force_value chains thunks ──────────────────────────
8385
8386    #[test]
8387    fn force_value_through_thunk() {
8388        let root = rnix::Root::parse("1 + 2");
8389        let expr = root.tree().expr().unwrap();
8390        let thunk = Thunk::new_suspended(expr, Env::new());
8391        let val = Value::Thunk(thunk);
8392        assert_eq!(force_value(&val).unwrap(), Value::Int(3));
8393    }
8394
8395    // ── Builtin name "tryEval" lazy arg path ──────────────
8396
8397    #[test]
8398    fn try_eval_catches_thrown_error() {
8399        // tryEval wraps the thunk and catches throws inside.
8400        let v = ev(r#"(builtins.tryEval (builtins.throw "oops")).success"#);
8401        assert_eq!(v, Value::Bool(false));
8402    }
8403
8404    #[test]
8405    fn try_eval_returns_value_on_success() {
8406        let v = ev("(builtins.tryEval 42).value");
8407        assert_eq!(v, Value::Int(42));
8408    }
8409
8410    // ── LegacyLet (`let { body = ...; ...}`) ───────────────
8411
8412    #[test]
8413    fn legacy_let_returns_body_attr() {
8414        // `let { x = 1; body = x + 41; }` is the legacy let form: it
8415        // is desugared as a recursive set whose `body` attr is the
8416        // result.
8417        assert_eq!(ev("let { x = 1; body = x + 41; }"), Value::Int(42));
8418    }
8419
8420    #[test]
8421    fn legacy_let_missing_body_errors() {
8422        let result = eval("let { x = 1; }");
8423        assert!(result.is_err());
8424    }
8425
8426    #[test]
8427    fn legacy_let_with_inherit_from_scope() {
8428        assert_eq!(
8429            ev("let outer = 5; in let { inherit outer; body = outer * 2; }"),
8430            Value::Int(10),
8431        );
8432    }
8433
8434    // ── eval_str interpolation more cases ──────────────────
8435
8436    #[test]
8437    fn interp_with_string_concat_preserves_order() {
8438        assert_eq!(
8439            ev(r#"let a = "x"; b = "y"; in "${a}-${b}""#),
8440            Value::string("x-y"),
8441        );
8442    }
8443
8444    #[test]
8445    fn interp_only_literal_part() {
8446        assert_eq!(ev(r#""no interp here""#), Value::string("no interp here"));
8447    }
8448
8449    // ── eval_attr dynamic / string keys ────────────────────
8450
8451    #[test]
8452    fn dynamic_attr_via_string_key_in_set() {
8453        // `{ "a" = 1; }.a` works because attr keys can be string literals.
8454        assert_eq!(ev(r#"{ "a" = 1; }.a"#), Value::Int(1));
8455    }
8456
8457    #[test]
8458    fn dynamic_attr_via_interpolated_key() {
8459        let v = ev(r#"let k = "foo"; in { ${k} = 99; }.foo"#);
8460        assert_eq!(v, Value::Int(99));
8461    }
8462
8463    // ── String key access via select with dynamic ──────────
8464
8465    #[test]
8466    fn select_with_string_key() {
8467        let v = ev(r#"{ a = 42; }."a""#);
8468        assert_eq!(v, Value::Int(42));
8469    }
8470
8471    // ── Apply via __functor on attrset ─────────────────────
8472
8473    #[test]
8474    fn apply_attrset_with_functor_works() {
8475        let v = ev("let s = { __functor = self: x: x + 1; }; in s 5");
8476        assert_eq!(v, Value::Int(6));
8477    }
8478
8479    // ── Negation of negative ───────────────────────────────
8480
8481    #[test]
8482    fn double_negate_int() {
8483        assert_eq!(ev("- (-5)"), Value::Int(5));
8484    }
8485
8486    // ── Inherit from rec scope binding visibility ──────────
8487
8488    #[test]
8489    fn inherit_in_let_makes_name_available() {
8490        assert_eq!(
8491            ev("let src = { a = 7; }; in let inherit (src) a; in a"),
8492            Value::Int(7),
8493        );
8494    }
8495
8496    // ── String + path ──────────────────────────────────────
8497
8498    #[test]
8499    fn path_plus_string_yields_path() {
8500        let v = ev(r#"/foo + "/bar""#);
8501        match v {
8502            Value::Path(p) => assert_eq!(&*p, "/foo/bar"),
8503            _ => panic!("expected path"),
8504        }
8505    }
8506
8507    // ── Lazy attrset value not forced unless selected ──────
8508
8509    #[test]
8510    fn attrset_value_not_forced_unless_selected() {
8511        // `bad` is an attr whose value would error if forced, but we
8512        // only ever select `good`, so it's never touched.
8513        assert_eq!(
8514            ev(r#"{ bad = builtins.throw "boom"; good = 42; }.good"#),
8515            Value::Int(42),
8516        );
8517    }
8518
8519    // ── Lambda calling itself via let ──────────────────────
8520
8521    #[test]
8522    fn lambda_recursive_via_let() {
8523        // factorial via let-bound recursive function
8524        assert_eq!(
8525            ev("let fact = n: if n == 0 then 1 else n * fact (n - 1); in fact 5"),
8526            Value::Int(120),
8527        );
8528    }
8529
8530    // ── Dynamic key in select ──────────────────────────────
8531
8532    #[test]
8533    fn select_with_dynamic_key_via_var() {
8534        // ${k} interpolation in select position is not standard Nix
8535        // syntax, but a string-literal key works for select.
8536        assert_eq!(ev(r#"let k = { x = 1; }; in k.x"#), Value::Int(1));
8537    }
8538
8539    // ── Compare strings ────────────────────────────────────
8540
8541    #[test]
8542    fn compare_string_lex_greater_or_equal() {
8543        assert_eq!(ev(r#""b" >= "a""#), Value::Bool(true));
8544        assert_eq!(ev(r#""a" >= "a""#), Value::Bool(true));
8545        assert_eq!(ev(r#""a" >= "b""#), Value::Bool(false));
8546    }
8547
8548    // ── PartialEq across types ─────────────────────────────
8549
8550    #[test]
8551    fn equal_int_string_false() {
8552        assert_eq!(ev(r#"1 == "1""#), Value::Bool(false));
8553    }
8554
8555    #[test]
8556    fn equal_null_int_false() {
8557        assert_eq!(ev("null == 0"), Value::Bool(false));
8558    }
8559
8560    // ── Update operator on thunked operands ────────────────
8561
8562    #[test]
8563    fn update_with_let_bound_operands() {
8564        assert_eq!(
8565            ev("let a = { x = 1; }; b = { y = 2; }; in (a // b).y"),
8566            Value::Int(2),
8567        );
8568    }
8569
8570    // ── Concat on let-bound lists ──────────────────────────
8571
8572    #[test]
8573    fn concat_lists_from_let() {
8574        assert_eq!(
8575            ev("let a = [1 2]; b = [3 4]; in builtins.length (a ++ b)"),
8576            Value::Int(4),
8577        );
8578    }
8579
8580    // ── String interpolation: list coercion ─────────────────
8581
8582    #[test]
8583    fn interp_list_coerces_with_spaces() {
8584        // Lists in interpolation are now coerced via coerce_to_string
8585        // (space-joined elements).
8586        assert_eq!(
8587            ev(r#""${toString [1 2 3]}""#),
8588            Value::string("1 2 3"),
8589        );
8590    }
8591
8592    #[test]
8593    fn interp_list_directly_coerces() {
8594        // Direct list interpolation space-joins elements via coerce_to_string.
8595        assert_eq!(
8596            ev(r#""${[1 2]}""#),
8597            Value::string("1 2"),
8598        );
8599    }
8600
8601    // ── String interpolation: outPath ─────────────────────
8602
8603    #[test]
8604    fn interp_outpath_attrset() {
8605        assert_eq!(
8606            ev(r#"let x = { outPath = "/nix/store/abc"; }; in "${x}""#),
8607            Value::string("/nix/store/abc"),
8608        );
8609    }
8610
8611    #[test]
8612    fn interp_tostring_takes_priority_over_outpath() {
8613        assert_eq!(
8614            ev(r#"let x = { __toString = self: "custom"; outPath = "/ignored"; }; in "${x}""#),
8615            Value::string("custom"),
8616        );
8617    }
8618
8619    #[test]
8620    fn interp_derivation_coerces_to_outpath() {
8621        // derivation produces an attrset with outPath
8622        let result = eval(r#"
8623            let drv = builtins.derivation {
8624                name = "test";
8625                system = "x86_64-linux";
8626                builder = "/bin/sh";
8627            };
8628            in "${drv}"
8629        "#).unwrap();
8630        if let Value::String(s) = result {
8631            assert!(s.chars.starts_with("/nix/store/"), "got: {}", s.chars);
8632        } else {
8633            panic!("expected string");
8634        }
8635    }
8636
8637    // ── String interpolation: lambda error ─────────────────
8638
8639    #[test]
8640    fn interp_lambda_errors() {
8641        let result = eval(r#""${x: x}""#);
8642        assert!(result.is_err());
8643    }
8644
8645    // ── force_value tests ────────────────────────────────────
8646
8647    #[test]
8648    fn force_value_int_returns_same() {
8649        let v = Value::Int(42);
8650        assert_eq!(force_value(&v).unwrap(), Value::Int(42));
8651    }
8652
8653    #[test]
8654    fn force_value_bool_returns_same() {
8655        let v = Value::Bool(true);
8656        assert_eq!(force_value(&v).unwrap(), Value::Bool(true));
8657    }
8658
8659    #[test]
8660    fn force_value_string_returns_same() {
8661        let v = Value::string("hello");
8662        assert_eq!(force_value(&v).unwrap(), Value::string("hello"));
8663    }
8664
8665    #[test]
8666    fn force_value_attrs_returns_same() {
8667        let mut a = NixAttrs::new();
8668        a.insert("x".to_string(), Value::Int(1));
8669        let v = Value::Attrs(Rc::new(a.clone()));
8670        assert_eq!(force_value(&v).unwrap(), Value::Attrs(Rc::new(a)));
8671    }
8672
8673    #[test]
8674    fn force_value_list_returns_same() {
8675        let v = Value::list(vec![Value::Int(1), Value::Int(2)]);
8676        assert_eq!(
8677            force_value(&v).unwrap(),
8678            Value::list(vec![Value::Int(1), Value::Int(2)]),
8679        );
8680    }
8681
8682    #[test]
8683    fn force_value_null_returns_null() {
8684        let v = Value::Null;
8685        assert_eq!(force_value(&v).unwrap(), Value::Null);
8686    }
8687
8688    #[test]
8689    fn force_value_evaluated_thunk_returns_cached() {
8690        // Thunk wrapping a simple expression should evaluate and cache
8691        let v = ev("let x = 1 + 2; in x");
8692        assert_eq!(v, Value::Int(3));
8693        // Force again — should return the cached value
8694        assert_eq!(force_value(&v).unwrap(), Value::Int(3));
8695    }
8696
8697    // ── Tail-call loop tests ─────────────────────────────────
8698
8699    #[test]
8700    fn tco_if_true_condition() {
8701        assert_eq!(ev("if true then 42 else 0"), Value::Int(42));
8702    }
8703
8704    #[test]
8705    fn tco_if_false_condition() {
8706        assert_eq!(ev("if false then 42 else 0"), Value::Int(0));
8707    }
8708
8709    #[test]
8710    fn tco_deeply_nested_if_else_chain() {
8711        // Build a chain: if false then 1 else if false then 2 else ... else 150
8712        // All conditions are false except the final else, which produces 150.
8713        let mut expr = String::from("150");
8714        for i in (1..150).rev() {
8715            expr = format!("if false then {} else {}", i, expr);
8716        }
8717        let v = ev(&expr);
8718        assert_eq!(v, Value::Int(150));
8719    }
8720
8721    #[test]
8722    fn tco_assert_true_passes_through() {
8723        assert_eq!(ev("assert true; 42"), Value::Int(42));
8724    }
8725
8726    #[test]
8727    fn tco_assert_false_throws_assertion_failed() {
8728        let result = eval("assert false; 42");
8729        assert!(result.is_err());
8730        let err = result.unwrap_err();
8731        assert!(
8732            matches!(err, EvalError::AssertionFailed(_)),
8733            "expected AssertionFailed, got: {err}",
8734        );
8735    }
8736
8737    #[test]
8738    fn tco_with_makes_scope_available() {
8739        assert_eq!(ev("with { x = 10; y = 20; }; x + y"), Value::Int(30));
8740    }
8741
8742    #[test]
8743    fn tco_let_in_creates_bindings() {
8744        assert_eq!(ev("let a = 5; in a"), Value::Int(5));
8745    }
8746
8747    #[test]
8748    fn tco_let_in_multiple_bindings() {
8749        assert_eq!(ev("let a = 1; b = 2; c = 3; in a + b + c"), Value::Int(6));
8750    }
8751
8752    // ── eval_attrset tests ───────────────────────────────────
8753
8754    #[test]
8755    fn eval_attrset_empty() {
8756        let v = ev("{}");
8757        if let Value::Attrs(attrs) = v {
8758            assert!(attrs.is_empty(), "expected empty attrset");
8759        } else {
8760            panic!("expected attrset, got {v:?}");
8761        }
8762    }
8763
8764    #[test]
8765    fn eval_attrset_simple_kv() {
8766        let v = ev("{ a = 1; b = 2; }");
8767        if let Value::Attrs(attrs) = v {
8768            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
8769            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
8770        } else {
8771            panic!("expected attrset, got {v:?}");
8772        }
8773    }
8774
8775    #[test]
8776    fn eval_attrset_recursive() {
8777        assert_eq!(ev("(rec { a = 1; b = a + 1; }).b"), Value::Int(2));
8778        assert_eq!(ev("(rec { a = 1; b = a + 1; }).a"), Value::Int(1));
8779    }
8780
8781    #[test]
8782    fn eval_attrset_inherit_from_scope() {
8783        assert_eq!(ev("let x = 1; in { inherit x; }.x"), Value::Int(1));
8784    }
8785
8786    #[test]
8787    fn eval_attrset_inherit_from_expr() {
8788        assert_eq!(
8789            ev("{ inherit (builtins) true; }.true"),
8790            Value::Bool(true),
8791        );
8792    }
8793
8794    #[test]
8795    fn eval_attrset_dotted_path() {
8796        assert_eq!(ev("{ a.b.c = 1; }.a.b.c"), Value::Int(1));
8797    }
8798
8799    #[test]
8800    fn eval_attrset_update_merge() {
8801        let v = ev("{ a = 1; } // { b = 2; }");
8802        if let Value::Attrs(attrs) = v {
8803            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
8804            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
8805        } else {
8806            panic!("expected attrset, got {v:?}");
8807        }
8808    }
8809
8810    // ── eval_apply tests ─────────────────────────────────────
8811
8812    #[test]
8813    fn eval_apply_simple_function() {
8814        assert_eq!(ev("(x: x + 1) 2"), Value::Int(3));
8815    }
8816
8817    #[test]
8818    fn eval_apply_pattern_destructuring() {
8819        assert_eq!(ev("({a, b}: a + b) { a = 1; b = 2; }"), Value::Int(3));
8820    }
8821
8822    #[test]
8823    fn eval_apply_default_arguments() {
8824        assert_eq!(ev("({a, b ? 0}: a + b) { a = 1; }"), Value::Int(1));
8825    }
8826
8827    #[test]
8828    fn eval_apply_ellipsis() {
8829        assert_eq!(ev("({a, ...}: a) { a = 1; b = 2; }"), Value::Int(1));
8830    }
8831
8832    // ── eval_select tests ────────────────────────────────────
8833
8834    #[test]
8835    fn eval_select_single_key() {
8836        assert_eq!(ev("{ a = 1; }.a"), Value::Int(1));
8837    }
8838
8839    #[test]
8840    fn eval_select_multi_level() {
8841        assert_eq!(ev("{ a.b = 1; }.a.b"), Value::Int(1));
8842    }
8843
8844    #[test]
8845    fn eval_select_with_or_default() {
8846        assert_eq!(ev("{}.a or 42"), Value::Int(42));
8847    }
8848
8849    #[test]
8850    fn eval_select_missing_key_without_default_throws() {
8851        let result = eval("{}.a");
8852        assert!(result.is_err());
8853    }
8854
8855    // ── BinOp tests ──────────────────────────────────────────
8856
8857    #[test]
8858    fn binop_add_ints() {
8859        assert_eq!(ev("1 + 2"), Value::Int(3));
8860    }
8861
8862    #[test]
8863    fn binop_sub_ints() {
8864        assert_eq!(ev("3 - 1"), Value::Int(2));
8865    }
8866
8867    #[test]
8868    fn binop_mul_ints() {
8869        assert_eq!(ev("2 * 3"), Value::Int(6));
8870    }
8871
8872    #[test]
8873    fn binop_div_ints() {
8874        assert_eq!(ev("6 / 2"), Value::Int(3));
8875    }
8876
8877    #[test]
8878    fn binop_float_arithmetic() {
8879        assert_eq!(ev("1.5 + 2.5"), Value::Float(4.0));
8880    }
8881
8882    #[test]
8883    fn binop_string_concat() {
8884        assert_eq!(
8885            ev(r#""hello" + " " + "world""#),
8886            Value::string("hello world"),
8887        );
8888    }
8889
8890    #[test]
8891    fn binop_list_concat() {
8892        assert_eq!(
8893            ev("[1 2] ++ [3 4]"),
8894            Value::list(vec![
8895                Value::Int(1),
8896                Value::Int(2),
8897                Value::Int(3),
8898                Value::Int(4),
8899            ]),
8900        );
8901    }
8902
8903    #[test]
8904    fn binop_attrset_update() {
8905        let v = ev("{ a = 1; } // { b = 2; }");
8906        if let Value::Attrs(attrs) = v {
8907            assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
8908            assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
8909        } else {
8910            panic!("expected attrset, got {v:?}");
8911        }
8912    }
8913
8914    #[test]
8915    fn binop_less_than() {
8916        assert_eq!(ev("1 < 2"), Value::Bool(true));
8917        assert_eq!(ev("2 < 1"), Value::Bool(false));
8918    }
8919
8920    #[test]
8921    fn binop_greater_than() {
8922        assert_eq!(ev("2 > 1"), Value::Bool(true));
8923        assert_eq!(ev("1 > 2"), Value::Bool(false));
8924    }
8925
8926    #[test]
8927    fn binop_equal() {
8928        assert_eq!(ev("1 == 1"), Value::Bool(true));
8929        assert_eq!(ev("1 == 2"), Value::Bool(false));
8930    }
8931
8932    #[test]
8933    fn binop_not_equal() {
8934        assert_eq!(ev("1 != 2"), Value::Bool(true));
8935        assert_eq!(ev("1 != 1"), Value::Bool(false));
8936    }
8937
8938    #[test]
8939    fn binop_logical_and() {
8940        assert_eq!(ev("true && false"), Value::Bool(false));
8941        assert_eq!(ev("true && true"), Value::Bool(true));
8942    }
8943
8944    #[test]
8945    fn binop_logical_or() {
8946        assert_eq!(ev("true || false"), Value::Bool(true));
8947        assert_eq!(ev("false || false"), Value::Bool(false));
8948    }
8949
8950    #[test]
8951    fn binop_logical_not() {
8952        assert_eq!(ev("!true"), Value::Bool(false));
8953        assert_eq!(ev("!false"), Value::Bool(true));
8954    }
8955
8956    #[test]
8957    fn binop_implication() {
8958        assert_eq!(ev("false -> true"), Value::Bool(true));
8959        assert_eq!(ev("false -> false"), Value::Bool(true));
8960        assert_eq!(ev("true -> true"), Value::Bool(true));
8961        assert_eq!(ev("true -> false"), Value::Bool(false));
8962    }
8963}
8964
8965/// Build an attrset from a `sui-normalize` [`GroupPlan`].
8966///
8967/// This is the plan-driven replacement for the entry loops in
8968/// [`eval_attrset`] / the `LetIn` arm / `eval_entries`. It exists because
8969/// nix's duplicate-key merge is a **parse-time splice into the first-declared
8970/// node**, not a value-level union: the second side's bindings become
8971/// bindings *of the first node*, so they are scoped by it and the later
8972/// `rec` is discarded. `sui-normalize` performed that splice; this function
8973/// only evaluates the result.
8974///
8975/// The consequence worth stating: there is no merging here, and no collision
8976/// to resolve. `attrs.insert` is a plain insert because the plan's
8977/// postcondition is that no name appears twice. That is what retires
8978/// `merge_nested_insert` from the construction path — and with it the
8979/// force-to-WHNF-on-collision that turned
8980/// `let f = x: x+1; a.b = {x = f 1;}; a.b.y = 2; in a.b.x` into
8981/// `UndefinedVar 'f'` on an expression nix evaluates to `2`.
8982pub fn eval_plan_group(
8983    plan: &sui_normalize::GroupPlan,
8984    env: &Env,
8985) -> Result<Value, EvalError> {
8986    let (attrs, _scope) = bind_plan_group(plan, env)?;
8987    Ok(Value::Attrs(std::rc::Rc::new(attrs)))
8988}
8989
8990/// Build a plan's bindings, returning BOTH the attrset and the scope they were
8991/// bound in.
8992///
8993/// Two consumers need different halves of this. An attrset literal wants the
8994/// attrs; a `let` wants the scope, because a `let` is a binder for a body and
8995/// produces no attrset at all. Legacy-`let` (`let { … body = …; }`) wants the
8996/// attrs and then selects `body` from them.
8997fn bind_plan_group(
8998    plan: &sui_normalize::GroupPlan,
8999    env: &Env,
9000) -> Result<(NixAttrs, Env), EvalError> {
9001    use sui_normalize::Binding;
9002
9003    let mut attrs = NixAttrs::new();
9004    // A recursive group binds its own names; a non-recursive one does not.
9005    // `rec`-ness came from the FIRST declaration — see `sui-normalize`.
9006    let mut scope_env = if plan.recursive { env.child() } else { env.clone() };
9007    let mut thunks: Vec<Thunk> = Vec::new();
9008
9009    // `inherit (e)` sources: ONE thunk per clause, shared across every name
9010    // that clause binds, so `e` is evaluated at most once. Built against the
9011    // group's OWN scope — measured on nix: `rec { b = {x=99;}; inherit (b) x; }`
9012    // is `x = 99`, so the source sees the group it is being bound into.
9013    let from_thunks: Vec<Thunk> = plan
9014        .inherit_froms
9015        .iter()
9016        .map(|e| Thunk::new_suspended(e.clone(), scope_env.clone()))
9017        .collect();
9018
9019    for b in &plan.statics {
9020        let name = sui_intern::resolve(b.name).to_string();
9021        let value = match &b.binding {
9022            Binding::Leaf(expr) => {
9023                let t = Thunk::new_suspended(expr.clone(), scope_env.clone());
9024                thunks.push(t.clone());
9025                Value::Thunk(t)
9026            }
9027            Binding::Group(sub) => {
9028                let t = Thunk::new_plan_group(sub.clone(), scope_env.clone());
9029                thunks.push(t.clone());
9030                Value::Thunk(t)
9031            }
9032            // `inherit x` resolves in the ENCLOSING scope, never the group's
9033            // own rec scope — that is what makes it shadow rather than
9034            // self-reference, and why it can never merge.
9035            Binding::Inherit => env
9036                .lookup(&name)
9037                .ok_or_else(|| EvalError::UndefinedVar(format!("'{name}'")))?,
9038            Binding::InheritFrom { from } => {
9039                let t = Thunk::new_inherit_select(from_thunks[*from].clone(), &name);
9040                thunks.push(t.clone());
9041                Value::Thunk(t)
9042            }
9043        };
9044        // PLAIN insert: the plan guarantees no repeated name.
9045        attrs.insert(name.clone(), value.clone());
9046        if plan.recursive {
9047            scope_env.bind(name, value);
9048        }
9049    }
9050
9051    // Phase 2: re-point every thunk at the completed scope, so a binding that
9052    // references a LATER sibling resolves. `PlanGroup` is re-pointable for
9053    // exactly this reason.
9054    if plan.recursive {
9055        for t in &thunks {
9056            t.update_env(&scope_env);
9057        }
9058    }
9059
9060    // ── dynamic keys ─────────────────────────────────────────────────────
9061    //
9062    // `${e}` keys that did not constant-fold. They are resolved AFTER every
9063    // static key, in source order, in the group's own scope — nix's ordering,
9064    // and the reason a dynamic key can never participate in the parse-time
9065    // merge. Omitting this dropped them entirely: two corpus fixtures built
9066    // `{ a = {}; }` where nix builds `{ a = { b = …; c = …; }; }`.
9067    //
9068    // A key evaluating to `null` SKIPS the binding (CppNix), rather than
9069    // inserting a `"null"` name.
9070    for d in &plan.dynamics {
9071        let key_val = eval_expr(&d.key, &scope_env)?;
9072        let key_concrete = key_val.demand()?;
9073        if matches!(key_concrete, Concrete::Null) {
9074            continue;
9075        }
9076        let name = key_concrete.into_value().as_string()?.to_string();
9077        let value = match &d.value {
9078            sui_normalize::Binding::Leaf(expr) => {
9079                Value::Thunk(Thunk::new_suspended(expr.clone(), scope_env.clone()))
9080            }
9081            sui_normalize::Binding::Group(sub) => {
9082                Value::Thunk(Thunk::new_plan_group(sub.clone(), scope_env.clone()))
9083            }
9084            sui_normalize::Binding::Inherit => env
9085                .lookup(&name)
9086                .ok_or_else(|| EvalError::UndefinedVar(format!("'{name}'")))?,
9087            sui_normalize::Binding::InheritFrom { from } => {
9088                Value::Thunk(Thunk::new_inherit_select(from_thunks[*from].clone(), &name))
9089            }
9090        };
9091        attrs.insert(name, value);
9092    }
9093
9094    // ★ Positions, which `builtins.unsafeGetAttrPos` reads. Dropping this was
9095    // a real regression caught by `every_binding_form_carries_a_position` —
9096    // the plan path built the right VALUES with every key position NULL.
9097    //
9098    // `StaticBinding::pos` is already the offset the AST path records: an
9099    // `AttrpathValue` starts at its head attr (`a` in `a.b = 1`, which is what
9100    // CppNix reports for the outer key), and an inherited name carries its own
9101    // ident's offset. And because the splice keeps the FIRST declaration's
9102    // `pos`, a merged key reports where it was first defined — which is what
9103    // nix reports too.
9104    if !plan.statics.is_empty() {
9105        let mut table = crate::pos::AttrPositions::new(current_eval_file());
9106        for b in &plan.statics {
9107            table.insert(b.name, b.pos.into());
9108        }
9109        attrs.set_positions(std::rc::Rc::new(table));
9110    }
9111
9112    Ok((attrs, scope_env))
9113}