From 668a5b9206b7958cf32d004f18a5392f1536eb7f Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Sat, 24 Oct 2026 02:48:41 +0200 Subject: [PATCH 1/3] test(check): a `[string]` index signature allows injecting name keys ```lua ---@class Accessor ---@field [string] any ---@type Accessor local g = {} g.aaa = true -- was: inject-field ``` Upstream e1cd626e ("unify index signature resolution") replaced the `member.name.starts_with('[')` skip in `check_index_assign` with an `applicable_index_infos` lookup, which accepts this; the test passes on 1b6df859 without a code change here. This commit only pins the case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01923KEUKXBrPZHHVvqPVpA1 Claude-Session: https://claude.ai/code/session_018NxUURS1MVzowfNDjH6GGy --- .../src/check/test/inject_field_test.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/emmylua_code_analysis/src/check/test/inject_field_test.rs b/crates/emmylua_code_analysis/src/check/test/inject_field_test.rs index 9fe0756d1..edddfb133 100644 --- a/crates/emmylua_code_analysis/src/check/test/inject_field_test.rs +++ b/crates/emmylua_code_analysis/src/check/test/inject_field_test.rs @@ -771,6 +771,23 @@ return items )); } + /// A class with a `[string]` index signature accepts any name key. + #[test] + fn test_index_signature_class_allows_name_keys() { + let mut ws = VirtualWorkspace::new(); + assert!(ws.has_no_diagnostic( + DiagnosticCode::InjectField, + r#" + --- @class Accessor + --- @field [string] any + + ---@type Accessor + local g = {} + g.aaa = true + "#, + )); + } + #[test] fn test_alias_unknown_allows_field_injection() { let mut ws = VirtualWorkspace::new(); From 6c229674c54dbdb5fe9ef15cf3a805f6ada1c048 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Sat, 24 Oct 2026 02:48:41 +0200 Subject: [PATCH 2/3] fix(semantic): declared member type beats `__index`; keep guarded returns (#1319) Neovim declares `vim.env` as ```lua --- @type table vim.env = setmetatable({}, { __index = function(_, k) local v = os.getenv(k) if v == nil then return nil end return v end }) ``` and every `if vim.env.X then` was reported "always falsy". Three causes: 1. A member's `---@type` was ignored. `type_of_member_impl` returned the VM type of a call value before looking at the doc type, and the shell `member_type` never read `doc_type_syntax`. Both now let a declared type win, as `decl_type` already does for locals. 2. `signature_returns` merged a `return` it could not type (the std call `os.getenv(k)` is unknown to the shell) away, so the function returned only `nil`. An unknown row now makes the shell result unknown and callers use the VM's return inference (`string?`). 3. Typing `v == nil` first (as unnecessary-if does) went `os.getenv(k)` -> param `k` -> the `setmetatable` call -> `member_info(mt, "__index")` -> the closure's return -> `return v`, whose narrowing was still in progress; the truncated `nil` was cached. The `setmetatable` builtin only needs to know whether `__index` is a named type, so it no longer types an `__index = function ... end` literal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01923KEUKXBrPZHHVvqPVpA1 --- .../src/check/test/unnecessary_if_test.rs | 70 +++++++++++++++++++ .../src/semantic_db/query.rs | 19 +++++ .../src/semantic_model/infer/vm.rs | 26 ++++++- .../src/semantic_model/types.rs | 3 + 4 files changed, 116 insertions(+), 2 deletions(-) diff --git a/crates/emmylua_code_analysis/src/check/test/unnecessary_if_test.rs b/crates/emmylua_code_analysis/src/check/test/unnecessary_if_test.rs index fe7c87d33..893589cd3 100644 --- a/crates/emmylua_code_analysis/src/check/test/unnecessary_if_test.rs +++ b/crates/emmylua_code_analysis/src/check/test/unnecessary_if_test.rs @@ -77,4 +77,74 @@ mod test { "# )); } + /// #1319: a declared `---@type` on a member wins over the metatable's `__index` return + /// (Neovim declares `vim.env` this way). + #[test] + fn test_issue_1319_declared_type_wins_over_metatable_index() { + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + ws.def_file( + "def.lua", + r#" + G = {} + + --- @type table + G.envA = setmetatable({}, { + __index = function(_, k) + local v = os.getenv(k) + if v == nil then return nil end + return v + end, + }) + + --- @type table + G.envD = setmetatable({}, { __index = function(_, k) return 'always' end }) + "#, + ); + for member in ["G.envA", "G.envD"] { + let ty = ws.expr_ty(member); + assert_eq!(ws.humanize_type(ty), "table", "{member}"); + } + assert!(ws.has_no_diagnostic( + DiagnosticCode::UnnecessaryIf, + r#" + if G.envA.X then print 'A' end + if G.envD.X then print 'D' end + "# + )); + } + + /// #1319: `if v == nil then return nil end return v` returns `string?`, not `nil`, also + /// as an `__index` function and when the inner condition is checked first. + #[test] + fn test_issue_1319_guarded_return_keeps_both_paths() { + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + ws.def_file( + "def.lua", + r#" + F = function(_, k) + local v = os.getenv(k) + if v == nil then return nil end + return v + end + ENV = setmetatable({}, { __index = F }) + "#, + ); + let fun = ws.expr_ty("F"); + assert!(ws.humanize_type(fun).ends_with("-> string?")); + let field = ws.expr_ty("ENV.X"); + assert_eq!(ws.humanize_type(field), "string?"); + assert!(ws.has_no_diagnostic( + DiagnosticCode::UnnecessaryIf, + r#" + local env = setmetatable({}, { + __index = function(_, k) + local v = os.getenv(k) + if v == nil then return nil end + return v + end, + }) + if env.X then print 'A' end + "# + )); + } } diff --git a/crates/emmylua_code_analysis/src/semantic_db/query.rs b/crates/emmylua_code_analysis/src/semantic_db/query.rs index 78b4ab597..767393d69 100644 --- a/crates/emmylua_code_analysis/src/semantic_db/query.rs +++ b/crates/emmylua_code_analysis/src/semantic_db/query.rs @@ -2382,6 +2382,17 @@ pub(crate) fn member_type( return TypeShell::from_module_ref(module_file); } + // `---@type T` on a runtime member assignment (`---@type T` + `M.x = v`) wins over the value, + // as it does for a local declaration in `decl_type`. + if !matches!(member.owner, SemanticId::TypeDef(_)) + && let Some(type_syntax) = member.doc_type_syntax + { + let shell = lower_doc_type(db, file, type_syntax, &[]); + if !shell.is_unknown() { + return shell; + } + } + // Value: owner is `TypeDef` (@field) -> doc type node; otherwise -> expression. if let Some(value_syntax) = member.value_syntax { match &member.owner { @@ -2671,6 +2682,10 @@ pub(crate) fn signature_returns( }) .collect(); let mut rows = TypeShell::unknown(); + // A `return` whose value the shell cannot type (a std call such as `os.getenv(k)`) makes the + // whole result unknown, so callers fall back to the VM instead of trusting the other returns + // alone (`if v == nil then return nil end return v` must not become `nil`). + let mut has_unknown_row = false; for ret in returns { let exprs: Vec<_> = ret.get_expr_list().collect(); let mut slots = Vec::with_capacity(exprs.len()); @@ -2696,8 +2711,12 @@ pub(crate) fn signature_returns( candidates: vec![TypeCandidate::Multi(slots)], } }; + has_unknown_row |= row.is_unknown(); rows.merge(&row); } + if has_unknown_row { + rows = TypeShell::unknown(); + } // When there is no explicit return annotation and the body cannot infer a type, keep member returns from class-field declarations. if rows.is_unknown() { if let Some(expected) = member_expected_returns(db, &facts, file, config, closure_syntax) { 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 b372beeeb..6fc31b227 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs @@ -12,7 +12,7 @@ use std::rc::Rc; use emmylua_parser::{ BinaryOperator, LuaAstNode, LuaCallExpr, LuaClosureExpr, LuaDocType, LuaExpr, LuaIndexKey, - LuaReturnStat, LuaSyntaxId, + LuaReturnStat, LuaSyntaxId, LuaSyntaxKind, }; use hashbrown::HashMap; @@ -1447,7 +1447,9 @@ impl<'a> InferVm<'a> { let Some(first) = args.first() else { return Value::plain(LuaType::Unknown); }; - if let Some(metatable) = args.get(1) { + if let Some(metatable) = args.get(1) + && !self.metatable_index_is_closure(&metatable.ty) + { let index_key = LuaMemberKey::Name(SmolStr::new("__index")); if let Some(info) = self.model.member_info(&metatable.ty, &index_key) { let index_ty = match &info.typ { @@ -2448,6 +2450,26 @@ impl<'a> InferVm<'a> { candidates } + /// Whether `mt` is a table literal with `__index = function ... end`. Such an `__index` + /// never gives the instance a named type, and typing the closure would infer its returns, + /// which can read back into the expression being inferred (a `k` param of that closure). + fn metatable_index_is_closure(&self, metatable: &LuaType) -> bool { + let LuaType::TableConst(table) = metatable else { + return false; + }; + let owner = SemanticId::member(table.file_id, table.value); + self.model + .members_of_owner_named(&owner, "__index") + .iter() + .any(|member_ref| { + self.model + .file_facts_of(member_ref.file_id) + .and_then(|facts| facts.member_by_id(&member_ref.id)) + .and_then(|member| member.value_syntax) + .is_some_and(|syntax| syntax.get_kind() == LuaSyntaxKind::ClosureExpr) + }) + } + /// Resolve the `__call` candidate from a `setmetatable(t, mt)` initializer. /// /// Only handles callees whose declaration/table identity is directly created by diff --git a/crates/emmylua_code_analysis/src/semantic_model/types.rs b/crates/emmylua_code_analysis/src/semantic_model/types.rs index dd9d4164b..f41650615 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/types.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/types.rs @@ -802,9 +802,12 @@ impl<'db> SemanticModel<'db> { // Runtime member assignments prefer VM projection: the TypeShell path does not perform higher-order generic call inference, // and would keep `E.foo_wrapped = wrap(function(a) ... end)` as `fun(...: T...)`. // Cycles/reentry are handled by `CacheEntry::InProgress` in the shared cache. + // A declared `---@type` on the member wins over its value (`---@type table` + // on `G.env = setmetatable({}, { __index = ... })`); the shell below lowers that doc type. if let Some(facts) = self.file_facts_of(member_file) && let Some(member_def) = facts.member_by_id(member) && !matches!(member_def.owner, SemanticId::TypeDef(_)) + && member_def.doc_type_syntax.is_none() && let Some(value_syntax) = member_def.value_syntax { // Table-literal fields keep the expression type from construction (`[key] = 1`, named fields From 0ffb9181c79c36e95669adb2bcca1661484bfac5 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Sun, 25 Oct 2026 02:48:27 +0200 Subject: [PATCH 3/3] fix(semantic): a member's declared object type keeps its fields Letting a member's `---@type` win (previous commit) read it through the shell, which lowers a structural doc type to a bare `table`: `M.state = { waiting = 0 } ---@type { waiting: integer }` made `M.state.waiting` unknown, so `M.state.waiting + 1` was `number` and assigning it back mismatched `integer`. When the shell degrades a member's doc type to `table`/unknown, use the rich projection, as a declaration's `---@type` already does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QkccaWeuDEcV9sJ8pLapCM --- .../infer/legacy_tests/member_infer_test.rs | 14 +++++++++++ .../src/semantic_model/types.rs | 25 +++++++++++++------ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/member_infer_test.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/member_infer_test.rs index a6569c179..ee1412972 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/member_infer_test.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/member_infer_test.rs @@ -598,4 +598,18 @@ mod test { let ty = ws.expr_ty("B"); assert_eq!(ws.humanize_type(ty), "1"); } + + /// A member's declared object type keeps its fields: `---@type { waiting: integer }` on + /// `M.state = { waiting = 0 }` does not degrade to a bare `table`. + #[test] + fn test_member_declared_object_type_keeps_fields() { + let mut ws = VirtualWorkspace::new(); + ws.def( + r#" + M = {} + M.state = { waiting = 0 } ---@type { prev: string?, waiting: integer } + "#, + ); + assert_eq!(ws.expr_ty("M.state.waiting"), ws.ty("integer")); + } } diff --git a/crates/emmylua_code_analysis/src/semantic_model/types.rs b/crates/emmylua_code_analysis/src/semantic_model/types.rs index f41650615..c1991d4b7 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/types.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/types.rs @@ -840,14 +840,23 @@ impl<'db> SemanticModel<'db> { let ty = self .analysis() .type_shell_lua_in(member_file, &shell, &generic_names); - let ty = if let Some(facts) = self.file_facts_of(member_file) - && let Some(member_def) = facts.member_by_id(member) - && member_def.doc_type_syntax.is_none() - && let Some(value_syntax) = member_def.value_syntax - { - flow::apply_expr_casts(self, value_syntax, ty, flow::ExprCastMode::AsOnly) - } else { - ty + let Some(member_def) = self + .file_facts_of(member_file) + .and_then(|facts| facts.member_by_id(member).cloned()) + else { + return Some(ty); + }; + let ty = match (member_def.doc_type_syntax, member_def.value_syntax) { + // The shell lowers a structural doc type (`---@type { x: T }`) to a bare `table`; + // the rich projection keeps it, as for a declaration's `---@type`. + (Some(doc_syntax), _) if matches!(ty, LuaType::Table | LuaType::Unknown) => { + let rich = self.doc_type_lua_rich_in(member_file, doc_syntax); + if rich.is_unknown() { ty } else { rich } + } + (None, Some(value_syntax)) => { + flow::apply_expr_casts(self, value_syntax, ty, flow::ExprCastMode::AsOnly) + } + _ => ty, }; Some(ty) }