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