Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions crates/emmylua_code_analysis/src/check/test/inject_field_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
70 changes: 70 additions & 0 deletions crates/emmylua_code_analysis/src/check/test/unnecessary_if_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string?>
G.envA = setmetatable({}, {
__index = function(_, k)
local v = os.getenv(k)
if v == nil then return nil end
return v
end,
})

--- @type table<string, string?>
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<string,string?>", "{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
"#
));
}
}
8 changes: 8 additions & 0 deletions crates/emmylua_code_analysis/src/semantic_db/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
}
26 changes: 24 additions & 2 deletions crates/emmylua_code_analysis/src/semantic_model/infer/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
Loading