Skip to main content

sui_eval/
normalize_env.rs

1//! The tree-walker's *consume* side of the `sui-normalize` attrset-binding
2//! plan.
3//!
4//! Mirrors [`crate::resolve_env`]'s three parts — a one-way env-flag latch, a
5//! thread-local table keyed by `(source_id, text_offset)`, and
6//! populate/lookup/clear hooks wired into `eval_with_file` — because the
7//! keying hazard is identical: a plan recorded for a binder at offset `o` in
8//! one parse tree must never be read for a different (imported) tree that
9//! happens to have a binder at the same offset.
10//!
11//! # ★ The failure discipline here is the INVERSE of `resolve_env`'s
12//!
13//! `sui-resolve` fails SAFE to `Dynamic` because its fallback is
14//! *equivalent* — `lookup_fast` probes the same map with the same symbol, so
15//! falling back costs only speed.
16//!
17//! **This table's fallback path is the divergence itself.** Falling back means
18//! "walk `set.entries()` yourself", which is precisely the code that produces
19//! the silent wrong answers `sui-normalize` exists to remove. So a miss must
20//! never be treated as "nothing to do" in a group that NEEDED a plan.
21//!
22//! The shape that makes that safe: `sui-normalize` records a group **only**
23//! when it has a duplicate static key or a dotted path. A miss therefore means
24//! "this group has neither", which is exactly when the existing path is
25//! already correct. The absence is a *positive* statement, not a fallback —
26//! and that is what bounds this change's blast radius to the groups that are
27//! wrong today.
28//!
29//! # Default ON since 2026-08-18
30//!
31//! `SUI_NORMALIZE=0` opts OUT, restoring the pre-plan construction path. The
32//! latch survives the flip on purpose — a divergence suspected to come from
33//! this pass is then one command away from being confirmed or cleared, which
34//! is worth more than the tidiness of deleting it.
35
36use std::cell::RefCell;
37use std::sync::OnceLock;
38
39use std::rc::Rc;
40
41use sui_normalize::GroupPlan;
42
43/// One-time read of `SUI_NORMALIZE`. Default ON; `SUI_NORMALIZE=0` opts out.
44static ENABLED: OnceLock<bool> = OnceLock::new();
45
46/// Whether plan-driven attrset construction is enabled. **Default: yes.**
47///
48/// Flipped from opt-in to opt-out on 2026-08-18, on this evidence:
49///
50/// * every wrong-answer shape in the class matches nix, including the
51///   acceptance case `{ a = rec { b = c+1; d = 2; }; a.c = d+3; }.a.b` -> 6,
52///   which needs mutual recursion ACROSS the merge boundary;
53/// * a fleet scan of 4562 `.nix` files found ZERO false rejects — the one
54///   rejection is a file `nix-instantiate --parse` also refuses;
55/// * `sui perf-seal` moved DOWN or held on all three attr-merge rows
56///   (`dotted full-set leaf deep-merge` 6 -> 5), which is what confirms the
57///   splice happens at PARSE time rather than adding eval work;
58/// * the suites are green both ways.
59///
60/// The latch is KEPT, deliberately, in the `SUI_SCOPE_NARROW` spirit:
61/// `SUI_NORMALIZE=0` restores the pre-plan construction path, so a divergence
62/// suspected to come from this pass can be bisected in one command instead of
63/// a revert. That is also why the old entry loops are not deleted yet.
64#[must_use]
65pub fn enabled() -> bool {
66    *ENABLED.get_or_init(|| std::env::var("SUI_NORMALIZE").ok().as_deref() != Some("0"))
67}
68
69thread_local! {
70    /// `(source_id << 32) | text_offset` -> the binder's plan. Same keying as
71    /// `resolve_env::RESOLVE_TABLE` and `value::intern_cached`.
72    /// `Rc` because a lookup happens on EVERY evaluation of a planned attrset.
73    /// Storing the plan by value made `plan_for` a deep copy of the whole plan
74    /// subtree per evaluation; refcounted, it is a pointer bump.
75    static PLAN_TABLE: RefCell<rustc_hash::FxHashMap<u64, Memo>> =
76        RefCell::new(rustc_hash::FxHashMap::default());
77}
78
79#[inline]
80fn key(source_id: u32, text_offset: u32) -> u64 {
81    (u64::from(source_id) << 32) | u64::from(text_offset)
82}
83
84/// The plan for one binder node, computed ON DEMAND and memoized.
85///
86/// ★ Replaces a parse-door walk that planned every binder in every parsed
87/// file. Laziness means most of those are never evaluated, so that work was
88/// mostly discarded — measured as a ~4% wall-clock tax on a real nixpkgs eval.
89/// Planning at first evaluation is identical in result (a group's plan depends
90/// only on its own entries) and pays only for groups that are reached.
91///
92/// The memo is keyed exactly as before, so a plan computed for a node at
93/// offset `o` in one parse tree is never read for a different (imported) tree
94/// with a binder at the same offset.
95///
96/// A `None` return is a POSITIVE statement — the group has no duplicate static
97/// key and no dotted path, so the caller's existing path is already correct.
98/// See the module docs on why that is not a fallback.
99pub fn plan_for_node<N>(node: &N, recursive: bool, source_id: u32, offset: u32) -> Option<Rc<GroupPlan>>
100where
101    N: rnix::ast::HasEntry,
102{
103    if !enabled() {
104        return None;
105    }
106    let k = key(source_id, offset);
107    if let Some(hit) = PLAN_TABLE.with(|t| t.borrow().get(&k).cloned()) {
108        return hit.0;
109    }
110    // A rejected group records `None` — matching the walker's parse-door
111    // behaviour of swallowing `NormalizeError` until the rejection tier lands.
112    let computed = sui_normalize::plan_for_group(node, recursive)
113        .ok()
114        .flatten()
115        .map(Rc::new);
116    PLAN_TABLE.with(|t| t.borrow_mut().insert(k, Memo(computed.clone())));
117    computed
118}
119
120/// A memo entry. `Memo(None)` records "this group needs no plan", which must be
121/// remembered too — otherwise every evaluation of an ordinary attrset re-runs
122/// `needs_plan`, which is the cost this change exists to remove.
123#[derive(Clone)]
124struct Memo(Option<Rc<GroupPlan>>);
125
126
127/// Drop every recorded plan. Wired into the same lifecycle point as
128/// `resolve_env::clear`.
129pub fn clear() {
130    PLAN_TABLE.with(|t| t.borrow_mut().clear());
131}