Skip to main content

sui_eval/
value.rs

1//! Nix value types and environments.
2//!
3//! The evaluator is single-threaded: `Env` and `NixAttrs` contain
4//! `Rc<UnsafeCell<ThunkRepr>>` thunks.  All shared pointers use `Rc`
5//! (not `Arc`) because the values are never sent across threads.
6
7use std::cell::{Cell, OnceCell, RefCell, UnsafeCell};
8
9use std::fmt;
10pub use std::rc::Rc;
11
12use rustc_hash::FxBuildHasher;
13use smallvec::SmallVec;
14pub use smol_str::SmolStr;
15
16use rowan::ast::AstNode;
17
18use sui_intern::Symbol;
19
20/// Type alias for the persistent hash map used by `NixAttrs` and `Env`.
21///
22/// Uses `FxBuildHasher` (fast multiplication-based hash) instead of the
23/// default `RandomState`. This is optimal for `Symbol(u32)` keys where
24/// the hash is a single multiply-shift — no SipHash overhead.
25pub type FxHashMap<K, V> = im_rc::HashMap<K, V, FxBuildHasher>;
26
27/// Compact attrset map — a real `hashbrown` (std) `HashMap` with `FxBuildHasher`.
28///
29/// Used ONLY for `NixAttrs` (attribute sets), which are immutable-after-
30/// construction. Unlike `FxHashMap` (the persistent `im_rc` HAMT, retained for
31/// `Env` where `child()`/scope-push relies on O(1) structural sharing), this is a
32/// flat open-addressing table with ~0.875 load factor and NO branch-node
33/// allocations — a symbolicated dhat profile proved the `im_rc` HAMT branch nodes
34/// dominate eval heap, and the attrset slice is the safe one to compact.
35///
36/// BYTE-NEUTRAL: attrset observation order (which feeds drvPath hashing) comes
37/// from `NixAttrs::sorted_entries()` — it resolves each `Symbol` to its `String`
38/// and string-sorts on observation — NOT from this map's internal iteration
39/// order. Both `im_rc::HashMap` and `std::HashMap` are unordered, so swapping the
40/// implementation cannot change any observed order → drvPaths are unchanged.
41pub type AttrsMap<K, V> = std::collections::HashMap<K, V, FxBuildHasher>;
42
43/// Env-gated LIVE-OBJECT CENSUS.
44///
45/// A permanent, zero-cost-when-off diagnostic answering the question:
46/// when sui's eval peak is ~2× nix's, is the overhead (a) cyclic/lingering
47/// producer garbage sui retains, or (b) a uniform per-object representation
48/// overhead? These need different fixes, so we MEASURE.
49///
50/// Gated behind `SUI_LIVE_CENSUS=1`. The atomics are always compiled but the
51/// `_MADE`/`_LIVE` bookkeeping and the RSS/dump thread only run when enabled.
52/// All counters use `Relaxed` — we want a cheap high-water snapshot, not a
53/// linearizable total.
54///
55/// `_MADE` + `_LIVE` are incremented in the INNER heap type's constructor;
56/// `_LIVE` is decremented in the inner type's `Drop` so it fires exactly once
57/// when the last `Rc` drops. Counters live on the inner heap types
58/// (`NixAttrs`, `ThunkInner`, `EnvInner`, `NixString`, the list `Vec`) so we
59/// count distinct heap allocations, not `Rc` clones.
60pub mod census {
61    use std::sync::atomic::{AtomicI64, Ordering::Relaxed};
62    use std::sync::OnceLock;
63
64    pub static ATTRS_LIVE: AtomicI64 = AtomicI64::new(0);
65    pub static ATTRS_MADE: AtomicI64 = AtomicI64::new(0);
66    pub static THUNK_LIVE: AtomicI64 = AtomicI64::new(0);
67    pub static THUNK_MADE: AtomicI64 = AtomicI64::new(0);
68    pub static THUNK_EVALUATED: AtomicI64 = AtomicI64::new(0);
69    pub static ENV_LIVE: AtomicI64 = AtomicI64::new(0);
70    pub static ENV_MADE: AtomicI64 = AtomicI64::new(0);
71    pub static NIXSTR_LIVE: AtomicI64 = AtomicI64::new(0);
72    pub static NIXSTR_MADE: AtomicI64 = AtomicI64::new(0);
73    pub static LIST_LIVE: AtomicI64 = AtomicI64::new(0);
74    pub static LIST_MADE: AtomicI64 = AtomicI64::new(0);
75
76    /// Scope-narrowing verdict counters (`SUI_SCOPE_NARROW`, `eval.rs`).
77    ///
78    /// Every `let` / `rec` / pattern-default binding whose value is a thunk is
79    /// classified exactly once: NARROWED means it kept its outer-env capture
80    /// (no `Thunk -> Env -> Thunk` cycle closed), PINNED means its RHS reaches
81    /// a sibling in the same scope and it still takes Phase 2's `update_env`.
82    ///
83    /// The ratio is the whole point: it is what says whether narrowing does
84    /// anything on REAL code rather than on a synthetic probe. Both counters
85    /// are monotonic totals, not live counts — there is nothing to decrement,
86    /// which is why they need no `Drop` partner (and so cannot acquire
87    /// `ENV_LIVE`'s under-reporting bug, where `Env::bind`'s `Rc::make_mut`
88    /// clone is never counted as `made` while every drop is counted).
89    pub static SCOPE_THUNKS_NARROWED: AtomicI64 = AtomicI64::new(0);
90    pub static SCOPE_THUNKS_PINNED: AtomicI64 = AtomicI64::new(0);
91
92    /// Record a binding that kept its outer-env capture.
93    #[inline(always)]
94    pub fn scope_narrowed() {
95        if enabled() {
96            SCOPE_THUNKS_NARROWED.fetch_add(1, Relaxed);
97        }
98    }
99
100    /// Record a binding that still needs the scope env.
101    #[inline(always)]
102    pub fn scope_pinned() {
103        if enabled() {
104            SCOPE_THUNKS_PINNED.fetch_add(1, Relaxed);
105        }
106    }
107
108    /// True iff `SUI_LIVE_CENSUS=1`. Cached — read once.
109    #[inline]
110    pub fn enabled() -> bool {
111        static ON: OnceLock<bool> = OnceLock::new();
112        *ON.get_or_init(|| std::env::var("SUI_LIVE_CENSUS").as_deref() == Ok("1"))
113    }
114
115    #[inline(always)]
116    pub fn made(made: &AtomicI64, live: &AtomicI64) {
117        if enabled() {
118            made.fetch_add(1, Relaxed);
119            live.fetch_add(1, Relaxed);
120        }
121    }
122
123    #[inline(always)]
124    pub fn dropped(live: &AtomicI64) {
125        if enabled() {
126            live.fetch_sub(1, Relaxed);
127        }
128    }
129
130    #[inline(always)]
131    pub fn evaluated() {
132        if enabled() {
133            THUNK_EVALUATED.fetch_add(1, Relaxed);
134        }
135    }
136
137    /// Resident set size of this process, in bytes (macOS + Linux).
138    pub fn rss_bytes() -> u64 {
139        #[cfg(target_os = "macos")]
140        unsafe {
141            let mut info: libc::mach_task_basic_info = std::mem::zeroed();
142            let mut count = (std::mem::size_of::<libc::mach_task_basic_info>()
143                / std::mem::size_of::<libc::natural_t>()) as libc::mach_msg_type_number_t;
144            let kr = libc::task_info(
145                libc::mach_task_self(),
146                libc::MACH_TASK_BASIC_INFO,
147                std::ptr::addr_of_mut!(info).cast(),
148                &mut count,
149            );
150            if kr == libc::KERN_SUCCESS {
151                return info.resident_size;
152            }
153            0
154        }
155        #[cfg(not(target_os = "macos"))]
156        {
157            std::fs::read_to_string("/proc/self/statm")
158                .ok()
159                .and_then(|s| s.split_whitespace().nth(1).map(String::from))
160                .and_then(|pages| pages.parse::<u64>().ok())
161                .map(|pages| pages * 4096)
162                .unwrap_or(0)
163        }
164    }
165
166    /// Print all live/made counts + RSS to stderr, tagged.
167    ///
168    /// No-op unless `SUI_LIVE_CENSUS=1`. The counters only accumulate when the
169    /// census is enabled, so dumping while disabled emits an all-zeros
170    /// `[census exit] …` line to stderr — pure noise that pollutes any tool
171    /// parsing sui's stderr. Concretely it regressed the `derivation show→add`
172    /// ATerm round-trip parity row: that probe collects every non-`#` stderr
173    /// line from `derivation add` as the round-tripped ATerm, and the
174    /// exit-guard's unconditional dump appended the census line to it. Gating
175    /// here makes census-pollution-when-disabled unrepresentable at EVERY call
176    /// site (the process-exit guard AND the periodic poller), not just the one
177    /// that regressed.
178    pub fn dump(tag: &str) {
179        if !enabled() {
180            return;
181        }
182        let rss = rss_bytes();
183        eprintln!(
184            "[census {tag}] rss={rss_mb:.1}MB \
185attrs_live={al} attrs_made={am} \
186thunk_live={tl} thunk_made={tm} thunk_eval={te} \
187env_live={el} env_made={em} \
188nixstr_live={sl} nixstr_made={sm} \
189list_live={ll} list_made={lm} \
190scope_narrowed={sn} scope_pinned={sp}",
191            rss_mb = rss as f64 / (1024.0 * 1024.0),
192            al = ATTRS_LIVE.load(Relaxed),
193            am = ATTRS_MADE.load(Relaxed),
194            tl = THUNK_LIVE.load(Relaxed),
195            tm = THUNK_MADE.load(Relaxed),
196            te = THUNK_EVALUATED.load(Relaxed),
197            el = ENV_LIVE.load(Relaxed),
198            em = ENV_MADE.load(Relaxed),
199            sl = NIXSTR_LIVE.load(Relaxed),
200            sm = NIXSTR_MADE.load(Relaxed),
201            ll = LIST_LIVE.load(Relaxed),
202            lm = LIST_MADE.load(Relaxed),
203            sn = SCOPE_THUNKS_NARROWED.load(Relaxed),
204            sp = SCOPE_THUNKS_PINNED.load(Relaxed),
205        );
206        let (src_files, src_bytes) = crate::pos::source_text_census();
207        eprintln!(
208            "[census {tag}] src_files={src_files} src_bytes={src_mb:.1}MB",
209            src_mb = src_bytes as f64 / (1024.0 * 1024.0),
210        );
211    }
212
213    /// Spawn the periodic-dump thread (only when enabled). Dumps every 2s so a
214    /// 30s+ eval captures the high-water region. Also usable as an at-exit
215    /// hook via the returned guard.
216    pub fn spawn_poller() {
217        if !enabled() {
218            return;
219        }
220        std::thread::spawn(|| loop {
221            std::thread::sleep(std::time::Duration::from_millis(2000));
222            dump("periodic");
223        });
224    }
225}
226
227// -- String interner (shared with sui-bytecode via sui-intern's thread-local) --
228//
229// Previously this module owned its own `thread_local! INTERNER`. That
230// diverged from `sui-bytecode`'s `sui_intern::*` thread-local — Symbols
231// were NOT portable across the tree-walker ↔ VM fallback boundary,
232// which only worked because both paths happened to re-intern strings
233// from the same source text. Delegating both to the same thread-local
234// closes the gap and makes `sui_intern::prewarm()` affect this crate
235// too.
236
237/// Intern a string key, returning a Symbol handle.
238/// Used for NixAttrs keys and Env binding names.
239pub fn intern(s: &str) -> Symbol {
240    sui_intern::intern(s)
241}
242
243/// Resolve a Symbol back to its string content. Allocates a fresh
244/// `String`. For hot paths prefer [`resolve_rc`] or [`with_resolved`]
245/// — `Rc::clone` is ~20x cheaper than `String::from` for identifier-
246/// sized inputs.
247pub fn resolve(sym: Symbol) -> String {
248    sui_intern::resolve(sym)
249}
250
251/// Resolve a Symbol to a shared `Rc<str>`. Zero-copy.
252pub fn resolve_rc(sym: Symbol) -> std::rc::Rc<str> {
253    sui_intern::resolve_rc(sym)
254}
255
256/// Borrow the resolved string inside a closure without allocating.
257pub fn with_resolved<F, R>(sym: Symbol, f: F) -> R
258where
259    F: FnOnce(&str) -> R,
260{
261    sui_intern::with_resolved(sym, f)
262}
263
264// -- Identifier symbol cache --
265//
266// Caches the interned Symbol for each AST identifier by (source_id, text_offset).
267// Avoids re-hashing identifier strings on repeated evaluations of the
268// same expression (common in loops, recursion, overlay fixpoints).
269//
270// The source_id discriminates different parse trees (main file vs imports)
271// so that identifiers at the same byte offset in different files don't
272// collide in the cache.
273
274thread_local! {
275    /// Monotonically increasing counter — bumped on each `rnix::Root::parse`.
276    // STARTS AT 1, NOT 0 — 0 is the reserved "untagged env" sentinel.
277    //
278    // `Env::new()` defaults `source_id: 0`. While the generator also started at
279    // 0, the FIRST file parsed shared key-space with every untagged env, so an
280    // identifier in that file could collide with one from an untagged context at
281    // the same byte offset. That is the same aliasing class as the
282    // CURRENT_SOURCE_ID bug fixed alongside this (see eval.rs's Ident arms) —
283    // reserving 0 costs nothing and removes the overlap by construction.
284    static SOURCE_GEN: Cell<u32> = const { Cell::new(1) };
285
286    /// Maps `(source_id, text_offset)` → interned `Symbol`.
287    static IDENT_CACHE: RefCell<rustc_hash::FxHashMap<u64, Symbol>> =
288        RefCell::new(rustc_hash::FxHashMap::default());
289}
290
291/// Allocate a new source ID for a freshly parsed AST tree.
292///
293/// Call once per `rnix::Root::parse` invocation. The returned ID is
294/// used as the high 32 bits of the `IDENT_CACHE` key, ensuring that
295/// identifiers from different source texts never collide.
296pub fn next_source_id() -> u32 {
297    SOURCE_GEN.with(|g| {
298        let id = g.get();
299        g.set(id.wrapping_add(1));
300        id
301    })
302}
303
304/// Intern a string with caching by source ID and AST text offset.
305///
306/// First call for a given `(source_id, text_offset)`: hash + intern
307/// (same cost as [`intern`]).
308/// Subsequent calls: `FxHashMap` u64 lookup (~5 ns) — no string hashing.
309pub fn intern_cached(name: &str, source_id: u32, text_offset: u32) -> Symbol {
310    intern_cached_with(source_id, text_offset, || intern(name))
311}
312
313/// Cache an interned `Symbol` by `(source_id, text_offset)`, computing it
314/// lazily via `cold` only on a cache miss.
315///
316/// Steady-state hit: `FxHashMap` u64 lookup — no string materialization, no
317/// string hashing. This lets the identifier-eval hot path avoid the
318/// per-lookup `ident_text().to_string()` heap allocation entirely, since the
319/// `&str` is only needed to intern on the (once-per-offset) cold miss.
320pub fn intern_cached_with<F>(source_id: u32, text_offset: u32, cold: F) -> Symbol
321where
322    F: FnOnce() -> Symbol,
323{
324    let key = (u64::from(source_id) << 32) | u64::from(text_offset);
325    IDENT_CACHE.with(|c| {
326        let mut cache = c.borrow_mut();
327        *cache.entry(key).or_insert_with(cold)
328    })
329}
330
331/// Clear the identifier symbol cache.
332///
333/// Call between independent top-level evaluations to reclaim memory.
334/// The cache grows unboundedly during a single evaluation pass.
335pub fn clear_ident_cache() {
336    IDENT_CACHE.with(|c| c.borrow_mut().clear());
337}
338
339// ── Nix string context ─────────────────────────────────────────
340
341/// An element of a Nix string's context set.
342#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
343pub enum ContextElement {
344    /// Store path reference (e.g., "/nix/store/abc-hello").
345    Plain(SmolStr),
346    /// Derivation output reference.
347    Output { drv: SmolStr, output: SmolStr },
348    /// Entire derivation closure.
349    DrvDeep(SmolStr),
350}
351
352impl fmt::Display for ContextElement {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        match self {
355            ContextElement::Plain(p) => write!(f, "{p}"),
356            ContextElement::Output { drv, output } => write!(f, "{drv}!{output}"),
357            ContextElement::DrvDeep(d) => write!(f, "={d}"),
358        }
359    }
360}
361
362/// The context attached to a Nix string: a set of store-path references that
363/// the string depends on. Plain string literals have an empty context.
364///
365/// Uses a `Vec` with linear deduplication instead of `BTreeSet`.  Most strings
366/// have 0-2 context elements where linear search is faster than tree overhead,
367/// and `Vec` has the same size as `BTreeSet` (3 words) without per-node heap
368/// allocations for small sets.
369#[derive(Debug, Clone, PartialEq, Eq, Default)]
370pub struct StringContext(SmallVec<[ContextElement; 2]>);
371
372impl StringContext {
373    /// Create an empty context.
374    pub fn new() -> Self {
375        Self(SmallVec::new())
376    }
377
378    /// Merge another context into this one.
379    pub fn merge(&mut self, other: &StringContext) {
380        for elem in &other.0 {
381            if !self.0.contains(elem) {
382                self.0.push(elem.clone());
383            }
384        }
385    }
386
387    /// Add a plain store-path reference.
388    pub fn add_plain(&mut self, path: impl Into<SmolStr>) {
389        let elem = ContextElement::Plain(path.into());
390        if !self.0.contains(&elem) {
391            self.0.push(elem);
392        }
393    }
394
395    /// Add a derivation output reference.
396    pub fn add_output(&mut self, drv: impl Into<SmolStr>, output: impl Into<SmolStr>) {
397        let elem = ContextElement::Output { drv: drv.into(), output: output.into() };
398        if !self.0.contains(&elem) {
399            self.0.push(elem);
400        }
401    }
402
403    /// Add a derivation-deep reference.
404    pub fn add_drv_deep(&mut self, drv: impl Into<SmolStr>) {
405        let elem = ContextElement::DrvDeep(drv.into());
406        if !self.0.contains(&elem) {
407            self.0.push(elem);
408        }
409    }
410
411    /// Whether this context set is empty.
412    #[must_use]
413    pub fn is_empty(&self) -> bool {
414        self.0.is_empty()
415    }
416
417    /// Return the number of context elements.
418    #[must_use]
419    pub fn len(&self) -> usize {
420        self.0.len()
421    }
422
423    /// Iterate over all context elements.
424    pub fn iter(&self) -> impl Iterator<Item = &ContextElement> {
425        self.0.iter()
426    }
427
428    /// Insert a raw context element (deduplicating).
429    pub fn insert(&mut self, elem: ContextElement) {
430        if !self.0.contains(&elem) {
431            self.0.push(elem);
432        }
433    }
434
435    /// Return the elements as a slice.
436    pub fn elements(&self) -> &[ContextElement] {
437        &self.0
438    }
439}
440
441/// A Nix string value with associated context (store-path references).
442#[derive(Debug, PartialEq, Eq)]
443pub struct NixString {
444    /// The character data.
445    pub chars: SmolStr,
446    /// The context set (empty for plain string literals).
447    pub context: StringContext,
448}
449
450// `Clone` is hand-written so the census counts every NixString that comes
451// into existence (a clone is a fresh heap object once Rc-wrapped), keeping
452// `NIXSTR_MADE`/`NIXSTR_LIVE` consistent with the `Drop` below.
453impl Clone for NixString {
454    fn clone(&self) -> Self {
455        census::made(&census::NIXSTR_MADE, &census::NIXSTR_LIVE);
456        Self {
457            chars: self.chars.clone(),
458            context: self.context.clone(),
459        }
460    }
461}
462
463impl Drop for NixString {
464    fn drop(&mut self) {
465        census::dropped(&census::NIXSTR_LIVE);
466    }
467}
468
469impl NixString {
470    /// Create a context-free string.
471    pub fn plain(s: impl Into<SmolStr>) -> Self {
472        census::made(&census::NIXSTR_MADE, &census::NIXSTR_LIVE);
473        Self {
474            chars: s.into(),
475            context: StringContext::default(),
476        }
477    }
478
479    /// Create a string with an explicit context.
480    pub fn with_context(s: impl Into<SmolStr>, ctx: StringContext) -> Self {
481        census::made(&census::NIXSTR_MADE, &census::NIXSTR_LIVE);
482        Self {
483            chars: s.into(),
484            context: ctx,
485        }
486    }
487
488    /// Borrow the string content.
489    #[must_use]
490    pub fn as_str(&self) -> &str {
491        &self.chars
492    }
493
494    /// Whether this string carries any context (store path references).
495    #[must_use]
496    pub fn has_context(&self) -> bool {
497        !self.context.is_empty()
498    }
499}
500
501impl AsRef<str> for NixString {
502    fn as_ref(&self) -> &str {
503        &self.chars
504    }
505}
506
507/// Census wrapper around a list's backing `Vec<Value>`.
508///
509/// `#[repr(transparent)]` + `Deref`/`DerefMut` to `Vec<Value>` so nearly every
510/// existing call site (`.len()`, `.iter()`, indexing, `.as_slice()`, `.clone()`
511/// → produces a `NixList`) works unchanged. Its sole job is to carry the census
512/// hooks (`LIST_MADE`/`LIST_LIVE`) on the inner heap allocation.
513#[repr(transparent)]
514#[derive(Debug, PartialEq)]
515pub struct NixList(pub Vec<Value>);
516
517impl NixList {
518    #[inline]
519    pub fn new(v: Vec<Value>) -> Self {
520        census::made(&census::LIST_MADE, &census::LIST_LIVE);
521        NixList(v)
522    }
523
524    /// Consume into the backing `Vec<Value>`. `mem::take` because `NixList`
525    /// has a `Drop` impl (can't move the field out); the emptied husk's Drop
526    /// still fires, decrementing LIVE — correct, the list is consumed.
527    #[inline]
528    pub fn into_vec(mut self) -> Vec<Value> {
529        std::mem::take(&mut self.0)
530    }
531}
532
533impl From<Vec<Value>> for NixList {
534    #[inline]
535    fn from(v: Vec<Value>) -> Self {
536        NixList::new(v)
537    }
538}
539
540// Slice/array comparison so `assert_eq!(nixlist, [..])` in tests keeps working.
541impl<T: AsRef<[Value]>> PartialEq<T> for NixList {
542    #[inline]
543    fn eq(&self, other: &T) -> bool {
544        self.0.as_slice() == other.as_ref()
545    }
546}
547
548impl Clone for NixList {
549    fn clone(&self) -> Self {
550        census::made(&census::LIST_MADE, &census::LIST_LIVE);
551        NixList(self.0.clone())
552    }
553}
554
555impl Drop for NixList {
556    fn drop(&mut self) {
557        census::dropped(&census::LIST_LIVE);
558    }
559}
560
561impl FromIterator<Value> for NixList {
562    #[inline]
563    fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
564        NixList::new(iter.into_iter().collect())
565    }
566}
567
568impl std::ops::Deref for NixList {
569    type Target = Vec<Value>;
570    #[inline]
571    fn deref(&self) -> &Vec<Value> {
572        &self.0
573    }
574}
575
576impl std::ops::DerefMut for NixList {
577    #[inline]
578    fn deref_mut(&mut self) -> &mut Vec<Value> {
579        &mut self.0
580    }
581}
582
583impl<'a> IntoIterator for &'a NixList {
584    type Item = &'a Value;
585    type IntoIter = std::slice::Iter<'a, Value>;
586    #[inline]
587    fn into_iter(self) -> Self::IntoIter {
588        self.0.iter()
589    }
590}
591
592impl IntoIterator for NixList {
593    type Item = Value;
594    type IntoIter = std::vec::IntoIter<Value>;
595    #[inline]
596    fn into_iter(mut self) -> Self::IntoIter {
597        // Move the Vec out. `NixList`'s Drop still fires on the emptied husk,
598        // decrementing LIVE — correct, since the elements move to the iterator
599        // and the list allocation is consumed.
600        std::mem::take(&mut self.0).into_iter()
601    }
602}
603
604impl std::ops::Deref for NixString {
605    type Target = str;
606
607    fn deref(&self) -> &str {
608        &self.chars
609    }
610}
611
612impl fmt::Display for NixString {
613    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614        write!(f, "{}", self.chars)
615    }
616}
617
618// ── Value enum ────────────────────────────────────────────────
619
620/// A Nix value — potentially lazy (may be a Thunk).
621///
622/// To get a guaranteed-concrete value, call `.demand()` which returns
623/// `Concrete`. The `Concrete` type has thunk-free accessors that the
624/// compiler enforces — you cannot accidentally skip forcing.
625#[derive(Debug, Clone)]
626#[derive(Default)]
627pub enum Value {
628    #[default]
629    Null,
630    Bool(bool),
631    Int(i64),
632    Float(f64),
633    String(Rc<NixString>),
634    Path(Box<SmolStr>),
635    List(Rc<NixList>),
636    Attrs(Rc<NixAttrs>),
637    Lambda(Rc<Closure>),
638    Builtin(Box<BuiltinFn>),
639    /// A lazy value (thunk) with memoization and blackhole detection.
640    Thunk(Thunk),
641}
642
643// ── Concrete: construction-guaranteed non-thunk ──────────────
644
645/// A demanded Nix value. Guaranteed NOT a Thunk at the TYPE level.
646///
647/// Unlike `Value` (which has a `Thunk` variant), `Concrete` is a separate
648/// enum that DOES NOT HAVE a Thunk variant. The compiler rejects any attempt
649/// to construct a `Concrete` from a thunk — the variant simply doesn't exist.
650///
651/// The ONLY way to obtain a `Concrete` is through `Value::demand()`.
652///
653/// ```rust,ignore
654/// let val: Value = eval_expr(expr, env)?;  // might be Thunk
655/// let c: Concrete = val.demand()?;          // NOW guaranteed concrete
656/// let n: i64 = c.as_int()?;                // type-safe, thunk-free
657/// ```
658#[derive(Debug, Clone)]
659pub enum Concrete {
660    Null,
661    Bool(bool),
662    Int(i64),
663    Float(f64),
664    String(Rc<NixString>),
665    Path(Box<SmolStr>),
666    List(Rc<NixList>),      // elements may be lazy (correct for Nix)
667    Attrs(Rc<NixAttrs>),       // values may be lazy (correct for Nix)
668    Lambda(Rc<Closure>),
669    Builtin(Box<BuiltinFn>),
670    // NO Thunk variant. The compiler enforces this.
671}
672
673impl Concrete {
674    /// Convert back to a Value (for APIs that still take Value).
675    #[inline]
676    pub fn into_value(self) -> Value {
677        match self {
678            Concrete::Null => Value::Null,
679            Concrete::Bool(b) => Value::Bool(b),
680            Concrete::Int(n) => Value::Int(n),
681            Concrete::Float(f) => Value::Float(f),
682            Concrete::String(s) => Value::String(s),
683            Concrete::Path(p) => Value::Path(p),
684            Concrete::List(l) => Value::List(l),
685            Concrete::Attrs(a) => Value::Attrs(a),
686            Concrete::Lambda(c) => Value::Lambda(c),
687            Concrete::Builtin(b) => Value::Builtin(b),
688        }
689    }
690
691    /// Borrow as a Value reference. Constructs a temporary Value.
692    /// Prefer specific accessors (as_bool, as_int, etc.) when possible.
693    pub fn to_value(&self) -> Value {
694        self.clone().into_value()
695    }
696
697    /// Extract bool — guaranteed no thunk.
698    pub fn as_bool(&self) -> Result<bool, EvalError> {
699        match self {
700            Concrete::Bool(b) => Ok(*b),
701            other => Err(EvalError::TypeMismatch { expected: "bool", got: other.type_name() }),
702        }
703    }
704
705    /// Extract int — guaranteed no thunk.
706    pub fn as_int(&self) -> Result<i64, EvalError> {
707        match self {
708            Concrete::Int(n) => Ok(*n),
709            other => Err(EvalError::TypeMismatch { expected: "int", got: other.type_name() }),
710        }
711    }
712
713    /// Extract string ref — guaranteed no thunk.
714    pub fn as_str(&self) -> Result<&str, EvalError> {
715        match self {
716            Concrete::String(s) => Ok(&s.chars),
717            other => Err(EvalError::TypeMismatch { expected: "string", got: other.type_name() }),
718        }
719    }
720
721    /// Extract NixString ref — guaranteed no thunk.
722    pub fn as_nix_string(&self) -> Result<&NixString, EvalError> {
723        match self {
724            Concrete::String(s) => Ok(s),
725            other => Err(EvalError::TypeMismatch { expected: "string", got: other.type_name() }),
726        }
727    }
728
729    /// Extract list ref — guaranteed no thunk at this level.
730    /// Note: list ELEMENTS may still be lazy (Value, not Concrete).
731    pub fn as_list(&self) -> Result<&[Value], EvalError> {
732        match self {
733            Concrete::List(l) => Ok(l.as_slice()),
734            other => Err(EvalError::TypeMismatch { expected: "list", got: other.type_name() }),
735        }
736    }
737
738    /// Extract attrs ref — guaranteed no thunk at this level.
739    /// Note: attr VALUES may still be lazy (Value, not Concrete).
740    pub fn as_attrs(&self) -> Result<&NixAttrs, EvalError> {
741        match self {
742            Concrete::Attrs(a) => Ok(a),
743            other => Err(EvalError::TypeMismatch { expected: "set", got: other.type_name() }),
744        }
745    }
746
747    /// Extract float — guaranteed no thunk.
748    pub fn as_float(&self) -> Result<f64, EvalError> {
749        match self {
750            Concrete::Float(f) => Ok(*f),
751            Concrete::Int(n) => Ok(*n as f64),
752            other => Err(EvalError::TypeMismatch { expected: "float", got: other.type_name() }),
753        }
754    }
755
756    /// Check the value type name.
757    pub fn type_name(&self) -> &'static str {
758        match self {
759            Concrete::Null => "null",
760            Concrete::Bool(_) => "bool",
761            Concrete::Int(_) => "int",
762            Concrete::Float(_) => "float",
763            Concrete::String(_) => "string",
764            Concrete::Path(_) => "path",
765            Concrete::List(_) => "list",
766            Concrete::Attrs(_) => "set",
767            Concrete::Lambda(_) | Concrete::Builtin(_) => "lambda",
768        }
769    }
770
771    /// Alias for `as_str()` — API parity with Value::as_string().
772    pub fn as_string(&self) -> Result<&str, EvalError> {
773        self.as_str()
774    }
775
776    /// Extract owned NixAttrs — guaranteed no thunk at this level.
777    pub fn to_attrs(&self) -> Result<NixAttrs, EvalError> {
778        match self {
779            Concrete::Attrs(a) => Ok((**a).clone()),
780            other => Err(EvalError::TypeMismatch { expected: "set", got: other.type_name() }),
781        }
782    }
783
784    /// Extract owned list — guaranteed no thunk at this level.
785    pub fn to_list(&self) -> Result<Vec<Value>, EvalError> {
786        match self {
787            Concrete::List(l) => Ok((**l).0.clone()),
788            other => Err(EvalError::TypeMismatch { expected: "list", got: other.type_name() }),
789        }
790    }
791
792    /// Extract a filesystem path from Path or String.
793    pub fn coerce_to_path(&self, context: &str) -> Result<String, EvalError> {
794        match self {
795            Concrete::Path(p) => Ok(p.to_string()),
796            Concrete::String(ns) => Ok(ns.chars.to_string()),
797            Concrete::Attrs(attrs) => {
798                if let Some(out_path) = attrs.get("outPath") {
799                    let forced = crate::eval::force_value(out_path)?;
800                    forced.coerce_to_path(context)
801                } else {
802                    Err(EvalError::type_error(format!(
803                        "{context}: expected path or string, got set without outPath"
804                    )))
805                }
806            }
807            other => Err(EvalError::type_error(format!(
808                "{context}: expected path or string, got {}", other.type_name()
809            ))),
810        }
811    }
812
813    /// Extract owned string.
814    pub fn to_str(&self) -> Result<String, EvalError> {
815        match self {
816            Concrete::String(s) => Ok(s.chars.to_string()),
817            other => Err(EvalError::TypeMismatch { expected: "string", got: other.type_name() }),
818        }
819    }
820
821    /// Extract owned NixString (with context).
822    pub fn to_nix_string(&self) -> Result<NixString, EvalError> {
823        match self {
824            Concrete::String(s) => Ok((**s).clone()),
825            other => Err(EvalError::TypeMismatch { expected: "string", got: other.type_name() }),
826        }
827    }
828
829    /// Check if value is a function (lambda or builtin).
830    pub fn is_function(&self) -> bool {
831        matches!(self, Concrete::Lambda(_) | Concrete::Builtin(_))
832    }
833}
834
835// Type-safe conversion: Concrete → Value (infallible)
836impl From<Concrete> for Value {
837    fn from(c: Concrete) -> Value {
838        c.into_value()
839    }
840}
841
842impl PartialEq for Concrete {
843    fn eq(&self, other: &Self) -> bool {
844        match (self, other) {
845            (Concrete::Null, Concrete::Null) => true,
846            (Concrete::Bool(a), Concrete::Bool(b)) => a == b,
847            (Concrete::Int(a), Concrete::Int(b)) => a == b,
848            (Concrete::Float(a), Concrete::Float(b)) => a == b,
849            (Concrete::Int(a), Concrete::Float(b)) | (Concrete::Float(b), Concrete::Int(a)) => (*a as f64) == *b,
850            (Concrete::String(a), Concrete::String(b)) => Rc::ptr_eq(a, b) || a.chars == b.chars,
851            (Concrete::Path(a), Concrete::Path(b)) => a == b,
852            (Concrete::List(a), Concrete::List(b)) => Rc::ptr_eq(a, b) || a == b,
853            (Concrete::Attrs(a), Concrete::Attrs(b)) => {
854                if Rc::ptr_eq(a, b) {
855                    return true;
856                }
857                // cppnix `EvalState::eqValues` derivation short-circuit:
858                // two attrsets that are BOTH derivations (each has
859                // `type == "derivation"`) AND each carry an `outPath`
860                // compare by their `outPath` string ONLY — never by deep
861                // structural equality.  This is load-bearing: derivations
862                // hold thunks/functions (`meta`, `override`, …) that never
863                // compare structurally-equal even when the two describe the
864                // same store output, and forcing every attr can throw.
865                // (Empirically characterized against the live nix oracle:
866                //  `hello == (hello // { x = 5; })` ⇒ true.)
867                if let (Some(pa), Some(pb)) =
868                    (derivation_out_path(a), derivation_out_path(b))
869                {
870                    return pa == pb;
871                }
872                // Structural compare by BORROW, not by clone. The prior
873                // `a.inner() == b.inner()` flattened AND cloned *both* backing
874                // `AttrsMap`s (`inner()` = `as_flat().clone()`) purely to feed
875                // `HashMap::eq` — the clone is dead work. `as_flat()` returns a
876                // borrow into the (memoized-if-overlay) map, so
877                // `a.as_flat() == b.as_flat()` runs the *identical*
878                // `HashMap::eq`: same keys, same per-value `Value::eq` calls.
879                // `HashMap::eq` is ORDER-INDEPENDENT by construction (it iterates
880                // one map and looks each key up in the other), so this holds
881                // regardless of the map's internal iteration order — true for the
882                // std `AttrsMap` exactly as it was for the old `im_rc` map.
883                // PROVABLY-NEUTRAL
884                // on the demand axis: cloning a `Value` is an `Rc`-bump that
885                // forces NOTHING; the only `.demand()` calls in this arm are (1)
886                // the derivation short-circuit above (unchanged) and (2) inside
887                // `Value::eq` (unchanged — same values, same order). Removing the
888                // clone cannot move which thunk forces, when, or whether a throw
889                // surfaces. See docs/PERF-ARSENAL.md C-A.
890                let (fa, fb) = (a.as_flat(), b.as_flat());
891                if crate::perf::enabled() {
892                    crate::perf::inc(crate::perf::Counter::AttrsEqStructuralCalls);
893                    // Combined entry count of the two maps the old `inner()`
894                    // path would have cloned before comparing.
895                    crate::perf::add(
896                        crate::perf::Counter::AttrsEqEntriesCloneElided,
897                        (fa.len() + fb.len()) as u64,
898                    );
899                }
900                fa == fb
901            }
902            (Concrete::Lambda(a), Concrete::Lambda(b)) => Rc::ptr_eq(a, b),
903            _ => false,
904        }
905    }
906}
907
908/// Concatenate two Nix lists: `left ++ right_elems`.
909///
910/// `left` must be a `Value::List`; `right_elems` is the right list's element
911/// slice. When `left`'s backing `Rc<Vec>` is uniquely owned (a fresh
912/// temporary, as in a left-associative `acc ++ [x]` fold), the right elements
913/// are appended IN PLACE — amortized O(1) instead of the O(n) full clone that
914/// `left.to_vec()` would cost. When the `Rc` is shared, the shared list is
915/// left untouched and a fresh clone-extended Vec is built (identical to the
916/// prior `to_vec()` + `extend_from_slice` path).
917///
918/// # Byte-neutrality
919/// PROVABLY-NEUTRAL. Both paths produce the identical ordered sequence of the
920/// same `Rc`-shared lazy `Value` thunks — no element is forced, reordered, or
921/// re-identified. The only observable difference is heap allocation reuse,
922/// which is not a Nix-observable property. See `docs/PERF-ARSENAL.md`.
923pub fn concat_lists(left: Value, right_elems: &[Value]) -> Result<Value, EvalError> {
924    // Take ownership of the left backing Vec, reusing its allocation when the
925    // Rc is unique. `Rc::try_unwrap` returns the inner Vec on refcount 1;
926    // otherwise it clones (identical bytes to the old `to_vec()`).
927    let mut la = match left {
928        Value::List(rc) => {
929            let reused = Rc::strong_count(&rc) == 1;
930            let vec: Vec<Value> = match Rc::try_unwrap(rc) {
931                Ok(v) => v.into_vec(), // uniquely owned: allocation reused
932                Err(rc) => (*rc).0.clone(), // shared: clone the left (unchanged)
933            };
934            if crate::perf::enabled() {
935                crate::perf::inc(crate::perf::Counter::ListConcatCalls);
936                if reused {
937                    // Left elements appended in place — copy elided.
938                    crate::perf::add(
939                        crate::perf::Counter::ListConcatElemsReused,
940                        vec.len() as u64,
941                    );
942                } else {
943                    // Left elements cloned into a fresh Vec (the storm).
944                    crate::perf::add(
945                        crate::perf::Counter::ListConcatElemsCopied,
946                        vec.len() as u64,
947                    );
948                }
949            }
950            vec
951        }
952        other => {
953            return Err(EvalError::TypeMismatch {
954                expected: "list",
955                got: other.type_name(),
956            });
957        }
958    };
959    // Right elements are always copied (appended); their thunks are Rc-shared.
960    la.extend_from_slice(right_elems);
961    Ok(Value::list(la))
962}
963
964/// If `attrs` is a derivation — an attrset whose `type` forces to the string
965/// `"derivation"` AND which carries a forceable `outPath` — return that
966/// `outPath` string.  Otherwise `None` (caller falls back to structural
967/// equality).  A force error on `type`/`outPath` yields `None`, so a broken
968/// derivation degrades to structural compare rather than a spurious match.
969fn derivation_out_path(attrs: &NixAttrs) -> Option<String> {
970    match attrs.get("type")?.demand().ok()? {
971        Concrete::String(s) if s.chars == "derivation" => {}
972        _ => return None,
973    }
974    match attrs.get("outPath")?.demand().ok()? {
975        Concrete::String(s) => Some(s.chars.to_string()),
976        _ => None,
977    }
978}
979
980/// If `attrs` is a **derivation** (`type` forces to `"derivation"`) carrying a
981/// forceable `drvPath` AND `outPath`, return `Ok(Some((drv_path, out_path)))`.
982///
983/// Returns `Ok(None)` when `attrs` is not a derivation (no `type ==
984/// "derivation"`, or missing `drvPath`) — e.g. a plain attrset that merely
985/// carries an `outPath` (a `{ outPath = "…"; }` path-like), which has nothing
986/// to realize. Returns `Err` only if forcing `drvPath`/`outPath` itself fails
987/// (a genuinely broken derivation), so the caller surfaces the eval error
988/// rather than silently treating a broken drv as "not a derivation".
989///
990/// This is the import-from-derivation sibling of [`derivation_out_path`]: that
991/// helper only needs `outPath` for equality; realize also needs `drvPath` to
992/// know *what* to build.
993fn derivation_drv_and_out(
994    attrs: &NixAttrs,
995) -> Result<Option<(String, String)>, EvalError> {
996    // Not a derivation unless `type` forces to exactly "derivation".
997    match attrs.get("type") {
998        Some(t) => match crate::eval::force_value(t)? {
999            Value::String(s) if s.chars == "derivation" => {}
1000            _ => return Ok(None),
1001        },
1002        None => return Ok(None),
1003    }
1004    // A derivation without a drvPath cannot be realized — treat as non-drv so
1005    // the caller falls back to plain coercion (the outPath arm).
1006    let drv_path = match attrs.get("drvPath") {
1007        Some(d) => crate::eval::force_value(d)?.coerce_to_path("drvPath")?,
1008        None => return Ok(None),
1009    };
1010    let out_path = match attrs.get("outPath") {
1011        Some(o) => crate::eval::force_value(o)?.coerce_to_path("outPath")?,
1012        None => return Ok(None),
1013    };
1014    Ok(Some((drv_path, out_path)))
1015}
1016
1017/// Given a store-path STRING (produced by interpolating a derivation) and its
1018/// string context, return the producing `.drv` path IF this store path is a
1019/// derivation output that should be realized on a filesystem read.
1020///
1021/// Returns `Some(drv_path)` only when the context carries a
1022/// `ContextElement::Output { drv, output }` whose `output` store path matches
1023/// `out_path` — i.e. this string IS the output of a derivation named by the
1024/// context. `Plain`/`DrvDeep`-only contexts (a plain store-path reference, or a
1025/// `.drv` self-reference) don't name an output to realize, and an
1026/// empty-context string is a literal path with nothing to build.
1027///
1028/// This is how cppnix decides IFD across interpolation: the derivation-ness of
1029/// `"${drv}"` survives as string context, not as a value shape.
1030fn out_path_needs_realize(out_path: &str, ctx: &StringContext) -> Option<String> {
1031    // Only store-path strings can be derivation outputs.
1032    if !out_path.starts_with("/nix/store/") {
1033        return None;
1034    }
1035    for elem in ctx.iter() {
1036        if let ContextElement::Output { drv, output } = elem {
1037            // The context stores the OUTPUT NAME (e.g. "out"/"dev"), while the
1038            // string IS the output's store path. cppnix's `Output.outputName`
1039            // matches the string it decorates; sui's tree-walker builds the
1040            // interpolated string FROM this output's store path, so a single
1041            // `Output` element on a store-path string is the producing drv.
1042            let _ = output; // output name is not needed to build the closure
1043            return Some(drv.to_string());
1044        }
1045    }
1046    None
1047}
1048
1049impl Value {
1050    /// Convert a known-concrete Value to Concrete. Panics if Thunk.
1051    /// Only use when the caller guarantees the value is not a thunk.
1052    pub(crate) fn demand_unchecked(self) -> Concrete {
1053        match self {
1054            Value::Null => Concrete::Null,
1055            Value::Bool(b) => Concrete::Bool(b),
1056            Value::Int(n) => Concrete::Int(n),
1057            Value::Float(f) => Concrete::Float(f),
1058            Value::String(s) => Concrete::String(s),
1059            Value::Path(p) => Concrete::Path(p),
1060            Value::List(l) => Concrete::List(l),
1061            Value::Attrs(a) => Concrete::Attrs(a),
1062            Value::Lambda(c) => Concrete::Lambda(c),
1063            Value::Builtin(b) => Concrete::Builtin(b),
1064            Value::Thunk(_) => panic!("demand_unchecked called on Thunk"),
1065        }
1066    }
1067}
1068
1069impl Value {
1070    /// Demand a concrete value. Forces if Thunk, returns as-is if concrete.
1071    ///
1072    /// This is the TYPED forcing API. The returned `Concrete` is guaranteed
1073    /// non-Thunk — enforced by the Concrete enum having NO Thunk variant.
1074    pub fn demand(&self) -> Result<Concrete, EvalError> {
1075        let v = match self {
1076            Value::Thunk(_) => crate::eval::force_value(self)?,
1077            other => other.clone(),
1078        };
1079        // Convert Value → Concrete. Thunk is impossible after force_value.
1080        match v {
1081            Value::Null => Ok(Concrete::Null),
1082            Value::Bool(b) => Ok(Concrete::Bool(b)),
1083            Value::Int(n) => Ok(Concrete::Int(n)),
1084            Value::Float(f) => Ok(Concrete::Float(f)),
1085            Value::String(s) => Ok(Concrete::String(s)),
1086            Value::Path(p) => Ok(Concrete::Path(p)),
1087            Value::List(l) => Ok(Concrete::List(l)),
1088            Value::Attrs(a) => Ok(Concrete::Attrs(a)),
1089            Value::Lambda(c) => Ok(Concrete::Lambda(c)),
1090            Value::Builtin(b) => Ok(Concrete::Builtin(b)),
1091            Value::Thunk(_) => {
1092                // force_value returned a Thunk — chase it.
1093                // This can happen when the transitive unwrap loop hits
1094                // a depth limit. Re-force to resolve.
1095                let re_forced = crate::eval::force_value(&v)?;
1096                match re_forced {
1097                    Value::Null => Ok(Concrete::Null),
1098                    Value::Bool(b) => Ok(Concrete::Bool(b)),
1099                    Value::Int(n) => Ok(Concrete::Int(n)),
1100                    Value::Float(f) => Ok(Concrete::Float(f)),
1101                    Value::String(s) => Ok(Concrete::String(s)),
1102                    Value::Path(p) => Ok(Concrete::Path(p)),
1103                    Value::List(l) => Ok(Concrete::List(l)),
1104                    Value::Attrs(a) => Ok(Concrete::Attrs(a)),
1105                    Value::Lambda(c) => Ok(Concrete::Lambda(c)),
1106                    Value::Builtin(b) => Ok(Concrete::Builtin(b)),
1107                    Value::Thunk(_) => Err(EvalError::InfiniteRecursion(
1108                        "demand: thunk chain could not be resolved".to_string(),
1109                    )),
1110                }
1111            }
1112        }
1113    }
1114}
1115
1116#[cfg(target_pointer_width = "64")]
1117const _: () = assert!(std::mem::size_of::<Value>() <= 16);
1118
1119/// Runaway backstop for overlay-fixpoint promotion.  A genuine fixpoint
1120/// re-entry converges in a bounded number of nested promotions (the
1121/// nixpkgs `libxcrypt`/`self:super:` overlay needs ≤18 concurrent
1122/// promotions).  A non-converging demand (e.g. a cross-system stdenv
1123/// fixpoint that keeps re-entering the empty partial) climbs the nesting
1124/// without bound.  When the active concurrent-promotion nesting
1125/// (`IN_PROMISE_EVAL`) reaches this cap we STOP promoting and fall through
1126/// to `InfiniteRecursion` — which `eval_select`'s `x.y or default` arm
1127/// recovers exactly like nix's lazy fall-through, converting a would-be
1128/// native stack overflow into the recoverable error nix itself raises.
1129///
1130/// This is the runaway half of the same discipline the release-build
1131/// `MAX_EVAL_DEPTH` guard provides (which is `None` in release to
1132/// admit nixpkgs' legitimately-deep fixpoints); scoping the bound to
1133/// *promotions* keeps ordinary deep evaluation unbounded while still
1134/// catching a non-terminating fixpoint before the OS stack does.
1135const FIXPOINT_PROMOTE_NEST_CAP: u32 = 32;
1136
1137/// Force-stack-depth backstop that arms once a fixpoint promotion has fired
1138/// (`promotion_occurred()`).  A converging fixpoint (`libxcrypt`) bottoms
1139/// out at a force depth of a few dozen; a non-converging promoted partial
1140/// recurses without bound.  This cap (10× any observed real fixpoint's force
1141/// depth) converts a force-stack runaway into a recoverable
1142/// `InfiniteRecursion` before the native OS stack aborts, without touching
1143/// ordinary (non-promotion) deep evaluation.  Paired with the eval-depth
1144/// backstop (`eval::PROMOTION_RUNAWAY_EVAL_DEPTH`) for runaways that don't
1145/// climb the force stack.
1146const PROMOTION_RUNAWAY_FORCE_DEPTH: usize = 500;
1147
1148thread_local! {
1149    /// Depth counter for "currently evaluating the body of a Promise-state
1150    /// thunk".  Incremented before the body of a `ThunkRepr::Promise`
1151    /// runs, decremented after.  Used by `eval_select` to treat missing
1152    /// attribute lookups on the Promise's sentinel value as `null`
1153    /// instead of erroring with `AttrNotFound`.  Scoped to Promise
1154    /// evaluation so unrelated user code retains cppnix-strict semantics.
1155    pub(crate) static IN_PROMISE_EVAL: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1156
1157    /// Set once a fixpoint promotion has occurred anywhere in the current
1158    /// top-level evaluation.  Arms the release-active force-depth runaway
1159    /// backstop for the REST of the eval (not just while `IN_PROMISE_EVAL`
1160    /// is non-zero) — a corrupted promoted partial can send a DOWNSTREAM
1161    /// fixpoint (`makeOverridable`/`commonAttrs`) into unbounded recursion
1162    /// AFTER the promoting force has already returned, so the backstop must
1163    /// outlive the promotion's own softening scope.
1164    pub(crate) static PROMOTION_OCCURRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1165}
1166
1167/// `true` if any overlay-fixpoint promotion has fired in this eval.
1168#[inline(always)]
1169pub fn promotion_occurred() -> bool {
1170    PROMOTION_OCCURRED.with(|c| c.get())
1171}
1172
1173/// `true` if the evaluator is currently inside the body of a
1174/// `ThunkRepr::Promise` (used by `eval_select` to relax
1175/// `AttrNotFound` errors during fix-point construction).
1176#[inline(always)]
1177pub fn in_promise_eval() -> bool {
1178    IN_PROMISE_EVAL.with(|c| c.get() > 0)
1179}
1180
1181/// Internal representation of a thunk's state machine.
1182///
1183/// Transitions: `Suspended` → `Blackhole` → `Evaluated` (on success),
1184/// or `Suspended` → `Blackhole` → `Suspended` (on failure, to allow retry).
1185pub enum ThunkRepr {
1186    /// Not yet evaluated. Holds the AST expression and captured environment.
1187    Suspended {
1188        expr: rnix::ast::Expr,
1189        env: Env,
1190    },
1191    /// Pending `inherit (source) name` selection. When forced,
1192    /// forces the shared `source_thunk` and pulls out `name`.
1193    ///
1194    /// The `source_thunk` is created once per `inherit (source) a b c`
1195    /// clause and shared (via `Rc` clone) across all inherited names.
1196    /// This means N names share one source evaluation instead of N
1197    /// independent evaluations — the source thunk's own memoization
1198    /// ensures it is evaluated at most once.
1199    ///
1200    /// This is its own variant (rather than synthesizing a Select AST
1201    /// node) because rnix doesn't expose a public AST builder, and
1202    /// we want each inherited name to defer evaluation of the source
1203    /// expression so that `inherit (lib.trivial) ...` at the top of
1204    /// trivial.nix doesn't blackhole on the still-being-constructed
1205    /// `lib.trivial`.
1206    InheritSelect {
1207        source_thunk: Thunk,
1208        name: SmolStr,
1209    },
1210    /// A lazy value backed by a Rust closure.  Used for flake input
1211    /// evaluation: the closure calls `evaluate_flake` on first access
1212    /// instead of eagerly during flake setup, matching CppNix semantics
1213    /// where each input's outputs function is wrapped in a thunk.
1214    Native(Box<dyn FnOnce() -> Result<Value, EvalError>>),
1215    /// A deferred with-scope ident lookup.  Stores a direct reference to the
1216    /// with-scope's shared cache and the ident name.  When forced, checks the
1217    /// cache for the resolved attrset and looks up the name — O(1) hash lookup,
1218    /// no Env traversal, no fixpoint re-forcing.
1219    ///
1220    /// This is the construction-guarantee solution for the with-scope fixpoint
1221    /// problem: instead of creating 80K+ Env-capturing thunks (each doing a
1222    /// full lookup on force), we create 80K lightweight cache-referencing thunks
1223    /// that share the same resolved attrset.
1224    WithIdent {
1225        /// The ident name to look up
1226        name: SmolStr,
1227        /// Direct reference to the with-scope's cached attrset.
1228        /// Shared via Rc<RefCell> — all idents from the same `with` scope
1229        /// reference the same cache.  When ANY lookup forces the scope,
1230        /// the cache is populated and all subsequent WithIdent forces are O(1).
1231        scope_cache: Rc<RefCell<Option<NixAttrs>>>,
1232        /// The scope value (for initial force if cache is empty)
1233        scope_value: Value,
1234        /// Fallback: the full env for lexical+outer-scope lookup if the
1235        /// with-scope doesn't contain this name
1236        env: Env,
1237    },
1238    /// Currently being evaluated -- detects infinite recursion.
1239    Blackhole,
1240    /// Currently being evaluated, but the thunk is known to be
1241    /// self-recursive (its RHS references the bound name).  Inner
1242    /// re-entrance returns the partial value from the cell instead
1243    /// of erroring with `InfiniteRecursion` — matches cppnix's
1244    /// `let x = f x; in x` semantics where inner accesses to `x`
1245    /// see the not-yet-complete attrset under construction.
1246    ///
1247    /// The cell starts as `Value::Attrs(empty)` (the cheapest
1248    /// sentinel that propagates through `mapAttrs` / `attrNames` /
1249    /// `concatMap` without further type errors).  When the body
1250    /// completes, the cell is replaced with the final value and
1251    /// the repr transitions to `Evaluated`.
1252    Promise(Rc<RefCell<Value>>),
1253    /// A `Native` (`FnOnce`) thunk whose closure already ran and
1254    /// FAILED.  The closure is consumed and cannot be retried, so we
1255    /// memoize the error itself and re-raise it on every subsequent
1256    /// force.  This is the correctness-preserving replacement for the
1257    /// old `Evaluated(Null)` poisoning: a thunk that threw on its first
1258    /// force MUST NOT silently become `null` on a second read (which
1259    /// turned a swallowed transient flake-input error into a bogus
1260    /// `AttrNotFound`/`cannot select from set` far downstream — the
1261    /// stylix `darwinModules` marquee root).  A re-force re-throws the
1262    /// original error, exactly as cppnix re-throws a thunk that failed.
1263    Failed(EvalError),
1264    /// Already evaluated and memoized as a THUNK value.  The `cache`
1265    /// `OnceCell` is intentionally empty for this variant (caching a thunk
1266    /// would spin `force_value`), so the boxed `Value` is the sole store.
1267    Evaluated(Box<Value>),
1268    /// Already evaluated and memoized as a CONCRETE (non-thunk) value.
1269    /// The value lives ONLY in the `cache` `OnceCell` (`Box<Concrete>`);
1270    /// this variant is a valueless terminal marker that collapses the
1271    /// former double-store (a redundant `Evaluated(Box<Value>)` alongside
1272    /// the cache).  Any reader that finds this marker reconstructs the
1273    /// `Value` from `cache` via `Concrete::into_value()`, which is a
1274    /// byte-identical, lossless inverse of `demand_unchecked` (same enum
1275    /// shape, moves the inner `Rc`/`Box` — preserving string context and
1276    /// list/attrs `Rc` identity).  In practice the `cache` fast path in
1277    /// `force`/`force_inner` returns before this arm is ever matched.
1278    EvaluatedConcrete,
1279}
1280
1281/// Inner storage for a thunk: a fast-path `OnceCell` cache plus the
1282/// full `UnsafeCell` state machine.  Reads of already-evaluated thunks
1283/// hit the `OnceCell` and never touch the `UnsafeCell`, eliminating
1284/// all runtime overhead on the hot path (~150M+ cache hits per nixpkgs
1285/// eval).  The cold path (1.8M forces) uses `UnsafeCell` directly —
1286/// safe because the evaluator is single-threaded (`Rc`, not `Arc`) and
1287/// the state machine ensures no overlapping mutable access
1288/// (`Suspended` → `Blackhole` → `Evaluated` transitions are sequential).
1289struct ThunkInner {
1290    /// Fast-path cache for already-evaluated thunks.
1291    /// Set once when `Evaluated` is stored, never cleared.
1292    /// Reads bypass the `UnsafeCell` entirely.
1293    cache: OnceCell<Box<Concrete>>,
1294    /// Full state machine for the thunk lifecycle.
1295    repr: UnsafeCell<ThunkRepr>,
1296    /// `true` when the thunk's RHS references its own bound name
1297    /// (a fix-point pattern like `let x = f x; in x`).  On force,
1298    /// transitions to `ThunkRepr::Promise` instead of `Blackhole`
1299    /// so inner re-entrance sees the partial value rather than
1300    /// erroring.  Detected at thunk-construction time via AST
1301    /// text search.
1302    recursive: bool,
1303}
1304
1305impl Drop for ThunkInner {
1306    fn drop(&mut self) {
1307        census::dropped(&census::THUNK_LIVE);
1308    }
1309}
1310
1311/// A lazy value with memoization and blackhole detection.
1312#[derive(Clone)]
1313pub struct Thunk(pub(crate) Rc<ThunkInner>);
1314
1315impl Thunk {
1316    /// Create a thunk that will evaluate `expr` in `env` when forced.
1317    pub fn new_suspended(expr: rnix::ast::Expr, env: Env) -> Self {
1318        crate::trace::inc_thunks_created();
1319        census::made(&census::THUNK_MADE, &census::THUNK_LIVE);
1320        Self(Rc::new(ThunkInner {
1321            cache: OnceCell::new(),
1322            repr: UnsafeCell::new(ThunkRepr::Suspended { expr, env }),
1323            recursive: false,
1324        }))
1325    }
1326
1327    /// Like [`new_suspended`] but marks the thunk as self-recursive.
1328    /// On force, inner re-entrance returns the partial value from the
1329    /// promise cell instead of erroring with `InfiniteRecursion`,
1330    /// matching cppnix's `let x = f x; in x` semantics.  Use this for
1331    /// let-bindings whose RHS textually references the bound name
1332    /// (see `eval::is_self_recursive_binding`).
1333    pub fn new_suspended_recursive(expr: rnix::ast::Expr, env: Env) -> Self {
1334        crate::trace::inc_thunks_created();
1335        census::made(&census::THUNK_MADE, &census::THUNK_LIVE);
1336        crate::perf::inc(crate::perf::Counter::ThunkSiteLetForward);
1337        Self(Rc::new(ThunkInner {
1338            cache: OnceCell::new(),
1339            repr: UnsafeCell::new(ThunkRepr::Suspended { expr, env }),
1340            recursive: true,
1341        }))
1342    }
1343
1344    /// Create a thunk that, when forced, forces the shared
1345    /// `source_thunk` and pulls out the attribute named `name`.
1346    ///
1347    /// The caller creates ONE `Thunk::new_suspended(source_expr, env)`
1348    /// per `inherit (source)` clause and passes clones (Rc bump) to
1349    /// each inherited name.  This way the source is evaluated at most
1350    /// once regardless of how many names are inherited.
1351    pub fn new_inherit_select(source_thunk: Thunk, name: impl Into<SmolStr>) -> Self {
1352        crate::trace::inc_thunks_created();
1353        census::made(&census::THUNK_MADE, &census::THUNK_LIVE);
1354        crate::perf::inc(crate::perf::Counter::ThunkSiteInheritSrc);
1355        Self(Rc::new(ThunkInner {
1356            cache: OnceCell::new(),
1357            repr: UnsafeCell::new(ThunkRepr::InheritSelect {
1358                source_thunk,
1359                name: name.into(),
1360            }),
1361            recursive: false,
1362        }))
1363    }
1364
1365    /// Create a WithIdent thunk — a deferred with-scope ident lookup.
1366    /// Stores a direct reference to the shared with-scope cache.
1367    /// When forced: O(1) hash lookup in the cache, no Env traversal.
1368    pub fn new_with_ident(
1369        name: SmolStr,
1370        scope_cache: Rc<RefCell<Option<NixAttrs>>>,
1371        scope_value: Value,
1372        env: Env,
1373    ) -> Self {
1374        crate::trace::inc_thunks_created();
1375        census::made(&census::THUNK_MADE, &census::THUNK_LIVE);
1376        crate::perf::inc(crate::perf::Counter::ThunkSiteOther);
1377        Self(Rc::new(ThunkInner {
1378            cache: OnceCell::new(),
1379            repr: UnsafeCell::new(ThunkRepr::WithIdent {
1380                name,
1381                scope_cache,
1382                scope_value,
1383                env,
1384            }),
1385            recursive: false,
1386        }))
1387    }
1388
1389    /// Create a thunk backed by a Rust closure.  When forced, the
1390    /// closure is called exactly once and its result is memoized.
1391    /// This is used for lazy flake input evaluation.
1392    pub fn new_native(f: impl FnOnce() -> Result<Value, EvalError> + 'static) -> Self {
1393        crate::trace::inc_thunks_created();
1394        census::made(&census::THUNK_MADE, &census::THUNK_LIVE);
1395        crate::perf::inc(crate::perf::Counter::ThunkSiteNative);
1396        Self(Rc::new(ThunkInner {
1397            cache: OnceCell::new(),
1398            repr: UnsafeCell::new(ThunkRepr::Native(Box::new(f))),
1399            recursive: false,
1400        }))
1401    }
1402
1403    /// Create a thunk that is already evaluated (an optimization).
1404    /// Pre-populates the `OnceCell` cache so the fast path is
1405    /// immediately available.
1406    pub fn new_evaluated(value: Value) -> Self {
1407        crate::trace::inc_thunks_created();
1408        census::made(&census::THUNK_MADE, &census::THUNK_LIVE);
1409        crate::perf::inc(crate::perf::Counter::ThunkSiteEvaluated);
1410        let cache = OnceCell::new();
1411        // Collapse the double-store: a concrete value lives ONLY in the
1412        // cache with an `EvaluatedConcrete` marker repr; a thunk value
1413        // keeps the boxed `Evaluated` repr and an empty cache.
1414        let repr = if matches!(value, Value::Thunk(_)) {
1415            ThunkRepr::Evaluated(Box::new(value))
1416        } else {
1417            let _ = cache.set(Box::new(value.demand_unchecked()));
1418            ThunkRepr::EvaluatedConcrete
1419        };
1420        Self(Rc::new(ThunkInner {
1421            cache,
1422            repr: UnsafeCell::new(repr),
1423            recursive: false,
1424        }))
1425    }
1426
1427    /// Check whether this thunk has already been forced.
1428    /// Uses the `OnceCell` cache for a fast, borrow-free check.
1429    pub fn is_evaluated(&self) -> bool {
1430        self.0.cache.get().is_some()
1431    }
1432
1433    /// Check whether this thunk is a native (Rust closure) thunk.
1434    ///
1435    /// Native thunks are used for lazy flake input evaluation and can
1436    /// be very expensive to force (e.g., evaluating all of nixpkgs).
1437    /// This lets callers skip them in eager conversion paths.
1438    pub fn is_native(&self) -> bool {
1439        // SAFETY: Single-threaded evaluator (Rc, not Arc). Read-only access,
1440        // no mutable reference exists at this point.
1441        matches!(unsafe { &*self.0.repr.get() }, ThunkRepr::Native(_))
1442    }
1443
1444    /// Peek at the cached value WITHOUT forcing.
1445    /// Returns Some(&Value) if the thunk has been evaluated, None otherwise.
1446    /// This is used by with-scope lookup to check if the fixpoint thunk
1447    /// has already been resolved (by another evaluation path) without
1448    /// entering the force state machine.
1449    pub fn peek(&self) -> Option<&Concrete> {
1450        self.0.cache.get().map(|v| &**v)
1451    }
1452
1453    /// Replace the environment captured in a suspended thunk.
1454    /// For `InheritSelect`, delegates to the shared source thunk's
1455    /// `update_env` (which updates the source's captured env).
1456    /// No-op if the thunk is already evaluated or a blackhole.
1457    pub fn update_env(&self, new_env: &Env) {
1458        // SAFETY: Single-threaded evaluator. No other reference to repr
1459        // exists during env replacement.
1460        let repr = unsafe { &mut *self.0.repr.get() };
1461        match repr {
1462            ThunkRepr::Suspended { env, .. } => {
1463                *env = new_env.clone();
1464            }
1465            ThunkRepr::InheritSelect { source_thunk, .. } => {
1466                source_thunk.update_env(new_env);
1467            }
1468            _ => {}
1469        }
1470    }
1471
1472    /// Store a forced result into this thunk's terminal state, collapsing
1473    /// the former thunk double-store.
1474    ///
1475    /// - A CONCRETE (non-thunk) result is stored ONLY in the `cache`
1476    ///   `OnceCell` (`Box<Concrete>`), and `repr` becomes the valueless
1477    ///   `EvaluatedConcrete` marker — freeing the redundant
1478    ///   `Box<Value>` that `Evaluated` used to hold. Reconstruction via
1479    ///   `Concrete::into_value()` is a byte-identical inverse of the
1480    ///   `demand_unchecked()` used to fill the cache.
1481    /// - A THUNK result keeps `repr = Evaluated(Box<Value>)` and leaves
1482    ///   the cache empty (caching a thunk would spin `force_value`).
1483    ///
1484    /// SAFETY: single-threaded evaluator (`Rc`, not `Arc`); the caller
1485    /// must hold no other borrow of `repr` — every call site here is on
1486    /// the sequential `Suspended → Blackhole/Promise → Evaluated`
1487    /// transition, so no overlapping mutable access exists.
1488    ///
1489    /// Takes `&Value` and clones exactly as the former open-coded stores
1490    /// did (`Box::new(value.clone())` for the thunk repr,
1491    /// `Box::new(value.clone().demand_unchecked())` for the cache) — so the
1492    /// clone count is identical to the pre-collapse code and the change is
1493    /// byte-neutral by construction.
1494    #[inline]
1495    unsafe fn store_evaluated(&self, value: &Value) {
1496        census::evaluated();
1497        if matches!(value, Value::Thunk(_)) {
1498            *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Evaluated(Box::new(value.clone()));
1499        } else {
1500            let _ = self.0.cache.set(Box::new(value.clone().demand_unchecked()));
1501            *unsafe { &mut *self.0.repr.get() } = ThunkRepr::EvaluatedConcrete;
1502        }
1503    }
1504
1505    /// Owned-value variant of the concrete branch of [`store_evaluated`],
1506    /// for the `force_inner` early-return that OWNS `value` and does not
1507    /// need it afterward.
1508    ///
1509    /// `store_evaluated(&value)` clones the whole `Value` to fill the
1510    /// cache (`Box::new(value.clone().demand_unchecked())`) and the caller
1511    /// then returns the owned `value` separately — an extra *outer*
1512    /// `Value` clone. Here we MOVE `value` into the cache (no outer clone)
1513    /// and clone the cheaper inner `Concrete` for the return, trading one
1514    /// `Value::clone` for one `Concrete::clone` (the same inner `Rc` bumps,
1515    /// one fewer throwaway `Value` temporary).
1516    ///
1517    /// Content-, order-, and census-neutral versus the
1518    /// `store_evaluated(&value); return Ok(value)` it replaces: the cache
1519    /// holds the identical `Box<Concrete>`, `repr` becomes the identical
1520    /// `EvaluatedConcrete` marker, `census::evaluated()` fires exactly
1521    /// once, and the returned `Value` is a byte-identical reconstruction
1522    /// of `value`.
1523    ///
1524    /// Panics (via `demand_unchecked`) if `value` is a `Thunk` — the sole
1525    /// call site only reaches it on the `!was_thunk_before_loop` branch,
1526    /// where `value` is guaranteed non-`Thunk`.
1527    ///
1528    /// SAFETY: same contract as [`store_evaluated`] — single-threaded,
1529    /// no overlapping `repr` borrow.
1530    #[inline]
1531    unsafe fn store_evaluated_owned(&self, value: Value) -> Value {
1532        census::evaluated();
1533        let concrete = value.demand_unchecked();
1534        let ret = concrete.clone().into_value();
1535        let _ = self.0.cache.set(Box::new(concrete));
1536        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::EvaluatedConcrete;
1537        ret
1538    }
1539
1540    /// Force this thunk using the given evaluator function.
1541    ///
1542    /// On first force: transitions Suspended -> Blackhole -> Evaluated.
1543    /// Re-entering a Blackhole signals infinite recursion.
1544    /// If the evaluated result is itself a thunk, it is forced transitively.
1545    ///
1546    /// Uses `stacker::maybe_grow` to ensure sufficient stack space for
1547    /// deeply nested thunk chains (e.g., nixpkgs overlay fixpoints).
1548    pub fn force(
1549        &self,
1550        evaluator: &dyn Fn(&rnix::ast::Expr, &Env) -> Result<Value, EvalError>,
1551    ) -> Result<Value, EvalError> {
1552        // Ultra-fast path: if already evaluated, return cached value
1553        // WITHOUT entering stacker::maybe_grow. This avoids the stack
1554        // check overhead on ~150M cache hits during nixpkgs evaluation.
1555        if let Some(cached) = self.0.cache.get() {
1556            crate::perf::inc(crate::perf::Counter::ThunkHit);
1557            return Ok((**cached).clone().into_value());
1558        }
1559        // Cold path: evaluation may recurse deeply, so use stacker.
1560        stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || {
1561            self.force_inner(evaluator)
1562        })
1563    }
1564
1565    /// Inner implementation of [`Thunk::force`] — called from the
1566    /// `stacker` trampoline.
1567    fn force_inner(
1568        &self,
1569        evaluator: &dyn Fn(&rnix::ast::Expr, &Env) -> Result<Value, EvalError>,
1570    ) -> Result<Value, EvalError> {
1571        // SAFETY (all `unsafe` blocks in this method): The evaluator is
1572        // single-threaded (`Rc`, not `Arc`).  `ThunkInner` is `!Send`/`!Sync`.
1573        // The `OnceCell` fast path handles all concurrent-safe reads (150M+
1574        // hits).  Only the cold path (1.8M forces) touches the `UnsafeCell`.
1575        // The state machine guarantees no overlapping mutable access:
1576        // Suspended → Blackhole → Evaluated transitions are sequential.
1577
1578        // Ultra-fast path: check OnceCell cache (no borrow).
1579        if let Some(cached) = self.0.cache.get() {
1580            crate::perf::inc(crate::perf::Counter::ThunkHit);
1581            return Ok((**cached).clone().into_value());
1582        }
1583
1584        let thunk_id = Rc::as_ptr(&self.0) as usize;
1585
1586        // Promise fast-path: if this thunk is currently in `Promise`
1587        // state (a self-recursive fix-point whose outer body is still
1588        // running, and *this* call is an inner re-entrance), return
1589        // the cell's current partial value without consuming the
1590        // repr.  Matches cppnix's `let x = f x; in x` semantics:
1591        // inner accesses to `x` during f's evaluation see the not-
1592        // yet-complete value instead of erroring with
1593        // `InfiniteRecursion`.
1594        //
1595        // SAFETY: Single-threaded evaluator. The immutable borrow
1596        // is scoped to this `if let` block; the early return exits
1597        // before any further access to `repr`.
1598        if let ThunkRepr::Promise(cell) = unsafe { &*self.0.repr.get() } {
1599            return Ok(cell.borrow().clone());
1600        }
1601
1602        // Take the current repr.  Replace with `Promise(cell)` if the
1603        // thunk is self-recursive (so inner re-entrance during body
1604        // evaluation hits the fast-path above), otherwise classic
1605        // `Blackhole` (so inner re-entrance errors with
1606        // `InfiniteRecursion`, which is the correct behaviour for
1607        // non-recursive bindings like `let r = r; in r`).
1608        // SAFETY: Single-threaded evaluator. State machine ensures no
1609        // overlapping mutable access: Suspended->Blackhole/Promise->Evaluated.
1610        let new_repr_on_force = if self.0.recursive {
1611            ThunkRepr::Promise(Rc::new(RefCell::new(
1612                Value::Attrs(Rc::new(NixAttrs::new())),
1613            )))
1614        } else {
1615            ThunkRepr::Blackhole
1616        };
1617        let is_promise = self.0.recursive;
1618        let repr = std::mem::replace(unsafe { &mut *self.0.repr.get() }, new_repr_on_force);
1619
1620        match repr {
1621            ThunkRepr::Suspended { expr, env } => {
1622                crate::perf::inc(crate::perf::Counter::ThunkForce);
1623                crate::trace::inc_thunks_forced_unique();
1624                let tracing = crate::trace::trace_enabled();
1625                // Always push a force frame — `pop_force` is matched in every
1626                // exit path below.  This keeps the cycle chain on
1627                // `EvalError::InfiniteRecursion` populated WITHOUT requiring
1628                // the operator to set `SUI_TRACE_EVAL=verbose` first.  In
1629                // tracing mode we also capture the (expensive) source-text
1630                // description; otherwise we keep the frame cheap (just the
1631                // file + thunk id) so the always-on overhead stays bounded.
1632                let desc: String = if tracing {
1633                    expr.syntax().text().to_string().chars().take(60).collect()
1634                } else {
1635                    String::new()
1636                };
1637                crate::trace::push_force(crate::trace::ForceFrame {
1638                    defined_in: env.eval_file().cloned(),
1639                    description: desc.clone(),
1640                    thunk_id,
1641                });
1642                // Runaway backstop #1 (force-stack depth) for overlay-fixpoint
1643                // promotion (release-active; belt-and-suspenders with the
1644                // eval-depth backstop in `eval::DepthGuard::enter`).
1645                //
1646                // A promoted empty-attrs partial is byte-correct for the
1647                // native-system stdenv fixpoint (`libxcrypt` — the actual
1648                // byte-parity root; its promotions bottom out at a force depth
1649                // ≤ ~50), but is the WRONG partial for a demand that indexes it
1650                // as a list / non-attrs (the cross-system Darwin `apple-sdk`
1651                // path `hello` hits when `builtins.currentSystem` is macOS).
1652                // There the empty partial feeds a downstream `makeOverridable`
1653                // fixpoint that recurses without bound.  Release disables the
1654                // general `MAX_EVAL_DEPTH` guard (`None`) to admit
1655                // nixpkgs' legitimately-deep fixpoints, so nothing else stops
1656                // that recursion before the OS stack aborts.
1657                //
1658                // Armed only once a promotion has fired (`promotion_occurred()`)
1659                // and for the REST of the eval — a corrupted partial can send a
1660                // downstream fixpoint runaway AFTER the promoting force returns,
1661                // so the backstop must outlive the promotion's own softening
1662                // scope.  A runaway that climbs the force stack is caught here;
1663                // one that climbs `eval_expr` without pushing force frames is
1664                // caught by the eval-depth backstop.  Either converts the
1665                // would-be native abort into a recoverable `InfiniteRecursion`
1666                // (which `x.y or default` recovers exactly like nix).
1667                if crate::value::promotion_occurred()
1668                    && crate::trace::current_force_depth() as usize
1669                        > PROMOTION_RUNAWAY_FORCE_DEPTH
1670                {
1671                    crate::trace::pop_force();
1672                    *unsafe { &mut *self.0.repr.get() } =
1673                        ThunkRepr::Suspended { expr, env };
1674                    return Err(EvalError::InfiniteRecursion(
1675                        "overlay-fixpoint promotion runaway (force depth exceeded)".into(),
1676                    ));
1677                }
1678                if tracing {
1679                    crate::trace::trace_force_enter(
1680                        env.eval_file().map(|p| p.as_path()),
1681                        &desc,
1682                    );
1683                    if let Err(msg) = crate::trace::check_force_depth() {
1684                        crate::trace::dump_trace_on_error();
1685                        crate::trace::pop_force();
1686                        crate::trace::trace_force_exit();
1687                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Suspended {
1688                            expr,
1689                            env,
1690                        };
1691                        return Err(EvalError::InfiniteRecursion(msg));
1692                    }
1693                }
1694                // Push the thunk's captured eval_file onto the thread-local
1695                // stack so PathRel literals and relative imports inside the
1696                // thunk body resolve against the file where the thunk was
1697                // *defined*, not where it is forced from. The RAII guard
1698                // pops on drop (including on error paths).
1699                let _file_guard = env.eval_file().cloned().map(crate::eval::push_eval_file);
1700                // Restore the thunk's DEFINING source_id in lockstep with
1701                // eval_file above, so idents evaluated in the thunk body key
1702                // the `(source_id, offset)` symbol cache against the file the
1703                // thunk was defined in — not the ambient source at force time.
1704                // Without this a cross-file force (a lazy thunk from an
1705                // imported file, forced after `eval_with_file` restored the
1706                // top-level source_id) collides on a reused offset and returns
1707                // a wrong Symbol (`parse.nix` `cannot select from null`).
1708                let _srcid_guard = crate::eval::push_source_id(env.source_id());
1709                // M2.6 Promise scope: bump the thread-local counter so
1710                // downstream `eval_select` can soften `AttrNotFound`
1711                // errors on the Promise's sentinel value to `null`.
1712                // Scoped strictly to Promise-thunk body evaluation;
1713                // non-recursive thunks retain cppnix-strict semantics.
1714                if is_promise {
1715                    IN_PROMISE_EVAL.with(|c| c.set(c.get() + 1));
1716                }
1717                let result = evaluator(&expr, &env);
1718                if is_promise {
1719                    IN_PROMISE_EVAL.with(|c| c.set(c.get().saturating_sub(1)));
1720                }
1721                // A `Blackhole` thunk (non-recursive at construction) may have
1722                // been PROMOTED to `Promise` mid-body by a same-thunk fixpoint
1723                // re-entry (the overlay-fixpoint path in the Blackhole arm
1724                // below).  That promotion bumped `IN_PROMISE_EVAL` once; balance
1725                // it here, and populate its cell exactly like a
1726                // recursive-at-construction Promise.  `is_promise` covers the
1727                // construction-time case; `became_promise` covers the mid-body
1728                // semantic-promotion case.  They're mutually exclusive (a
1729                // construction-time Promise never re-enters the Blackhole arm).
1730                let became_promise = !is_promise
1731                    && matches!(unsafe { &*self.0.repr.get() }, ThunkRepr::Promise(_));
1732                if became_promise {
1733                    IN_PROMISE_EVAL.with(|c| c.set(c.get().saturating_sub(1)));
1734                }
1735                match result {
1736                    Ok(mut value) => {
1737                        crate::perf::inc(crate::perf::Counter::ThunkStoreWrites);
1738                        // M2.6 Promise update: if this thunk transitioned
1739                        // through Promise(cell), populate the cell with the
1740                        // final value BEFORE setting Evaluated.  Any
1741                        // outstanding Rc clones of the cell (held by inner
1742                        // thunks whose bodies haven't yet run) will see the
1743                        // complete value when they later force.
1744                        if is_promise || became_promise {
1745                            if let ThunkRepr::Promise(cell) = unsafe { &*self.0.repr.get() } {
1746                                *cell.borrow_mut() = value.clone();
1747                            }
1748                        }
1749                        // Whether the body returned a Thunk decides the store
1750                        // shape.  Computed BEFORE the store so the non-thunk
1751                        // path can MOVE `value` into the cache (owned store)
1752                        // instead of cloning it (see `store_evaluated_owned`).
1753                        //
1754                        // C-store PROVABLY-NEUTRAL narrow win (M2, byte-verified):
1755                        // when `value` is NOT a Thunk, the collapse loop below
1756                        // does not execute (its guard is `while let Value::Thunk`),
1757                        // so the second store (in the thunk branch) would rewrite
1758                        // BYTE-IDENTICAL repr content and re-attempt a no-op
1759                        // OnceCell `cache.set`.  Skipping it is content-AND-order-
1760                        // neutral: the single store already established the
1761                        // terminal (cache=concrete, repr=EvaluatedConcrete);
1762                        // nothing between the stores observes `self.0.repr` (the
1763                        // body has returned — no re-entrant force of self is in
1764                        // flight; the loop only `peek()`s OTHER thunks' OnceCell
1765                        // caches, never self's repr), and no code observes the
1766                        // `Box`'s pointer identity (repr is only ever read by
1767                        // value — grep-confirmed). Only when `value` IS a Thunk
1768                        // (the loop may collapse it to a different concrete) do we
1769                        // re-store the unwrapped result.
1770                        let was_thunk_before_loop = matches!(value, Value::Thunk(_));
1771                        if !was_thunk_before_loop {
1772                            // Non-thunk: single owned store (no outer Value clone),
1773                            // return the reconstruction. Byte-, order-, and census-
1774                            // identical to `store_evaluated(&value); return Ok(value)`
1775                            // (Store#2 is pure redundant and skipped, as before).
1776                            crate::perf::inc(crate::perf::Counter::ThunkStoreRedundant);
1777                            let ret = unsafe { self.store_evaluated_owned(value) };
1778                            crate::trace::pop_force();
1779                            if tracing { crate::trace::trace_force_exit(); }
1780                            return Ok(ret);
1781                        }
1782                        // Thunk path (unchanged): Store#1, collapse loop, Store#2.
1783                        unsafe { self.store_evaluated(&value) };
1784                        // Transitively unwrap thunk-in-thunk chains, with a
1785                        // depth limit to catch `let x = x; in x` cycles.
1786                        // Chase already-resolved thunks only (peek).
1787                        // force_value handles full transitive resolution.
1788                        while let Value::Thunk(ref inner) = value {
1789                            match inner.peek() {
1790                                Some(cached) => value = cached.clone().into_value(),
1791                                None => break,
1792                            }
1793                        }
1794                        if !matches!(value, Value::Thunk(_)) {
1795                            crate::perf::inc(crate::perf::Counter::ThunkStoreLoopMutated);
1796                        }
1797                        unsafe { self.store_evaluated(&value) };
1798                        crate::trace::pop_force();
1799                        if tracing { crate::trace::trace_force_exit(); }
1800                        Ok(value)
1801                    }
1802                    Err(e) => {
1803                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Suspended { expr, env };
1804                        if tracing { crate::trace::dump_trace_on_error(); }
1805                        crate::trace::pop_force();
1806                        if tracing { crate::trace::trace_force_exit(); }
1807                        Err(e)
1808                    }
1809                }
1810            }
1811            ThunkRepr::InheritSelect { source_thunk, name } => {
1812                let tracing = crate::trace::trace_enabled();
1813                let desc = if tracing { format!("inherit (..) {name}") } else { String::new() };
1814                crate::trace::push_force(crate::trace::ForceFrame {
1815                    defined_in: None,
1816                    description: desc.clone(),
1817                    thunk_id,
1818                });
1819                if tracing {
1820                    crate::trace::trace_force_enter(None, &desc);
1821                }
1822                crate::trace::inc_thunks_forced_unique();
1823                if tracing {
1824                    if let Err(msg) = crate::trace::check_force_depth() {
1825                        crate::trace::dump_trace_on_error();
1826                        crate::trace::pop_force();
1827                        crate::trace::trace_force_exit();
1828                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::InheritSelect {
1829                            source_thunk,
1830                            name,
1831                        };
1832                        return Err(EvalError::InfiniteRecursion(msg));
1833                    }
1834                }
1835                let attempt = (|| -> Result<Value, EvalError> {
1836                    let mut forced = source_thunk.force(evaluator)?;
1837                    while let Value::Thunk(inner) = forced {
1838                        forced = inner.force(evaluator)?;
1839                    }
1840                    let attrs = match &forced {
1841                        Value::Attrs(a) => a,
1842                        _ => {
1843                            return Err(EvalError::TypeError(format!(
1844                                "inherit (source) {name}: source is {}, not a set",
1845                                forced.type_name()
1846                            )))
1847                        }
1848                    };
1849                    attrs
1850                        .get(&name)
1851                        .cloned()
1852                        .ok_or_else(|| EvalError::AttrNotFound(name.to_string()))
1853                })();
1854                match attempt {
1855                    Ok(mut value) => {
1856                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Evaluated(Box::new(value.clone()));
1857                        while let Value::Thunk(ref inner) = value {
1858                            match inner.peek() { Some(c) => value = c.clone().into_value(), None => break }
1859                        }
1860                        unsafe { self.store_evaluated(&value) };
1861                        crate::trace::pop_force();
1862                        if tracing { crate::trace::trace_force_exit(); }
1863                        Ok(value)
1864                    }
1865                    Err(e) => {
1866                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::InheritSelect { source_thunk, name };
1867                        if tracing { crate::trace::dump_trace_on_error(); }
1868                        crate::trace::pop_force();
1869                        if tracing { crate::trace::trace_force_exit(); }
1870                        Err(e)
1871                    }
1872                }
1873            }
1874            ThunkRepr::Native(f) => {
1875                let tracing = crate::trace::trace_enabled();
1876                crate::trace::push_force(crate::trace::ForceFrame {
1877                    defined_in: None,
1878                    description: if tracing { "<native-thunk>".into() } else { String::new() },
1879                    thunk_id,
1880                });
1881                if tracing {
1882                    crate::trace::trace_force_enter(None, "<native-thunk>");
1883                }
1884                crate::trace::inc_thunks_forced_unique();
1885                // The closure is consumed (FnOnce).  On success we
1886                // memoize the result.  On failure we leave Blackhole
1887                // — unlike Suspended thunks the closure cannot be
1888                // retried because it has been consumed.
1889                match f() {
1890                    Ok(mut value) => {
1891                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Evaluated(Box::new(value.clone()));
1892                        while let Value::Thunk(ref inner) = value {
1893                            match inner.peek() { Some(c) => value = c.clone().into_value(), None => break }
1894                        }
1895                        unsafe { self.store_evaluated(&value) };
1896                        crate::trace::pop_force();
1897                        if tracing { crate::trace::trace_force_exit(); }
1898                        Ok(value)
1899                    }
1900                    Err(e) => {
1901                        // The `FnOnce` closure is consumed and cannot be
1902                        // retried.  Memoize the ERROR (not `Null`): a
1903                        // re-force must re-raise, never silently return a
1904                        // value the first force did not produce.  The old
1905                        // `Evaluated(Null)` here poisoned a flake-input
1906                        // thunk whose first force failed transiently
1907                        // (e.g. a not-yet-cached transitive source) so a
1908                        // later re-read saw `null` — surfacing as a bogus
1909                        // downstream `AttrNotFound` /
1910                        // `cannot select from set` (the stylix
1911                        // `darwinModules` marquee root).  Do NOT populate
1912                        // the OnceCell (there is no correct concrete value
1913                        // to cache); the `Failed` repr arm re-raises.
1914                        *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Failed(e.clone());
1915                        if tracing { crate::trace::dump_trace_on_error(); }
1916                        crate::trace::pop_force();
1917                        if tracing { crate::trace::trace_force_exit(); }
1918                        Err(e)
1919                    }
1920                }
1921            }
1922            ThunkRepr::WithIdent { name, scope_cache, scope_value, env } => {
1923                crate::perf::inc(crate::perf::Counter::ThunkForce);
1924                crate::trace::inc_thunks_forced_unique();
1925                // Fast path: check the shared with-scope cache.
1926                // All WithIdent thunks from the same `with` scope share
1927                // this cache. Once ANY lookup populates it, all others
1928                // are O(1) hash lookups.
1929                {
1930                    let cache = scope_cache.borrow();
1931                    if let Some(ref attrs) = *cache {
1932                        if let Some(v) = attrs.get(&name) {
1933                            let value = v.clone();
1934                            unsafe { self.store_evaluated(&value) };
1935                            return Ok(value);
1936                        }
1937                        // Name not in cached attrset — fall through to env lookup
1938                    }
1939                }
1940                // Cache not populated yet — force the scope value to populate it
1941                if let Ok(forced) = crate::eval::force_value(&scope_value) {
1942                    if let Value::Attrs(ref attrs) = forced {
1943                        *scope_cache.borrow_mut() = Some((**attrs).clone());
1944                        if let Some(v) = attrs.get(&name) {
1945                            let value = v.clone();
1946                            unsafe { self.store_evaluated(&value) };
1947                            return Ok(value);
1948                        }
1949                    }
1950                }
1951                // Name not in with-scope — fall back to full env lookup.
1952                //
1953                // The cache-first with-scope search may have skipped a scope
1954                // whose CACHE is a stale mid-fixpoint PARTIAL — e.g. `f self`
1955                // cached BEFORE makeScope's `self = f self // { callPackage = …; }`
1956                // merged the scope infra in, so `callPackage` is absent from
1957                // the stale partial yet present in the COMPLETED `self`. On any
1958                // lexical-scope miss (both inside and outside a Promise body),
1959                // re-resolve by force_value-ing each with-scope FRESH (bypassing
1960                // the cache) via `lookup_fresh`. It catches errors, so a
1961                // genuinely mid-fixpoint / throwing scope simply skips and
1962                // returns None — leaving the Promise-body null softening (below)
1963                // for the case where the with-source really IS the empty-attrset
1964                // sentinel. A completed value always wins over the null sentinel.
1965                //
1966                // This is the SAME class as the neovim/python27
1967                // `with self; with super; callPackage` root, but reached through
1968                // the resholve `python27' = (…).override { self = python27'; }`
1969                // recursive-fixpoint hooks scope, where the miss lands inside a
1970                // Promise body (`in_promise_eval()` true) and was previously
1971                // softened to `null` BEFORE `lookup_fresh` ran — silently
1972                // dropping `pip = callPackage …` (→ empty `propagatedBuildInputs`
1973                // on `pip-install-hook.drv`). Trying the completed-`self`
1974                // resolution first restores the drop.
1975                //
1976                // Byte-neutral: `lookup_fresh` only ever returns a value nix's
1977                // single lazy `self` would ALSO expose; when it misses (genuine
1978                // empty-partial sentinel) the softening / error behavior below is
1979                // exactly as before.
1980                let result = match env.lookup(&name) {
1981                    Some(v) => v,
1982                    None => match env.lookup_fresh(&name) {
1983                        Some(v) => v,
1984                        None if in_promise_eval() => Value::Null,
1985                        None => return Err(EvalError::UndefinedVar(format!("'{name}'"))),
1986                    },
1987                };
1988                unsafe { self.store_evaluated(&result) };
1989                Ok(result)
1990            }
1991            ThunkRepr::Blackhole => {
1992                // M2.6 bridge: when an inner force re-enters a thunk
1993                // that's currently being evaluated, cppnix's effective
1994                // behavior is to expose the not-yet-complete value
1995                // (typically a partial attrset).  Without the proper
1996                // `Promise(NixAttrs)` thunk variant (see
1997                // docs/M2.6-MODULE-SYSTEM-FIXPOINT.md::Genuine fix),
1998                // we approximate by returning a sentinel of the
1999                // operator's choice:
2000                //
2001                //   SUI_BLACKHOLE_AS_NULL=1         → Value::Null
2002                //   SUI_BLACKHOLE_AS_EMPTY_ATTRS=1  → Value::Attrs({})
2003                //   SUI_BLACKHOLE_AS_EMPTY_LIST=1   → Value::List([])
2004                //
2005                // `EMPTY_ATTRS` is the closest approximation for the
2006                // NixOS module-system fix-point because the cppnix
2007                // partial is itself an attrset — downstream
2008                // `mapAttrs`/`attrNames`/`concatMap` on the sentinel
2009                // see "no keys to map" rather than a type error.
2010                //
2011                // Default-off for all variants because each silently
2012                // hides legitimate cycles in user code (`let r = r;
2013                // in r.x` would return missing-attr or 0 instead of
2014                // erroring).
2015                if std::env::var_os("SUI_BLACKHOLE_AS_NULL").is_some() {
2016                    return Ok(Value::Null);
2017                }
2018                if std::env::var_os("SUI_BLACKHOLE_AS_EMPTY_LIST").is_some() {
2019                    return Ok(Value::List(Rc::new(NixList::new(Vec::new()))));
2020                }
2021                if std::env::var_os("SUI_BLACKHOLE_AS_EMPTY_ATTRS").is_some() {
2022                    return Ok(Value::Attrs(Rc::new(NixAttrs::new())));
2023                }
2024                if std::env::var_os("SUI_DEBUG_CYCLE").is_some() {
2025                    let same = crate::trace::force_stack_contains(thunk_id);
2026                    eprintln!(
2027                        "[SUI_DEBUG_CYCLE] blackhole re-entry thunk_id={thunk_id:#x} same_thunk_on_stack={same} recursive_flag={}",
2028                        self.0.recursive
2029                    );
2030                    crate::trace::dump_force_stack_ids();
2031                }
2032                // OVERLAY-FIXPOINT SEMANTIC PROMOTION (2026-07-10, default-ON).
2033                //
2034                // When the re-entered thunk is the SAME thunk currently
2035                // mid-evaluation on the force stack, this is a genuine fixpoint
2036                // self-reference — the nixpkgs `self:super:` overlay / `lib.fix`
2037                // pattern threading through `callPackage`/`self`/`super` across
2038                // file boundaries.  `is_self_recursive_binding` (syntactic RHS
2039                // name search) MISSES this because the binding's RHS never
2040                // textually names itself, so the thunk was classified
2041                // `recursive=false` and installed a hard `Blackhole` where nix
2042                // exposes the not-yet-complete value.  That misclassification is
2043                // exactly the byte-parity defect (`sui-spec/src/laziness.rs`
2044                // `RecursionKind::Fixpoint` ⇒ MUST be recursive + Promise): the
2045                // dropped perl `nativeBuildInput` on `pkgs.libxcrypt` (sui
2046                // q9b9v7a9… vs nix jb9k6090…).
2047                //
2048                // The FIX is the Blackhole↔Promise machinery, not a sentinel:
2049                // retroactively PROMOTE this Blackhole to a real `Promise(cell)`
2050                // and return the cell's in-progress partial.  Unlike the earlier
2051                // blank-empty-attrs sentinel (which left the thunk in Blackhole
2052                // forever and stack-overflowed `hello`), the promoted cell is a
2053                // first-class fixpoint cell:
2054                //   * the outer body populates it on completion (the
2055                //     `is_promise || became_promise` branch below), so any inner
2056                //     Rc clones that already read the empty partial converge, and
2057                //     the repr transitions cleanly to `Evaluated`;
2058                //   * `IN_PROMISE_EVAL` is bumped so downstream `eval_select`
2059                //     softens `AttrNotFound`/`cannot-select` on the partial to
2060                //     `null` (the `x.y or default` fall-through nix relies on),
2061                //     which is what stops the `hello` overflow.
2062                //
2063                // Genuine NON-terminating cycles (`let r = r; in r`) remain
2064                // errors: the promoted partial cannot make progress, so the
2065                // force-depth backstop (`check_force_depth`, ~2048/100 in
2066                // test/release) still fires `InfiniteRecursion` — nix's own
2067                // behaviour.  This is the semantic (fixpoint) classification the
2068                // typed discipline demands, done in the demand-order engine
2069                // instead of at syntactic construction time.
2070                if crate::trace::force_stack_contains(thunk_id)
2071                    && IN_PROMISE_EVAL.with(|c| c.get()) < FIXPOINT_PROMOTE_NEST_CAP
2072                {
2073                    if std::env::var_os("SUI_DEBUG_CYCLE").is_some() {
2074                        let chain = crate::trace::capture_cycle(thunk_id);
2075                        let nest = IN_PROMISE_EVAL.with(|c| c.get());
2076                        let fdepth = crate::trace::current_force_depth();
2077                        eprintln!("[SUI_PROMOTE] thunk_id={thunk_id:#x} cycle_len={} nest={nest} fdepth={fdepth}", chain.0.len());
2078                    }
2079                    let cell = Rc::new(RefCell::new(
2080                        Value::Attrs(Rc::new(NixAttrs::new())),
2081                    ));
2082                    // SAFETY: single-threaded evaluator; we hold no other borrow
2083                    // of `repr` here (the outer match consumed it, we replace it).
2084                    *unsafe { &mut *self.0.repr.get() } =
2085                        ThunkRepr::Promise(cell.clone());
2086                    // Enable Promise-body softening for the remainder of the
2087                    // outer force.  Decremented once by the outer force's
2088                    // post-body reconciliation (`became_promise`).
2089                    IN_PROMISE_EVAL.with(|c| c.set(c.get() + 1));
2090                    // Arm the release runaway backstop for the rest of the eval.
2091                    PROMOTION_OCCURRED.with(|c| c.set(true));
2092                    return Ok(cell.borrow().clone());
2093                }
2094                let chain = crate::trace::capture_cycle(thunk_id);
2095                crate::trace::dump_trace_on_error();
2096                Err(EvalError::InfiniteRecursion(chain.to_string()))
2097            }
2098            ThunkRepr::Promise(cell) => {
2099                // Inner re-entrance into a self-recursive thunk that's
2100                // currently being evaluated.  Return the partial value
2101                // the body has constructed so far (the cell starts as
2102                // `Value::Attrs(empty)` and gets updated on body return).
2103                // This is sui's cppnix-equivalent for `let x = f x; in x`
2104                // — the inner reference to `x` during f's evaluation
2105                // sees a partial attrset instead of the original cycle's
2106                // `InfiniteRecursion`.
2107                Ok(cell.borrow().clone())
2108            }
2109            ThunkRepr::Evaluated(v) => {
2110                // Reached when OnceCell wasn't populated (value was a thunk
2111                // when first evaluated). Cache only concrete values — caching
2112                // a thunk would cause force_value's loop to spin.
2113                crate::perf::inc(crate::perf::Counter::ThunkHit);
2114                let cloned = (*v).clone();
2115                if !matches!(cloned, Value::Thunk(_)) {
2116                    if !matches!(cloned, Value::Thunk(_)) { let _ = self.0.cache.set(Box::new(cloned.clone().demand_unchecked())); }
2117                }
2118                *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Evaluated(v);
2119                Ok(cloned)
2120            }
2121            ThunkRepr::EvaluatedConcrete => {
2122                // The concrete value lives in `cache`; the repr is a valueless
2123                // marker (the collapsed former double-store). In practice this
2124                // arm is unreachable: `force`/`force_inner` check the `cache`
2125                // fast path BEFORE the `mem::replace` that consumes the repr,
2126                // and `EvaluatedConcrete` always co-occurs with a populated
2127                // cache — so the fast path returns first. Handle it faithfully
2128                // anyway: reconstruct the `Value` from the cache (a byte-
2129                // identical inverse of `demand_unchecked`) and restore the
2130                // marker (the outer `mem::replace` swapped in Blackhole/Promise).
2131                crate::perf::inc(crate::perf::Counter::ThunkHit);
2132                let value = self
2133                    .0
2134                    .cache
2135                    .get()
2136                    .expect("EvaluatedConcrete implies a populated cache")
2137                    .as_ref()
2138                    .clone()
2139                    .into_value();
2140                *unsafe { &mut *self.0.repr.get() } = ThunkRepr::EvaluatedConcrete;
2141                Ok(value)
2142            }
2143            ThunkRepr::Failed(e) => {
2144                // A previously-forced `Native` thunk whose closure threw.
2145                // Re-raise the memoized error — never fall through to a
2146                // silent value.  Restore the repr (the outer
2147                // `mem::replace` swapped in Blackhole/Promise).
2148                let err = e.clone();
2149                *unsafe { &mut *self.0.repr.get() } = ThunkRepr::Failed(e);
2150                Err(err)
2151            }
2152        }
2153    }
2154}
2155
2156impl fmt::Debug for Thunk {
2157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2158        // SAFETY: Single-threaded evaluator, read-only access during formatting.
2159        match unsafe { &*self.0.repr.get() } {
2160            ThunkRepr::Suspended { .. } => write!(f, "<thunk>"),
2161            ThunkRepr::InheritSelect { name, .. } => write!(f, "<inherit-select {name}>"),
2162            ThunkRepr::Native(_) => write!(f, "<native-thunk>"),
2163            ThunkRepr::WithIdent { name, .. } => write!(f, "<with-ident {name}>"),
2164            ThunkRepr::Blackhole => write!(f, "<blackhole>"),
2165            ThunkRepr::Promise(_) => write!(f, "<promise>"),
2166            ThunkRepr::Failed(e) => write!(f, "<failed-thunk: {e}>"),
2167            ThunkRepr::Evaluated(v) => write!(f, "{v:?}"),
2168            ThunkRepr::EvaluatedConcrete => match self.0.cache.get() {
2169                Some(c) => write!(f, "{:?}", c.as_ref().clone().into_value()),
2170                None => write!(f, "<evaluated-concrete>"),
2171            },
2172        }
2173    }
2174}
2175
2176/// A Nix attribute set with lazy overlay support.
2177///
2178/// Internally uses either a concrete compact `AttrsMap` or a lazy overlay chain.
2179/// The `//` operator creates O(1) overlay nodes instead of O(m log n) merges.
2180/// Attribute access walks the chain right-to-left in O(depth).
2181/// Full iteration (attrNames, attrValues) flattens on demand.
2182///
2183/// The second tuple field is an OPTIONAL source-position table (`None` for
2184/// the vast majority of attrsets — merges, overlays, builtin-built, dynamic
2185/// keys). `eval_attrset` attaches it for a literal with static keys so
2186/// `builtins.unsafeGetAttrPos` can report a key's file/line/column (the
2187/// `attrTag` `declarations` — options.json dock root). It is behind `Rc`, so
2188/// a clone is a refcount bump; `None` costs one pointer-sized word.
2189pub struct NixAttrs(AttrsInner, Option<Rc<crate::pos::AttrPositions>>);
2190
2191// Hand-written `Clone`/`Drop` so the census counts every NixAttrs value that
2192// comes into existence (a clone is a fresh heap object once Rc-wrapped),
2193// keeping `ATTRS_MADE`/`ATTRS_LIVE` consistent. Fresh (non-clone)
2194// constructions bump the counter at each `NixAttrs(...)` tuple-construct site.
2195impl Clone for NixAttrs {
2196    fn clone(&self) -> Self {
2197        census::made(&census::ATTRS_MADE, &census::ATTRS_LIVE);
2198        NixAttrs(self.0.clone(), self.1.clone())
2199    }
2200}
2201
2202impl Drop for NixAttrs {
2203    fn drop(&mut self) {
2204        census::dropped(&census::ATTRS_LIVE);
2205    }
2206}
2207
2208/// Internal representation: either a flat map or an overlay chain.
2209#[derive(Clone)]
2210enum AttrsInner {
2211    /// Concrete attribute set — compact flat `AttrsMap` (std hashbrown).
2212    Flat(AttrsMap<Symbol, Value>),
2213    /// Lazy overlay: right overrides left. O(1) construction.
2214    /// `cache` is populated on first full iteration (attrNames, etc.).
2215    ///
2216    /// `left`/`right` are interior-mutable so they can be RELEASED (swapped to an
2217    /// empty attrs) once `cache` is populated: after flatten the merged `cache`
2218    /// is the complete answer and every reader (`get_sym`/`contains_key`/
2219    /// `is_empty`) routes through `as_flat()` (the cache), so the un-merged
2220    /// parents are dead weight. Releasing them cascade-frees the intermediate
2221    /// overlay chain (the 50+-deep module-fixpoint retention — `EVAL-MEMORY.md`).
2222    /// Byte-neutral: the cache is the same map nix's flatten yields.
2223    Overlay {
2224        left: RefCell<Rc<NixAttrs>>,
2225        right: RefCell<Rc<NixAttrs>>,
2226        cache: Rc<OnceCell<AttrsMap<Symbol, Value>>>,
2227    },
2228}
2229
2230impl fmt::Debug for NixAttrs {
2231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2232        write!(f, "NixAttrs({})", self.len())
2233    }
2234}
2235
2236impl Default for NixAttrs {
2237    fn default() -> Self {
2238        census::made(&census::ATTRS_MADE, &census::ATTRS_LIVE);
2239        Self(AttrsInner::Flat(AttrsMap::default()), None)
2240    }
2241}
2242
2243impl NixAttrs {
2244    pub fn new() -> Self {
2245        Self::default()
2246    }
2247
2248    pub fn with_capacity(_capacity: usize) -> Self {
2249        Self::default()
2250    }
2251
2252    /// Attach a source-position table (the static keys' byte offsets of the
2253    /// literal that built this attrset). Called by `eval_attrset`; consumed
2254    /// by `builtins.unsafeGetAttrPos`. Never affects any observed value.
2255    pub fn set_positions(&mut self, pos: Rc<crate::pos::AttrPositions>) {
2256        self.1 = Some(pos);
2257    }
2258
2259    /// The source-position table, if this attrset carries one (a literal with
2260    /// static keys). `None` for merges/overlays/builtin-built/dynamic-key
2261    /// attrsets.
2262    #[must_use]
2263    pub fn positions(&self) -> Option<&Rc<crate::pos::AttrPositions>> {
2264        self.1.as_ref()
2265    }
2266
2267    /// Resolve the source position of `key` in this attrset — the file/line/
2268    /// column `builtins.unsafeGetAttrPos` returns. `None` when the attrset
2269    /// has no position table, the key is absent from it, or the source has
2270    /// no file (a `<string>`-eval'd literal).
2271    #[must_use]
2272    pub fn pos_for(&self, key: &str) -> Option<crate::pos::ResolvedPos> {
2273        let sym = intern(key);
2274        let (file, offset) = self.pos_entry(sym)?;
2275        crate::pos::resolve(file.as_deref(), offset)
2276    }
2277
2278    /// Find `sym`'s (file, offset) — walking an `//` overlay RIGHT first, then
2279    /// LEFT, so a key's reported position follows the same precedence `//`
2280    /// itself gives the key's VALUE.
2281    ///
2282    /// Why this walks instead of reading `self.1`: `overlay` builds the
2283    /// `AttrsInner::Overlay` node with an empty position slot (it is O(1) and
2284    /// lazy by construction — eagerly merging two tables on every `//` would
2285    /// cost on a very hot path). Reading only the slot therefore reported
2286    /// `null` for EVERY key of every `//` result.
2287    ///
2288    /// That was not cosmetic. nixpkgs' `lib.nixosSystem` ends in
2289    /// `{ …; modules = …; } // removeAttrs args [ "modules" ]`, and
2290    /// `nixos/lib/eval-config.nix:28` derives `modulesLocation` from
2291    /// `unsafeGetAttrPos "modules"` on exactly that attrset. A `null` there
2292    /// skips `setDefaultModuleLocation`, which skips wrapping every user
2293    /// module in `{ _file; imports = [ m ]; }` — and since `collectModules`
2294    /// walks breadth-first via `genericClosure`, the missing wrapper leaves
2295    /// each user module one level SHALLOWER than CppNix puts it, permuting
2296    /// NixOS option definition order and diverging the toplevel drvPath.
2297    fn pos_entry(&self, sym: Symbol) -> Option<(Option<std::path::PathBuf>, u32)> {
2298        if let Some(table) = self.1.as_ref() {
2299            if let Some(offset) = table.keys.get(&sym) {
2300                return Some((table.file.clone(), *offset));
2301            }
2302        }
2303        match &self.0 {
2304            AttrsInner::Overlay { left, right, .. } => {
2305                let r = right.borrow().pos_entry(sym);
2306                if r.is_some() {
2307                    return r;
2308                }
2309                let l = left.borrow().pos_entry(sym);
2310                l
2311            }
2312            _ => None,
2313        }
2314    }
2315
2316    /// Borrow the underlying map. Flattens if overlay.
2317    #[must_use]
2318    pub fn inner(&self) -> AttrsMap<Symbol, Value> {
2319        self.as_flat().clone()
2320    }
2321
2322    /// Get a reference to a flat `AttrsMap`, populating cache if overlay.
2323    fn as_flat(&self) -> &AttrsMap<Symbol, Value> {
2324        match &self.0 {
2325            AttrsInner::Flat(m) => m,
2326            AttrsInner::Overlay { left, right, cache } => {
2327                crate::perf::inc(crate::perf::Counter::OverlayFlattenAttempt);
2328                let flat = cache.get_or_init(|| {
2329                    // Cache MISS: this Overlay node is being flattened for the
2330                    // first time — real O(left+right) merge work.
2331                    crate::perf::inc(crate::perf::Counter::OverlayFlattenBuild);
2332                    let timed = crate::perf::enabled();
2333                    let t0 = if timed { Some(std::time::Instant::now()) } else { None };
2334                    let mut result = left.borrow().as_flat().clone();
2335                    for (k, v) in right.borrow().as_flat().iter() {
2336                        result.insert(*k, v.clone());
2337                    }
2338                    crate::perf::add(
2339                        crate::perf::Counter::OverlayFlattenEntries,
2340                        result.len() as u64,
2341                    );
2342                    if let Some(t0) = t0 {
2343                        crate::trace::add_overlay_flatten_nanos(t0.elapsed().as_nanos());
2344                    }
2345                    result
2346                });
2347                // RELEASE the parents now that `cache` is the complete answer —
2348                // cascade-frees the intermediate overlay chain + their caches
2349                // (nothing else references them). Byte-neutral: every reader now
2350                // routes through this `cache`. Only swaps a still-held parent; a
2351                // second as_flat sees them already empty and skips. The closure's
2352                // borrows above are dropped by here, so these borrow_muts can't
2353                // conflict (single-threaded, sequential).
2354                // Release VALUES but keep the POSITION SKELETON. Swapping in a
2355                // bare `NixAttrs::new()` also discarded every `AttrPositions`
2356                // table in the released subtree, so `pos_entry`'s overlay walk
2357                // found nothing and `unsafeGetAttrPos` returned null for any
2358                // `//` result that had been TOUCHED — measured:
2359                //   fresh overlay        nix line 1, sui line 1
2360                //   after one attr read  nix line 1, sui NULL
2361                // which is every real use, since nixpkgs reads from an attrset
2362                // before anyone asks for a position. `position_husk` keeps the
2363                // same tree shape and the position tables (small, and only
2364                // present on literals) while dropping the values, so the
2365                // cascade-free still reclaims the expensive part.
2366                {
2367                    let mut l = left.borrow_mut();
2368                    if !l.is_empty() { *l = Rc::new(l.position_husk()); }
2369                }
2370                {
2371                    let mut r = right.borrow_mut();
2372                    if !r.is_empty() { *r = Rc::new(r.position_husk()); }
2373                }
2374                flat
2375            }
2376        }
2377    }
2378
2379    /// A value-free copy carrying only what `pos_entry` reads: this node's own
2380    /// position table and, for an overlay, the same shape recursively.
2381    ///
2382    /// Used when `as_flat` releases a flattened overlay's parents. The values
2383    /// are what cost memory; the `AttrPositions` tables are small and exist
2384    /// only on attrset LITERALS with static keys, so keeping the skeleton
2385    /// preserves `unsafeGetAttrPos` at negligible cost. Returns an empty
2386    /// position-less set when the subtree carries no positions at all, so the
2387    /// common case allocates no more than the old `NixAttrs::new()` did.
2388    fn position_husk(&self) -> NixAttrs {
2389        match &self.0 {
2390            AttrsInner::Overlay { left, right, .. } => {
2391                let (l, r) = (left.borrow().position_husk(), right.borrow().position_husk());
2392                if l.1.is_none() && r.1.is_none() && !matches!(l.0, AttrsInner::Overlay { .. })
2393                    && !matches!(r.0, AttrsInner::Overlay { .. })
2394                {
2395                    // Nothing below carries a position — collapse to the cheap
2396                    // empty set rather than rebuilding a pointless spine.
2397                    return NixAttrs(AttrsInner::Flat(AttrsMap::default()), self.1.clone());
2398                }
2399                NixAttrs(
2400                    AttrsInner::Overlay {
2401                        left: RefCell::new(Rc::new(l)),
2402                        right: RefCell::new(Rc::new(r)),
2403                        cache: Rc::new(OnceCell::new()),
2404                    },
2405                    self.1.clone(),
2406                )
2407            }
2408            AttrsInner::Flat(_) => NixAttrs(AttrsInner::Flat(AttrsMap::default()), self.1.clone()),
2409        }
2410    }
2411
2412    fn sorted_entries(&self) -> Vec<(String, &Value)> {
2413        crate::perf::inc(crate::perf::Counter::SortedEntriesCalls);
2414        let m = self.as_flat();
2415        crate::perf::add(crate::perf::Counter::SortedEntriesRows, m.len() as u64);
2416        let timed = crate::perf::enabled();
2417        let t0 = if timed { Some(std::time::Instant::now()) } else { None };
2418        let mut pairs: Vec<(String, &Value)> = m.iter()
2419            .map(|(sym, v)| (resolve(*sym), v))
2420            .collect();
2421        pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
2422        if let Some(t0) = t0 {
2423            crate::trace::add_sorted_entries_nanos(t0.elapsed().as_nanos());
2424        }
2425        pairs
2426    }
2427
2428    /// Look up an attribute by name. Walks overlay chain right-to-left.
2429    #[must_use]
2430    pub fn get(&self, key: &str) -> Option<&Value> {
2431        let sym = intern(key);
2432        self.get_sym(&sym)
2433    }
2434
2435    /// Look up by pre-interned Symbol.
2436    ///
2437    /// Fast path: if the overlay's flat cache has been populated (by any
2438    /// prior full iteration — `attrNames`, `attrValues`, `//` merge that
2439    /// needed key enumeration, etc.), read directly from it in O(1). This
2440    /// matters in real Nix workloads where an attrset is first iterated
2441    /// (module eval, `with` desugaring) and then hit many times by dotted
2442    /// access — CppNix has no such structure and pays O(1) always; we want
2443    /// to match that whenever the cache is warm.
2444    ///
2445    /// Slow path: walk the overlay chain right-to-left in O(depth). Not
2446    /// populating the cache on cold lookups is deliberate — the cache
2447    /// costs O(n) to build and the chain is usually short (1–3 overlays).
2448    #[must_use]
2449    pub fn get_sym(&self, sym: &Symbol) -> Option<&Value> {
2450        match &self.0 {
2451            AttrsInner::Flat(m) => m.get(sym),
2452            // Route through `as_flat()` (the memoized cache) rather than borrowing
2453            // into `left`/`right` — this is what lets the parents be released
2454            // post-flatten. `as_flat` returns the cached map in O(1) when warm and
2455            // flattens+caches on the first cold lookup; the returned `&Value`
2456            // borrows the stable `cache`, never a `RefCell`.
2457            AttrsInner::Overlay { .. } => self.as_flat().get(sym),
2458        }
2459    }
2460
2461    /// Insert or overwrite an attribute. Flattens overlay if needed.
2462    pub fn insert(&mut self, key: String, value: Value) {
2463        self.ensure_flat();
2464        if let AttrsInner::Flat(ref mut m) = self.0 {
2465            m.insert(intern(&key), value);
2466        }
2467    }
2468
2469    /// Ensure the inner representation is Flat (for mutation).
2470    fn ensure_flat(&mut self) {
2471        if matches!(self.0, AttrsInner::Overlay { .. }) {
2472            self.0 = AttrsInner::Flat(self.as_flat().clone());
2473        }
2474    }
2475
2476    #[must_use]
2477    pub fn contains_key(&self, key: &str) -> bool {
2478        let sym = intern(key);
2479        self.contains_key_sym(&sym)
2480    }
2481
2482    #[must_use]
2483    pub fn contains_key_sym(&self, sym: &Symbol) -> bool {
2484        match &self.0 {
2485            AttrsInner::Flat(m) => m.contains_key(sym),
2486            // Route through the cache (see get_sym) so left/right stay releasable.
2487            AttrsInner::Overlay { .. } => self.as_flat().contains_key(sym),
2488        }
2489    }
2490
2491    pub fn keys(&self) -> impl Iterator<Item = String> {
2492        self.sorted_entries().into_iter().map(|(k, _)| k)
2493    }
2494
2495    pub fn iter(&self) -> impl Iterator<Item = (String, &Value)> {
2496        self.sorted_entries().into_iter()
2497    }
2498
2499    pub fn iter_unsorted(&self) -> impl Iterator<Item = (String, &Value)> {
2500        self.as_flat().iter().map(|(sym, v)| (resolve(*sym), v)).collect::<Vec<_>>().into_iter()
2501    }
2502
2503    /// Sym-keyed unsorted iteration — ZERO interner traffic, zero allocation.
2504    ///
2505    /// This exists because live-sampling the cid marquee eval (2026-07-21,
2506    /// release-profiling binary) showed the **interner round-trip as the #1 CPU
2507    /// sink — 27–39% of the eval thread, sustained**: `iter_unsorted` above
2508    /// materializes a fresh heap `String` per key via `resolve` AND collects
2509    /// the whole map into a `Vec` on every call, and callers like
2510    /// `intersectAttrs` then re-intern each of those Strings straight back to
2511    /// the `Symbol` they started as (`contains_key(&str)` → `intern`), with a
2512    /// third intern inside `insert`. Sym→String→hash+memcmp→Sym, three times
2513    /// per key per call, at nixpkgs scale.
2514    ///
2515    /// `Symbol` is `Copy(u32)` and `as_flat()` hands back a real borrow (the
2516    /// Overlay case populates its cache), so this iterator borrows instead of
2517    /// collecting. Byte-neutral by the same argument already sealed for the
2518    /// unsorted-iteration change: the observable order of any *result* attrset
2519    /// is re-derived at observation time via `sorted_entries`.
2520    pub fn iter_syms(&self) -> impl Iterator<Item = (Symbol, &Value)> {
2521        self.as_flat().iter().map(|(sym, v)| (*sym, v))
2522    }
2523
2524    /// Sym-keyed insert — the zero-intern sibling of `insert`, for callers
2525    /// that already hold the `Symbol` (every `iter_syms` consumer).
2526    pub fn insert_sym(&mut self, sym: Symbol, value: Value) {
2527        self.ensure_flat();
2528        if let AttrsInner::Flat(ref mut m) = self.0 {
2529            m.insert(sym, value);
2530        }
2531    }
2532
2533    pub fn values(&self) -> impl Iterator<Item = &Value> {
2534        self.sorted_entries().into_iter().map(|(_, v)| v)
2535    }
2536
2537
2538    pub fn remove(&mut self, key: &str) -> Option<Value> {
2539        self.ensure_flat();
2540        if let AttrsInner::Flat(ref mut m) = self.0 {
2541            m.remove(&intern(key))
2542        } else {
2543            None
2544        }
2545    }
2546
2547    #[must_use]
2548    pub fn len(&self) -> usize {
2549        match &self.0 {
2550            AttrsInner::Flat(m) => m.len(),
2551            AttrsInner::Overlay { .. } => {
2552                // Must flatten to count unique keys, but `as_flat()` already
2553                // returns a borrow into the memoized map — cloning it just to
2554                // read `.len()` was pure O(n) waste on every overlay `len()`.
2555                self.as_flat().len()
2556            }
2557        }
2558    }
2559
2560    #[must_use]
2561    pub fn is_empty(&self) -> bool {
2562        match &self.0 {
2563            AttrsInner::Flat(m) => m.is_empty(),
2564            // Cache-first (see get_sym): a released-parent overlay is NOT empty —
2565            // its content lives in the flattened cache. Reading left/right here
2566            // (which post-release are empty) would wrongly report empty.
2567            AttrsInner::Overlay { .. } => self.as_flat().is_empty(),
2568        }
2569    }
2570
2571    /// O(1) lazy overlay: `self // other`. Does NOT merge eagerly.
2572    #[must_use]
2573    pub fn overlay(self, other: NixAttrs) -> NixAttrs {
2574        if other.is_empty() { return self; }
2575        if self.is_empty() { return other; }
2576        crate::perf::inc(crate::perf::Counter::OverlayCreated);
2577        census::made(&census::ATTRS_MADE, &census::ATTRS_LIVE);
2578        NixAttrs(AttrsInner::Overlay {
2579            left: RefCell::new(Rc::new(self)),
2580            right: RefCell::new(Rc::new(other)),
2581            cache: Rc::new(OnceCell::new()),
2582        }, None)
2583    }
2584
2585    /// Eager merge (legacy API — prefer `overlay` for `//`).
2586    #[must_use]
2587    pub fn update(&self, other: &NixAttrs) -> NixAttrs {
2588        match (&self.0, &other.0) {
2589            (AttrsInner::Flat(l), AttrsInner::Flat(r)) => {
2590                let mut result = l.clone();
2591                for (k, v) in r.iter() {
2592                    result.insert(*k, v.clone());
2593                }
2594                census::made(&census::ATTRS_MADE, &census::ATTRS_LIVE);
2595                NixAttrs(AttrsInner::Flat(result), None)
2596            }
2597            _ => {
2598                // For overlay inputs, flatten then merge
2599                let mut result = self.as_flat().clone();
2600                let other_flat = other.as_flat();
2601                for (k, v) in other_flat.iter() {
2602                    result.insert(*k, v.clone());
2603                }
2604                census::made(&census::ATTRS_MADE, &census::ATTRS_LIVE);
2605                NixAttrs(AttrsInner::Flat(result), None)
2606            }
2607        }
2608    }
2609}
2610
2611impl FromIterator<(String, Value)> for NixAttrs {
2612    fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self {
2613        census::made(&census::ATTRS_MADE, &census::ATTRS_LIVE);
2614        NixAttrs(AttrsInner::Flat(iter.into_iter().map(|(k, v)| (intern(&k), v)).collect()), None)
2615    }
2616}
2617
2618impl IntoIterator for NixAttrs {
2619    type Item = (String, Value);
2620    type IntoIter = Box<dyn Iterator<Item = (String, Value)>>;
2621
2622    fn into_iter(self) -> Self::IntoIter {
2623        let flat = self.as_flat().clone();
2624        Box::new(flat.into_iter().map(|(sym, v)| (resolve(sym), v)))
2625    }
2626}
2627
2628/// A closure — lambda + captured environment.
2629///
2630/// Stores rnix AST nodes so we can re-evaluate the body in the captured env.
2631///
2632/// The environment is `Rc`-wrapped so that cloning a closure (e.g., once per
2633/// element in `map`/`filter`) is a refcount bump instead of a deep copy of the
2634/// entire binding map.
2635#[derive(Debug, Clone)]
2636pub struct Closure {
2637    pub param: rnix::ast::Param,
2638    pub body: rnix::ast::Expr,
2639    pub env: Env,
2640}
2641
2642/// The function signature stored inside a [`BuiltinFn`].
2643pub type BuiltinFunc = dyn Fn(&[Value]) -> Result<Value, EvalError>;
2644
2645/// A builtin function.
2646///
2647/// Not `Send`/`Sync` because `Value` contains rnix AST nodes (rowan `SyntaxNode`)
2648/// which use `NonNull` internally. The evaluator is single-threaded.
2649#[derive(Clone)]
2650pub struct BuiltinFn {
2651    /// Name used for display and debug printing.
2652    pub name: &'static str,
2653    /// The implementation closure.
2654    pub func: Rc<BuiltinFunc>,
2655}
2656
2657impl fmt::Debug for BuiltinFn {
2658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2659        write!(f, "<builtin {}>", self.name)
2660    }
2661}
2662
2663/// A `with` scope with optional cached forced attrset.
2664///
2665/// On first lookup, the scope value is forced and the resulting attrset
2666/// is cached.  Subsequent lookups skip forcing entirely.
2667///
2668/// The cache is wrapped in `Rc<RefCell<…>>` so that child environments
2669/// (which clone the `Vec<WithScope>`) share the same cache cell —
2670/// once any environment forces a scope, every related environment
2671/// benefits.
2672#[derive(Clone)]
2673struct WithScope {
2674    value: Value,
2675    /// Cached forced attrset.  Shared via Rc so child environments
2676    /// benefit from a parent having already forced the scope.
2677    cached: Rc<RefCell<Option<NixAttrs>>>,
2678}
2679
2680impl fmt::Debug for WithScope {
2681    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2682        f.debug_struct("WithScope")
2683            .field("value", &self.value)
2684            .field("cached", &self.cached.borrow().is_some())
2685            .finish()
2686    }
2687}
2688
2689/// Inner data for an evaluation environment.
2690///
2691/// Wrapped in `Rc` by [`Env`] so that cloning an `Env` is always a
2692/// refcount bump — never a deep copy of the binding map.
2693///
2694/// Uses a flattened `FxHashMap` for bindings: `child()` clones
2695/// the parent's map with O(1) structural sharing instead of building
2696/// a linked parent chain. Lookups are a single O(log32 n) probe
2697/// instead of walking a chain.
2698#[derive(Debug, Clone, Default)]
2699struct EnvInner {
2700    bindings: FxHashMap<Symbol, Value>,
2701    /// Dynamic `with` scopes, innermost last.
2702    with_scopes: Vec<WithScope>,
2703    /// Source file currently being evaluated, for relative path
2704    /// literals (`./foo.nix`) inside function defaults that get
2705    /// evaluated *after* control has left the file scope.
2706    eval_file: Option<std::path::PathBuf>,
2707    /// The `source_id` of the parse tree this env belongs to. Restored
2708    /// on thunk force (in lockstep with `eval_file`) so a lazily-forced
2709    /// thunk's idents key `IDENT_CACHE` against the file where the thunk
2710    /// was DEFINED, not the ambient source at force time. Without this, a
2711    /// cross-file force collides on `(source_id, text_offset)` and returns
2712    /// a wrong Symbol (the `parse.nix` `cannot select from null` bug).
2713    source_id: u32,
2714}
2715
2716/// Evaluation environment — flattened binding map with structural sharing.
2717///
2718/// Internally an `Rc<EnvInner>`, so cloning is always O(1) (refcount
2719/// bump).  `child()` clones the `FxHashMap` (O(1) structural
2720/// sharing) instead of building a parent chain.  `bind()` uses
2721/// `Rc::make_mut` for copy-on-write: if the Rc is shared, only then
2722/// does it clone the inner data.
2723#[derive(Clone, Default)]
2724pub struct Env(Rc<EnvInner>);
2725
2726impl fmt::Debug for Env {
2727    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2728        self.0.fmt(f)
2729    }
2730}
2731
2732/// Decrements `ENV_LIVE` so the census reports a live COUNT rather than a
2733/// monotonic total. One relaxed atomic, and only when `SUI_LIVE_CENSUS=1` —
2734/// `census::dropped` checks `enabled()` first.
2735///
2736/// `EnvInner` derives `Clone`, so a clone is a NEW allocation and must be
2737/// counted; `Env` itself is `Rc`-cloned and must not be. That is why the
2738/// increments sit in `Env::new`/`Env::child` (the two `Rc::new(EnvInner …)`
2739/// sites) rather than in a `Clone` impl.
2740impl Drop for EnvInner {
2741    fn drop(&mut self) {
2742        census::dropped(&census::ENV_LIVE);
2743    }
2744}
2745
2746impl Env {
2747    /// Create a root environment with no bindings.
2748    #[must_use]
2749    pub fn new() -> Self {
2750        census::made(&census::ENV_MADE, &census::ENV_LIVE);
2751        Self(Rc::new(EnvInner {
2752            bindings: FxHashMap::default(),
2753            with_scopes: Vec::new(),
2754            eval_file: None,
2755            source_id: 0,
2756        }))
2757    }
2758
2759    /// Create a child environment that inherits from this one.
2760    ///
2761    /// O(1) — the `FxHashMap` clone is structural sharing (refcount
2762    /// bump on internal tree nodes), not a deep copy.
2763    #[must_use]
2764    pub fn child(&self) -> Self {
2765        crate::perf::inc(crate::perf::Counter::EnvClone);
2766        // `ENV_MADE`/`ENV_LIVE` existed but nothing ever incremented them, so
2767        // `census dump` reported `env_live=0 env_made=0` — and `Env` is the
2768        // leading suspect for sui's 12.3x footprint over CppNix, since every
2769        // suspended thunk holds one and nixpkgs makes them constantly. The one
2770        // structure most worth counting was the one the census could not see.
2771        census::made(&census::ENV_MADE, &census::ENV_LIVE);
2772        Self(Rc::new(EnvInner {
2773            bindings: self.0.bindings.clone(), // O(1) structural sharing
2774            with_scopes: self.0.with_scopes.clone(),
2775            // Children inherit the parent's eval file so that
2776            // path literals nested deep in let-chains still
2777            // resolve against the right directory.
2778            eval_file: self.0.eval_file.clone(),
2779            // Children inherit the parent's source_id — a child scope is
2780            // in the same parse tree as its parent (a new source_id only
2781            // arises on `eval_with_file` for an imported file).
2782            source_id: self.0.source_id,
2783        }))
2784    }
2785
2786    /// Attach a `with` scope to this environment.
2787    ///
2788    /// If the value is a thunk that's ALREADY evaluated (OnceCell cache hit),
2789    /// pre-populate the with-scope cache immediately. This avoids creating
2790    /// deferred WithIdent thunks when the fixpoint is already resolved —
2791    /// critical for the overlay chain where multiple stages access the same
2792    /// fixpoint through different `with self;` scopes.
2793    #[must_use]
2794    pub fn with_scope(mut self, value: Value) -> Self {
2795        // Pre-populate cache if the value is already resolved
2796        let pre_cached = match &value {
2797            Value::Attrs(attrs) => Some((**attrs).clone()),
2798            Value::Thunk(thunk) => thunk.peek().and_then(|v| {
2799                if let Concrete::Attrs(attrs) = v { Some((**attrs).clone()) } else { None }
2800            }),
2801            _ => None,
2802        };
2803        Rc::make_mut(&mut self.0).with_scopes.push(WithScope {
2804            value,
2805            cached: Rc::new(RefCell::new(pre_cached)),
2806        });
2807        self
2808    }
2809
2810    /// Bind a name to a value in this environment's own scope.
2811    ///
2812    /// Uses copy-on-write: if the inner `Rc` is shared, clones the
2813    /// inner data before mutating.
2814    pub fn bind(&mut self, name: String, value: Value) {
2815        Rc::make_mut(&mut self.0).bindings.insert(intern(&name), value);
2816    }
2817
2818    /// Bind many names in ONE copy-on-write step: a single `Rc::make_mut` on the
2819    /// inner env, then N inserts on the owned map — instead of N successive
2820    /// `bind()` calls each re-borrowing + re-`make_mut`-ing `self.0`.
2821    ///
2822    /// Byte-identical to calling [`bind`](Self::bind) once per pair in the same
2823    /// order (same `intern`, same insert sequence, same final HAMT) — a byte-SAFE
2824    /// `RedundantWrite`-class optimization: it removes intermediate re-borrows,
2825    /// not any observable value. Consumed by pattern-lambda binding (`bind_param`),
2826    /// where an N-formal pattern otherwise pays N `make_mut` refcount checks.
2827    pub fn bind_many(&mut self, pairs: impl IntoIterator<Item = (String, Value)>) {
2828        let inner = Rc::make_mut(&mut self.0);
2829        for (name, value) in pairs {
2830            inner.bindings.insert(intern(&name), value);
2831        }
2832    }
2833
2834    /// Get the eval_file for this environment.
2835    #[must_use]
2836    pub fn eval_file(&self) -> Option<&std::path::PathBuf> {
2837        self.0.eval_file.as_ref()
2838    }
2839
2840    /// Set the eval_file for this environment.
2841    pub fn set_eval_file(&mut self, file: Option<std::path::PathBuf>) {
2842        Rc::make_mut(&mut self.0).eval_file = file;
2843    }
2844
2845    /// The `source_id` of the parse tree this env belongs to (0 = top level).
2846    #[must_use]
2847    pub fn source_id(&self) -> u32 {
2848        self.0.source_id
2849    }
2850
2851    /// Set the `source_id` for this environment (called by `eval_with_file`
2852    /// for an imported parse tree).
2853    pub fn set_source_id(&mut self, id: u32) {
2854        Rc::make_mut(&mut self.0).source_id = id;
2855    }
2856
2857    /// Number of direct bindings in this environment (debug).
2858    #[must_use]
2859    pub fn binding_count(&self) -> usize {
2860        self.0.bindings.len()
2861    }
2862
2863    /// First N binding names (debug).
2864    #[must_use]
2865    pub fn binding_names_preview(&self, n: usize) -> Vec<String> {
2866        self.0.bindings.keys().take(n).map(|s| resolve(*s)).collect()
2867    }
2868
2869    /// Number of `with` scopes (debug).
2870    #[must_use]
2871    pub fn with_scope_count(&self) -> usize {
2872        self.0.with_scopes.len()
2873    }
2874
2875    /// Lookup in LEXICAL scope only (no with-scopes).
2876    /// Used by maybe_thunk to avoid forcing with-scope fixpoints during
2877    /// attrset construction.
2878    #[must_use]
2879    pub fn lookup_lexical(&self, name: &str) -> Option<Value> {
2880        let sym = intern(name);
2881        self.0.bindings.get(&sym).cloned()
2882    }
2883
2884    /// Lookup in LEXICAL scope only, by pre-interned [`Symbol`] — the
2885    /// Symbol-keyed sibling of [`lookup_lexical`](Self::lookup_lexical).
2886    ///
2887    /// Probes ONLY the lexical `bindings` map (the first thing
2888    /// [`lookup_fast`](Self::lookup_fast) does, by the same Symbol) — never
2889    /// the `with`-chain. The ENV-RESOLVE M0 fast path uses this: a
2890    /// `Resolution::Lexical{sym}` reference probes here directly with its
2891    /// precomputed Symbol; on a hit the returned value is byte-identical to
2892    /// `lookup_fast`'s (same map, same Symbol); on a miss the caller falls
2893    /// back to today's exact runtime path.
2894    #[must_use]
2895    pub fn lookup_lexical_sym(&self, sym: Symbol) -> Option<Value> {
2896        self.0.bindings.get(&sym).cloned()
2897    }
2898
2899    /// Look up a name using ONLY with-scope caches (no forcing).
2900    /// Returns Some if the name is in a cached with-scope, None otherwise.
2901    /// Used by maybe_thunk to resolve with-scope idents without forcing fixpoints.
2902    #[must_use]
2903    pub fn lookup_with_cache_only(&self, name: &str) -> Option<Value> {
2904        for scope in self.0.with_scopes.iter().rev() {
2905            let cache = scope.cached.borrow();
2906            if let Some(ref attrs) = *cache {
2907                if let Some(v) = attrs.get(name) {
2908                    return Some(v.clone());
2909                }
2910            }
2911            // Also check if the thunk is already evaluated (peek)
2912            drop(cache);
2913            if let Value::Thunk(ref thunk) = scope.value {
2914                if let Some(cached_val) = thunk.peek() {
2915                    if let Concrete::Attrs(ref attrs) = *cached_val {
2916                        // Populate the with-scope cache for future lookups
2917                        *scope.cached.borrow_mut() = Some((**attrs).clone());
2918                        if let Some(v) = attrs.get(name) {
2919                            return Some(v.clone());
2920                        }
2921                    }
2922                }
2923            } else if let Value::Attrs(ref attrs) = scope.value {
2924                *scope.cached.borrow_mut() = Some((**attrs).clone());
2925                if let Some(v) = attrs.get(name) {
2926                    return Some(v.clone());
2927                }
2928            }
2929        }
2930        None
2931    }
2932
2933    /// Get the innermost with-scope's cache and value for creating WithIdent thunks.
2934    /// Returns None if there are no with-scopes.
2935    #[must_use]
2936    pub fn innermost_with_scope(&self) -> Option<(Rc<RefCell<Option<NixAttrs>>>, Value)> {
2937        self.0.with_scopes.last().map(|scope| {
2938            (scope.cached.clone(), scope.value.clone())
2939        })
2940    }
2941
2942    /// Lookup matching Nix semantics:
2943    ///
2944    /// 1. Probe the flattened binding map (single O(log32 n) lookup).
2945    ///    Any explicit `let`/`rec`/function-arg binding wins over every
2946    ///    `with` scope.
2947    /// 2. If no lexical binding matched, iterate `with_scopes` in
2948    ///    reverse order (innermost first). So `with X; with Y; x`
2949    ///    finds `x` in Y if Y has it, otherwise in X.
2950    #[must_use]
2951    pub fn lookup(&self, name: &str) -> Option<Value> {
2952        self.lookup_fast(intern(name), name)
2953    }
2954
2955    /// Cache-BYPASSING with-scope lookup: force each `with`-scope value FRESH
2956    /// (through the full thunk chain) and check for `name`, refreshing the
2957    /// per-scope cache on the way. A force that errors (a mid-fixpoint blackhole
2958    /// or a `with (throw …); …` namespace) is caught and the scope skipped.
2959    ///
2960    /// This exists ONLY for the last-ditch retry on the about-to-throw
2961    /// `UndefinedVar` path (see the WithIdent force): the normal cache-first
2962    /// [`lookup_fast`] can trust a stale mid-fixpoint PARTIAL cached for a scope
2963    /// (e.g. `f self` before makeScope merged `callPackage` into `self`) and skip
2964    /// it; a fresh force sees the now-completed scope. Never call this on a hot
2965    /// path — it re-forces every scope.
2966    #[must_use]
2967    pub fn lookup_fresh(&self, name: &str) -> Option<Value> {
2968        let sym = intern(name);
2969        if let Some(v) = self.0.bindings.get(&sym) {
2970            return Some(v.clone());
2971        }
2972        for scope in self.0.with_scopes.iter().rev() {
2973            if let Ok(Value::Attrs(attrs)) = crate::eval::force_value(&scope.value) {
2974                if let Some(v) = attrs.get_sym(&sym) {
2975                    // Refresh the stale cache with the completed scope so a later
2976                    // lookup of a sibling name also sees it.
2977                    *scope.cached.borrow_mut() = Some((*attrs).clone());
2978                    return Some(v.clone());
2979                }
2980            }
2981        }
2982        None
2983    }
2984
2985    /// Lookup by pre-interned Symbol + string name. Avoids re-interning.
2986    #[must_use]
2987    pub fn lookup_fast(&self, sym: Symbol, name: &str) -> Option<Value> {
2988        crate::perf::inc(crate::perf::Counter::EnvLookup);
2989        if let Some(v) = self.0.bindings.get(&sym) {
2990            return Some(v.clone());
2991        }
2992        // 2. With-scope lookup — iterate innermost-first (reverse order).
2993        for scope in self.0.with_scopes.iter().rev() {
2994            // Fast path: use cached forced attrset
2995            {
2996                let cache = scope.cached.borrow();
2997                if let Some(ref attrs) = *cache {
2998                    if let Some(v) = attrs.get_sym(&sym) {
2999                        return Some(v.clone());
3000                    }
3001                    continue;
3002                }
3003            }
3004            // Slow path: force, cache, then check.
3005            // If the value is already concrete (not a thunk), use it directly.
3006            // If it's a thunk, try to force. On blackhole (fixpoint being
3007            // computed), return None so the caller can defer.
3008            let resolved = match &scope.value {
3009                Value::Attrs(attrs) => {
3010                    // Already concrete — cache and use directly
3011                    crate::perf::inc(crate::perf::Counter::WithScopeCacheClone);
3012                    *scope.cached.borrow_mut() = Some((**attrs).clone());
3013                    Some((**attrs).clone())
3014                }
3015                Value::Thunk(thunk) => {
3016                    // Check if the thunk is already evaluated (OnceCell cache)
3017                    // without entering the force state machine
3018                    if let Some(cached_val) = thunk.peek() {
3019                        if let Concrete::Attrs(ref attrs) = *cached_val {
3020                            crate::perf::inc(crate::perf::Counter::WithScopeCacheClone);
3021                            *scope.cached.borrow_mut() = Some((**attrs).clone());
3022                            Some((**attrs).clone())
3023                        } else {
3024                            None
3025                        }
3026                    } else {
3027                        // Thunk not yet evaluated — force it FULLY. Must use
3028                        // `force_value` (which chases the whole thunk chain),
3029                        // NOT `force_value_tracked` (single `force_thunk` step):
3030                        // a with-scope head like `lib.platforms` is often a
3031                        // lazy `Thunk(Thunk(Attrs))`, so one step yields a
3032                        // `Value::Thunk` whose `type_name()` peeks to "set" but
3033                        // which the `if let Value::Attrs` match REJECTS — the
3034                        // scope is then wrongly skipped and every bare-ident
3035                        // lookup through it (`with lib.platforms; unix`) fails
3036                        // with a spurious UndefinedVar.
3037                        match crate::eval::force_value(&scope.value) {
3038                            Ok(forced) => {
3039                                if let Value::Attrs(ref attrs) = forced {
3040                                    crate::perf::inc(crate::perf::Counter::WithScopeCacheClone);
3041                                    *scope.cached.borrow_mut() = Some((**attrs).clone());
3042                                    Some((**attrs).clone())
3043                                } else {
3044                                    None
3045                                }
3046                            }
3047                            Err(_) => None, // blackhole or other error — skip
3048                        }
3049                    }
3050                }
3051                _ => {
3052                    // Same full-chain force as the Thunk arm above.
3053                    match crate::eval::force_value(&scope.value) {
3054                        Ok(forced) => {
3055                            if let Value::Attrs(ref attrs) = forced {
3056                                crate::perf::inc(crate::perf::Counter::WithScopeCacheClone);
3057                                *scope.cached.borrow_mut() = Some((**attrs).clone());
3058                                Some((**attrs).clone())
3059                            } else {
3060                                None
3061                            }
3062                        }
3063                        Err(_) => None,
3064                    }
3065                }
3066            };
3067            if let Some(ref attrs) = resolved {
3068                if let Some(v) = attrs.get(name) {
3069                    return Some(v.clone());
3070                }
3071            }
3072            // If forcing fails or it's not an attrset, try next scope
3073        }
3074        None
3075    }
3076
3077    /// Look up a binding by pre-interned [`Symbol`].
3078    ///
3079    /// Same semantics as [`lookup`](Self::lookup) but skips the
3080    /// `intern()` call — for use when the caller has already cached
3081    /// the symbol (e.g. via [`intern_cached`]).
3082    #[must_use]
3083    pub fn lookup_sym(&self, sym: Symbol) -> Option<Value> {
3084        crate::perf::inc(crate::perf::Counter::EnvLookup);
3085        // 1. Flat lexical lookup — single O(1) hash + O(log32 n) probe.
3086        if let Some(v) = self.0.bindings.get(&sym) {
3087            return Some(v.clone());
3088        }
3089        // 2. With-scope lookup — iterate innermost-first (reverse order).
3090        for scope in self.0.with_scopes.iter().rev() {
3091            // Fast path: use cached forced attrset
3092            {
3093                let cache = scope.cached.borrow();
3094                if let Some(ref attrs) = *cache {
3095                    if let Some(v) = attrs.get_sym(&sym) {
3096                        return Some(v.clone());
3097                    }
3098                    continue;
3099                }
3100            }
3101            // Slow path: force, cache, then check
3102            if let Ok(forced) = crate::eval::force_value_tracked(&scope.value, "with_scope") {
3103                if let Value::Attrs(ref attrs) = forced {
3104                    let result = attrs.get_sym(&sym).cloned();
3105                    crate::perf::inc(crate::perf::Counter::WithScopeCacheClone);
3106                    *scope.cached.borrow_mut() = Some((**attrs).clone());
3107                    if result.is_some() {
3108                        return result;
3109                    }
3110                }
3111            }
3112            // If forcing fails or it's not an attrset, try next scope
3113        }
3114        None
3115    }
3116}
3117
3118/// Evaluation errors produced by the Nix evaluator.
3119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
3120#[non_exhaustive]
3121pub enum EvalError {
3122    /// A variable was referenced but not bound in scope.
3123    #[error("undefined variable: {0}")]
3124    UndefinedVar(String),
3125    /// A type mismatch or coercion failure.
3126    #[error("type error: {0}")]
3127    TypeError(String),
3128    /// An attribute was selected from a set that does not contain it.
3129    #[error("attribute not found: {0}")]
3130    AttrNotFound(String),
3131    /// A type mismatch with structured expected/got information.
3132    #[error("type error: expected {expected}, got {got}")]
3133    TypeMismatch {
3134        expected: &'static str,
3135        got: &'static str,
3136    },
3137    /// An `assert` expression's condition evaluated to false.
3138    #[error("assertion failed{0}")]
3139    AssertionFailed(String),
3140    /// Integer division by zero.
3141    #[error("division by zero")]
3142    DivisionByZero,
3143    /// Infinite recursion detected (thunk blackhole or eval depth).
3144    #[error("infinite recursion ({0})")]
3145    InfiniteRecursion(String),
3146    /// An I/O error from the host filesystem.
3147    #[error("I/O error: {context}: {message}")]
3148    IoError { context: String, message: String },
3149    /// Explicit `throw` from Nix code — CATCHABLE by `builtins.tryEval`.
3150    #[error("{0}")]
3151    Throw(String),
3152    /// An `abort` from Nix code — UNCATCHABLE (CppNix's `abort`/`builtins.abort`
3153    /// is a hard error `tryEval` does NOT catch, unlike `throw`/`assert`).
3154    /// Verified: `nix eval '(builtins.tryEval (abort "x")).success'` errors.
3155    #[error("{0}")]
3156    Abort(String),
3157    /// A language feature that is not yet implemented.
3158    #[error("not yet implemented: {0}")]
3159    NotImplemented(String),
3160    /// A syntax error in the input expression.
3161    #[error("parse error: {0}")]
3162    ParseError(String),
3163    /// Maximum recursion depth exceeded.
3164    #[error("recursion limit: {0}")]
3165    RecursionLimit(String),
3166}
3167
3168impl EvalError {
3169    /// Convenience constructor for a `TypeError` variant.
3170    #[must_use]
3171    pub fn type_error(msg: impl Into<String>) -> Self {
3172        EvalError::TypeError(msg.into())
3173    }
3174
3175    /// Convenience constructor for a `TypeMismatch` variant.
3176    #[must_use]
3177    pub fn type_mismatch(expected: &'static str, got: &'static str) -> Self {
3178        EvalError::TypeMismatch { expected, got }
3179    }
3180
3181    /// Create a type error for a builtin argument type mismatch.
3182    #[must_use]
3183    pub fn builtin_type(builtin: &str, expected: &str, got: &str) -> Self {
3184        EvalError::TypeError(format!("{builtin}: expected {expected}, got {got}"))
3185    }
3186
3187    /// Create a type error for a binary operator type mismatch.
3188    ///
3189    /// CARRIES THE EVAL FILE (added 2026-07-20). Every arithmetic/comparison
3190    /// raise site routes through here, and none of them appended
3191    /// `eval_file_ctx()` — unlike the ~12 sibling raise sites in `eval.rs` that
3192    /// do — so an operator type error named no file at all. Nor could the frame
3193    /// stack help: `NixTraceGuard::drop` pops every frame during unwind, so by
3194    /// the time the error surfaces `attach_trace` has nothing left to attach.
3195    ///
3196    /// The cost of that was concrete. "cannot add string and null" was the sole
3197    /// symptom of the ident-cache aliasing bug that stopped sui evaluating
3198    /// nixpkgs, and it pointed nowhere: four parallel investigations each spent
3199    /// most of their budget just locating it, and the only tool that worked was
3200    /// `SUI_TRACE_EVAL=1` dumping 521k lines to be read backwards. One
3201    /// `format!` argument here would have named `make-derivation.nix`
3202    /// immediately.
3203    ///
3204    /// Fixing it in `op_type` rather than at the `Add` arm means every operator
3205    /// — add, sub, mul, div, comparison, update — gains the context at once,
3206    /// instead of the next one to bite us needing its own patch.
3207    #[must_use]
3208    pub fn op_type(op: &str, lhs: &str, rhs: &str) -> Self {
3209        EvalError::TypeError(format!(
3210            "cannot {op} {lhs} and {rhs}{}",
3211            crate::eval::eval_file_ctx()
3212        ))
3213    }
3214
3215    /// Whether this error was caused by `throw` or `abort`.
3216    #[must_use]
3217    pub fn is_throw(&self) -> bool {
3218        matches!(self, EvalError::Throw(_))
3219    }
3220
3221    /// Whether this error is an infinite recursion.
3222    #[must_use]
3223    pub fn is_infinite_recursion(&self) -> bool {
3224        matches!(self, EvalError::InfiniteRecursion(_))
3225    }
3226}
3227
3228impl Value {
3229    /// Convenience constructor for a context-free string.
3230    #[must_use]
3231    pub fn string(s: impl Into<SmolStr>) -> Self {
3232        Value::String(Rc::new(NixString::plain(s)))
3233    }
3234
3235    /// Convenience constructor that wraps a `Vec<Value>` in `Rc` for the
3236    /// `List` variant.
3237    #[must_use]
3238    pub fn list(items: Vec<Value>) -> Self {
3239        Value::List(Rc::new(NixList::new(items)))
3240    }
3241
3242    /// True when `self` is a `List` whose backing `Rc<Vec>` is uniquely owned
3243    /// (refcount 1). Used by [`concat_lists`] to decide the in-place fast path.
3244    #[must_use]
3245    pub fn is_uniquely_owned_list(&self) -> bool {
3246        matches!(self, Value::List(rc) if Rc::strong_count(rc) == 1)
3247    }
3248
3249    /// Convert a value to JSON for API output.
3250    #[must_use]
3251    pub fn to_json(&self) -> serde_json::Value {
3252        match self {
3253            Value::Null => serde_json::Value::Null,
3254            Value::Bool(b) => serde_json::Value::Bool(*b),
3255            Value::Int(n) => serde_json::json!(n),
3256            Value::Float(f) => serde_json::json!(f),
3257            Value::String(s) => serde_json::Value::String(s.chars.to_string()),
3258            Value::Path(p) => serde_json::Value::String(p.to_string()),
3259            Value::List(items) => {
3260                serde_json::Value::Array(items.iter().map(|v| v.to_json()).collect())
3261            }
3262            Value::Attrs(attrs) => {
3263                // nix-faithful (CppNix value-to-json.cc `tryAttrsToString`):
3264                // a derivation — an attrset carrying `__toString` or `outPath`
3265                // — serializes to THAT STRING, never its own attrs. Without
3266                // this, `to_json` recurses forever on the self-referential
3267                // derivation graph (`drv.out.drv == drv`, `drv.all`, …) and
3268                // overflows the stack. Mirrors `coerce_to_string` below.
3269                if attrs.get("__toString").is_some() || attrs.get("outPath").is_some() {
3270                    if let Ok((s, _ctx)) = self.coerce_to_string() {
3271                        return serde_json::Value::String(s);
3272                    }
3273                }
3274                let map: serde_json::Map<String, serde_json::Value> = attrs
3275                    .iter()
3276                    .map(|(k, v)| (k.clone(), v.to_json()))
3277                    .collect();
3278                serde_json::Value::Object(map)
3279            }
3280            Value::Lambda(_) => serde_json::Value::String("<lambda>".to_string()),
3281            Value::Builtin(b) => serde_json::Value::String(format!("<builtin {}>", b.name)),
3282            Value::Thunk(thunk) => {
3283                // Force the thunk for JSON conversion.
3284                match thunk.force(&|expr, env| crate::eval::eval_expr(expr, env)) {
3285                    Ok(v) => v.to_json(),
3286                    Err(_) => serde_json::Value::String("<thunk:error>".to_string()),
3287                }
3288            }
3289        }
3290    }
3291
3292    /// Like [`Self::to_json`], but **refuses** where that one emits a
3293    /// placeholder.
3294    ///
3295    /// `to_json` renders a lambda as the string `"<lambda>"`, a builtin as
3296    /// `"<builtin name>"`, and — worst — a thunk whose force FAILED as
3297    /// `"<thunk:error>"`. All three produce valid JSON and let the caller exit
3298    /// 0. Measured against nix 2.31.5:
3299    ///
3300    /// ```text
3301    /// nix eval --json --expr '{ f = x: x; }'        exit 1
3302    /// sui eval --json -E    '{ f = x: x; }'         exit 0  {"f":"<lambda>"}
3303    /// nix eval --json --expr '{ x = throw "boom"; }' exit 1
3304    /// sui eval --json -E    '{ x = throw "boom"; }'  exit 0  {"x":"<thunk:error>"}
3305    /// ```
3306    ///
3307    /// The last one is the sharpest silent divergence in the CLI: a real
3308    /// evaluation error becomes a VALUE, and a consumer parsing that JSON sees
3309    /// a string where nix would have refused outright.
3310    ///
3311    /// `to_json` itself is deliberately left alone. It is the body of
3312    /// `builtins.toJSON`, whose placeholder behaviour is load-bearing for the
3313    /// existing corpus, and changing it would be a language-semantics change
3314    /// rather than a CLI fix. This variant is for OUTPUT BOUNDARIES — where a
3315    /// human or a script reads the result and an exit code is the contract.
3316    ///
3317    /// # Errors
3318    ///
3319    /// A function, a builtin, or a thunk whose force fails. The force error is
3320    /// propagated verbatim so the operator sees the `throw`'s own message
3321    /// rather than a generic refusal.
3322    pub fn try_to_json(&self) -> Result<serde_json::Value, EvalError> {
3323        Ok(match self {
3324            Value::Null => serde_json::Value::Null,
3325            Value::Bool(b) => serde_json::Value::Bool(*b),
3326            Value::Int(n) => serde_json::json!(n),
3327            Value::Float(f) => serde_json::json!(f),
3328            Value::String(s) => serde_json::Value::String(s.chars.to_string()),
3329            Value::Path(p) => serde_json::Value::String(p.to_string()),
3330            Value::List(items) => {
3331                let mut out = Vec::with_capacity(items.len());
3332                for v in items.iter() {
3333                    out.push(v.try_to_json()?);
3334                }
3335                serde_json::Value::Array(out)
3336            }
3337            Value::Attrs(attrs) => {
3338                // Mirror `to_json`'s CppNix `tryAttrsToString` rule: an attrset
3339                // carrying `__toString` or `outPath` serializes to that string.
3340                // Dropping it here would not merely change the output, it would
3341                // recurse forever on the self-referential derivation graph —
3342                // the reason that rule exists in `to_json` at all.
3343                if let Some(v) = attrs.get("outPath").or_else(|| attrs.get("__toString")) {
3344                    return v.try_to_json();
3345                }
3346                let mut map = serde_json::Map::new();
3347                for (k, v) in attrs.iter() {
3348                    map.insert(k.clone(), v.try_to_json()?);
3349                }
3350                serde_json::Value::Object(map)
3351            }
3352            Value::Lambda(_) => {
3353                return Err(EvalError::TypeError(
3354                    "cannot convert a function to JSON".to_string(),
3355                ))
3356            }
3357            Value::Builtin(b) => {
3358                return Err(EvalError::TypeError(format!(
3359                    "cannot convert a function to JSON (builtin '{}')",
3360                    b.name
3361                )))
3362            }
3363            Value::Thunk(thunk) => {
3364                // Propagate rather than swallow. This arm is the whole point:
3365                // `to_json` turns this error into the string "<thunk:error>".
3366                let forced = thunk.force(&|expr, env| crate::eval::eval_expr(expr, env))?;
3367                forced.try_to_json()?
3368            }
3369        })
3370    }
3371
3372    /// Like [`to_json`] but threads string context into `ctx`. Used by
3373    /// `__structuredAttrs` derivation-env building: a derivation value
3374    /// serializes to its outPath (a store-path string) and its drv reference
3375    /// must flow into the derivation's `inputDrvs`; a bare path is copy-to-store
3376    /// coerced. (`to_json` drops context, which is fine for `builtins.toJSON`
3377    /// but not for building a derivation's `__json`.)
3378    pub fn to_json_with_context(
3379        &self,
3380        ctx: &mut StringContext,
3381    ) -> Result<serde_json::Value, EvalError> {
3382        Ok(match self {
3383            Value::Null => serde_json::Value::Null,
3384            Value::Bool(b) => serde_json::Value::Bool(*b),
3385            Value::Int(n) => serde_json::json!(n),
3386            Value::Float(f) => serde_json::json!(f),
3387            Value::String(s) => {
3388                ctx.merge(&s.context);
3389                serde_json::Value::String(s.chars.to_string())
3390            }
3391            Value::Path(_) => {
3392                let (str, c) = self.coerce_to_string_copy_to_store()?;
3393                ctx.merge(&c);
3394                serde_json::Value::String(str)
3395            }
3396            Value::List(items) => {
3397                let mut arr = Vec::with_capacity(items.len());
3398                for v in items.iter() {
3399                    let fv = crate::eval::force_value(v)?;
3400                    arr.push(fv.to_json_with_context(ctx)?);
3401                }
3402                serde_json::Value::Array(arr)
3403            }
3404            Value::Attrs(attrs) => {
3405                // A derivation (attrset with `outPath`/`__toString`) serializes
3406                // to that string with its context — never its own attrs.
3407                if attrs.get("__toString").is_some() || attrs.get("outPath").is_some() {
3408                    let (s, c) = self.coerce_to_string_copy_to_store()?;
3409                    ctx.merge(&c);
3410                    return Ok(serde_json::Value::String(s));
3411                }
3412                let mut map = serde_json::Map::new();
3413                for (k, v) in attrs.iter() {
3414                    let fv = crate::eval::force_value(v)?;
3415                    map.insert(k.clone(), fv.to_json_with_context(ctx)?);
3416                }
3417                serde_json::Value::Object(map)
3418            }
3419            Value::Thunk(_) => {
3420                let forced = crate::eval::force_value(self)?;
3421                forced.to_json_with_context(ctx)?
3422            }
3423            other => {
3424                return Err(EvalError::TypeError(format!(
3425                    "cannot serialize {} to JSON (__structuredAttrs)",
3426                    other.type_name()
3427                )));
3428            }
3429        })
3430    }
3431
3432    /// Return the Nix type name for this value (e.g. `"int"`, `"set"`).
3433    #[must_use]
3434    pub fn type_name(&self) -> &'static str {
3435        match self {
3436            Value::Null => "null",
3437            Value::Bool(_) => "bool",
3438            Value::Int(_) => "int",
3439            Value::Float(_) => "float",
3440            Value::String(_) => "string",
3441            Value::Path(_) => "path",
3442            Value::List(_) => "list",
3443            Value::Attrs(_) => "set",
3444            Value::Lambda(_) => "lambda",
3445            Value::Builtin(_) => "lambda",
3446            Value::Thunk(thunk) => {
3447                // Force and delegate.
3448                match thunk.force(&|expr, env| crate::eval::eval_expr(expr, env)) {
3449                    Ok(v) => v.type_name(),
3450                    Err(_) => "thunk",
3451                }
3452            }
3453        }
3454    }
3455
3456    // ── Value coercion methods ──────────────────────────────────
3457    //
3458    // Naming conventions:
3459    //
3460    // • `as_*(&self)` — borrow. Returns a reference or Copy type.
3461    //   Primitives (`as_bool`, `as_int`) force thunks transparently
3462    //   because they return owned Copy values. Reference accessors
3463    //   (`as_string`, `as_nix_string`, `as_attrs`, `as_list`) CANNOT
3464    //   force thunks (the forced value is transient and we can't
3465    //   return a borrow into it), so they error on Thunk inputs.
3466    //
3467    // • `to_*(&self)` — clone / force. Returns an owned value and
3468    //   DOES force thunks. Use when the value may be a thunk and you
3469    //   need an owned result. Examples: `to_float`, `to_string`,
3470    //   `to_attrs`, `to_list`.
3471    //
3472    // • `coerce_to_path` — a Nix-specific coercion that accepts both
3473    //   Path and String values (many builtins accept either).
3474
3475    /// Extract a bool, forcing thunks if needed.
3476    pub fn as_bool(&self) -> Result<bool, EvalError> {
3477        match self {
3478            Value::Bool(b) => Ok(*b),
3479            Value::Thunk(thunk) => {
3480                thunk.force(&|e, env| crate::eval::eval_expr(e, env))?.as_bool()
3481            }
3482            // M2.6 Promise softening: coercion of a sentinel to bool
3483            // inside a fix-point body returns false (the cheapest sentinel
3484            // that lets `if x then … else …` take the else branch).
3485            _ if in_promise_eval() => Ok(false),
3486            _ => Err(EvalError::TypeMismatch { expected: "bool", got: self.type_name() }),
3487        }
3488    }
3489
3490    /// Extract an integer, forcing thunks if needed.
3491    pub fn as_int(&self) -> Result<i64, EvalError> {
3492        match self {
3493            Value::Int(n) => Ok(*n),
3494            Value::Thunk(thunk) => {
3495                thunk.force(&|e, env| crate::eval::eval_expr(e, env))?.as_int()
3496            }
3497            // M2.6 Promise softening: coercion of a sentinel to int
3498            // returns 0.
3499            _ if in_promise_eval() => Ok(0),
3500            _ => Err(EvalError::TypeMismatch { expected: "int", got: self.type_name() }),
3501        }
3502    }
3503
3504    /// Borrow the string content without forcing thunks.
3505    pub fn as_string(&self) -> Result<&str, EvalError> {
3506        match self {
3507            Value::String(s) => Ok(&s.chars),
3508            Value::Thunk(_) => Err(EvalError::TypeError(
3509                "thunk in as_string: force first via force_value()".into(),
3510            )),
3511            _ if in_promise_eval() => Ok(""),
3512            _ => Err(EvalError::TypeMismatch { expected: "string", got: self.type_name() }),
3513        }
3514    }
3515
3516    /// Return a reference to the full `NixString` (with context).
3517    pub fn as_nix_string(&self) -> Result<&NixString, EvalError> {
3518        match self {
3519            Value::String(ns) => Ok(ns),
3520            Value::Thunk(_) => Err(EvalError::TypeError(
3521                "thunk in as_nix_string: force first via force_value()".into(),
3522            )),
3523            _ => Err(EvalError::TypeMismatch { expected: "string", got: self.type_name() }),
3524        }
3525    }
3526
3527    /// Force-aware string extraction. Returns an owned String by forcing
3528    /// thunks if needed. Use this instead of `as_string()` when you may
3529    /// be operating on thunked attrset values.
3530    pub fn to_str(&self) -> Result<String, EvalError> {
3531        match self {
3532            Value::String(s) => Ok(s.chars.to_string()),
3533            Value::Thunk(thunk) => {
3534                let forced = thunk.force(&|e, env| crate::eval::eval_expr(e, env))?;
3535                forced.to_str()
3536            }
3537            _ if in_promise_eval() => Ok(String::new()),
3538            _ => Err(EvalError::TypeMismatch { expected: "string", got: self.type_name() }),
3539        }
3540    }
3541
3542    /// Force-aware `NixString` extraction. Returns an owned `NixString`
3543    /// (with context) by forcing thunks if needed.
3544    pub fn to_nix_string(&self) -> Result<NixString, EvalError> {
3545        match self {
3546            Value::String(s) => Ok((**s).clone()),
3547            Value::Thunk(thunk) => {
3548                let forced = thunk.force(&|e, env| crate::eval::eval_expr(e, env))?;
3549                forced.to_nix_string()
3550            }
3551            _ if in_promise_eval() => Ok(NixString::plain("")),
3552            _ => Err(EvalError::TypeMismatch { expected: "string", got: self.type_name() }),
3553        }
3554    }
3555
3556    /// Borrow the inner attrs without forcing. If the value is a
3557    /// thunk, the caller should have force_value'd it first; we
3558    /// return an error rather than silently mutating the thunk
3559    /// (which would require &mut self).
3560    ///
3561    /// Most call sites should use `to_attrs()` (which forces and
3562    /// clones) unless they're certain the value is already
3563    /// concrete and want to avoid the clone.
3564    pub fn as_attrs(&self) -> Result<&NixAttrs, EvalError> {
3565        match self {
3566            Value::Attrs(a) => Ok(a),
3567            Value::Thunk(_) => Err(EvalError::TypeError(
3568                "thunk in as_attrs: force first via force_value() or use to_attrs()".into(),
3569            )),
3570            _ => Err(EvalError::TypeMismatch { expected: "set", got: self.type_name() }),
3571        }
3572    }
3573
3574    /// Borrow the list content without forcing thunks.
3575    pub fn as_list(&self) -> Result<&[Value], EvalError> {
3576        match self {
3577            Value::List(l) => Ok(l.as_slice()),
3578            Value::Thunk(_) => Err(EvalError::TypeError(
3579                "thunk in as_list: force first via force_value()".into(),
3580            )),
3581            _ => Err(crate::eval::attach_trace(
3582                EvalError::TypeMismatch { expected: "list", got: self.type_name() }
3583            )),
3584        }
3585    }
3586
3587    /// Force-aware attrs extraction. Forces the value if it is a thunk.
3588    pub fn to_attrs(&self) -> Result<NixAttrs, EvalError> {
3589        match self {
3590            Value::Attrs(a) => Ok((**a).clone()),
3591            Value::Thunk(thunk) => {
3592                let forced = thunk.force(&|e, env| crate::eval::eval_expr(e, env))?;
3593                forced.to_attrs()
3594            }
3595            // M2.6 Promise softening: a coercion of null (or any
3596            // non-attrset sentinel) to an attrset inside a fix-point
3597            // body returns an empty attrset, so downstream builtins
3598            // (mapAttrs, attrNames, ...) see "no keys" rather than a
3599            // type error.
3600            _ if in_promise_eval() => Ok(NixAttrs::new()),
3601            _ => Err(EvalError::TypeMismatch { expected: "set", got: self.type_name() }),
3602        }
3603    }
3604
3605    /// Force-aware list extraction. Forces the value if it is a thunk.
3606    pub fn to_list(&self) -> Result<Vec<Value>, EvalError> {
3607        match self {
3608            Value::List(l) => Ok((**l).0.clone()),
3609            Value::Thunk(thunk) => {
3610                let forced = thunk.force(&|e, env| crate::eval::eval_expr(e, env))?;
3611                forced.to_list()
3612            }
3613            // M2.6 Promise softening: coercion of a sentinel to a list
3614            // inside a fix-point body returns an empty list.
3615            _ if in_promise_eval() => Ok(Vec::new()),
3616            _ => Err(EvalError::TypeMismatch { expected: "list", got: self.type_name() }),
3617        }
3618    }
3619
3620    /// Extract a filesystem path from a `Path` or `String` value.
3621    ///
3622    /// Many builtins (`readFile`, `import`, `pathExists`, etc.) accept
3623    /// either `Path` or `String` arguments. This method centralises
3624    /// that coercion so every call-site doesn't repeat the same match.
3625    pub fn coerce_to_path(&self, context: &str) -> Result<String, EvalError> {
3626        match self {
3627            Value::Path(p) => Ok(p.to_string()),
3628            Value::String(ns) => Ok(ns.chars.to_string()),
3629            Value::Attrs(attrs) => {
3630                if let Some(out_path) = attrs.get("outPath") {
3631                    let forced = crate::eval::force_value(out_path)?;
3632                    forced.coerce_to_path(context)
3633                } else {
3634                    Err(EvalError::TypeError(format!(
3635                        "{context}: expected path or string, got set without outPath"
3636                    )))
3637                }
3638            }
3639            _ => Err(EvalError::TypeError(format!(
3640                "{context}: expected path or string, got {}",
3641                self.type_name()
3642            ))),
3643        }
3644    }
3645
3646    /// Coerce to a filesystem path AND, if this value is a **derivation**
3647    /// whose output is not yet materialized on disk, realize that output first
3648    /// (import-from-derivation).
3649    ///
3650    /// Used by the disk-read builtins (`import`, `readFile`, `readDir`,
3651    /// `pathExists`, `builtins.path`) so a read under a derivation's `outPath`
3652    /// triggers a build/substitute of that output, exactly as cppnix does.
3653    ///
3654    /// Semantics:
3655    /// - A `Path`/`String` coerces as usual — no realize (nothing to build).
3656    /// - A derivation attrset (`type == "derivation"` with `drvPath` +
3657    ///   `outPath`) whose `outPath` (after input-source materialization) does
3658    ///   **not** exist on disk invokes the realize hook with `(drvPath,
3659    ///   outPath)`. On success the returned path is the (now-present) `outPath`.
3660    /// - A non-derivation attrset with `outPath` coerces via `outPath` as usual
3661    ///   (no drv to realize).
3662    /// - If no realize hook is installed, this degrades to `coerce_to_path`
3663    ///   (the read that follows will ENOENT — a real error, never a wrong
3664    ///   value).
3665    ///
3666    /// The realize hook mutates no value the evaluator observes; it only makes
3667    /// the bytes at the already-byte-correct `outPath` present on disk (see
3668    /// [`crate::realize`]).
3669    pub fn coerce_to_realized_path(&self, context: &str) -> Result<String, EvalError> {
3670        match self {
3671            // Direct derivation attrset (`import <drv>`): drvPath + outPath are
3672            // right there.
3673            Value::Attrs(attrs) => {
3674                if let Some((drv_path, out_path)) = derivation_drv_and_out(attrs)? {
3675                    self.realize_if_absent(&drv_path, &out_path, context)?;
3676                    return Ok(out_path);
3677                }
3678            }
3679            // A string produced by interpolating a derivation
3680            // (`readFile "${drv}"`) is a store-path STRING that carries a
3681            // `ContextElement::Output { drv, output }` — the derivation-ness
3682            // survives interpolation *as string context*, which is exactly how
3683            // cppnix decides to realize. If the coerced store path is absent and
3684            // the context names the producing `.drv`, realize it.
3685            Value::String(ns) => {
3686                let out_path = ns.chars.to_string();
3687                if let Some(drv_path) = out_path_needs_realize(&out_path, &ns.context) {
3688                    self.realize_if_absent(&drv_path, &out_path, context)?;
3689                }
3690                return Ok(out_path);
3691            }
3692            _ => {}
3693        }
3694        self.coerce_to_path(context)
3695    }
3696
3697    /// If `out_path` (after input-source materialization) is not present on
3698    /// disk, invoke the realize hook to build/substitute `drv_path`. A missing
3699    /// hook is a silent fall-through (the following read ENOENTs — a real error,
3700    /// never a wrong value); a hook error is surfaced as an eval `IoError`.
3701    fn realize_if_absent(
3702        &self,
3703        drv_path: &str,
3704        out_path: &str,
3705        context: &str,
3706    ) -> Result<(), EvalError> {
3707        // The existence probe must consult the REAL tree — a fetched flake
3708        // input's `-source` prefix is redirected — so materialize first.
3709        let read_path = crate::path::materialize_str(out_path);
3710        if std::path::Path::new(&read_path).exists() {
3711            return Ok(());
3712        }
3713        match crate::realize::realize_output(drv_path, out_path) {
3714            Ok(true) | Ok(false) => Ok(()),
3715            Err(msg) => Err(EvalError::IoError {
3716                context: context.to_string(),
3717                message: format!(
3718                    "import-from-derivation: realizing {drv_path} -> {out_path}: {msg}"
3719                ),
3720            }),
3721        }
3722    }
3723
3724    /// Coerce a numeric value to float.
3725    pub fn to_float(&self) -> Result<f64, EvalError> {
3726        match self {
3727            Value::Float(f) => Ok(*f),
3728            Value::Int(n) => Ok(*n as f64),
3729            Value::Thunk(thunk) => {
3730                thunk.force(&|e, env| crate::eval::eval_expr(e, env))?.to_float()
3731            }
3732            _ => Err(EvalError::TypeMismatch { expected: "number", got: self.type_name() }),
3733        }
3734    }
3735
3736    /// Coerce this value to a string following CppNix semantics.
3737    ///
3738    /// This is the single source of truth for string coercion used by
3739    /// string interpolation, `builtins.toString`, and derivation env
3740    /// var construction.
3741    ///
3742    /// Rules (in order):
3743    /// - String → its content (with context)
3744    /// - Path → path string (adds Plain context element)
3745    /// - Int → decimal representation
3746    /// - Float → decimal representation
3747    /// - Bool → "1" for true, "" for false
3748    /// - Null → ""
3749    /// - Attrs with `__toString` → call `__toString(self)` and coerce result
3750    /// - Attrs with `outPath` → coerce outPath recursively
3751    /// - List → space-joined coerced elements
3752    /// - Lambda/Builtin/Thunk → error
3753    pub fn coerce_to_string(&self) -> Result<(String, StringContext), EvalError> {
3754        self.coerce_to_string_impl(false)
3755    }
3756
3757    /// Coerce to string in CppNix **copy-to-store** mode — the coercion used by
3758    /// string interpolation (`"${./foo}"`) and derivation-attribute population.
3759    /// A source path that isn't already in the store is absolutized,
3760    /// canonicalized, required to exist, and NAR-copied into
3761    /// `/nix/store/<hash>-<basename>`; the result string is that store path and
3762    /// it carries store-path context. This is what makes `src = ./.` reference
3763    /// the correct store path (and thus the correct drv hash) instead of a raw
3764    /// filesystem path. `builtins.toString` keeps the plain mode
3765    /// ([`coerce_to_string`]) — it does *not* copy.
3766    pub fn coerce_to_string_copy_to_store(
3767        &self,
3768    ) -> Result<(String, StringContext), EvalError> {
3769        self.coerce_to_string_impl(true)
3770    }
3771
3772    fn coerce_to_string_impl(
3773        &self,
3774        copy_to_store: bool,
3775    ) -> Result<(String, StringContext), EvalError> {
3776        let mut ctx = StringContext::new();
3777        let s = match self {
3778            Value::String(ns) => {
3779                ctx.merge(&ns.context);
3780                ns.chars.to_string()
3781            }
3782            Value::Path(p) => {
3783                let raw: &str = &**p;
3784                if copy_to_store {
3785                    // CppNix copy-to-store coercion: resolve the path to its
3786                    // canonical absolute location (relative literals resolve
3787                    // against the evaluating file's dir, matching CppNix's
3788                    // parse-time absolutization; canonicalize also yields the
3789                    // realpath, e.g. macOS /tmp → /private/tmp), require it to
3790                    // exist (CppNix errors "path '…' does not exist"), NAR-copy
3791                    // it, and reference the resulting store path.
3792                    //
3793                    // A Path VALUE is ALWAYS copied, even one already under
3794                    // /nix/store — CppNix re-NAR-copies a bare path literal
3795                    // (a store subpath like `<nixpkgs-source>/pkgs/…/default-
3796                    // builder.sh` → its own `<hash>-default-builder.sh`, or even
3797                    // a store root) to a fresh basename-named store path,
3798                    // verified against nix 2.34. Store paths that must NOT be
3799                    // re-copied (derivation outputs, fetchurl `src`, storePath)
3800                    // arrive as context-carrying *Strings*, never as Path values,
3801                    // so they never reach this arm. (The earlier `/nix/store/`
3802                    // guard kept stdenv's builder-script subpaths verbatim, which
3803                    // diverged every nixpkgs input-drv hash from nix.)
3804                    let pb = std::path::Path::new(raw);
3805                    let abs = if pb.is_absolute() {
3806                        pb.to_path_buf()
3807                    } else if let Some(dir) = crate::eval::current_eval_dir() {
3808                        dir.join(pb)
3809                    } else {
3810                        std::env::current_dir()
3811                            .map_err(|e| EvalError::IoError {
3812                                context: format!("copy-to-store coercion of {raw}"),
3813                                message: e.to_string(),
3814                            })?
3815                            .join(pb)
3816                    };
3817                    // Redirect the on-disk read to the input's real source
3818                    // tree when `abs` lies under a fetched flake input's
3819                    // `-source` store prefix (sui does not materialize that
3820                    // store path). The resulting store path is NAR-hashed
3821                    // from the tree CONTENT — byte-identical whether read from
3822                    // the store path or the cache — so no value changes.
3823                    let read_abs = crate::path::materialize(&abs);
3824                    let canon = read_abs.canonicalize().map_err(|_| {
3825                        EvalError::TypeError(format!(
3826                            "path '{}' does not exist",
3827                            abs.display()
3828                        ))
3829                    })?;
3830                    // The copied source's STORE-PATH NAME must match CppNix's
3831                    // `baseNameOf` of the input's own `-source` store path when
3832                    // the path being copied IS a fetched flake input's whole
3833                    // tree (the darwin `system-path` root): blx's `src = ./.`
3834                    // copies the blx input tree back into the store, and CppNix
3835                    // names that copy `<inner>-source` (blx's `/nix/store/<h>-
3836                    // source` basename), NOT `blx-<rev>`. sui reads the bytes
3837                    // from the fetcher cache (`canon`, basename `blx-<rev>`), so
3838                    // `canon.file_name()` gave the wrong NAME while the bytes
3839                    // (→ NAR hash) were already correct. Recover the logical
3840                    // `-source` name from the input-source map; fall back to the
3841                    // real dir's basename for a normal local `src = ./.`.
3842                    // `strip_store_hash_prefix`: `canon` may ALREADY be a store
3843                    // path, whose basename is `<hash>-<name>`. Without the strip
3844                    // the copy lands at `<newhash>-<oldhash>-<name>`. See the
3845                    // helper's docs for the measured 2026-08-11 receipt.
3846                    let name = crate::path::source_name_for_read_dir(&canon)
3847                        .or_else(|| {
3848                            canon
3849                                .file_name()
3850                                .map(|n| sui_compat::source::strip_store_hash_prefix(
3851                                    &n.to_string_lossy()).to_string())
3852                        })
3853                        .unwrap_or_else(|| "source".to_string());
3854                    let src = sui_compat::source::nar_hash_source_tree(&canon, &name)
3855                        .map_err(|e| {
3856                            EvalError::TypeError(format!(
3857                                "copy-to-store coercion of '{}': {e}",
3858                                canon.display()
3859                            ))
3860                        })?;
3861                    ctx.add_plain(src.store_path.clone());
3862                    src.store_path
3863                } else {
3864                    ctx.add_plain(raw.to_string());
3865                    raw.to_string()
3866                }
3867            }
3868            Value::Int(n) => n.to_string(),
3869            // CppNix uses C printf "%f" for float → string coercion,
3870            // which always emits 6 decimal places (`1.5` → "1.500000",
3871            // `3.14159` → "3.141590"). Rust's `{}` formatter strips
3872            // trailing zeros. Match CppNix so `lib.strings.floatToString`
3873            // and module-system defaults round-trip identically.
3874            Value::Float(f) => format!("{f:.6}"),
3875            Value::Bool(true) => "1".to_string(),
3876            Value::Bool(false) => String::new(),
3877            Value::Null => String::new(),
3878            Value::Attrs(attrs) => {
3879                if let Some(to_str) = attrs.get("__toString") {
3880                    let result =
3881                        crate::eval::apply(to_str.clone(), Value::Attrs(attrs.clone()))?;
3882                    let forced = crate::eval::force_value(&result)?;
3883                    let (s, c) = forced.coerce_to_string_impl(copy_to_store)?;
3884                    ctx.merge(&c);
3885                    s
3886                } else if let Some(out_path) = attrs.get("outPath") {
3887                    let forced = crate::eval::force_value(out_path)?;
3888                    let (s, c) = forced.coerce_to_string_impl(copy_to_store)?;
3889                    ctx.merge(&c);
3890                    s
3891                } else {
3892                    return Err(EvalError::TypeError(
3893                        "cannot coerce set to string (no __toString or outPath)".into(),
3894                    ));
3895                }
3896            }
3897            Value::List(items) => {
3898                let mut parts = Vec::new();
3899                for item in items.iter() {
3900                    let forced = crate::eval::force_value(item)?;
3901                    let (s, c) = forced.coerce_to_string_impl(copy_to_store)?;
3902                    ctx.merge(&c);
3903                    parts.push(s);
3904                }
3905                parts.join(" ")
3906            }
3907            Value::Thunk(_) => {
3908                // Force thunk then coerce the result.
3909                let forced = crate::eval::force_value(self)?;
3910                let (s, c) = forced.coerce_to_string_impl(copy_to_store)?;
3911                ctx.merge(&c);
3912                s
3913            }
3914            other => {
3915                return Err(EvalError::TypeError(format!(
3916                    "cannot coerce {} to string",
3917                    other.type_name()
3918                )));
3919            }
3920        };
3921        Ok((s, ctx))
3922    }
3923}
3924
3925// ── Conversions from foreign value types ────────────────────
3926
3927impl From<&serde_json::Value> for Value {
3928    fn from(json: &serde_json::Value) -> Self {
3929        match json {
3930            serde_json::Value::Null => Value::Null,
3931            serde_json::Value::Bool(b) => Value::Bool(*b),
3932            serde_json::Value::Number(n) => {
3933                if let Some(i) = n.as_i64() {
3934                    Value::Int(i)
3935                } else {
3936                    Value::Float(n.as_f64().unwrap_or(0.0))
3937                }
3938            }
3939            serde_json::Value::String(s) => Value::string(s.clone()),
3940            serde_json::Value::Array(arr) => {
3941                Value::List(Rc::new(NixList::new(arr.iter().map(Value::from).collect())))
3942            }
3943            serde_json::Value::Object(obj) => {
3944                let mut attrs = NixAttrs::new();
3945                for (k, v) in obj {
3946                    attrs.insert(k.clone(), Value::from(v));
3947                }
3948                Value::Attrs(Rc::new(attrs))
3949            }
3950        }
3951    }
3952}
3953
3954impl From<&toml::Value> for Value {
3955    fn from(v: &toml::Value) -> Self {
3956        match v {
3957            toml::Value::String(s) => Value::string(s.clone()),
3958            toml::Value::Integer(n) => Value::Int(*n),
3959            toml::Value::Float(f) => Value::Float(*f),
3960            toml::Value::Boolean(b) => Value::Bool(*b),
3961            toml::Value::Array(arr) => {
3962                Value::List(Rc::new(NixList::new(arr.iter().map(Value::from).collect())))
3963            }
3964            toml::Value::Table(t) => {
3965                let mut attrs = NixAttrs::new();
3966                for (k, val) in t {
3967                    attrs.insert(k.clone(), Value::from(val));
3968                }
3969                Value::Attrs(Rc::new(attrs))
3970            }
3971            toml::Value::Datetime(dt) => Value::string(dt.to_string()),
3972        }
3973    }
3974}
3975
3976
3977// ── From impls for ergonomic Value construction ─────────────
3978
3979impl From<bool> for Value {
3980    fn from(b: bool) -> Self {
3981        Value::Bool(b)
3982    }
3983}
3984
3985impl From<i64> for Value {
3986    fn from(n: i64) -> Self {
3987        Value::Int(n)
3988    }
3989}
3990
3991impl From<f64> for Value {
3992    fn from(f: f64) -> Self {
3993        Value::Float(f)
3994    }
3995}
3996
3997impl From<NixString> for Value {
3998    fn from(s: NixString) -> Self {
3999        Value::String(Rc::new(s))
4000    }
4001}
4002
4003impl From<NixAttrs> for Value {
4004    fn from(attrs: NixAttrs) -> Self {
4005        Value::Attrs(Rc::new(attrs))
4006    }
4007}
4008
4009impl From<Vec<Value>> for Value {
4010    fn from(list: Vec<Value>) -> Self {
4011        Value::List(Rc::new(NixList::new(list)))
4012    }
4013}
4014
4015impl PartialEq for Value {
4016    fn eq(&self, other: &Self) -> bool {
4017        // Quick path: pointer-equal thunks are always equal.
4018        if let (Value::Thunk(a), Value::Thunk(b)) = (self, other) {
4019            if Rc::ptr_eq(&a.0, &b.0) { return true; }
4020        }
4021        // Force to Concrete, delegate to Concrete::PartialEq.
4022        // Single source of truth — no duplicated comparison logic.
4023        let l = self.demand().unwrap_or(Concrete::Null);
4024        let r = other.demand().unwrap_or(Concrete::Null);
4025        l == r
4026    }
4027}
4028
4029impl fmt::Display for Value {
4030    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4031        match self {
4032            Value::Null => write!(f, "null"),
4033            Value::Bool(b) => write!(f, "{b}"),
4034            Value::Int(n) => write!(f, "{n}"),
4035            Value::Float(n) => write!(f, "{}", sui_compat::versions::cppnix_format_float(*n)),
4036            Value::String(s) => write!(f, "\"{}\"", s.chars.replace('\\', "\\\\").replace('"', "\\\"")),
4037            Value::Path(p) => write!(f, "{p}"),
4038            Value::List(items) => {
4039                write!(f, "[ ")?;
4040                for item in items.iter() {
4041                    write!(f, "{item} ")?;
4042                }
4043                write!(f, "]")
4044            }
4045            Value::Attrs(attrs) => {
4046                write!(f, "{{ ")?;
4047                for (k, v) in attrs.iter() {
4048                    write!(f, "{k} = {v}; ")?;
4049                }
4050                write!(f, "}}")
4051            }
4052            Value::Lambda(_) => write!(f, "<<lambda>>"),
4053            Value::Builtin(b) => write!(f, "<<builtin {}>>" , b.name),
4054            Value::Thunk(thunk) => {
4055                match thunk.force(&|e, env| crate::eval::eval_expr(e, env)) {
4056                    Ok(v) => write!(f, "{v}"),
4057                    Err(_) => write!(f, "<<thunk:error>>"),
4058                }
4059            }
4060        }
4061    }
4062}
4063
4064#[cfg(test)]
4065mod tests {
4066    use super::*;
4067    use std::rc::Rc;
4068
4069    // ── Value size assertion ──────────────────────────────
4070
4071    /// Measures the per-map cost of the persistent HAMT against a flat map at
4072    /// the sizes nixpkgs actually uses. Not an assertion — a measurement, run
4073    /// with `--nocapture`. See docs/COMPLETE-REPLACEMENT.md §V.34.
4074    #[test]
4075    #[ignore = "measurement, not a gate: run with --ignored --nocapture"]
4076    fn measure_hamt_vs_flat_attrset_cost() {
4077        use crate::value::census::rss_bytes;
4078        const N: usize = 300_000;
4079        const ENTRIES: usize = 4; // typical small nixpkgs attrset
4080
4081        let syms: Vec<Symbol> = (0..ENTRIES).map(|i| intern(&format!("k{i}"))).collect();
4082
4083        let base = rss_bytes();
4084        let mut hamts: Vec<FxHashMap<Symbol, Value>> = Vec::with_capacity(N);
4085        for _ in 0..N {
4086            let mut m = FxHashMap::default();
4087            for s in &syms { m.insert(*s, Value::Int(1)); }
4088            hamts.push(m);
4089        }
4090        let after_hamt = rss_bytes();
4091
4092        let mut flats: Vec<std::collections::HashMap<Symbol, Value>> = Vec::with_capacity(N);
4093        for _ in 0..N {
4094            let mut m = std::collections::HashMap::with_capacity(ENTRIES);
4095            for s in &syms { m.insert(*s, Value::Int(1)); }
4096            flats.push(m);
4097        }
4098        let after_flat = rss_bytes();
4099
4100        let hamt_cost = after_hamt.saturating_sub(base);
4101        let flat_cost = after_flat.saturating_sub(after_hamt);
4102        eprintln!("N={N} entries={ENTRIES}");
4103        eprintln!("  im_rc HAMT : {} B total, {} B/map", hamt_cost, hamt_cost / N as u64);
4104        eprintln!("  std flat   : {} B total, {} B/map", flat_cost, flat_cost / N as u64);
4105        if flat_cost > 0 {
4106            eprintln!("  ratio      : {:.2}x", hamt_cost as f64 / flat_cost as f64);
4107        }
4108        std::hint::black_box((&hamts, &flats));
4109    }
4110
4111    #[test]
4112    fn value_is_16_bytes() {
4113        assert_eq!(std::mem::size_of::<Value>(), 16);
4114    }
4115
4116    // ── `//` carries attr positions (regression) ─────────
4117
4118    /// A key's position must survive `//` — from either side, with the RIGHT
4119    /// winning, matching the precedence `//` gives the key's value.
4120    ///
4121    /// Regression: `overlay()` builds its node with an empty position slot, so
4122    /// reading only that slot reported `null` for every key of every `//`
4123    /// result. nixpkgs' `lib.nixosSystem` ends in
4124    /// `{ …; modules = …; } // removeAttrs args [ "modules" ]` and
4125    /// `eval-config.nix:28` reads `unsafeGetAttrPos "modules"` off it to set
4126    /// `modulesLocation`; a null there permutes NixOS definition order and
4127    /// diverges the toplevel drvPath from CppNix.
4128    #[test]
4129    fn overlay_carries_attr_positions_from_both_sides() {
4130        let tbl = |file: &str, key: &str, off: u32| {
4131            let mut t = crate::pos::AttrPositions::new(Some(std::path::PathBuf::from(file)));
4132            t.insert(intern(key), off);
4133            Rc::new(t)
4134        };
4135        // Both operands must be NON-empty: `overlay` short-circuits to the
4136        // other side when either is empty, so an empty operand would never
4137        // build the Overlay node this test exists to walk.
4138        let mk = |file: &str, key: &str, off: u32| {
4139            let mut a = NixAttrs::new();
4140            a.insert(key.to_string(), Value::Int(1));
4141            a.set_positions(tbl(file, key, off));
4142            a
4143        };
4144
4145        // Key only on the LEFT — the shape nixosSystem actually hits, since
4146        // `removeAttrs args [ "modules" ]` strips it from the right.
4147        let left_only = mk("/l.nix", "modules", 11).overlay(mk("/r.nix", "other", 22));
4148        assert_eq!(
4149            left_only.pos_entry(intern("modules")),
4150            Some((Some(std::path::PathBuf::from("/l.nix")), 11)),
4151        );
4152
4153        // Key on BOTH sides — right wins, as it does for the value.
4154        let both = mk("/l.nix", "modules", 11).overlay(mk("/r.nix", "modules", 22));
4155        assert_eq!(
4156            both.pos_entry(intern("modules")),
4157            Some((Some(std::path::PathBuf::from("/r.nix")), 22)),
4158        );
4159
4160        // Absent key stays absent — the walk must not invent a position.
4161        assert_eq!(both.pos_entry(intern("nope")), None);
4162    }
4163
4164    // ── Value::to_json for every variant ─────────────────
4165
4166    #[test]
4167    fn to_json_null() {
4168        assert_eq!(Value::Null.to_json(), serde_json::Value::Null);
4169    }
4170
4171    #[test]
4172    fn to_json_bool() {
4173        assert_eq!(Value::Bool(true).to_json(), serde_json::Value::Bool(true));
4174        assert_eq!(Value::Bool(false).to_json(), serde_json::Value::Bool(false));
4175    }
4176
4177    #[test]
4178    fn to_json_int() {
4179        assert_eq!(Value::Int(42).to_json(), serde_json::json!(42));
4180    }
4181
4182    #[test]
4183    fn to_json_float() {
4184        assert_eq!(Value::Float(3.14).to_json(), serde_json::json!(3.14));
4185    }
4186
4187    #[test]
4188    fn to_json_string() {
4189        assert_eq!(
4190            Value::string("hello").to_json(),
4191            serde_json::Value::String("hello".to_string()),
4192        );
4193    }
4194
4195    #[test]
4196    fn to_json_path() {
4197        assert_eq!(
4198            Value::Path(Box::new(SmolStr::from("/nix/store"))).to_json(),
4199            serde_json::Value::String("/nix/store".to_string()),
4200        );
4201    }
4202
4203    #[test]
4204    fn to_json_list() {
4205        let v = Value::list(vec![Value::Int(1), Value::Bool(true)]);
4206        assert_eq!(v.to_json(), serde_json::json!([1, true]));
4207    }
4208
4209    #[test]
4210    fn to_json_attrs() {
4211        let mut attrs = NixAttrs::new();
4212        attrs.insert("a".to_string(), Value::Int(1));
4213        let v = Value::Attrs(Rc::new(attrs));
4214        assert_eq!(v.to_json(), serde_json::json!({"a": 1}));
4215    }
4216
4217    // ── cppnix derivation-equality short-circuit (curl/git root) ─────────
4218
4219    fn mk_drv_attrs(out_path: &str, extra_key: &str, extra_val: i64) -> Value {
4220        let mut a = NixAttrs::new();
4221        a.insert("type".to_string(), Value::string("derivation"));
4222        a.insert("outPath".to_string(), Value::string(out_path));
4223        a.insert(extra_key.to_string(), Value::Int(extra_val));
4224        Value::Attrs(Rc::new(a))
4225    }
4226
4227    #[test]
4228    fn derivations_same_outpath_differing_attrs_are_equal() {
4229        // The load-bearing rule: two attrsets that are BOTH `type=="derivation"`
4230        // with an `outPath` compare by `outPath` string ONLY — differing extra
4231        // attrs must NOT make them unequal. This is what nixpkgs'
4232        // `isMismatchedPython` (`drv.pythonModule != python`) relies on; a deep
4233        // structural compare here spuriously fired the guard and dropped
4234        // `python` from flit-core's `propagatedBuildInputs` (curl/git root).
4235        let a = mk_drv_attrs("/nix/store/x-foo", "foo", 1);
4236        let b = mk_drv_attrs("/nix/store/x-foo", "bar", 2);
4237        assert!(a == b, "same-outPath derivations must compare equal");
4238        assert!(!(a != b));
4239    }
4240
4241    #[test]
4242    fn derivations_differing_outpath_are_unequal() {
4243        let a = mk_drv_attrs("/nix/store/x-foo", "foo", 1);
4244        let b = mk_drv_attrs("/nix/store/y-foo", "foo", 1);
4245        assert!(a != b, "different-outPath derivations must compare unequal");
4246    }
4247
4248    #[test]
4249    fn non_derivation_attrs_with_outpath_use_structural_eq() {
4250        // `outPath` alone (no `type == "derivation"`) does NOT trigger the
4251        // short-circuit — nix falls back to structural equality.
4252        let mut a = NixAttrs::new();
4253        a.insert("outPath".to_string(), Value::string("/nix/store/x"));
4254        a.insert("foo".to_string(), Value::Int(1));
4255        let mut b = NixAttrs::new();
4256        b.insert("outPath".to_string(), Value::string("/nix/store/x"));
4257        b.insert("foo".to_string(), Value::Int(2));
4258        assert!(
4259            Value::Attrs(Rc::new(a)) != Value::Attrs(Rc::new(b)),
4260            "non-derivation attrs with equal outPath but differing foo must be unequal",
4261        );
4262    }
4263
4264    // ── C-A: attrs-eq structural compare BY BORROW (PERF-ARSENAL) ─────────
4265    // These seal that `Concrete::eq`'s Attrs arm — now `a.as_flat() ==
4266    // b.as_flat()` instead of `a.inner() == b.inner()` — is result- and
4267    // force-identical. The clone the old path did was pure allocation waste.
4268
4269    #[test]
4270    fn attrs_eq_borrow_result_matches_multi_key() {
4271        // Structural equality over a multi-key set with a nested attrset value
4272        // must be unaffected by dropping the pre-compare clone.
4273        let mk = || {
4274            let mut inner = NixAttrs::new();
4275            inner.insert("n".to_string(), Value::Int(7));
4276            let mut a = NixAttrs::new();
4277            a.insert("a".to_string(), Value::Int(1));
4278            a.insert("b".to_string(), Value::string("two"));
4279            a.insert("c".to_string(), Value::Attrs(Rc::new(inner)));
4280            Value::Attrs(Rc::new(a))
4281        };
4282        assert!(mk() == mk(), "equal multi-key attrsets must compare equal (borrow path)");
4283
4284        // Differ in one value → unequal.
4285        let mut b = NixAttrs::new();
4286        b.insert("a".to_string(), Value::Int(1));
4287        b.insert("b".to_string(), Value::string("TWO"));
4288        let mut a2 = NixAttrs::new();
4289        a2.insert("a".to_string(), Value::Int(1));
4290        a2.insert("b".to_string(), Value::string("two"));
4291        assert!(
4292            Value::Attrs(Rc::new(a2)) != Value::Attrs(Rc::new(b)),
4293            "attrsets differing in one value must be unequal (borrow path)",
4294        );
4295
4296        // Differ in key SET → unequal.
4297        let mut a3 = NixAttrs::new();
4298        a3.insert("a".to_string(), Value::Int(1));
4299        let mut b3 = NixAttrs::new();
4300        b3.insert("a".to_string(), Value::Int(1));
4301        b3.insert("extra".to_string(), Value::Int(9));
4302        assert!(
4303            Value::Attrs(Rc::new(a3)) != Value::Attrs(Rc::new(b3)),
4304            "attrsets differing in key set must be unequal (borrow path)",
4305        );
4306    }
4307
4308    #[test]
4309    fn attrs_eq_borrow_does_not_force_or_throw_on_shared_thunk() {
4310        // The demand-order verification obligation, made concrete:
4311        // `Value::eq` swallows force errors to `Null` (unwrap_or), so the
4312        // Attrs arm NEVER throws in the map-value-compare path. Two attrsets
4313        // that carry the SAME `Rc`-shared throwing thunk under a key that is
4314        // NOT decisive for (in)equality must:
4315        //   (a) compare via the structural (borrow) path without panicking, and
4316        //   (b) never let the throw escape.
4317        // If the borrow-compare forced the thunk and propagated the error, this
4318        // test would fail — proving the clone-elision touched no `.demand()`
4319        // behaviour that the old `inner()` clone path did not already exhibit.
4320        let boom = Value::Thunk(Thunk::new_native(|| {
4321            Err(EvalError::Throw("kaboom".to_string()))
4322        }));
4323        let mut a = NixAttrs::new();
4324        a.insert("x".to_string(), Value::Int(1));
4325        a.insert("t".to_string(), boom.clone()); // same Rc-shared throwing thunk
4326        let mut b = NixAttrs::new();
4327        b.insert("x".to_string(), Value::Int(2)); // decisive differ on `x`
4328        b.insert("t".to_string(), boom);
4329        // No panic, no escaped Err: the comparison returns a bool. `x` differs,
4330        // so they are unequal — and crucially the throwing `t` thunk did not
4331        // abort the comparison.
4332        let va = Value::Attrs(Rc::new(a));
4333        let vb = Value::Attrs(Rc::new(b));
4334        assert!(va != vb, "differ on x → unequal, throwing thunk must not abort eq");
4335    }
4336
4337    #[test]
4338    fn attrs_eq_borrow_overlay_still_compares() {
4339        // The `as_flat()` borrow path must also work when one side is an
4340        // Overlay (its cache is populated by `as_flat()`), matching the old
4341        // `inner()` path which flattened via the same `as_flat()`.
4342        let mut base = NixAttrs::new();
4343        base.insert("a".to_string(), Value::Int(1));
4344        let mut over = NixAttrs::new();
4345        over.insert("b".to_string(), Value::Int(2));
4346        // Build an overlay { a = 1; } // { b = 2; } (lazy Overlay variant),
4347        // exercising the `as_flat()` cache-population path on one side.
4348        let merged = base.overlay(over);
4349        let mut flat = NixAttrs::new();
4350        flat.insert("a".to_string(), Value::Int(1));
4351        flat.insert("b".to_string(), Value::Int(2));
4352        assert!(
4353            Value::Attrs(Rc::new(merged)) == Value::Attrs(Rc::new(flat)),
4354            "overlay and equivalent flat attrset must compare equal (borrow path)",
4355        );
4356    }
4357
4358    #[test]
4359    fn to_json_lambda() {
4360        // Build a minimal rnix lambda for testing
4361        let root = rnix::Root::parse("x: x");
4362        let expr = root.tree().expr().unwrap();
4363        let lambda = match expr {
4364            rnix::ast::Expr::Lambda(l) => l,
4365            _ => panic!("expected lambda"),
4366        };
4367        let closure = Closure {
4368            param: lambda.param().unwrap(),
4369            body: lambda.body().unwrap(),
4370            env: Env::new(),
4371        };
4372        assert_eq!(
4373            Value::Lambda(Rc::new(closure)).to_json(),
4374            serde_json::Value::String("<lambda>".to_string()),
4375        );
4376    }
4377
4378    #[test]
4379    fn to_json_builtin() {
4380        let b = BuiltinFn {
4381            name: "test",
4382            func: Rc::new(|_| Ok(Value::Null)),
4383        };
4384        assert_eq!(
4385            Value::Builtin(Box::new(b)).to_json(),
4386            serde_json::Value::String("<builtin test>".to_string()),
4387        );
4388    }
4389
4390    // ── Value::type_name for every variant ───────────────
4391
4392    #[test]
4393    fn type_name_null() { assert_eq!(Value::Null.type_name(), "null"); }
4394
4395    #[test]
4396    fn type_name_bool() { assert_eq!(Value::Bool(false).type_name(), "bool"); }
4397
4398    #[test]
4399    fn type_name_int() { assert_eq!(Value::Int(0).type_name(), "int"); }
4400
4401    #[test]
4402    fn type_name_float() { assert_eq!(Value::Float(0.0).type_name(), "float"); }
4403
4404    #[test]
4405    fn type_name_string() { assert_eq!(Value::string("").type_name(), "string"); }
4406
4407    #[test]
4408    fn type_name_path() { assert_eq!(Value::Path(Box::new(SmolStr::from(""))).type_name(), "path"); }
4409
4410    #[test]
4411    fn type_name_list() { assert_eq!(Value::list(vec![]).type_name(), "list"); }
4412
4413    #[test]
4414    fn type_name_set() { assert_eq!(Value::Attrs(Rc::new(NixAttrs::new())).type_name(), "set"); }
4415
4416    #[test]
4417    fn type_name_lambda() {
4418        let root = rnix::Root::parse("x: x");
4419        let expr = root.tree().expr().unwrap();
4420        let lambda = match expr {
4421            rnix::ast::Expr::Lambda(l) => l,
4422            _ => panic!("expected lambda"),
4423        };
4424        let closure = Closure {
4425            param: lambda.param().unwrap(),
4426            body: lambda.body().unwrap(),
4427            env: Env::new(),
4428        };
4429        assert_eq!(Value::Lambda(Rc::new(closure)).type_name(), "lambda");
4430    }
4431
4432    #[test]
4433    fn type_name_builtin() {
4434        let b = BuiltinFn {
4435            name: "t",
4436            func: Rc::new(|_| Ok(Value::Null)),
4437        };
4438        assert_eq!(Value::Builtin(Box::new(b)).type_name(), "lambda");
4439    }
4440
4441    // ── as_* error on wrong type ─────────────────────────
4442
4443    #[test]
4444    fn as_bool_error_on_non_bool() {
4445        assert!(Value::Int(1).as_bool().is_err());
4446        assert!(Value::string("true").as_bool().is_err());
4447    }
4448
4449    #[test]
4450    fn as_int_error_on_non_int() {
4451        assert!(Value::Bool(true).as_int().is_err());
4452        assert!(Value::Float(1.0).as_int().is_err());
4453    }
4454
4455    #[test]
4456    fn as_string_error_on_non_string() {
4457        assert!(Value::Int(42).as_string().is_err());
4458        assert!(Value::Null.as_string().is_err());
4459    }
4460
4461    #[test]
4462    fn as_attrs_error_on_non_attrs() {
4463        assert!(Value::Int(1).as_attrs().is_err());
4464        assert!(Value::list(vec![]).as_attrs().is_err());
4465    }
4466
4467    #[test]
4468    fn as_list_error_on_non_list() {
4469        assert!(Value::Int(1).as_list().is_err());
4470        assert!(Value::Attrs(Rc::new(NixAttrs::new())).as_list().is_err());
4471    }
4472
4473    // ── concat_lists structural share (byte-neutrality) ──────────
4474
4475    #[test]
4476    fn concat_lists_uniquely_owned_reuses_and_is_correct() {
4477        // A fresh left list (Rc strong_count == 1) hits the in-place path.
4478        let left = Value::list(vec![Value::Int(1), Value::Int(2)]);
4479        assert!(left.is_uniquely_owned_list());
4480        let right = [Value::Int(3), Value::Int(4)];
4481        let out = super::concat_lists(left, &right).unwrap();
4482        assert_eq!(
4483            out.as_list().unwrap(),
4484            &[Value::Int(1), Value::Int(2), Value::Int(3), Value::Int(4)]
4485        );
4486    }
4487
4488    #[test]
4489    fn concat_lists_shared_left_is_left_untouched_and_correct() {
4490        // Keep an outstanding Rc clone so the left is NOT uniquely owned;
4491        // the clone-extend fallback fires and the shared list is unchanged.
4492        let shared = Rc::new(NixList::new(vec![Value::Int(1), Value::Int(2)]));
4493        let left = Value::List(Rc::clone(&shared));
4494        assert!(!left.is_uniquely_owned_list());
4495        let right = [Value::Int(3)];
4496        let out = super::concat_lists(left, &right).unwrap();
4497        assert_eq!(
4498            out.as_list().unwrap(),
4499            &[Value::Int(1), Value::Int(2), Value::Int(3)]
4500        );
4501        // The original shared backing Vec is untouched.
4502        assert_eq!(&*shared, &[Value::Int(1), Value::Int(2)]);
4503    }
4504
4505    #[test]
4506    fn concat_lists_empty_operands() {
4507        let out = super::concat_lists(Value::list(vec![]), &[]).unwrap();
4508        assert!(out.as_list().unwrap().is_empty());
4509        let out2 = super::concat_lists(Value::list(vec![Value::Int(9)]), &[]).unwrap();
4510        assert_eq!(out2.as_list().unwrap(), &[Value::Int(9)]);
4511        let out3 = super::concat_lists(Value::list(vec![]), &[Value::Int(9)]).unwrap();
4512        assert_eq!(out3.as_list().unwrap(), &[Value::Int(9)]);
4513    }
4514
4515    #[test]
4516    fn concat_lists_non_list_left_errors() {
4517        assert!(super::concat_lists(Value::Int(1), &[]).is_err());
4518    }
4519
4520    #[test]
4521    fn concat_lists_preserves_element_identity() {
4522        // The concatenated list must share the SAME element Rc, not deep-copy.
4523        let inner = Rc::new(NixString::plain("x"));
4524        let a = Value::String(Rc::clone(&inner));
4525        let left = Value::list(vec![a]);
4526        let out = super::concat_lists(left, &[]).unwrap();
4527        if let Value::String(rc) = &out.as_list().unwrap()[0] {
4528            assert!(Rc::ptr_eq(rc, &inner), "element Rc identity preserved");
4529        } else {
4530            panic!("expected string element");
4531        }
4532    }
4533
4534    // ── to_float int->float coercion ─────────────────────
4535
4536    #[test]
4537    fn to_float_coerces_int() {
4538        assert_eq!(Value::Int(5).to_float().unwrap(), 5.0);
4539        assert_eq!(Value::Float(2.5).to_float().unwrap(), 2.5);
4540        assert!(Value::string("x").to_float().is_err());
4541    }
4542
4543    // ── PartialEq ────────────────────────────────────────
4544
4545    #[test]
4546    fn partial_eq_int_float_cross() {
4547        assert_eq!(Value::Int(3), Value::Float(3.0));
4548        assert_eq!(Value::Float(3.0), Value::Int(3));
4549        assert_ne!(Value::Int(3), Value::Float(3.5));
4550    }
4551
4552    #[test]
4553    fn partial_eq_different_types_not_equal() {
4554        assert_ne!(Value::Int(1), Value::string("1"));
4555        assert_ne!(Value::Bool(true), Value::Int(1));
4556        assert_ne!(Value::Null, Value::Bool(false));
4557        assert_ne!(Value::list(vec![]), Value::Attrs(Rc::new(NixAttrs::new())));
4558    }
4559
4560    // ── Display for all variants ─────────────────────────
4561
4562    #[test]
4563    fn display_null() { assert_eq!(format!("{}", Value::Null), "null"); }
4564
4565    #[test]
4566    fn display_bool() {
4567        assert_eq!(format!("{}", Value::Bool(true)), "true");
4568        assert_eq!(format!("{}", Value::Bool(false)), "false");
4569    }
4570
4571    #[test]
4572    fn display_int() { assert_eq!(format!("{}", Value::Int(42)), "42"); }
4573
4574    #[test]
4575    fn display_float() {
4576        let s = format!("{}", Value::Float(3.14));
4577        assert!(s.contains("3.14"));
4578    }
4579
4580    #[test]
4581    fn display_string() {
4582        assert_eq!(format!("{}", Value::string("hi")), "\"hi\"");
4583    }
4584
4585    #[test]
4586    fn display_string_with_escapes() {
4587        let v = Value::string("a\"b\\c");
4588        let s = format!("{v}");
4589        assert!(s.contains("\\\""));
4590        assert!(s.contains("\\\\"));
4591    }
4592
4593    #[test]
4594    fn display_path() {
4595        assert_eq!(format!("{}", Value::Path(Box::new(SmolStr::from("/foo")))), "/foo");
4596    }
4597
4598    #[test]
4599    fn display_list() {
4600        let v = Value::list(vec![Value::Int(1), Value::Int(2)]);
4601        assert_eq!(format!("{v}"), "[ 1 2 ]");
4602    }
4603
4604    #[test]
4605    fn display_attrs() {
4606        let mut attrs = NixAttrs::new();
4607        attrs.insert("x".to_string(), Value::Int(1));
4608        let v = Value::Attrs(Rc::new(attrs));
4609        assert_eq!(format!("{v}"), "{ x = 1; }");
4610    }
4611
4612    #[test]
4613    fn display_lambda() {
4614        let root = rnix::Root::parse("x: x");
4615        let expr = root.tree().expr().unwrap();
4616        let lambda = match expr {
4617            rnix::ast::Expr::Lambda(l) => l,
4618            _ => panic!("expected lambda"),
4619        };
4620        let closure = Closure {
4621            param: lambda.param().unwrap(),
4622            body: lambda.body().unwrap(),
4623            env: Env::new(),
4624        };
4625        assert_eq!(format!("{}", Value::Lambda(Rc::new(closure))), "<<lambda>>");
4626    }
4627
4628    #[test]
4629    fn display_builtin() {
4630        let b = BuiltinFn {
4631            name: "add",
4632            func: Rc::new(|_| Ok(Value::Null)),
4633        };
4634        assert_eq!(format!("{}", Value::Builtin(Box::new(b))), "<<builtin add>>");
4635    }
4636
4637    // ── NixAttrs ─────────────────────────────────────────
4638
4639    #[test]
4640    fn nixattrs_update_merging() {
4641        let mut a = NixAttrs::new();
4642        a.insert("x".to_string(), Value::Int(1));
4643        a.insert("y".to_string(), Value::Int(2));
4644        let mut b = NixAttrs::new();
4645        b.insert("y".to_string(), Value::Int(99));
4646        b.insert("z".to_string(), Value::Int(3));
4647        let merged = a.update(&b);
4648        assert_eq!(merged.get("x"), Some(&Value::Int(1)));
4649        assert_eq!(merged.get("y"), Some(&Value::Int(99)));
4650        assert_eq!(merged.get("z"), Some(&Value::Int(3)));
4651        assert_eq!(merged.len(), 3);
4652    }
4653
4654    #[test]
4655    fn nixattrs_contains_key() {
4656        let mut a = NixAttrs::new();
4657        a.insert("foo".to_string(), Value::Null);
4658        assert!(a.contains_key("foo"));
4659        assert!(!a.contains_key("bar"));
4660    }
4661
4662    // ── Env ──────────────────────────────────────────────
4663
4664    #[test]
4665    fn env_lookup_through_parent_chain() {
4666        let mut root = Env::new();
4667        root.bind("a".to_string(), Value::Int(1));
4668        let mut child = root.child();
4669        child.bind("b".to_string(), Value::Int(2));
4670        let grandchild = child.child();
4671        // grandchild can see both a and b through parent chain
4672        assert_eq!(grandchild.lookup("a"), Some(Value::Int(1)));
4673        assert_eq!(grandchild.lookup("b"), Some(Value::Int(2)));
4674        assert_eq!(grandchild.lookup("c"), None);
4675    }
4676
4677    #[test]
4678    fn env_with_scope_lookup() {
4679        let mut attrs = NixAttrs::new();
4680        attrs.insert("x".to_string(), Value::Int(42));
4681        let env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
4682        assert_eq!(env.lookup("x"), Some(Value::Int(42)));
4683        assert_eq!(env.lookup("y"), None);
4684    }
4685
4686    #[test]
4687    fn env_local_shadows_with_scope() {
4688        let mut attrs = NixAttrs::new();
4689        attrs.insert("x".to_string(), Value::Int(1));
4690        let mut env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
4691        env.bind("x".to_string(), Value::Int(99));
4692        assert_eq!(env.lookup("x"), Some(Value::Int(99)));
4693    }
4694
4695    // ── NixString context propagation ─────────────────────
4696
4697    #[test]
4698    fn string_context_merge_combines_elements() {
4699        let mut ctx_a = StringContext::new();
4700        ctx_a.add_plain("/nix/store/aaa".to_string());
4701        let mut ctx_b = StringContext::new();
4702        ctx_b.add_plain("/nix/store/bbb".to_string());
4703        ctx_a.merge(&ctx_b);
4704        assert_eq!(ctx_a.len(), 2);
4705        assert!(ctx_a.elements().contains(&ContextElement::Plain(SmolStr::from("/nix/store/aaa"))));
4706        assert!(ctx_a.elements().contains(&ContextElement::Plain(SmolStr::from("/nix/store/bbb"))));
4707    }
4708
4709    #[test]
4710    fn string_context_merge_deduplicates() {
4711        let mut ctx = StringContext::new();
4712        ctx.add_plain("/nix/store/same".to_string());
4713        ctx.add_plain("/nix/store/same".to_string());
4714        assert_eq!(ctx.len(), 1);
4715    }
4716
4717    #[test]
4718    fn string_context_mixed_element_types() {
4719        let mut ctx = StringContext::new();
4720        ctx.add_plain("/nix/store/foo".to_string());
4721        ctx.add_output("/nix/store/bar.drv".to_string(), "out".to_string());
4722        ctx.add_drv_deep("/nix/store/baz.drv".to_string());
4723        assert_eq!(ctx.len(), 3);
4724        assert!(!ctx.is_empty());
4725    }
4726
4727    #[test]
4728    fn string_context_new_is_empty() {
4729        let ctx = StringContext::new();
4730        assert!(ctx.is_empty());
4731        assert_eq!(ctx.len(), 0);
4732    }
4733
4734    #[test]
4735    fn string_context_merge_zero_elements() {
4736        let mut ctx_a = StringContext::new();
4737        let ctx_b = StringContext::new();
4738        ctx_a.merge(&ctx_b);
4739        assert!(ctx_a.is_empty());
4740    }
4741
4742    #[test]
4743    fn string_context_merge_one_element() {
4744        let mut ctx = StringContext::new();
4745        let mut other = StringContext::new();
4746        other.add_plain("/nix/store/only".to_string());
4747        ctx.merge(&other);
4748        assert_eq!(ctx.len(), 1);
4749        assert!(ctx.elements().contains(&ContextElement::Plain(SmolStr::from("/nix/store/only"))));
4750    }
4751
4752    #[test]
4753    fn string_context_merge_two_elements() {
4754        let mut ctx = StringContext::new();
4755        ctx.add_plain("/nix/store/a".to_string());
4756        let mut other = StringContext::new();
4757        other.add_plain("/nix/store/b".to_string());
4758        ctx.merge(&other);
4759        assert_eq!(ctx.len(), 2);
4760    }
4761
4762    #[test]
4763    fn string_context_merge_five_elements() {
4764        let mut ctx = StringContext::new();
4765        for i in 0..5 {
4766            ctx.add_plain(format!("/nix/store/path-{i}"));
4767        }
4768        assert_eq!(ctx.len(), 5);
4769        for i in 0..5 {
4770            assert!(ctx.elements().contains(&ContextElement::Plain(SmolStr::from(format!("/nix/store/path-{i}").as_str()))));
4771        }
4772    }
4773
4774    #[test]
4775    fn string_context_insert_deduplicates() {
4776        let mut ctx = StringContext::new();
4777        ctx.insert(ContextElement::Plain(SmolStr::from("/nix/store/dup")));
4778        ctx.insert(ContextElement::Plain(SmolStr::from("/nix/store/dup")));
4779        ctx.insert(ContextElement::Output { drv: SmolStr::from("/nix/store/x.drv"), output: SmolStr::from("out") });
4780        ctx.insert(ContextElement::Output { drv: SmolStr::from("/nix/store/x.drv"), output: SmolStr::from("out") });
4781        assert_eq!(ctx.len(), 2);
4782    }
4783
4784    #[test]
4785    fn nix_string_plain_has_no_context() {
4786        let s = NixString::plain("hello");
4787        assert!(!s.has_context());
4788        assert_eq!(s.as_str(), "hello");
4789    }
4790
4791    #[test]
4792    fn nix_string_with_context_reports_context() {
4793        let mut ctx = StringContext::new();
4794        ctx.add_plain("/nix/store/xyz".to_string());
4795        let s = NixString::with_context("hello", ctx);
4796        assert!(s.has_context());
4797        assert_eq!(s.as_str(), "hello");
4798    }
4799
4800    #[test]
4801    fn nix_string_display_shows_chars_only() {
4802        let mut ctx = StringContext::new();
4803        ctx.add_plain("/nix/store/abc".to_string());
4804        let s = NixString::with_context("visible", ctx);
4805        assert_eq!(format!("{s}"), "visible");
4806    }
4807
4808    #[test]
4809    fn nix_string_struct_eq_includes_context() {
4810        let plain = NixString::plain("hello");
4811        let mut ctx = StringContext::new();
4812        ctx.add_plain("/nix/store/xxx".to_string());
4813        let with_ctx = NixString::with_context("hello", ctx);
4814        // NixString's derived PartialEq compares context too
4815        assert_ne!(plain, with_ctx);
4816    }
4817
4818    #[test]
4819    fn value_string_eq_ignores_context() {
4820        let plain = Value::String(Rc::new(NixString::plain("hello")));
4821        let mut ctx = StringContext::new();
4822        ctx.add_plain("/nix/store/xxx".to_string());
4823        let with_ctx = Value::String(Rc::new(NixString::with_context("hello", ctx)));
4824        // Value::PartialEq only compares .chars, ignoring context
4825        assert_eq!(plain, with_ctx);
4826    }
4827
4828    // ── Env deeply nested with-scopes ─────────────────────
4829
4830    #[test]
4831    fn env_nested_with_inner_wins() {
4832        let mut outer_attrs = NixAttrs::new();
4833        outer_attrs.insert("x".to_string(), Value::Int(1));
4834        let outer = Env::new().with_scope(Value::Attrs(Rc::new(outer_attrs)));
4835        let mut inner_attrs = NixAttrs::new();
4836        inner_attrs.insert("x".to_string(), Value::Int(2));
4837        let inner = outer.child().with_scope(Value::Attrs(Rc::new(inner_attrs)));
4838        assert_eq!(inner.lookup("x"), Some(Value::Int(2)));
4839    }
4840
4841    #[test]
4842    fn env_nested_with_fallback_to_outer() {
4843        let mut outer_attrs = NixAttrs::new();
4844        outer_attrs.insert("x".to_string(), Value::Int(1));
4845        let outer = Env::new().with_scope(Value::Attrs(Rc::new(outer_attrs)));
4846        let mut inner_attrs = NixAttrs::new();
4847        inner_attrs.insert("y".to_string(), Value::Int(2));
4848        let inner = outer.child().with_scope(Value::Attrs(Rc::new(inner_attrs)));
4849        assert_eq!(inner.lookup("x"), Some(Value::Int(1)));
4850        assert_eq!(inner.lookup("y"), Some(Value::Int(2)));
4851    }
4852
4853    #[test]
4854    fn env_lexical_binding_wins_over_all_with_scopes() {
4855        let mut outer_attrs = NixAttrs::new();
4856        outer_attrs.insert("x".to_string(), Value::Int(1));
4857        let outer = Env::new().with_scope(Value::Attrs(Rc::new(outer_attrs)));
4858        let mut inner_attrs = NixAttrs::new();
4859        inner_attrs.insert("x".to_string(), Value::Int(2));
4860        let mut inner = outer.child().with_scope(Value::Attrs(Rc::new(inner_attrs)));
4861        inner.bind("x".to_string(), Value::Int(99));
4862        assert_eq!(inner.lookup("x"), Some(Value::Int(99)));
4863    }
4864
4865    #[test]
4866    fn env_parent_lexical_wins_over_child_with_scope() {
4867        let mut root = Env::new();
4868        root.bind("x".to_string(), Value::Int(10));
4869        let mut child_attrs = NixAttrs::new();
4870        child_attrs.insert("x".to_string(), Value::Int(20));
4871        let child = root.child().with_scope(Value::Attrs(Rc::new(child_attrs)));
4872        assert_eq!(child.lookup("x"), Some(Value::Int(10)));
4873    }
4874
4875    #[test]
4876    fn env_deeply_nested_with_scopes_three_levels() {
4877        let mut a = NixAttrs::new();
4878        a.insert("x".to_string(), Value::Int(1));
4879        let env1 = Env::new().with_scope(Value::Attrs(Rc::new(a)));
4880
4881        let mut b = NixAttrs::new();
4882        b.insert("y".to_string(), Value::Int(2));
4883        let env2 = env1.child().with_scope(Value::Attrs(Rc::new(b)));
4884
4885        let mut c = NixAttrs::new();
4886        c.insert("z".to_string(), Value::Int(3));
4887        let env3 = env2.child().with_scope(Value::Attrs(Rc::new(c)));
4888
4889        assert_eq!(env3.lookup("x"), Some(Value::Int(1)));
4890        assert_eq!(env3.lookup("y"), Some(Value::Int(2)));
4891        assert_eq!(env3.lookup("z"), Some(Value::Int(3)));
4892        assert_eq!(env3.lookup("w"), None);
4893    }
4894
4895    #[test]
4896    fn env_with_scope_does_not_pollute_bindings() {
4897        // With-scope values should not appear in the flat binding map.
4898        // They should only be found via the with-scope lookup path.
4899        let mut attrs = NixAttrs::new();
4900        attrs.insert("x".to_string(), Value::Int(42));
4901        let env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
4902        // The binding map itself should not contain "x"
4903        assert!(env.0.bindings.get(&intern("x")).is_none());
4904        // But lookup should find it via with-scope
4905        assert_eq!(env.lookup("x"), Some(Value::Int(42)));
4906    }
4907
4908    #[test]
4909    fn env_lexical_binding_not_in_with_scopes() {
4910        // Lexical bindings are in the flat binding map, not in with_scopes.
4911        let mut env = Env::new();
4912        env.bind("x".to_string(), Value::Int(42));
4913        // with_scopes should be empty
4914        assert!(env.0.with_scopes.is_empty());
4915        // But lookup finds it via the binding map
4916        assert_eq!(env.lookup("x"), Some(Value::Int(42)));
4917    }
4918
4919    #[test]
4920    fn env_child_inherits_eval_file() {
4921        let mut env = Env::new();
4922        env.set_eval_file(Some(std::path::PathBuf::from("/foo/bar.nix")));
4923        let child = env.child();
4924        assert_eq!(child.eval_file().cloned(), Some(std::path::PathBuf::from("/foo/bar.nix")));
4925    }
4926
4927    #[test]
4928    fn env_new_has_no_parent_no_with() {
4929        let env = Env::new();
4930        assert_eq!(env.lookup("anything"), None);
4931        assert!(env.eval_file().is_none());
4932    }
4933
4934    // ── Thunk state machine ───────────────────────────────
4935
4936    #[test]
4937    fn thunk_new_suspended_is_not_evaluated() {
4938        let root = rnix::Root::parse("42");
4939        let expr = root.tree().expr().unwrap();
4940        let thunk = Thunk::new_suspended(expr, Env::new());
4941        assert!(!thunk.is_evaluated());
4942    }
4943
4944    #[test]
4945    fn thunk_new_evaluated_is_evaluated() {
4946        let thunk = Thunk::new_evaluated(Value::Int(42));
4947        assert!(thunk.is_evaluated());
4948    }
4949
4950    #[test]
4951    fn thunk_force_evaluates_suspended() {
4952        let root = rnix::Root::parse("42");
4953        let expr = root.tree().expr().unwrap();
4954        let thunk = Thunk::new_suspended(expr, Env::new());
4955        let result = thunk.force(&|e, env| crate::eval::eval_expr(e, env));
4956        assert!(result.is_ok());
4957        assert_eq!(result.unwrap(), Value::Int(42));
4958        assert!(thunk.is_evaluated());
4959    }
4960
4961    #[test]
4962    fn thunk_force_memoizes_result() {
4963        let root = rnix::Root::parse("1 + 2");
4964        let expr = root.tree().expr().unwrap();
4965        let thunk = Thunk::new_suspended(expr, Env::new());
4966        let r1 = thunk.force(&|e, env| crate::eval::eval_expr(e, env)).unwrap();
4967        let r2 = thunk.force(&|e, env| crate::eval::eval_expr(e, env)).unwrap();
4968        assert_eq!(r1, Value::Int(3));
4969        assert_eq!(r2, Value::Int(3));
4970    }
4971
4972    #[test]
4973    fn thunk_force_already_evaluated_returns_value() {
4974        let thunk = Thunk::new_evaluated(Value::Bool(true));
4975        let result = thunk.force(&|_, _| panic!("should not be called"));
4976        assert_eq!(result.unwrap(), Value::Bool(true));
4977    }
4978
4979    // C-store PROVABLY-NEUTRAL seal (M2): a force whose body returns a
4980    // CONCRETE (non-Thunk) value takes the redundant-Store#2 skip path
4981    // (`!was_thunk_before_loop` early-return). It must still (a) return the
4982    // correct value, (b) be `is_evaluated()`, (c) populate the OnceCell so
4983    // the fast-path returns the identical value on re-force (proving Store#1's
4984    // guarded `cache.set` — NOT the skipped Store#2 — is what seals the cache),
4985    // and (d) `peek()` returns the value (repr holds it). If the skip dropped
4986    // the terminal state, one of these would regress.
4987    #[test]
4988    fn thunk_force_concrete_skips_redundant_store_but_caches() {
4989        // `1 + 2` evaluates directly to a concrete Int (no thunk-chain unwrap),
4990        // so it exercises the `!was_thunk_before_loop` skip branch.
4991        let root = rnix::Root::parse("1 + 2");
4992        let expr = root.tree().expr().unwrap();
4993        let thunk = Thunk::new_suspended(expr, Env::new());
4994
4995        let r1 = thunk.force(&|e, env| crate::eval::eval_expr(e, env)).unwrap();
4996        assert_eq!(r1, Value::Int(3));
4997        assert!(thunk.is_evaluated());
4998
4999        // OnceCell must be populated (peek sees the value) — proves Store#1's
5000        // guarded cache.set fired and the skipped Store#2 was truly redundant.
5001        assert_eq!(thunk.peek().map(|c| c.clone().into_value()), Some(Value::Int(3)));
5002
5003        // Re-force hits the OnceCell ultra-fast path and returns byte-identical.
5004        let r2 = thunk.force(&|_, _| panic!("re-force must hit the cache, not re-eval")).unwrap();
5005        assert_eq!(r2, Value::Int(3));
5006    }
5007
5008    #[test]
5009    fn thunk_blackhole_detects_infinite_recursion() {
5010        let root = rnix::Root::parse("42");
5011        let expr = root.tree().expr().unwrap();
5012        let thunk = Thunk::new_suspended(expr, Env::new());
5013
5014        // Manually set to blackhole to simulate re-entrance
5015        // SAFETY: Test-only, single-threaded.
5016        *unsafe { &mut *thunk.0.repr.get() } = ThunkRepr::Blackhole;
5017
5018        let result = thunk.force(&|_, _| Ok(Value::Null));
5019        assert!(result.is_err());
5020        let err_msg = format!("{}", result.unwrap_err());
5021        assert!(err_msg.contains("infinite recursion"));
5022    }
5023
5024    #[test]
5025    fn thunk_update_env_replaces_suspended_env() {
5026        let root = rnix::Root::parse("x");
5027        let expr = root.tree().expr().unwrap();
5028        let thunk = Thunk::new_suspended(expr, Env::new());
5029
5030        let mut new_env = Env::new();
5031        new_env.bind("x".to_string(), Value::Int(99));
5032        thunk.update_env(&new_env);
5033
5034        let result = thunk.force(&|e, env| crate::eval::eval_expr(e, env));
5035        assert_eq!(result.unwrap(), Value::Int(99));
5036    }
5037
5038    #[test]
5039    fn thunk_update_env_noop_when_evaluated() {
5040        let thunk = Thunk::new_evaluated(Value::Int(1));
5041        let mut new_env = Env::new();
5042        new_env.bind("x".to_string(), Value::Int(99));
5043        thunk.update_env(&new_env);
5044        assert_eq!(
5045            thunk.force(&|_, _| panic!("should not be called")).unwrap(),
5046            Value::Int(1),
5047        );
5048    }
5049
5050    #[test]
5051    fn thunk_debug_suspended() {
5052        let root = rnix::Root::parse("42");
5053        let expr = root.tree().expr().unwrap();
5054        let thunk = Thunk::new_suspended(expr, Env::new());
5055        assert_eq!(format!("{thunk:?}"), "<thunk>");
5056    }
5057
5058    #[test]
5059    fn thunk_debug_evaluated() {
5060        let thunk = Thunk::new_evaluated(Value::Int(42));
5061        let dbg = format!("{thunk:?}");
5062        assert!(dbg.contains("42"));
5063    }
5064
5065    #[test]
5066    fn thunk_error_restores_suspended_state() {
5067        let root = rnix::Root::parse("nonexistent_var");
5068        let expr = root.tree().expr().unwrap();
5069        let thunk = Thunk::new_suspended(expr, Env::new());
5070
5071        let result = thunk.force(&|e, env| crate::eval::eval_expr(e, env));
5072        assert!(result.is_err());
5073        // After error, thunk should be restored to Suspended, not stuck as Blackhole
5074        assert!(!thunk.is_evaluated());
5075        let dbg = format!("{thunk:?}");
5076        assert_eq!(dbg, "<thunk>");
5077    }
5078
5079    #[test]
5080    fn thunk_inherit_select_forces_and_selects() {
5081        let root = rnix::Root::parse(r#"{ x = 42; }"#);
5082        let expr = root.tree().expr().unwrap();
5083        let source = Thunk::new_suspended(expr, Env::new());
5084        let thunk = Thunk::new_inherit_select(source, "x".to_string());
5085        let result = thunk.force(&|e, env| crate::eval::eval_expr(e, env));
5086        assert_eq!(result.unwrap(), Value::Int(42));
5087        assert!(thunk.is_evaluated());
5088    }
5089
5090    #[test]
5091    fn thunk_inherit_select_missing_attr_errors() {
5092        let root = rnix::Root::parse(r#"{ x = 42; }"#);
5093        let expr = root.tree().expr().unwrap();
5094        let source = Thunk::new_suspended(expr, Env::new());
5095        let thunk = Thunk::new_inherit_select(source, "y".to_string());
5096        let result = thunk.force(&|e, env| crate::eval::eval_expr(e, env));
5097        assert!(result.is_err());
5098        // Thunk should restore to InheritSelect, not be stuck as Blackhole
5099        assert!(!thunk.is_evaluated());
5100    }
5101
5102    #[test]
5103    fn thunk_inherit_select_non_attrs_source_errors() {
5104        let root = rnix::Root::parse("42");
5105        let expr = root.tree().expr().unwrap();
5106        let source = Thunk::new_suspended(expr, Env::new());
5107        let thunk = Thunk::new_inherit_select(source, "x".to_string());
5108        let result = thunk.force(&|e, env| crate::eval::eval_expr(e, env));
5109        assert!(result.is_err());
5110        let msg = format!("{}", result.unwrap_err());
5111        assert!(msg.contains("not a set"));
5112    }
5113
5114    #[test]
5115    fn thunk_inherit_select_shares_source_thunk() {
5116        // Two InheritSelect thunks share the same source thunk.
5117        // Forcing one should evaluate the source; the second should
5118        // get a cache hit on the shared source thunk.
5119        let root = rnix::Root::parse(r#"{ a = 1; b = 2; }"#);
5120        let expr = root.tree().expr().unwrap();
5121        let source = Thunk::new_suspended(expr, Env::new());
5122        let thunk_a = Thunk::new_inherit_select(source.clone(), "a".to_string());
5123        let thunk_b = Thunk::new_inherit_select(source.clone(), "b".to_string());
5124        let result_a = thunk_a.force(&|e, env| crate::eval::eval_expr(e, env));
5125        assert_eq!(result_a.unwrap(), Value::Int(1));
5126        // Source thunk should now be evaluated (memoized).
5127        assert!(source.is_evaluated());
5128        // Second force should hit the source thunk's cache.
5129        let result_b = thunk_b.force(&|e, env| crate::eval::eval_expr(e, env));
5130        assert_eq!(result_b.unwrap(), Value::Int(2));
5131    }
5132
5133    // ── NixAttrs additional tests ─────────────────────────
5134
5135    #[test]
5136    fn nixattrs_empty_operations() {
5137        let a = NixAttrs::new();
5138        assert!(a.is_empty());
5139        assert_eq!(a.len(), 0);
5140        assert_eq!(a.get("x"), None);
5141        assert!(!a.contains_key("x"));
5142        assert_eq!(a.keys().count(), 0);
5143        assert_eq!(a.iter().count(), 0);
5144    }
5145
5146    #[test]
5147    fn nixattrs_update_with_empty() {
5148        let mut a = NixAttrs::new();
5149        a.insert("x".to_string(), Value::Int(1));
5150        let b = NixAttrs::new();
5151        let merged = a.update(&b);
5152        assert_eq!(merged.len(), 1);
5153        assert_eq!(merged.get("x"), Some(&Value::Int(1)));
5154    }
5155
5156    #[test]
5157    fn nixattrs_update_empty_with_nonempty() {
5158        let a = NixAttrs::new();
5159        let mut b = NixAttrs::new();
5160        b.insert("x".to_string(), Value::Int(1));
5161        let merged = a.update(&b);
5162        assert_eq!(merged.len(), 1);
5163        assert_eq!(merged.get("x"), Some(&Value::Int(1)));
5164    }
5165
5166    #[test]
5167    fn nixattrs_keys_sorted_order() {
5168        let mut a = NixAttrs::new();
5169        a.insert("c".to_string(), Value::Int(3));
5170        a.insert("a".to_string(), Value::Int(1));
5171        a.insert("b".to_string(), Value::Int(2));
5172        let keys: Vec<String> = a.keys().collect();
5173        assert_eq!(keys, vec!["a", "b", "c"]);
5174    }
5175
5176    // ── Value convenience methods ─────────────────────────
5177
5178    #[test]
5179    fn value_to_str_forces_thunks() {
5180        let root = rnix::Root::parse(r#""hello""#);
5181        let expr = root.tree().expr().unwrap();
5182        let thunk = Thunk::new_suspended(expr, Env::new());
5183        let val = Value::Thunk(thunk);
5184        assert_eq!(val.to_str().unwrap(), "hello");
5185    }
5186
5187    #[test]
5188    fn value_to_nix_string_forces_thunks() {
5189        let root = rnix::Root::parse(r#""world""#);
5190        let expr = root.tree().expr().unwrap();
5191        let thunk = Thunk::new_suspended(expr, Env::new());
5192        let val = Value::Thunk(thunk);
5193        let ns = val.to_nix_string().unwrap();
5194        assert_eq!(ns.as_str(), "world");
5195        assert!(!ns.has_context());
5196    }
5197
5198    #[test]
5199    fn value_to_attrs_forces_thunks() {
5200        let root = rnix::Root::parse("{ x = 1; }");
5201        let expr = root.tree().expr().unwrap();
5202        let thunk = Thunk::new_suspended(expr, Env::new());
5203        let val = Value::Thunk(thunk);
5204        let attrs = val.to_attrs().unwrap();
5205        assert_eq!(attrs.len(), 1);
5206    }
5207
5208    #[test]
5209    fn value_to_list_forces_thunks() {
5210        let root = rnix::Root::parse("[1 2 3]");
5211        let expr = root.tree().expr().unwrap();
5212        let thunk = Thunk::new_suspended(expr, Env::new());
5213        let val = Value::Thunk(thunk);
5214        let list = val.to_list().unwrap();
5215        assert_eq!(list.len(), 3);
5216    }
5217
5218    #[test]
5219    fn value_to_float_on_thunk() {
5220        let root = rnix::Root::parse("3.14");
5221        let expr = root.tree().expr().unwrap();
5222        let thunk = Thunk::new_suspended(expr, Env::new());
5223        let val = Value::Thunk(thunk);
5224        let f = val.to_float().unwrap();
5225        assert!((f - 3.14).abs() < f64::EPSILON);
5226    }
5227
5228    #[test]
5229    fn value_as_bool_on_thunk() {
5230        let root = rnix::Root::parse("true");
5231        let expr = root.tree().expr().unwrap();
5232        let thunk = Thunk::new_suspended(expr, Env::new());
5233        let val = Value::Thunk(thunk);
5234        assert!(val.as_bool().unwrap());
5235    }
5236
5237    #[test]
5238    fn value_as_int_on_thunk() {
5239        let root = rnix::Root::parse("42");
5240        let expr = root.tree().expr().unwrap();
5241        let thunk = Thunk::new_suspended(expr, Env::new());
5242        let val = Value::Thunk(thunk);
5243        assert_eq!(val.as_int().unwrap(), 42);
5244    }
5245
5246    #[test]
5247    fn value_string_constructor() {
5248        let v = Value::string("test");
5249        assert_eq!(v, Value::String(Rc::new(NixString::plain("test"))));
5250    }
5251
5252    #[test]
5253    fn value_partial_eq_null_null() {
5254        assert_eq!(Value::Null, Value::Null);
5255    }
5256
5257    #[test]
5258    fn value_partial_eq_lists_deep() {
5259        let a = Value::list(vec![Value::Int(1), Value::list(vec![Value::Int(2)])]);
5260        let b = Value::list(vec![Value::Int(1), Value::list(vec![Value::Int(2)])]);
5261        assert_eq!(a, b);
5262    }
5263
5264    #[test]
5265    fn value_partial_eq_attrs_deep() {
5266        let mut a = NixAttrs::new();
5267        a.insert("x".to_string(), Value::Int(1));
5268        let mut b = NixAttrs::new();
5269        b.insert("x".to_string(), Value::Int(1));
5270        assert_eq!(Value::Attrs(Rc::new(a)), Value::Attrs(Rc::new(b)));
5271    }
5272
5273    // ── EvalError variants & convenience constructors ────
5274
5275    #[test]
5276    fn eval_error_type_error_constructor() {
5277        let e = EvalError::type_error("oops");
5278        assert!(matches!(e, EvalError::TypeError(ref s) if s == "oops"));
5279    }
5280
5281    #[test]
5282    fn eval_error_type_mismatch_constructor() {
5283        let e = EvalError::type_mismatch("int", "string");
5284        match e {
5285            EvalError::TypeMismatch { expected, got } => {
5286                assert_eq!(expected, "int");
5287                assert_eq!(got, "string");
5288            }
5289            _ => panic!("expected TypeMismatch"),
5290        }
5291    }
5292
5293    #[test]
5294    fn eval_error_is_throw_yes_no() {
5295        assert!(EvalError::Throw("oops".into()).is_throw());
5296        assert!(!EvalError::TypeError("oops".into()).is_throw());
5297        assert!(!EvalError::AssertionFailed(String::new()).is_throw());
5298    }
5299
5300    #[test]
5301    fn eval_error_is_infinite_recursion_yes_no() {
5302        assert!(EvalError::InfiniteRecursion("loop".into()).is_infinite_recursion());
5303        assert!(!EvalError::DivisionByZero.is_infinite_recursion());
5304        assert!(!EvalError::Throw("x".into()).is_infinite_recursion());
5305    }
5306
5307    #[test]
5308    fn eval_error_display_undefined_var() {
5309        let s = format!("{}", EvalError::UndefinedVar("foo".into()));
5310        assert!(s.contains("undefined variable"));
5311        assert!(s.contains("foo"));
5312    }
5313
5314    #[test]
5315    fn eval_error_display_type_error() {
5316        let s = format!("{}", EvalError::TypeError("bad".into()));
5317        assert!(s.contains("type error"));
5318        assert!(s.contains("bad"));
5319    }
5320
5321    #[test]
5322    fn eval_error_display_attr_not_found() {
5323        let s = format!("{}", EvalError::AttrNotFound("x".into()));
5324        assert!(s.contains("attribute not found"));
5325        assert!(s.contains("x"));
5326    }
5327
5328    #[test]
5329    fn eval_error_display_type_mismatch() {
5330        let s = format!(
5331            "{}",
5332            EvalError::TypeMismatch { expected: "int", got: "string" }
5333        );
5334        assert!(s.contains("expected int"));
5335        assert!(s.contains("got string"));
5336    }
5337
5338    #[test]
5339    fn eval_error_display_assertion_failed() {
5340        let s = format!("{}", EvalError::AssertionFailed(String::new()));
5341        assert!(s.contains("assertion"));
5342    }
5343
5344    #[test]
5345    fn eval_error_display_division_by_zero() {
5346        let s = format!("{}", EvalError::DivisionByZero);
5347        assert!(s.contains("division by zero"));
5348    }
5349
5350    #[test]
5351    fn eval_error_display_infinite_recursion() {
5352        let s = format!("{}", EvalError::InfiniteRecursion("loop".into()));
5353        assert!(s.contains("infinite recursion"));
5354        assert!(s.contains("loop"));
5355    }
5356
5357    #[test]
5358    fn eval_error_display_io_error() {
5359        let s = format!(
5360            "{}",
5361            EvalError::IoError {
5362                context: "ctx".into(),
5363                message: "no such file".into(),
5364            }
5365        );
5366        assert!(s.contains("I/O"));
5367        assert!(s.contains("ctx"));
5368        assert!(s.contains("no such file"));
5369    }
5370
5371    #[test]
5372    fn eval_error_display_throw() {
5373        let s = format!("{}", EvalError::Throw("boom".into()));
5374        assert_eq!(s, "boom");
5375    }
5376
5377    #[test]
5378    fn eval_error_display_not_implemented() {
5379        let s = format!("{}", EvalError::NotImplemented("frob".into()));
5380        assert!(s.contains("not yet implemented"));
5381        assert!(s.contains("frob"));
5382    }
5383
5384    #[test]
5385    fn eval_error_display_parse_error() {
5386        let s = format!("{}", EvalError::ParseError("syntax".into()));
5387        assert!(s.contains("parse error"));
5388        assert!(s.contains("syntax"));
5389    }
5390
5391    #[test]
5392    fn eval_error_display_recursion_limit() {
5393        let s = format!(
5394            "{}",
5395            EvalError::RecursionLimit("max depth exceeded".into())
5396        );
5397        assert!(s.contains("recursion limit"));
5398        assert!(s.contains("max depth exceeded"));
5399    }
5400
5401    #[test]
5402    fn eval_error_partial_eq_same_variant() {
5403        assert_eq!(
5404            EvalError::UndefinedVar("x".into()),
5405            EvalError::UndefinedVar("x".into()),
5406        );
5407        assert_ne!(
5408            EvalError::UndefinedVar("x".into()),
5409            EvalError::UndefinedVar("y".into()),
5410        );
5411        assert_ne!(
5412            EvalError::UndefinedVar("x".into()),
5413            EvalError::AttrNotFound("x".into()),
5414        );
5415    }
5416
5417    // ── ContextElement display ───────────────────────────
5418
5419    #[test]
5420    fn context_element_display_plain() {
5421        let e = ContextElement::Plain("/nix/store/xyz".into());
5422        assert_eq!(format!("{e}"), "/nix/store/xyz");
5423    }
5424
5425    #[test]
5426    fn context_element_display_output() {
5427        let e = ContextElement::Output {
5428            drv: "/nix/store/abc.drv".into(),
5429            output: "out".into(),
5430        };
5431        assert_eq!(format!("{e}"), "/nix/store/abc.drv!out");
5432    }
5433
5434    #[test]
5435    fn context_element_display_drv_deep() {
5436        let e = ContextElement::DrvDeep("/nix/store/abc.drv".into());
5437        assert_eq!(format!("{e}"), "=/nix/store/abc.drv");
5438    }
5439
5440    // ── StringContext additional API ─────────────────────
5441
5442    #[test]
5443    fn string_context_iter_yields_all() {
5444        let mut ctx = StringContext::new();
5445        ctx.add_plain("/nix/store/aaa");
5446        ctx.add_plain("/nix/store/bbb");
5447        let count = ctx.iter().count();
5448        assert_eq!(count, 2);
5449    }
5450
5451    #[test]
5452    fn string_context_len_matches_set_size() {
5453        let mut ctx = StringContext::new();
5454        assert_eq!(ctx.len(), 0);
5455        ctx.add_plain("/nix/store/x");
5456        assert_eq!(ctx.len(), 1);
5457        ctx.add_output("/nix/store/y.drv", "out");
5458        assert_eq!(ctx.len(), 2);
5459    }
5460
5461    #[test]
5462    fn string_context_insert_raw_element() {
5463        let mut ctx = StringContext::new();
5464        ctx.insert(ContextElement::Plain("/nix/store/foo".into()));
5465        assert_eq!(ctx.len(), 1);
5466    }
5467
5468    #[test]
5469    fn string_context_default_is_empty() {
5470        let ctx = StringContext::default();
5471        assert!(ctx.is_empty());
5472    }
5473
5474    // ── NixString additional traits ──────────────────────
5475
5476    #[test]
5477    fn nix_string_as_ref_str() {
5478        let s = NixString::plain("hello");
5479        let r: &str = s.as_ref();
5480        assert_eq!(r, "hello");
5481    }
5482
5483    #[test]
5484    fn nix_string_deref_to_str_methods() {
5485        let s = NixString::plain("Hello World");
5486        assert_eq!(s.len(), 11);
5487        assert!(s.starts_with("Hello"));
5488        // Calling &str method via Deref proves Deref impl is wired up.
5489        assert_eq!(s.to_uppercase(), "HELLO WORLD");
5490    }
5491
5492    // ── NixAttrs additional API ──────────────────────────
5493
5494    #[test]
5495    fn nixattrs_remove_returns_value() {
5496        let mut a = NixAttrs::new();
5497        a.insert("x".into(), Value::Int(1));
5498        let removed = a.remove("x");
5499        assert_eq!(removed, Some(Value::Int(1)));
5500        assert!(!a.contains_key("x"));
5501        assert_eq!(a.remove("y"), None);
5502    }
5503
5504    #[test]
5505    fn nixattrs_values_iter() {
5506        let mut a = NixAttrs::new();
5507        a.insert("a".into(), Value::Int(1));
5508        a.insert("b".into(), Value::Int(2));
5509        let mut vs: Vec<&Value> = a.values().collect();
5510        vs.sort_by_key(|v| match v {
5511            Value::Int(n) => *n,
5512            _ => 0,
5513        });
5514        assert_eq!(vs, vec![&Value::Int(1), &Value::Int(2)]);
5515    }
5516
5517    #[test]
5518    fn nixattrs_iter_returns_sorted_pairs() {
5519        let mut a = NixAttrs::new();
5520        a.insert("zeta".into(), Value::Int(3));
5521        a.insert("alpha".into(), Value::Int(1));
5522        a.insert("mu".into(), Value::Int(2));
5523        let pairs: Vec<(String, &Value)> = a.iter().collect();
5524        assert_eq!(pairs[0].0, "alpha");
5525        assert_eq!(pairs[1].0, "mu");
5526        assert_eq!(pairs[2].0, "zeta");
5527    }
5528
5529    #[test]
5530    fn nixattrs_from_iterator() {
5531        let pairs = vec![
5532            ("a".to_string(), Value::Int(1)),
5533            ("b".to_string(), Value::Int(2)),
5534        ];
5535        let attrs: NixAttrs = pairs.into_iter().collect();
5536        assert_eq!(attrs.len(), 2);
5537        assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
5538        assert_eq!(attrs.get("b"), Some(&Value::Int(2)));
5539    }
5540
5541    #[test]
5542    fn nixattrs_into_iterator_yields_owned() {
5543        let mut a = NixAttrs::new();
5544        a.insert("x".into(), Value::Int(42));
5545        let pairs: Vec<(String, Value)> = a.into_iter().collect();
5546        assert_eq!(pairs.len(), 1);
5547        assert_eq!(pairs[0].0, "x");
5548        assert_eq!(pairs[0].1, Value::Int(42));
5549    }
5550
5551    #[test]
5552    fn nixattrs_default_is_empty() {
5553        let a = NixAttrs::default();
5554        assert!(a.is_empty());
5555    }
5556
5557    // ── Value::From conversions ──────────────────────────
5558
5559    #[test]
5560    fn value_from_bool() {
5561        assert_eq!(Value::from(true), Value::Bool(true));
5562        assert_eq!(Value::from(false), Value::Bool(false));
5563    }
5564
5565    #[test]
5566    fn value_from_i64() {
5567        assert_eq!(Value::from(42_i64), Value::Int(42));
5568        assert_eq!(Value::from(-1_i64), Value::Int(-1));
5569    }
5570
5571    #[test]
5572    fn value_from_f64() {
5573        assert_eq!(Value::from(2.5_f64), Value::Float(2.5));
5574    }
5575
5576    #[test]
5577    fn value_from_nix_string() {
5578        let v: Value = NixString::plain("hi").into();
5579        assert_eq!(v, Value::string("hi"));
5580    }
5581
5582    #[test]
5583    fn value_from_nix_attrs() {
5584        let mut a = NixAttrs::new();
5585        a.insert("x".into(), Value::Int(1));
5586        let v: Value = a.into();
5587        match v {
5588            Value::Attrs(_) => {}
5589            _ => panic!("expected Attrs"),
5590        }
5591    }
5592
5593    #[test]
5594    fn value_from_vec() {
5595        let v: Value = vec![Value::Int(1), Value::Int(2)].into();
5596        assert_eq!(v, Value::list(vec![Value::Int(1), Value::Int(2)]));
5597    }
5598
5599    #[test]
5600    fn value_default_is_null() {
5601        let v: Value = Value::default();
5602        assert_eq!(v, Value::Null);
5603    }
5604
5605    // ── From<&serde_json::Value> ─────────────────────────
5606
5607    #[test]
5608    fn value_from_json_null() {
5609        let v = Value::from(&serde_json::Value::Null);
5610        assert_eq!(v, Value::Null);
5611    }
5612
5613    #[test]
5614    fn value_from_json_bool() {
5615        let v = Value::from(&serde_json::Value::Bool(true));
5616        assert_eq!(v, Value::Bool(true));
5617    }
5618
5619    #[test]
5620    fn value_from_json_int() {
5621        let v = Value::from(&serde_json::json!(42));
5622        assert_eq!(v, Value::Int(42));
5623    }
5624
5625    #[test]
5626    fn value_from_json_float() {
5627        let v = Value::from(&serde_json::json!(3.14));
5628        match v {
5629            Value::Float(f) => assert!((f - 3.14).abs() < f64::EPSILON),
5630            _ => panic!("expected Float"),
5631        }
5632    }
5633
5634    #[test]
5635    fn value_from_json_string() {
5636        let v = Value::from(&serde_json::Value::String("hi".into()));
5637        assert_eq!(v, Value::string("hi"));
5638    }
5639
5640    #[test]
5641    fn value_from_json_array() {
5642        let v = Value::from(&serde_json::json!([1, true, "x"]));
5643        match v {
5644            Value::List(items) => {
5645                assert_eq!(items.len(), 3);
5646                assert_eq!(items[0], Value::Int(1));
5647                assert_eq!(items[1], Value::Bool(true));
5648                assert_eq!(items[2], Value::string("x"));
5649            }
5650            _ => panic!("expected List"),
5651        }
5652    }
5653
5654    #[test]
5655    fn value_from_json_object() {
5656        let v = Value::from(&serde_json::json!({"a": 1, "b": "x"}));
5657        match v {
5658            Value::Attrs(attrs) => {
5659                assert_eq!(attrs.get("a"), Some(&Value::Int(1)));
5660                assert_eq!(attrs.get("b"), Some(&Value::string("x")));
5661            }
5662            _ => panic!("expected Attrs"),
5663        }
5664    }
5665
5666    #[test]
5667    fn value_from_json_nested() {
5668        let v = Value::from(&serde_json::json!({"outer": {"inner": [1, 2]}}));
5669        let json_back = v.to_json();
5670        assert_eq!(json_back, serde_json::json!({"outer": {"inner": [1, 2]}}));
5671    }
5672
5673    // ── From<&toml::Value> ──────────────────────────────
5674
5675    #[test]
5676    fn value_from_toml_string() {
5677        let t = toml::Value::String("hi".into());
5678        assert_eq!(Value::from(&t), Value::string("hi"));
5679    }
5680
5681    #[test]
5682    fn value_from_toml_int() {
5683        let t = toml::Value::Integer(42);
5684        assert_eq!(Value::from(&t), Value::Int(42));
5685    }
5686
5687    #[test]
5688    fn value_from_toml_float() {
5689        let t = toml::Value::Float(3.14);
5690        match Value::from(&t) {
5691            Value::Float(f) => assert!((f - 3.14).abs() < f64::EPSILON),
5692            _ => panic!("expected Float"),
5693        }
5694    }
5695
5696    #[test]
5697    fn value_from_toml_bool() {
5698        let t = toml::Value::Boolean(true);
5699        assert_eq!(Value::from(&t), Value::Bool(true));
5700    }
5701
5702    #[test]
5703    fn value_from_toml_array() {
5704        let t = toml::Value::Array(vec![
5705            toml::Value::Integer(1),
5706            toml::Value::Integer(2),
5707        ]);
5708        assert_eq!(
5709            Value::from(&t),
5710            Value::list(vec![Value::Int(1), Value::Int(2)]),
5711        );
5712    }
5713
5714    #[test]
5715    fn value_from_toml_table() {
5716        let mut tbl = toml::map::Map::new();
5717        tbl.insert("k".into(), toml::Value::Integer(7));
5718        let t = toml::Value::Table(tbl);
5719        match Value::from(&t) {
5720            Value::Attrs(attrs) => {
5721                assert_eq!(attrs.get("k"), Some(&Value::Int(7)));
5722            }
5723            _ => panic!("expected Attrs"),
5724        }
5725    }
5726
5727    #[test]
5728    fn value_from_toml_datetime_becomes_string() {
5729        // toml::Value::Datetime serializes via Display.
5730        let dt: toml::value::Datetime = "2024-01-01T00:00:00Z".parse().unwrap();
5731        let t = toml::Value::Datetime(dt);
5732        match Value::from(&t) {
5733            Value::String(_) => {}
5734            other => panic!("expected String, got {other:?}"),
5735        }
5736    }
5737
5738    // ── Value::coerce_to_path ────────────────────────────
5739
5740    #[test]
5741    fn coerce_to_path_from_path() {
5742        let v = Value::Path(Box::new("/foo".into()));
5743        assert_eq!(v.coerce_to_path("ctx").unwrap(), "/foo");
5744    }
5745
5746    #[test]
5747    fn coerce_to_path_from_string() {
5748        let v = Value::string("/bar");
5749        assert_eq!(v.coerce_to_path("ctx").unwrap(), "/bar");
5750    }
5751
5752    // ── Import-from-derivation (IFD) detection + realize seal ──────────
5753    //
5754    // These lock the parity-critical decision "is this coercion an
5755    // import-from-derivation that must realize?" — the same decision cppnix
5756    // makes off a string's `Output` context. Regressing them silently reopens
5757    // the marquee `import ishou.stylix-fonts` root.
5758
5759    #[test]
5760    fn out_path_needs_realize_matches_output_context() {
5761        // A store-path string carrying a derivation `Output` context IS a
5762        // derivation output → its producing `.drv` is returned for realize.
5763        let mut ctx = StringContext::new();
5764        ctx.add_output("/nix/store/aaa-thing.drv", "out");
5765        assert_eq!(
5766            super::out_path_needs_realize("/nix/store/bbb-thing", &ctx),
5767            Some("/nix/store/aaa-thing.drv".to_string()),
5768        );
5769    }
5770
5771    #[test]
5772    fn out_path_needs_realize_ignores_plain_context() {
5773        // A plain store-path reference (not a derivation output) has nothing to
5774        // build — no realize.
5775        let mut ctx = StringContext::new();
5776        ctx.add_plain("/nix/store/ccc-plain");
5777        assert_eq!(super::out_path_needs_realize("/nix/store/ccc-plain", &ctx), None);
5778    }
5779
5780    #[test]
5781    fn out_path_needs_realize_ignores_non_store_path() {
5782        // A non-store path is never a derivation output, even with an (invalid)
5783        // Output context — nothing to realize.
5784        let mut ctx = StringContext::new();
5785        ctx.add_output("/nix/store/ddd.drv", "out");
5786        assert_eq!(super::out_path_needs_realize("/etc/passwd", &ctx), None);
5787    }
5788
5789    #[test]
5790    fn out_path_needs_realize_empty_context_is_none() {
5791        // A bare store-path literal (empty context) is not a derivation output.
5792        let ctx = StringContext::new();
5793        assert_eq!(super::out_path_needs_realize("/nix/store/eee-lit", &ctx), None);
5794    }
5795
5796    #[test]
5797    fn coerce_to_realized_path_present_output_is_passthrough() {
5798        // When the output already exists on disk, no hook is needed and the
5799        // path is returned unchanged (the no-op realize path — proven live on
5800        // the already-built ifd-test derivation).
5801        let dir = std::env::temp_dir().join("sui-ifd-present-test");
5802        std::fs::create_dir_all(&dir).unwrap();
5803        let file = dir.join("out");
5804        std::fs::write(&file, b"present").unwrap();
5805        let present = file.to_string_lossy().to_string();
5806
5807        let mut ctx = StringContext::new();
5808        // Pretend it's a derivation output (Output context) — but it exists,
5809        // so realize must NOT be invoked (no hook installed → would ENOENT if
5810        // it tried). A store-prefix check would skip a temp path, so assert the
5811        // simpler invariant: an existing plain string coerces to itself.
5812        ctx.add_plain(&present);
5813        let v = Value::String(std::rc::Rc::new(NixString::with_context(
5814            present.as_str(),
5815            ctx,
5816        )));
5817        assert_eq!(v.coerce_to_realized_path("readFile").unwrap(), present);
5818    }
5819
5820    #[test]
5821    fn coerce_to_realized_path_absent_output_invokes_hook() {
5822        // A store-path string with an Output context whose output is ABSENT
5823        // invokes the realize hook with the producing drv. The mock hook
5824        // "materializes" nothing (the store path stays absent) but records the
5825        // call — proving the trigger fires end-to-end through coercion.
5826        use std::sync::{Arc, Mutex};
5827        let seen: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
5828        let seen2 = seen.clone();
5829        let _guard = crate::realize::install_realize_hook(Box::new(move |drv, out| {
5830            seen2.lock().unwrap().push((drv.to_string(), out.to_string()));
5831            Ok(())
5832        }));
5833
5834        // An absent store path (unique per run to avoid collision with a real
5835        // build) carrying an Output context.
5836        let out = "/nix/store/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz-ifd-absent";
5837        assert!(!std::path::Path::new(out).exists(), "test store path must be absent");
5838        let mut ctx = StringContext::new();
5839        ctx.add_output("/nix/store/qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq-ifd-absent.drv", "out");
5840        let v = Value::String(std::rc::Rc::new(NixString::with_context(out, ctx)));
5841
5842        // Coercion returns the outPath and fires the hook exactly once.
5843        assert_eq!(v.coerce_to_realized_path("readFile").unwrap(), out);
5844        let s = seen.lock().unwrap();
5845        assert_eq!(s.len(), 1, "realize hook should fire once for an absent output");
5846        assert_eq!(s[0].0, "/nix/store/qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq-ifd-absent.drv");
5847        assert_eq!(s[0].1, out);
5848    }
5849
5850    #[test]
5851    fn coerce_to_path_errors_on_int() {
5852        let v = Value::Int(1);
5853        let e = v.coerce_to_path("readFile").unwrap_err();
5854        match e {
5855            EvalError::TypeError(ref msg) => {
5856                assert!(msg.contains("readFile"));
5857                assert!(msg.contains("path or string"));
5858                assert!(msg.contains("int"));
5859            }
5860            _ => panic!("expected TypeError"),
5861        }
5862    }
5863
5864    #[test]
5865    fn coerce_to_path_errors_on_null() {
5866        let v = Value::Null;
5867        assert!(v.coerce_to_path("ctx").is_err());
5868    }
5869
5870    #[test]
5871    fn coerce_to_path_attrs_with_outpath() {
5872        let mut attrs = NixAttrs::new();
5873        attrs.insert("outPath".to_string(), Value::string("/nix/store/test"));
5874        let val = Value::Attrs(Rc::new(attrs));
5875        assert_eq!(val.coerce_to_path("test").unwrap(), "/nix/store/test");
5876    }
5877
5878    #[test]
5879    fn coerce_to_path_attrs_without_outpath_fails() {
5880        let attrs = NixAttrs::new();
5881        let val = Value::Attrs(Rc::new(attrs));
5882        assert!(val.coerce_to_path("test").is_err());
5883    }
5884
5885    // ── Value::coerce_to_string ─────────────────────────
5886
5887    #[test]
5888    fn coerce_to_string_string() {
5889        let v = Value::string("hello");
5890        let (s, _ctx) = v.coerce_to_string().unwrap();
5891        assert_eq!(s, "hello");
5892    }
5893
5894    #[test]
5895    fn coerce_to_string_path() {
5896        let v = Value::Path(Box::new("/foo".into()));
5897        let (s, ctx) = v.coerce_to_string().unwrap();
5898        assert_eq!(s, "/foo");
5899        assert!(!ctx.is_empty()); // should add a Plain context element
5900    }
5901
5902    #[test]
5903    fn coerce_to_string_int() {
5904        let v = Value::Int(42);
5905        let (s, _ctx) = v.coerce_to_string().unwrap();
5906        assert_eq!(s, "42");
5907    }
5908
5909    #[test]
5910    fn coerce_to_string_float() {
5911        // CppNix %f-format: always 6 decimal places.
5912        let v = Value::Float(3.14);
5913        let (s, _ctx) = v.coerce_to_string().unwrap();
5914        assert_eq!(s, "3.140000");
5915    }
5916
5917    #[test]
5918    fn coerce_to_string_bool_true() {
5919        let (s, _ctx) = Value::Bool(true).coerce_to_string().unwrap();
5920        assert_eq!(s, "1");
5921    }
5922
5923    #[test]
5924    fn coerce_to_string_bool_false() {
5925        let (s, _ctx) = Value::Bool(false).coerce_to_string().unwrap();
5926        assert_eq!(s, "");
5927    }
5928
5929    #[test]
5930    fn coerce_to_string_null() {
5931        let (s, _ctx) = Value::Null.coerce_to_string().unwrap();
5932        assert_eq!(s, "");
5933    }
5934
5935    #[test]
5936    fn coerce_to_string_attrs_with_outpath() {
5937        let mut attrs = NixAttrs::new();
5938        attrs.insert("outPath".to_string(), Value::string("/nix/store/abc"));
5939        let val = Value::Attrs(Rc::new(attrs));
5940        let (s, _ctx) = val.coerce_to_string().unwrap();
5941        assert_eq!(s, "/nix/store/abc");
5942    }
5943
5944    #[test]
5945    fn coerce_to_string_attrs_without_outpath_or_tostring_fails() {
5946        let attrs = NixAttrs::new();
5947        let val = Value::Attrs(Rc::new(attrs));
5948        assert!(val.coerce_to_string().is_err());
5949    }
5950
5951    #[test]
5952    fn coerce_to_string_lambda_fails() {
5953        let root = rnix::Root::parse("x: x");
5954        let expr = root.tree().expr().unwrap();
5955        let closure = Closure {
5956            param: match expr {
5957                rnix::ast::Expr::Lambda(ref l) => l.param().unwrap(),
5958                _ => panic!("expected lambda"),
5959            },
5960            body: match expr {
5961                rnix::ast::Expr::Lambda(ref l) => l.body().unwrap(),
5962                _ => panic!("expected lambda"),
5963            },
5964            env: Env::new(),
5965        };
5966        let val = Value::Lambda(Rc::new(closure));
5967        assert!(val.coerce_to_string().is_err());
5968    }
5969
5970    // ── BuiltinFn debug ──────────────────────────────────
5971
5972    #[test]
5973    fn builtin_fn_debug_includes_name() {
5974        let b = BuiltinFn {
5975            name: "myFunc",
5976            func: Rc::new(|_| Ok(Value::Null)),
5977        };
5978        let s = format!("{b:?}");
5979        assert!(s.contains("myFunc"));
5980        assert!(s.contains("builtin"));
5981    }
5982
5983    // ── Thunk additional tests ───────────────────────────
5984
5985    #[test]
5986    fn thunk_force_chains_through_inner_thunks() {
5987        // Build a thunk whose evaluator yields another thunk.
5988        let inner_root = rnix::Root::parse("99");
5989        let inner_expr = inner_root.tree().expr().unwrap();
5990        let inner_thunk = Thunk::new_suspended(inner_expr, Env::new());
5991        let outer = Thunk::new_evaluated(Value::Thunk(inner_thunk));
5992        let result = outer.force(&|e, env| crate::eval::eval_expr(e, env));
5993        // Already-evaluated outer returns the inner thunk; the chain is
5994        // collapsed by the higher-level force_value, not by force() itself
5995        // when starting from Evaluated. So we just check we got a Thunk
5996        // back unchanged.
5997        match result.unwrap() {
5998            Value::Thunk(_) | Value::Int(99) => {}
5999            other => panic!("unexpected: {other:?}"),
6000        }
6001    }
6002
6003    #[test]
6004    fn thunk_inherit_select_debug_format() {
6005        let root = rnix::Root::parse("{ x = 1; }");
6006        let expr = root.tree().expr().unwrap();
6007        let source = Thunk::new_suspended(expr, Env::new());
6008        let thunk = Thunk::new_inherit_select(source, "x");
6009        let s = format!("{thunk:?}");
6010        assert!(s.contains("inherit-select"));
6011        assert!(s.contains("x"));
6012    }
6013
6014    #[test]
6015    fn thunk_blackhole_debug_format() {
6016        let root = rnix::Root::parse("1");
6017        let expr = root.tree().expr().unwrap();
6018        let thunk = Thunk::new_suspended(expr, Env::new());
6019        // SAFETY: Test-only, single-threaded.
6020        *unsafe { &mut *thunk.0.repr.get() } = ThunkRepr::Blackhole;
6021        assert_eq!(format!("{thunk:?}"), "<blackhole>");
6022    }
6023
6024    // ── Value display for thunks ─────────────────────────
6025
6026    #[test]
6027    fn value_display_thunk_evaluates() {
6028        let root = rnix::Root::parse("42");
6029        let expr = root.tree().expr().unwrap();
6030        let thunk = Thunk::new_suspended(expr, Env::new());
6031        let val = Value::Thunk(thunk);
6032        assert_eq!(format!("{val}"), "42");
6033    }
6034
6035    #[test]
6036    fn value_to_json_thunk_forces() {
6037        let root = rnix::Root::parse(r#""world""#);
6038        let expr = root.tree().expr().unwrap();
6039        let thunk = Thunk::new_suspended(expr, Env::new());
6040        let val = Value::Thunk(thunk);
6041        assert_eq!(val.to_json(), serde_json::Value::String("world".into()));
6042    }
6043
6044    #[test]
6045    fn value_type_name_thunk_forces() {
6046        let root = rnix::Root::parse("42");
6047        let expr = root.tree().expr().unwrap();
6048        let thunk = Thunk::new_suspended(expr, Env::new());
6049        let val = Value::Thunk(thunk);
6050        assert_eq!(val.type_name(), "int");
6051    }
6052
6053    // ── as_string / as_nix_string thunk error ────────────
6054
6055    #[test]
6056    fn as_string_errors_on_thunk() {
6057        let root = rnix::Root::parse(r#""x""#);
6058        let expr = root.tree().expr().unwrap();
6059        let thunk = Thunk::new_suspended(expr, Env::new());
6060        let val = Value::Thunk(thunk);
6061        let err = val.as_string().unwrap_err();
6062        match err {
6063            EvalError::TypeError(msg) => assert!(msg.contains("thunk")),
6064            _ => panic!("expected TypeError"),
6065        }
6066    }
6067
6068    #[test]
6069    fn as_nix_string_errors_on_thunk() {
6070        let root = rnix::Root::parse(r#""x""#);
6071        let expr = root.tree().expr().unwrap();
6072        let thunk = Thunk::new_suspended(expr, Env::new());
6073        let val = Value::Thunk(thunk);
6074        assert!(val.as_nix_string().is_err());
6075    }
6076
6077    #[test]
6078    fn as_attrs_errors_on_thunk() {
6079        let root = rnix::Root::parse("{}");
6080        let expr = root.tree().expr().unwrap();
6081        let thunk = Thunk::new_suspended(expr, Env::new());
6082        let val = Value::Thunk(thunk);
6083        assert!(val.as_attrs().is_err());
6084    }
6085
6086    #[test]
6087    fn as_list_errors_on_thunk() {
6088        let root = rnix::Root::parse("[]");
6089        let expr = root.tree().expr().unwrap();
6090        let thunk = Thunk::new_suspended(expr, Env::new());
6091        let val = Value::Thunk(thunk);
6092        assert!(val.as_list().is_err());
6093    }
6094
6095    // ── as_nix_string OK on string ───────────────────────
6096
6097    #[test]
6098    fn as_nix_string_ok_on_string() {
6099        let v = Value::string("hi");
6100        let ns = v.as_nix_string().unwrap();
6101        assert_eq!(ns.as_str(), "hi");
6102    }
6103
6104    #[test]
6105    fn as_nix_string_errors_on_int() {
6106        let v = Value::Int(1);
6107        match v.as_nix_string() {
6108            Err(EvalError::TypeMismatch { expected, got }) => {
6109                assert_eq!(expected, "string");
6110                assert_eq!(got, "int");
6111            }
6112            _ => panic!("expected TypeMismatch"),
6113        }
6114    }
6115
6116    // ════════════════════════════════════════════════════════════
6117    // 1. OnceCell Thunk Cache
6118    // ════════════════════════════════════════════════════════════
6119
6120    #[test]
6121    fn oncecell_cache_populated_after_force() {
6122        let root = rnix::Root::parse("42");
6123        let expr = root.tree().expr().unwrap();
6124        let thunk = Thunk::new_suspended(expr, Env::new());
6125        // Before forcing, cache should be empty.
6126        assert!(thunk.0.cache.get().is_none());
6127        let _ = thunk.force(&|e, env| crate::eval::eval_expr(e, env)).unwrap();
6128        // After forcing, cache should be populated.
6129        assert!(thunk.0.cache.get().is_some());
6130    }
6131
6132    #[test]
6133    fn oncecell_cache_matches_force_result() {
6134        let root = rnix::Root::parse("1 + 2");
6135        let expr = root.tree().expr().unwrap();
6136        let thunk = Thunk::new_suspended(expr, Env::new());
6137        let forced = thunk.force(&|e, env| crate::eval::eval_expr(e, env)).unwrap();
6138        let cached = thunk.0.cache.get().unwrap();
6139        // Cache stores Concrete (thunk-free); force returns Value.
6140        // Compare via Concrete→Value promotion.
6141        assert_eq!((**cached).clone().into_value(), forced);
6142    }
6143
6144    #[test]
6145    fn oncecell_new_evaluated_prepopulates_cache() {
6146        let thunk = Thunk::new_evaluated(Value::Int(77));
6147        // Cache should be set immediately.
6148        let cached = thunk.0.cache.get().expect("cache should be pre-populated");
6149        assert_eq!(**cached, Concrete::Int(77));
6150    }
6151
6152    #[test]
6153    fn oncecell_is_evaluated_uses_cache() {
6154        let thunk = Thunk::new_evaluated(Value::Bool(false));
6155        // is_evaluated() checks the OnceCell cache.
6156        assert!(thunk.is_evaluated());
6157        assert!(thunk.0.cache.get().is_some());
6158    }
6159
6160    #[test]
6161    fn oncecell_already_evaluated_returns_cached_without_repr() {
6162        // Create a thunk already evaluated. Force should return
6163        // the cached value without touching repr (the evaluator
6164        // closure should never be called).
6165        let thunk = Thunk::new_evaluated(Value::Int(55));
6166        let result = thunk.force(&|_, _| panic!("evaluator should not be called"));
6167        assert_eq!(result.unwrap(), Value::Int(55));
6168    }
6169
6170    // ════════════════════════════════════════════════════════════
6171    // 2. WithScope Memoization
6172    // ════════════════════════════════════════════════════════════
6173
6174    #[test]
6175    fn with_scope_created_with_empty_cache() {
6176        // Thunk-valued scopes start with empty cache (thunk not yet forced)
6177        let thunk = Thunk::new_suspended(
6178            rnix::Root::parse("{}").tree().expr().unwrap(),
6179            Env::new(),
6180        );
6181        let env = Env::new().with_scope(Value::Thunk(thunk));
6182        let scope = &env.0.with_scopes[0];
6183        assert!(scope.cached.borrow().is_none());
6184    }
6185
6186    #[test]
6187    fn with_scope_concrete_pre_populates_cache() {
6188        // Concrete attrset scopes pre-populate cache immediately
6189        let mut attrs = NixAttrs::new();
6190        attrs.insert("x".to_string(), Value::Int(1));
6191        let env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6192        let scope = &env.0.with_scopes[0];
6193        assert!(scope.cached.borrow().is_some());
6194    }
6195
6196    #[test]
6197    fn with_scope_first_lookup_populates_cache() {
6198        let mut attrs = NixAttrs::new();
6199        attrs.insert("x".to_string(), Value::Int(42));
6200        let env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6201        // Cache is pre-populated for concrete attrsets.
6202        assert!(env.0.with_scopes[0].cached.borrow().is_some());
6203        // Lookup hits the pre-populated cache.
6204        let _ = env.lookup("x");
6205        assert!(env.0.with_scopes[0].cached.borrow().is_some());
6206    }
6207
6208    #[test]
6209    fn with_scope_second_lookup_uses_cache() {
6210        let mut attrs = NixAttrs::new();
6211        attrs.insert("x".to_string(), Value::Int(10));
6212        let env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6213        // First lookup populates cache.
6214        assert_eq!(env.lookup("x"), Some(Value::Int(10)));
6215        assert!(env.0.with_scopes[0].cached.borrow().is_some());
6216        // Second lookup should still work (reads from cache).
6217        assert_eq!(env.lookup("x"), Some(Value::Int(10)));
6218    }
6219
6220    #[test]
6221    fn with_scope_child_shares_cache_via_rc() {
6222        let mut attrs = NixAttrs::new();
6223        attrs.insert("shared".to_string(), Value::Int(7));
6224        let parent = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6225        let child = parent.child();
6226        // Force via parent lookup.
6227        let _ = parent.lookup("shared");
6228        // Child's with-scope cache should share the same Rc, so
6229        // it should also show cached.
6230        assert!(child.0.with_scopes[0].cached.borrow().is_some());
6231    }
6232
6233    #[test]
6234    fn with_scope_innermost_checked_first() {
6235        let mut outer = NixAttrs::new();
6236        outer.insert("x".to_string(), Value::Int(1));
6237        outer.insert("y".to_string(), Value::Int(100));
6238        let mut inner = NixAttrs::new();
6239        inner.insert("x".to_string(), Value::Int(2));
6240        let env = Env::new()
6241            .with_scope(Value::Attrs(Rc::new(outer)))
6242            .with_scope(Value::Attrs(Rc::new(inner)));
6243        // Innermost scope has x=2, should win.
6244        assert_eq!(env.lookup("x"), Some(Value::Int(2)));
6245        // y only in outer, should fallback.
6246        assert_eq!(env.lookup("y"), Some(Value::Int(100)));
6247    }
6248
6249    // ════════════════════════════════════════════════════════════
6250    // 3. FxHashMap for NixAttrs
6251    // ════════════════════════════════════════════════════════════
6252
6253    #[test]
6254    fn fxhashmap_nixattrs_new_creates_empty() {
6255        let a = NixAttrs::new();
6256        assert!(a.is_empty());
6257        assert_eq!(a.len(), 0);
6258        // Internal map is a FxHashMap (im_rc::HashMap with FxBuildHasher).
6259        assert!(a.inner().is_empty());
6260    }
6261
6262    #[test]
6263    fn fxhashmap_insert_get_roundtrip_with_symbol_keys() {
6264        let mut a = NixAttrs::new();
6265        a.insert("mykey".to_string(), Value::Int(42));
6266        assert_eq!(a.get("mykey"), Some(&Value::Int(42)));
6267    }
6268
6269    #[test]
6270    fn fxhashmap_contains_key_with_interned_keys() {
6271        let mut a = NixAttrs::new();
6272        a.insert("alpha".to_string(), Value::Int(1));
6273        let sym = intern("alpha");
6274        assert!(a.inner().contains_key(&sym));
6275        let missing_sym = intern("beta");
6276        assert!(!a.inner().contains_key(&missing_sym));
6277    }
6278
6279    #[test]
6280    fn fxhashmap_remove_returns_value() {
6281        let mut a = NixAttrs::new();
6282        a.insert("key".to_string(), Value::Int(99));
6283        let removed = a.remove("key");
6284        assert_eq!(removed, Some(Value::Int(99)));
6285        assert!(a.is_empty());
6286    }
6287
6288    #[test]
6289    fn fxhashmap_keys_returns_sorted_strings() {
6290        let mut a = NixAttrs::new();
6291        a.insert("zulu".to_string(), Value::Int(1));
6292        a.insert("alpha".to_string(), Value::Int(2));
6293        a.insert("mike".to_string(), Value::Int(3));
6294        let keys: Vec<String> = a.keys().collect();
6295        assert_eq!(keys, vec!["alpha", "mike", "zulu"]);
6296    }
6297
6298    #[test]
6299    fn fxhashmap_iter_returns_sorted_string_value_pairs() {
6300        let mut a = NixAttrs::new();
6301        a.insert("b".to_string(), Value::Int(2));
6302        a.insert("a".to_string(), Value::Int(1));
6303        let pairs: Vec<(String, &Value)> = a.iter().collect();
6304        assert_eq!(pairs.len(), 2);
6305        assert_eq!(pairs[0].0, "a");
6306        assert_eq!(*pairs[0].1, Value::Int(1));
6307        assert_eq!(pairs[1].0, "b");
6308        assert_eq!(*pairs[1].1, Value::Int(2));
6309    }
6310
6311    #[test]
6312    fn fxhashmap_update_merges_correctly() {
6313        let mut left = NixAttrs::new();
6314        left.insert("a".to_string(), Value::Int(1));
6315        left.insert("b".to_string(), Value::Int(2));
6316        let mut right = NixAttrs::new();
6317        right.insert("b".to_string(), Value::Int(20));
6318        right.insert("c".to_string(), Value::Int(3));
6319        let merged = left.update(&right);
6320        assert_eq!(merged.get("a"), Some(&Value::Int(1)));
6321        assert_eq!(merged.get("b"), Some(&Value::Int(20))); // right overrides
6322        assert_eq!(merged.get("c"), Some(&Value::Int(3)));
6323        assert_eq!(merged.len(), 3);
6324    }
6325
6326    #[test]
6327    fn fxhashmap_from_iterator_collects_with_interning() {
6328        let pairs = vec![
6329            ("x".to_string(), Value::Int(10)),
6330            ("y".to_string(), Value::Int(20)),
6331            ("z".to_string(), Value::Int(30)),
6332        ];
6333        let attrs: NixAttrs = pairs.into_iter().collect();
6334        assert_eq!(attrs.len(), 3);
6335        assert_eq!(attrs.get("x"), Some(&Value::Int(10)));
6336        assert_eq!(attrs.get("y"), Some(&Value::Int(20)));
6337        assert_eq!(attrs.get("z"), Some(&Value::Int(30)));
6338        // Verify internal storage uses Symbol keys.
6339        let sym_x = intern("x");
6340        assert!(attrs.inner().contains_key(&sym_x));
6341    }
6342
6343    // ════════════════════════════════════════════════════════════
6344    // 4. SmallVec StringContext
6345    // ════════════════════════════════════════════════════════════
6346
6347    #[test]
6348    fn smallvec_context_empty() {
6349        let ctx = StringContext::new();
6350        assert!(ctx.is_empty());
6351        assert_eq!(ctx.len(), 0);
6352        assert_eq!(ctx.elements().len(), 0);
6353    }
6354
6355    #[test]
6356    fn smallvec_context_single_element_inline() {
6357        let mut ctx = StringContext::new();
6358        ctx.add_plain("/nix/store/single");
6359        assert_eq!(ctx.len(), 1);
6360        // SmallVec<[ContextElement; 2]> stores up to 2 inline.
6361        assert!(!ctx.is_empty());
6362    }
6363
6364    #[test]
6365    fn smallvec_context_two_elements_still_inline() {
6366        let mut ctx = StringContext::new();
6367        ctx.add_plain("/nix/store/one");
6368        ctx.add_output("/nix/store/two.drv", "out");
6369        assert_eq!(ctx.len(), 2);
6370    }
6371
6372    #[test]
6373    fn smallvec_context_three_plus_spills_to_heap() {
6374        let mut ctx = StringContext::new();
6375        ctx.add_plain("/nix/store/a");
6376        ctx.add_plain("/nix/store/b");
6377        ctx.add_drv_deep("/nix/store/c.drv");
6378        assert_eq!(ctx.len(), 3);
6379        // Verify all elements are accessible.
6380        assert!(ctx.elements().contains(&ContextElement::Plain(SmolStr::from("/nix/store/a"))));
6381        assert!(ctx.elements().contains(&ContextElement::Plain(SmolStr::from("/nix/store/b"))));
6382        assert!(ctx.elements().contains(&ContextElement::DrvDeep(SmolStr::from("/nix/store/c.drv"))));
6383    }
6384
6385    #[test]
6386    fn smallvec_context_merge_deduplicates() {
6387        let mut ctx1 = StringContext::new();
6388        ctx1.add_plain("/nix/store/dup");
6389        ctx1.add_output("/nix/store/x.drv", "out");
6390        let mut ctx2 = StringContext::new();
6391        ctx2.add_plain("/nix/store/dup");      // duplicate
6392        ctx2.add_plain("/nix/store/unique");    // new
6393        ctx1.merge(&ctx2);
6394        assert_eq!(ctx1.len(), 3); // dup not duplicated
6395    }
6396
6397    #[test]
6398    fn smallvec_context_add_plain_output_drv_deep() {
6399        let mut ctx = StringContext::new();
6400        ctx.add_plain("/nix/store/plain");
6401        assert_eq!(ctx.len(), 1);
6402        assert!(ctx.elements().contains(&ContextElement::Plain(SmolStr::from("/nix/store/plain"))));
6403
6404        ctx.add_output("/nix/store/out.drv", "lib");
6405        assert_eq!(ctx.len(), 2);
6406        assert!(ctx.elements().contains(&ContextElement::Output {
6407            drv: SmolStr::from("/nix/store/out.drv"),
6408            output: SmolStr::from("lib"),
6409        }));
6410
6411        ctx.add_drv_deep("/nix/store/deep.drv");
6412        assert_eq!(ctx.len(), 3);
6413        assert!(ctx.elements().contains(&ContextElement::DrvDeep(SmolStr::from("/nix/store/deep.drv"))));
6414    }
6415
6416    // ════════════════════════════════════════════════════════════
6417    // 5. Rc<Vec<Value>> for List
6418    // ════════════════════════════════════════════════════════════
6419
6420    #[test]
6421    fn rc_list_constructor_wraps_in_rc() {
6422        let v = Value::list(vec![Value::Int(1), Value::Int(2)]);
6423        match &v {
6424            Value::List(rc) => {
6425                assert_eq!(rc.len(), 2);
6426                assert_eq!(Rc::strong_count(rc), 1);
6427            }
6428            _ => panic!("expected List"),
6429        }
6430    }
6431
6432    #[test]
6433    fn rc_list_clone_is_refcount_bump() {
6434        let v = Value::list(vec![Value::Int(10)]);
6435        let rc1 = match &v {
6436            Value::List(rc) => rc.clone(),
6437            _ => panic!("expected List"),
6438        };
6439        let v2 = v.clone();
6440        let rc2 = match &v2 {
6441            Value::List(rc) => rc.clone(),
6442            _ => panic!("expected List"),
6443        };
6444        // Both point to the same allocation.
6445        assert!(Rc::ptr_eq(&rc1, &rc2));
6446        // Strong count should be 3: rc1, rc2, and the one inside v or v2.
6447        // Actually: v has one, v2 has one, rc1 has one, rc2 has one = 4.
6448        assert!(Rc::strong_count(&rc1) >= 2);
6449    }
6450
6451    #[test]
6452    fn rc_list_as_list_returns_slice() {
6453        let v = Value::list(vec![Value::Int(1), Value::Int(2), Value::Int(3)]);
6454        let slice = v.as_list().unwrap();
6455        assert_eq!(slice.len(), 3);
6456        assert_eq!(slice[0], Value::Int(1));
6457        assert_eq!(slice[1], Value::Int(2));
6458        assert_eq!(slice[2], Value::Int(3));
6459    }
6460
6461    #[test]
6462    fn rc_list_from_vec_wraps_in_rc() {
6463        let items = vec![Value::Bool(true), Value::Bool(false)];
6464        let v: Value = items.into();
6465        match &v {
6466            Value::List(rc) => {
6467                assert_eq!(rc.len(), 2);
6468                assert_eq!(Rc::strong_count(rc), 1);
6469            }
6470            _ => panic!("expected List"),
6471        }
6472    }
6473
6474    // ════════════════════════════════════════════════════════════
6475    // 6. String Interning
6476    // ════════════════════════════════════════════════════════════
6477
6478    #[test]
6479    fn intern_same_string_returns_same_symbol() {
6480        let s1 = intern("hello_intern_test");
6481        let s2 = intern("hello_intern_test");
6482        assert_eq!(s1, s2);
6483    }
6484
6485    #[test]
6486    fn intern_different_strings_returns_different_symbols() {
6487        let s1 = intern("unique_str_a_9182");
6488        let s2 = intern("unique_str_b_9182");
6489        assert_ne!(s1, s2);
6490    }
6491
6492    #[test]
6493    fn resolve_roundtrips_correctly() {
6494        let sym = intern("roundtrip_test_str");
6495        let resolved = resolve(sym);
6496        assert_eq!(resolved, "roundtrip_test_str");
6497    }
6498
6499    #[test]
6500    fn intern_cached_same_offset_returns_cached_symbol() {
6501        let sid = next_source_id();
6502        let sym1 = intern_cached("cached_ident_aa", sid, 100);
6503        let sym2 = intern_cached("cached_ident_aa", sid, 100);
6504        assert_eq!(sym1, sym2);
6505    }
6506
6507    #[test]
6508    fn intern_cached_different_offset_same_string_returns_same_symbol() {
6509        // Even with different offsets, the same string should intern
6510        // to the same Symbol (interning dedup at the interner level).
6511        let sid = next_source_id();
6512        let sym1 = intern_cached("dedup_test_str_77", sid, 200);
6513        let sym2 = intern_cached("dedup_test_str_77", sid, 300);
6514        // The symbols should be equal because the interner deduplicates.
6515        assert_eq!(sym1, sym2);
6516    }
6517
6518    #[test]
6519    fn clear_ident_cache_clears() {
6520        let sid = next_source_id();
6521        let _sym = intern_cached("to_be_cleared_99", sid, 500);
6522        clear_ident_cache();
6523        // After clearing, the cache is empty, but interning the same
6524        // string again should still return the same Symbol (the interner
6525        // itself is not cleared, just the offset cache).
6526        let sym2 = intern_cached("to_be_cleared_99", sid, 500);
6527        let resolved = resolve(sym2);
6528        assert_eq!(resolved, "to_be_cleared_99");
6529    }
6530
6531    #[test]
6532    fn next_source_id_increments_monotonically() {
6533        let id1 = next_source_id();
6534        let id2 = next_source_id();
6535        let id3 = next_source_id();
6536        assert_eq!(id2, id1 + 1);
6537        assert_eq!(id3, id2 + 1);
6538    }
6539
6540    // ════════════════════════════════════════════════════════════
6541    // 7. Env Operations
6542    // ════════════════════════════════════════════════════════════
6543
6544    #[test]
6545    fn env_new_creates_empty_bindings() {
6546        let env = Env::new();
6547        assert!(env.0.bindings.is_empty());
6548        assert!(env.0.with_scopes.is_empty());
6549        assert!(env.eval_file().is_none());
6550    }
6551
6552    #[test]
6553    fn env_bind_lookup_roundtrip() {
6554        let mut env = Env::new();
6555        env.bind("foo".to_string(), Value::Int(42));
6556        assert_eq!(env.lookup("foo"), Some(Value::Int(42)));
6557        assert_eq!(env.lookup("bar"), None);
6558    }
6559
6560    #[test]
6561    fn env_child_inherits_parent_bindings_flattened() {
6562        let mut parent = Env::new();
6563        parent.bind("a".to_string(), Value::Int(1));
6564        parent.bind("b".to_string(), Value::Int(2));
6565        let child = parent.child();
6566        // Child sees parent's bindings.
6567        assert_eq!(child.lookup("a"), Some(Value::Int(1)));
6568        assert_eq!(child.lookup("b"), Some(Value::Int(2)));
6569        // Verify bindings are in child's own map (flattened).
6570        let sym_a = intern("a");
6571        assert!(child.0.bindings.contains_key(&sym_a));
6572    }
6573
6574    #[test]
6575    fn env_child_inherits_with_scopes() {
6576        let mut attrs = NixAttrs::new();
6577        attrs.insert("ws".to_string(), Value::Int(10));
6578        let parent = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6579        let child = parent.child();
6580        // Child should have the same with_scopes as parent.
6581        assert_eq!(child.0.with_scopes.len(), parent.0.with_scopes.len());
6582        assert_eq!(child.lookup("ws"), Some(Value::Int(10)));
6583    }
6584
6585    #[test]
6586    fn env_lookup_sym_fast_path_matches_lookup() {
6587        let mut env = Env::new();
6588        env.bind("target".to_string(), Value::Int(88));
6589        let sym = intern("target");
6590        let via_lookup = env.lookup("target");
6591        let via_sym = env.lookup_sym(sym);
6592        assert_eq!(via_lookup, via_sym);
6593        assert_eq!(via_sym, Some(Value::Int(88)));
6594    }
6595
6596    #[test]
6597    fn env_lookup_sym_with_scope_fallback() {
6598        let mut attrs = NixAttrs::new();
6599        attrs.insert("sym_ws".to_string(), Value::Int(33));
6600        let env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6601        let sym = intern("sym_ws");
6602        assert_eq!(env.lookup_sym(sym), Some(Value::Int(33)));
6603    }
6604
6605    #[test]
6606    fn env_with_scope_ordering_multiple_innermost_wins() {
6607        let mut a1 = NixAttrs::new();
6608        a1.insert("x".to_string(), Value::Int(1));
6609        let mut a2 = NixAttrs::new();
6610        a2.insert("x".to_string(), Value::Int(2));
6611        let mut a3 = NixAttrs::new();
6612        a3.insert("x".to_string(), Value::Int(3));
6613        let env = Env::new()
6614            .with_scope(Value::Attrs(Rc::new(a1)))
6615            .with_scope(Value::Attrs(Rc::new(a2)))
6616            .with_scope(Value::Attrs(Rc::new(a3)));
6617        // Innermost (a3) should win.
6618        assert_eq!(env.lookup("x"), Some(Value::Int(3)));
6619    }
6620
6621    #[test]
6622    fn env_lookup_sym_not_found_returns_none() {
6623        let env = Env::new();
6624        let sym = intern("nonexistent_sym_99");
6625        assert_eq!(env.lookup_sym(sym), None);
6626    }
6627
6628    #[test]
6629    fn env_lookup_sym_lexical_wins_over_with_scope() {
6630        let mut attrs = NixAttrs::new();
6631        attrs.insert("priority".to_string(), Value::Int(1));
6632        let mut env = Env::new().with_scope(Value::Attrs(Rc::new(attrs)));
6633        env.bind("priority".to_string(), Value::Int(99));
6634        let sym = intern("priority");
6635        assert_eq!(env.lookup_sym(sym), Some(Value::Int(99)));
6636    }
6637}