From 473f89b445da5fcfabed4036f818bd4ec7896014 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Fri, 6 Nov 2026 14:33:26 +0100 Subject: [PATCH 1/3] fix(check): a member write's target ignores guards `if o.w == 'a' then o.w = fn end` reported expected `"a"`: the checker took the target from `type_of_member_at`, the narrowed read. A guard narrows reads, not what a write may store. The walk for a target now follows the member's writes and casts and skips guards, as a local's target does. It keeps its own memo states. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG --- .../src/check/checker/assign_type_mismatch.rs | 7 ++- .../check/test/assign_type_mismatch_test.rs | 61 ++++++++++++++++++- .../src/semantic_model/cache.rs | 1 + .../src/semantic_model/flow.rs | 45 ++++++++++++-- .../src/semantic_model/types.rs | 8 +++ 5 files changed, 113 insertions(+), 9 deletions(-) diff --git a/crates/emmylua_code_analysis/src/check/checker/assign_type_mismatch.rs b/crates/emmylua_code_analysis/src/check/checker/assign_type_mismatch.rs index 8b35760a2..d104c15c5 100644 --- a/crates/emmylua_code_analysis/src/check/checker/assign_type_mismatch.rs +++ b/crates/emmylua_code_analysis/src/check/checker/assign_type_mismatch.rs @@ -356,7 +356,10 @@ fn check_self_member_assign( && member.key.name() == Some(key.as_str()) && member.value_syntax != Some(value_expr.get_syntax_id()) }) - .map(|member| semantic_model.type_of_member_at(&member.id, index_expr.get_range().start())) + .map(|member| { + semantic_model + .type_of_member_assign_target_at(&member.id, index_expr.get_range().start()) + }) .or_else(|| { semantic_model.member_type(&owner_ty, &LuaMemberKey::Name(key.clone().into())) })?; @@ -373,7 +376,7 @@ fn check_member_assign( ) { let mut target = semantic_model.member_assignment_type( member_id, - semantic_model.type_of_member_at(member_id, target_offset), + semantic_model.type_of_member_assign_target_at(member_id, target_offset), ); // `t.x = value`: resolve_member first returns the synthesized member for this assignment; prefer the same-named member on the prefix's declared type. if let Some(facts) = semantic_model.file_facts() diff --git a/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs b/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs index a2a0b68d8..a5b5ed565 100644 --- a/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs +++ b/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs @@ -1,6 +1,6 @@ #[cfg(test)] mod tests { - use crate::check::test::{check_source, check_source_with_emmyrc}; + use crate::check::test::{check_source, check_source_with_emmyrc, count_by_code}; use crate::{DiagnosticCode, Emmyrc, LuaMemberKey, LuaType, VirtualWorkspace}; use tokio_util::sync::CancellationToken; @@ -2933,4 +2933,63 @@ return t assert_eq!(changed.0, expected.0); assert_eq!(changed.1.len(), 1, "{changed:?}"); } + + /// An undeclared member keeps following its writes, under a guard too. + #[test] + fn test_undeclared_member_write_target_ignores_guards() { + let diagnostics = check_source( + r#" + ---@param opts table + local function f(opts) + if opts.w == nil then + opts.w = function() return '' end + end + if opts.w == 'a' then + opts.w = function() return '' end + end + end + return f + "#, + ); + assert_eq!( + count_by_code(&diagnostics, DiagnosticCode::AssignTypeMismatch), + 0, + "{diagnostics:?}" + ); + } + + /// A guard narrows reads, not the contract of a write: inside `o.w == 'a'`, `o.w` may + /// still take anything its field declares, and nothing else. + #[test] + fn test_member_write_target_ignores_guards() { + for (write, expected) in [("function() return '' end", 0), ("1", 1)] { + for prefix in [ + "", + "if flag then o.w = 'b' end", + "if flag then o.w = function() return '' end end", + ] { + let source = format!( + r#" + ---@class GuardedWrite + ---@field w string|fun():string + + ---@param o GuardedWrite + ---@param flag boolean + local function f(o, flag) + {prefix} + if o.w == 'a' then + o.w = {write} + end + end + return f + "# + ); + assert_eq!( + count_by_code(&check_source(&source), DiagnosticCode::AssignTypeMismatch), + expected, + "{prefix} / {write}" + ); + } + } + } } diff --git a/crates/emmylua_code_analysis/src/semantic_model/cache.rs b/crates/emmylua_code_analysis/src/semantic_model/cache.rs index 44a352bcf..ca904903a 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/cache.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/cache.rs @@ -205,6 +205,7 @@ pub(crate) enum TraceSubject { Member { member: SemanticId, access: Option, + ignore_guards: bool, }, } diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 77b53917f..cbe7eb758 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -525,8 +525,27 @@ fn apply_field_nullable(model: &SemanticModel, member: &SemanticId, ty: LuaType) } /// Flow-sensitive type of the member at `offset` (member assignment flow + `---@cast t.x +T` widening). +/// Target type for a member write: its writes and casts, without guards. A guard narrows reads, +/// so inside `t.x == 1`, `t.x = "a"` is still held to what `t.x` may hold, not to `1`. +pub fn type_of_member_assign_target_at( + model: &SemanticModel, + member: &SemanticId, + offset: TextSize, +) -> LuaType { + member_type_at(model, member, offset, true) +} + /// Same as `type_of_decl_at`: exclude this assignment when `offset` lies on `t.x = value`. pub fn type_of_member_at(model: &SemanticModel, member: &SemanticId, offset: TextSize) -> LuaType { + member_type_at(model, member, offset, false) +} + +fn member_type_at( + model: &SemanticModel, + member: &SemanticId, + offset: TextSize, + ignore_guards: bool, +) -> LuaType { let fallback = || flow_member_value_type(model, member).unwrap_or(LuaType::Unknown); let Some(tree) = model.flow_tree() else { return fallback(); @@ -544,7 +563,10 @@ pub fn type_of_member_at(model: &SemanticModel, member: &SemanticId, offset: Tex && !tree.has_flow_event_between(assign_pos, offset, false) { let mut visited = HashSet::new(); - let mut path = PathState::default(); + let mut path = PathState { + ignore_guards, + ..PathState::default() + }; if let Some(ty) = trace_member( model, member, @@ -563,7 +585,10 @@ pub fn type_of_member_at(model: &SemanticModel, member: &SemanticId, offset: Tex } } let mut visited = HashSet::new(); - let mut path = PathState::default(); + let mut path = PathState { + ignore_guards, + ..PathState::default() + }; trace_member(model, member, None, &tree, start, &mut visited, &mut path) .unwrap_or_else(fallback) } @@ -1916,6 +1941,8 @@ struct PathState { narrowings: Vec, /// Most recent cast operation first. casts: Vec, + /// A member write's target: guards on the way are not collected. + ignore_guards: bool, } /// Checks from an antecedent toward the declaration whether a narrowing node already exists. @@ -2266,6 +2293,7 @@ fn trace_decl_uncached( let assign_path = PathState { narrowings, casts: path.casts.clone(), + ignore_guards: false, }; let base_before = model.type_of_decl(decl).unwrap_or(LuaType::Unknown); let frame = DeclAssignmentFrame { @@ -2510,6 +2538,7 @@ fn trace_member( subject: cache::TraceSubject::Member { member: member.clone(), access: access.map(|access| access.get_syntax_id()), + ignore_guards: path.ignore_guards, }, flow_id: flow_id.0, }; @@ -2580,6 +2609,7 @@ fn trace_member_uncached( let assign_path = PathState { narrowings: Vec::new(), casts: path.casts.clone(), + ignore_guards: path.ignore_guards, }; let mut value_ty = type_of_expr_with_cast(model, *value_syntax, AsOnly); if let Some(annotation) = member_annotation_type(model, member) { @@ -2605,15 +2635,17 @@ fn trace_member_uncached( collect_member_cast(model, member, cast_ptr, path); } FlowNodeKind::TrueCondition(cond_ptr) => { - if let Some(narrowing) = - narrow_member_condition(model, member, access, cond_ptr, true) + if !path.ignore_guards + && let Some(narrowing) = + narrow_member_condition(model, member, access, cond_ptr, true) { path.narrowings.push(narrowing); } } FlowNodeKind::FalseCondition(cond_ptr) => { - if let Some(narrowing) = - narrow_member_condition(model, member, access, cond_ptr, false) + if !path.ignore_guards + && let Some(narrowing) = + narrow_member_condition(model, member, access, cond_ptr, false) { path.narrowings.push(narrowing); } @@ -5941,6 +5973,7 @@ impl PathState { Self { narrowings: self.narrowings.iter().map(|n| n.clone_ref()).collect(), casts: self.casts.clone(), + ignore_guards: self.ignore_guards, } } } diff --git a/crates/emmylua_code_analysis/src/semantic_model/types.rs b/crates/emmylua_code_analysis/src/semantic_model/types.rs index dd9d4164b..e8fcf4280 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/types.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/types.rs @@ -1264,6 +1264,14 @@ impl<'db> SemanticModel<'db> { }); ty } + /// Assignment contract of a member: casts apply, conditional narrowing does not. + pub fn type_of_member_assign_target_at( + &self, + member: &SemanticId, + offset: TextSize, + ) -> LuaType { + flow::type_of_member_assign_target_at(self, member, offset) + } /// Decl type before the flow node at offset (for assignment checks: this assignment does not participate in the target type). pub fn type_of_decl_before_at(&self, decl: &SemanticId, offset: TextSize) -> LuaType { self.type_of_decl_before_at_impl(decl, offset) From 3f49362c8f94a0e6f98bab0d77ded18ccbec96a6 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Fri, 6 Nov 2026 14:34:08 +0100 Subject: [PATCH 2/3] fix(flow): a guard on a member no longer turns its memo off `trace_member` served its memo only to an empty path. A guard on the member leaves a narrowing on the path, so every later read walked both sides of every earlier guard: 2^n routes. `if h.b then print(1) end; print(h.b)` 20 times never finishes; 0.25.1 and a local are fine. The memo now holds the state for an empty path, and what the path collected applies to that state. Guards after a write now apply to the written value on reads, as they do for a local. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG --- .../phase_tests/flow_loop_memo_tests.rs | 40 ++++++++++++++++++- .../src/semantic_model/flow.rs | 25 +++++++++++- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_loop_memo_tests.rs b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_loop_memo_tests.rs index aa16866bf..604b140e5 100644 --- a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_loop_memo_tests.rs +++ b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_loop_memo_tests.rs @@ -4,7 +4,7 @@ //! function in it, so a chain of `n` guards in a loop-free function walked //! ~2^n routes (`walking.lua` of a real game client project never finished). -use emmylua_parser::{LuaAstNode, LuaNameExpr}; +use emmylua_parser::{LuaAstNode, LuaIndexExpr, LuaNameExpr}; use rowan::TextSize; use crate::semantic_model::flow::flow_metrics; @@ -103,3 +103,41 @@ fn flow_loop_in_other_function_keeps_guard_chain_linear() { } } } + +/// `n` guards on one field, each read again after its merge. +fn member_guard_chain(n: usize) -> String { + let mut content = String::from( + "---@class Hunk\n---@field count integer?\n\n---@param hunk Hunk\nlocal function f(hunk)\n", + ); + for _ in 0..n { + content.push_str(" if hunk.count then\n print(1)\n end\n print(hunk.count)\n"); + } + content.push_str("end\n"); + content +} + +/// A guard on a field leaves a narrowing on the path, and the member memo used to serve +/// only an empty path, so every read walked both sides of every earlier guard. diffs.nvim's +/// `highlight_hunk` never finished. The walk must stay polynomial in the number of guards. +#[test] +fn flow_member_guard_chain_keeps_the_memo() { + let mut measurements = Vec::new(); + for n in [4usize, 8, 12, 16] { + let mut ws = VirtualWorkspace::new(); + let file_id = ws.def_file("hunk.lua", &member_guard_chain(n)); + let model = ws.analysis.semantic_model(file_id); + flow_metrics::reset(); + for index in model.chunk().expect("chunk").descendants::() { + let _ = model.type_of_expr_at(index.get_syntax_id(), index.get_position()); + } + let steps = flow_metrics::trace_steps(); + measurements.push((n, steps)); + + let bound = 64 * (n as u64) * (n as u64) + 256; + assert!( + steps <= bound, + "the member walk took {steps} steps for {n} guards (bound {bound}). \ + So far: {measurements:?}" + ); + } +} diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index cbe7eb758..df9f4411d 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2530,9 +2530,32 @@ fn trace_member( visited: &mut HashSet, path: &mut PathState, ) -> Option { - if tree.is_loop_reachable(flow_id) || !path.casts.is_empty() || !path.narrowings.is_empty() { + if tree.is_loop_reachable(flow_id) + || path + .narrowings + .iter() + .any(|narrowing| matches!(narrowing, Narrowing::Correlated { .. })) + { return trace_member_uncached(model, member, access, tree, flow_id, visited, path); } + // The memo holds the state for an empty path, and what the path collected applies to + // that state. Walking on with it visits both sides of every earlier guard on this + // member, 2^n routes. + if !path.narrowings.is_empty() || !path.casts.is_empty() { + let state = trace_member( + model, + member, + access, + tree, + flow_id, + visited, + &mut PathState { + ignore_guards: path.ignore_guards, + ..PathState::default() + }, + )?; + return Some(finalize(model, state, path)); + } let key = cache::TraceStateKey { file_id: model.file_id(), subject: cache::TraceSubject::Member { From 586ea33cac0831b86e71d8490275872a700f9f52 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Fri, 6 Nov 2026 14:48:47 +0100 Subject: [PATCH 3/3] test(flow): mixed guards on one member, and doc placement From the bot review: a test for the memo replaying mixed guards, the doc line of `type_of_member_at` back on it, and `ignore_guards` carried in the decl walk too. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG --- .../check/test/assign_type_mismatch_test.rs | 32 +++++++++++++++++++ .../src/semantic_model/flow.rs | 4 +-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs b/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs index a5b5ed565..a8c302d27 100644 --- a/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs +++ b/crates/emmylua_code_analysis/src/check/test/assign_type_mismatch_test.rs @@ -2934,6 +2934,38 @@ return t assert_eq!(changed.1.len(), 1, "{changed:?}"); } + /// Mixed guards on one member, read past the merge of earlier ones: what the path + /// collected applies to the memoized state in the order of the program. + #[test] + fn test_mixed_member_guards_apply_to_the_memoized_state() { + for (read, expected) in [("string|integer", 0), ("string", 1)] { + let source = format!( + r#" + ---@class MixedGuards + ---@field v string|integer|nil + + ---@param o MixedGuards + local function f(o) + if o.v then print(1) end + if o.v == 'x' then print(2) end + if type(o.v) == 'number' then print(3) end + if o.v and o.v ~= 'y' then + ---@type {read} + local value = o.v + return value + end + end + return f + "# + ); + assert_eq!( + count_by_code(&check_source(&source), DiagnosticCode::AssignTypeMismatch), + expected, + "{read}" + ); + } + } + /// An undeclared member keeps following its writes, under a guard too. #[test] fn test_undeclared_member_write_target_ignores_guards() { diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index df9f4411d..145a1b93c 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -524,7 +524,6 @@ fn apply_field_nullable(model: &SemanticModel, member: &SemanticId, ty: LuaType) ty } -/// Flow-sensitive type of the member at `offset` (member assignment flow + `---@cast t.x +T` widening). /// Target type for a member write: its writes and casts, without guards. A guard narrows reads, /// so inside `t.x == 1`, `t.x = "a"` is still held to what `t.x` may hold, not to `1`. pub fn type_of_member_assign_target_at( @@ -535,6 +534,7 @@ pub fn type_of_member_assign_target_at( member_type_at(model, member, offset, true) } +/// Flow-sensitive type of the member at `offset` (member assignment flow + `---@cast t.x +T` widening). /// Same as `type_of_decl_at`: exclude this assignment when `offset` lies on `t.x = value`. pub fn type_of_member_at(model: &SemanticModel, member: &SemanticId, offset: TextSize) -> LuaType { member_type_at(model, member, offset, false) @@ -2293,7 +2293,7 @@ fn trace_decl_uncached( let assign_path = PathState { narrowings, casts: path.casts.clone(), - ignore_guards: false, + ignore_guards: path.ignore_guards, }; let base_before = model.type_of_decl(decl).unwrap_or(LuaType::Unknown); let frame = DeclAssignmentFrame {