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..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 @@ -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,95 @@ return t assert_eq!(changed.0, expected.0); 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() { + 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_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/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..145a1b93c 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -524,9 +524,28 @@ fn apply_field_nullable(model: &SemanticModel, member: &SemanticId, ty: LuaType) ty } +/// 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) +} + /// 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) +} + +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: path.ignore_guards, }; let base_before = model.type_of_decl(decl).unwrap_or(LuaType::Unknown); let frame = DeclAssignmentFrame { @@ -2502,14 +2530,38 @@ 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 { member: member.clone(), access: access.map(|access| access.get_syntax_id()), + ignore_guards: path.ignore_guards, }, flow_id: flow_id.0, }; @@ -2580,6 +2632,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 +2658,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 +5996,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)