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 3c5f00a15..0ad52d84d 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 @@ -2362,6 +2362,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(); 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 006d325cd..3a90c0fbc 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 @@ -78,4 +78,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 352563786..257826772 100644 --- a/crates/emmylua_code_analysis/src/semantic_db/query.rs +++ b/crates/emmylua_code_analysis/src/semantic_db/query.rs @@ -2773,6 +2773,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()); @@ -2798,8 +2802,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/legacy_tests/member_infer_test.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/member_infer_test.rs index 63cbb6d63..719f4cca5 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 @@ -842,4 +842,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/infer/vm.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs index d76fd612d..fb30b2e66 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs @@ -14,7 +14,7 @@ use std::rc::Rc; use emmylua_parser::{ BinaryOperator, LuaAstNode, LuaCallExpr, LuaClosureExpr, LuaDocFuncType, LuaDocType, LuaExpr, - LuaIndexKey, LuaReturnStat, LuaSyntaxId, + LuaIndexKey, LuaReturnStat, LuaSyntaxId, LuaSyntaxKind, }; use hashbrown::HashMap; @@ -1508,7 +1508,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 { @@ -2514,6 +2516,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