From a8b6139611332efe5d2bfe01ee0ab5c092e42864 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Sun, 22 Nov 2026 14:27:46 +0100 Subject: [PATCH] fix(infer): a member missing from an unresolved name or an alias of a union is unknown, not nil A read of a key missing from a `Ref`/`Def` owner returned `nil` for every such owner, though the comment above it says "declared class instances". A name with no declaration (`---@param m Missing`) knows nothing about its members: 0.25.1 reads `m.kind` as `unknown`, and `member_missing_in_union` already skips such a union component. Reading it as `nil` turned one `type-not-found` into follow-up false hits wherever the value flows (need-check-nil, param-type-mismatch, unnecessary-if, ...). The same rule was wrong for an alias of a union holding such a name: the alias read `nil` where the inline union reads `unknown`. New `missing_member_is_known`: a declared class or enum is known (`nil` stays), an alias reads like its target, an undeclared name is `unknown`. `undefined-field` still reports every such read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUUSjAWtbRaNWmmf1F3n --- .../check/test/assign_type_mismatch_test.rs | 54 ++++++++++++++++++- .../src/check/test/mod.rs | 13 +++++ .../src/semantic_model/infer/vm.rs | 47 +++++++++++----- 3 files changed, 101 insertions(+), 13 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 5d54a12dd..9b1104700 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,8 @@ #[cfg(test)] mod tests { - use crate::check::test::{check_source, check_source_with_emmyrc, count_by_code}; + use crate::check::test::{ + check_source, check_source_with_emmyrc, count_by_code, texts_by_code, + }; use crate::{DiagnosticCode, Emmyrc, LuaMemberKey, LuaType, VirtualWorkspace}; use tokio_util::sync::CancellationToken; @@ -3336,4 +3338,54 @@ return t } } } + + /// A member read through a name that resolves to no declaration is `unknown`, not `nil`: + /// nothing is known about such a type's members. The missing name is `type-not-found`'s and + /// the read `undefined-field`'s; the sink does not report it again. An alias reads like its + /// target. A declared class's or an object alias's missing member stays `nil`. + #[test] + fn test_member_of_an_unresolved_type_is_unknown_not_nil() { + let source = r#" + ---@param m Missing + local function h(m) + ---@type boolean + local z = m.kind + return z + end + + ---@alias AliasOfMissing Missing + ---@type AliasOfMissing + local a + ---@type boolean + local w = a.kind + + -- An alias of a union holding an unresolved name reads like the inline union. + ---@alias ItemOfMissing Missing|{ text?: string } + ---@type ItemOfMissing + local it + ---@type boolean + local v = it.kind + + ---@class DeclaredClass + ---@param d DeclaredClass + local function k(d) + ---@type boolean + local y = d.kind + return y + end + + ---@alias ObjectShape { text?: string } + ---@type ObjectShape + local s + ---@type boolean + local x = s.kind + return h, k, w, v, x + "#; + let diags = check_source(source); + let assign = texts_by_code(source, &diags, DiagnosticCode::AssignTypeMismatch); + assert_eq!(assign, vec!["d.kind", "s.kind"], "{diags:#?}"); + let undefined = texts_by_code(source, &diags, DiagnosticCode::UndefinedField); + // One per read (the range is the key): m, a, it, d, s. + assert_eq!(undefined, vec!["kind"; 5], "{diags:#?}"); + } } diff --git a/crates/emmylua_code_analysis/src/check/test/mod.rs b/crates/emmylua_code_analysis/src/check/test/mod.rs index 0a22f0aa8..5eca83e26 100644 --- a/crates/emmylua_code_analysis/src/check/test/mod.rs +++ b/crates/emmylua_code_analysis/src/check/test/mod.rs @@ -86,6 +86,19 @@ pub(crate) fn count_by_code(diagnostics: &[Diagnostic], code: DiagnosticCode) -> diagnostics.iter().filter(|d| d.code == code).count() } +/// The source text each diagnostic of `code` covers, in report order. +pub(crate) fn texts_by_code<'a>( + source: &'a str, + diagnostics: &[Diagnostic], + code: DiagnosticCode, +) -> Vec<&'a str> { + diagnostics + .iter() + .filter(|d| d.code == code) + .map(|d| &source[d.range]) + .collect() +} + /// End-to-end: EmmyLuaAnalysis::diagnose_file_with_config → lsp Diagnostic (range/code/severity). #[test] fn test_diagnose_semantic_end_to_end() { diff --git a/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs index 74174f785..19d8510ee 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs @@ -1034,6 +1034,38 @@ impl<'a> InferVm<'a> { Value::plain(self.table_missing_index_type(table)) } + /// Whether a key missing from `ty`'s members is known to be missing (a read is `nil`, not + /// `unknown`): a declared class or enum, an object, a table literal with members. A name + /// with no declaration knows nothing about its members, and an alias resolves to its + /// target. + fn missing_member_is_known( + model: &SemanticModel<'_>, + ty: &LuaType, + visited: &mut Vec, + ) -> bool { + match ty { + LuaType::TableConst(_) => Self::table_literal_has_members(model, ty), + LuaType::Object(_) => true, + LuaType::Ref(id) | LuaType::Def(id) => { + let defs = model.type_defs_of(id); + let Some(def) = defs.as_slice().first() else { + return false; + }; + if def.kind != TypeDefKind::Alias { + return true; + } + if visited.contains(id) { + return false; + } + visited.push(id.clone()); + model + .alias_target(def) + .is_some_and(|target| Self::missing_member_is_known(model, &target, visited)) + } + _ => false, + } + } + /// Whether an anonymous table literal already has a known member shape. /// An empty `{}` with no fields/runtime members is treated as "unknown shape"; missing /// keys return Unknown instead of a definite Nil so not-yet-initialized members are not @@ -1390,18 +1422,9 @@ impl<'a> InferVm<'a> { receiver: receiver_ty, }; } - // Named table literals / declared class instances return nil for missing keys (Lua - // member-index semantics), not Unknown; `t.missing` / `other.extra` should not - // degrade to "cannot infer". For empty table literals with no known member shape, - // still return Unknown because whether such fields are missing cannot be decided - // from the type side, and nil would treat not-yet-initialized members as definitely - // missing (issue 600). - let missing_is_known = match &owner.ty { - LuaType::TableConst(_) => Self::table_literal_has_members(self.model, &owner.ty), - LuaType::Ref(_) | LuaType::Def(_) | LuaType::Object(_) => true, - _ => false, - }; - if missing_is_known { + // A key missing from a known member set reads `nil` (Lua member-index semantics), so + // `t.missing` / `other.extra` do not degrade to "cannot infer"; otherwise `unknown`. + if Self::missing_member_is_known(self.model, &owner.ty, &mut Vec::new()) { return Value::plain(LuaType::Nil); } Value::plain(LuaType::Unknown)