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..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 @@ -294,4 +294,48 @@ mod test { "#, )); } + + /// `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(&format!( + 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 + {read} + "# + )); + let diagnostics = ws + .analysis + .diagnose_file(file_id, CancellationToken::new()) + .unwrap_or_default(); + let code = Some(NumberOrString::String( + DiagnosticCode::NeedCheckNil.get_name().to_string(), + )); + 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/cache.rs b/crates/emmylua_code_analysis/src/semantic_model/cache.rs index 6f269d3ca..3313ea12e 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/cache.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/cache.rs @@ -239,10 +239,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 -/// nodes outside a cycle, where every route to the 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 outside a cycle, 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 ebab731fb..cde16557c 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2214,9 +2214,8 @@ fn trace_decl( visited: &mut HashSet, path: &mut PathState, ) -> Option { - // Outside a cycle 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 + // Outside a cycle, 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 on a cycle keep the uncached path (see the type note // on `cache::TraceStateKey`), so a loop does not disable memoization for the @@ -2224,6 +2223,25 @@ fn trace_decl( if tree.is_in_cycle(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 (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().all(narrows_a_merged_state) + { + 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(); @@ -2841,6 +2859,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 {