From 75fdda6ac5257148448b8264b6bcc575ad5e00bf Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Wed, 4 Nov 2026 14:46:54 +0100 Subject: [PATCH 1/2] fix(flow): a memoized flow state keeps the guards a later query brings `trace_decl` memoizes a node's state without the incoming path, assuming every route to a node crosses the same guards. Within one query it does, but the memo outlives the query: a read that reached the node with no guards stored a state, and a later read whose route crosses a guard got that state with the guard dropped. The memo now holds the state for an empty incoming path, and a query arriving with guards narrows it. Incoming casts and correlated narrowings stay as they were. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUUQmc3YFNEXrUcrVPxV --- .../src/check/test/need_check_nil_test.rs | 36 +++++++++++++++++++ .../src/semantic_model/cache.rs | 7 ++-- .../src/semantic_model/flow.rs | 27 ++++++++++++-- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs b/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs index 9656297e3..706dcea99 100644 --- a/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs +++ b/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs @@ -294,4 +294,40 @@ mod test { "#, )); } + + #[test] + fn test_and_narrows_after_merge_of_earlier_guard() { + // After `if prev and ok()` merges back to `St?`, the later `prev and prev.sig` still + // narrows its right side, even when an unguarded read of `prev` memoized the merge + // first. Needs the std library and every check: with less, nothing reads `prev` + // before the guarded read, and the test passes without the fix. + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + let file_id = ws.def( + r#" + ---@class St + ---@field sig string + + ---@return St? + local function decode() end + + ---@return boolean + local function ok() return true end + + local prev = decode() + if prev and ok() then end + print(prev and prev.sig) + "#, + ); + let diagnostics = ws + .analysis + .diagnose_file(file_id, CancellationToken::new()) + .unwrap_or_default(); + let code = Some(NumberOrString::String( + DiagnosticCode::NeedCheckNil.get_name().to_string(), + )); + assert!( + !diagnostics.iter().any(|diag| diag.code == code), + "{diagnostics:#?}" + ); + } } diff --git a/crates/emmylua_code_analysis/src/semantic_model/cache.rs b/crates/emmylua_code_analysis/src/semantic_model/cache.rs index 44a352bcf..f520917f0 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/cache.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/cache.rs @@ -212,10 +212,9 @@ pub(crate) enum TraceSubject { /// Original-signature traces keep incoming PathState empty and memoize each /// node's transfer during unwind, so a cached node never contains later casts. /// -/// The incoming path is deliberately absent. It is safe to omit only for flow -/// graphs without loops, where every route to a flow node crosses the same -/// guards, so the path is a function of the node. [`super::flow`] consults this -/// memo only in that case and recomputes otherwise. +/// The state is the one for an empty incoming path: [`super::flow`] applies the +/// guards a query collected before reaching the node on top of it. The memo is +/// consulted only for nodes with no loop behind them, and recomputed otherwise. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct TraceStateKey { pub(crate) file_id: FileId, diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 77b53917f..ea56414cd 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2144,9 +2144,8 @@ fn trace_decl( visited: &mut HashSet, path: &mut PathState, ) -> Option { - // On a loop-free graph every route to a flow node crosses the same guards, so - // a state's value depends on the node and the purpose alone — never on the - // route. That makes the state cacheable, which matters because a nested + // On a loop-free graph a state for an empty incoming path depends on the node and + // the purpose alone. That makes it cacheable, which matters because a nested // conditional chain otherwise re-derives the same states along exponentially // many routes. Only nodes that can reach a loop backwards keep the uncached // path (see the type note on `cache::TraceStateKey`), so a loop in one function @@ -2154,6 +2153,28 @@ fn trace_decl( if tree.is_loop_reachable(flow_id) { return trace_decl_uncached(model, decl, tree, flow_id, purpose, mode, visited, path); } + // The memo holds the state for an empty incoming path. Guards collected between the query + // and this node narrow that state: they apply in program order and distribute over branch + // merges. Incoming casts and correlated narrowings do not commute that way. + if !path.narrowings.is_empty() + && path.casts.is_empty() + && !path + .narrowings + .iter() + .any(|narrowing| matches!(narrowing, Narrowing::Correlated { .. })) + { + let state = trace_decl( + model, + decl, + tree, + flow_id, + purpose, + mode, + visited, + &mut PathState::default(), + )?; + return Some(finalize(model, state, path)); + } let key = decl_trace_key(model, decl, flow_id, purpose, mode); { let cache = model.cache.borrow(); From 4cf1f18da30e50ba9a84149c65f0d665fb87d4a9 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Sun, 8 Nov 2026 00:07:19 +0100 Subject: [PATCH 2/2] docs(flow): say why guards may narrow a memoized merge, add a control `narrows_a_merged_state` matches every `Narrowing`, so a new variant has to be placed on purpose, and says when narrowing a merge agrees with narrowing each branch. The new control test shows the fixture reports `prev` when no guard covers the read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUURuoSufkUL6bLjXoS7 --- .../src/check/test/need_check_nil_test.rs | 36 +++++++++++-------- .../src/semantic_model/flow.rs | 34 ++++++++++++++---- 2 files changed, 50 insertions(+), 20 deletions(-) diff --git a/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs b/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs index 706dcea99..cdfe679cd 100644 --- a/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs +++ b/crates/emmylua_code_analysis/src/check/test/need_check_nil_test.rs @@ -295,14 +295,10 @@ mod test { )); } - #[test] - fn test_and_narrows_after_merge_of_earlier_guard() { - // After `if prev and ok()` merges back to `St?`, the later `prev and prev.sig` still - // narrows its right side, even when an unguarded read of `prev` memoized the merge - // first. Needs the std library and every check: with less, nothing reads `prev` - // before the guarded read, and the test passes without the fix. + /// `need-check-nil` hits on the fixture of the next two tests, with `read` as its last line. + fn need_check_nil_after_merge(read: &str) -> usize { let mut ws = VirtualWorkspace::new_with_init_std_lib(); - let file_id = ws.def( + let file_id = ws.def(&format!( r#" ---@class St ---@field sig string @@ -315,9 +311,9 @@ mod test { local prev = decode() if prev and ok() then end - print(prev and prev.sig) - "#, - ); + {read} + "# + )); let diagnostics = ws .analysis .diagnose_file(file_id, CancellationToken::new()) @@ -325,9 +321,21 @@ mod test { let code = Some(NumberOrString::String( DiagnosticCode::NeedCheckNil.get_name().to_string(), )); - assert!( - !diagnostics.iter().any(|diag| diag.code == code), - "{diagnostics:#?}" - ); + diagnostics.iter().filter(|diag| diag.code == code).count() + } + + #[test] + fn test_and_narrows_after_merge_of_earlier_guard() { + // After `if prev and ok()` merges back to `St?`, the later `prev and prev.sig` still + // narrows its right side, even when an unguarded read of `prev` memoized the merge + // first. Needs the std library and every check: with less, nothing reads `prev` + // before the guarded read, and the test passes without the fix. + assert_eq!(need_check_nil_after_merge("print(prev and prev.sig)"), 0); + } + + #[test] + fn test_unguarded_read_after_merge_needs_check_nil() { + // Control for the test above: the same fixture does report `prev` when nothing guards it. + assert_eq!(need_check_nil_after_merge("print(prev.sig)"), 1); } } diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index ea56414cd..73eb3075e 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2154,14 +2154,11 @@ fn trace_decl( return trace_decl_uncached(model, decl, tree, flow_id, purpose, mode, visited, path); } // The memo holds the state for an empty incoming path. Guards collected between the query - // and this node narrow that state: they apply in program order and distribute over branch - // merges. Incoming casts and correlated narrowings do not commute that way. + // and this node narrow that state (see `narrows_a_merged_state`). A query with incoming casts + // keeps the memo as before. if !path.narrowings.is_empty() && path.casts.is_empty() - && !path - .narrowings - .iter() - .any(|narrowing| matches!(narrowing, Narrowing::Correlated { .. })) + && path.narrowings.iter().all(narrows_a_merged_state) { let state = trace_decl( model, @@ -2735,6 +2732,31 @@ fn finalize(model: &SemanticModel, mut base: LuaType, path: &PathState) -> LuaTy base } +/// Whether a guard collected before a memoized node may narrow that node's state, which can be a +/// merge of branches. The uncached walk applies a guard to each branch's value; this applies it to +/// their union. The two agree for a guard `f` with `f(A | B) = f(A) | f(B)`: one that keeps or +/// drops each component of the value (`Remove`, `Truthy`, `Falsy`, `NotNil`, `FilterPrimitive`, +/// `MemberDiscriminant`, `MemberTruthy`), or that maps every value to one type (`Replace`). +/// They can differ where a guard looks at the whole value: `Remove` widens a lone integer constant +/// it would empty, and `ArrayLen`/`ArrayMinLen` touch only a value that is wholly an array. There +/// the merged answer can be less precise, but the guard still applies. `Correlated` keeps the +/// whole value when no row matches and reads the call that produced it, so it stays out. +fn narrows_a_merged_state(narrowing: &Narrowing) -> bool { + match narrowing { + Narrowing::Replace(_) + | Narrowing::Remove(_) + | Narrowing::Truthy + | Narrowing::Falsy + | Narrowing::NotNil + | Narrowing::FilterPrimitive { .. } + | Narrowing::MemberDiscriminant { .. } + | Narrowing::MemberTruthy { .. } + | Narrowing::ArrayLen(_) + | Narrowing::ArrayMinLen(_) => true, + Narrowing::Correlated { .. } => false, + } +} + /// Apply narrowing: replacement returns directly; removal removes components. fn apply_narrowing(model: &SemanticModel, mut ty: LuaType, narrowing: &Narrowing) -> LuaType { match narrowing {