Skip to content
Draft
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,18 @@ mod tests {
("fun(text: string): string", "fun(): string", false),
("fun(text: string)", "fun(...: string)", false),
("fun(text: string?)", "fun(...: string)", true),
("fun(text: string)", "fun(...)", true),
("fun(text: string)", "fun(...: any)", true),
(
"fun(first: string, text: string)",
"fun(first: string, ...)",
true,
),
(
"fun(first: integer, text: string)",
"fun(first: string, ...)",
false,
),
(
"fun(first: string, second: string)",
"fun(first: string, ...: string)",
Expand Down
140 changes: 140 additions & 0 deletions crates/emmylua_code_analysis/src/check/test/undefined_field_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1382,3 +1382,143 @@ fn enum_runtime_cross_file_dynamic_and_conditional_keys() {
eq(false)
);
}

#[cfg(test)]
mod table_field_param_docs {
use crate::{DiagnosticCode, VirtualWorkspace};
use googletest::prelude::*;

const OPTS: &str = "---@class Opts\n---@field name string\n";

/// Every table position a doc-annotated function field can sit in. `%BODY%` reads a field of `opts`.
const SHAPES: [(&str, &str); 5] = [
(
"local value",
"local t = {\n---@param opts Opts\nf = function(opts) %BODY% end,\n}",
),
(
"global value",
"T = {\n---@param opts Opts\nf = function(opts) %BODY% end,\n}",
),
(
"nested table",
"local t = {\n{\n---@param opts Opts\nf = function(opts) %BODY% end,\n},\n}",
),
(
"call argument",
"print({\n---@param opts Opts\nf = function(opts) %BODY% end,\n})",
),
(
"return value",
"return {\n---@param opts Opts\nf = function(opts) %BODY% end,\n}",
),
];

fn undefined_field_in(source: &str) -> bool {
let mut ws = VirtualWorkspace::new();
ws.def(OPTS);
!ws.has_no_diagnostic(DiagnosticCode::UndefinedField, source)
}

#[gtest]
fn param_type_reaches_the_body_in_every_table_position() {
for (shape, source) in SHAPES {
let wrong = source.replace("%BODY%", "local _ = opts.nope");
let right = source.replace("%BODY%", "local _ = opts.name");
expect_that!(undefined_field_in(&wrong), eq(true), "{shape}: wrong field");
expect_that!(
undefined_field_in(&right),
eq(false),
"{shape}: right field"
);
}
}

#[gtest]
fn each_sibling_field_uses_its_own_docs() {
let source = |first: &str, second: &str| {
format!(
"return {{
---@param a Opts
f = function(a) local _ = a.{first} end,
---@param b Opts
g = function(b) local _ = b.{second} end,
}}"
)
};
expect_that!(undefined_field_in(&source("nope", "name")), eq(true));
expect_that!(undefined_field_in(&source("name", "nope")), eq(true));
expect_that!(undefined_field_in(&source("name", "name")), eq(false));
}

#[gtest]
fn return_type_is_still_inferred_without_a_return_tag() {
for (shape, def, call) in [
(
"direct",
"local t = {\n---@param a integer\nf = function(a) return a end,\n}",
"t.f(1)",
),
(
"nested",
"local t = {\n{\n---@param a integer\nf = function(a) return a end,\n},\n}",
"t[1].f(1)",
),
] {
let mut ws = VirtualWorkspace::new();
ws.def(&format!("{def}\nR = {call}"));
let actual = ws.expr_ty("R");
let expected = ws.ty("integer");
expect_that!(actual, eq(&expected), "{shape}");
}
}

#[gtest]
fn return_tag_on_a_nested_field_is_read() {
let mut ws = VirtualWorkspace::new();
ws.def("local t = {\n{\n---@return string\nf = function() end,\n},\n}\nR = t[1].f()");
let actual = ws.expr_ty("R");
let expected = ws.ty("string");
expect_that!(actual, eq(&expected));
}

/// A field that doesn't hold the closure directly must not hand its docs to one.
#[gtest]
fn docs_stay_on_the_field_when_the_closure_is_wrapped() {
let source = "local function wrap(f) return f end
return {
---@param opts Opts
f = wrap(function(opts) local _ = opts.nope end),
}";
expect_that!(undefined_field_in(source), eq(false));
}

/// Docs on the statement holding the table describe the statement, not this closure.
#[gtest]
fn field_docs_beat_statement_docs() {
let source = |field: &str| {
format!(
"---@param opts string
local t = {{
---@param opts Opts
f = function(opts) local _ = opts.{field} end,
}}"
)
};
expect_that!(undefined_field_in(&source("nope")), eq(true));
expect_that!(undefined_field_in(&source("name")), eq(false));
}

/// Same as a trailing tag after any statement: the closure is already collected by then.
#[gtest]
fn trailing_tag_does_not_type_the_closure() {
let mut ws = VirtualWorkspace::new();
expect_that!(
ws.has_no_diagnostic(
DiagnosticCode::ParamTypeMismatch,
"local t = {\nf = function(a) end, ---@param a string\n}\nt.f(1)",
),
eq(true)
);
}
}
20 changes: 15 additions & 5 deletions crates/emmylua_code_analysis/src/semantic_db/facts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,14 @@ impl FileFacts {
.partition_point(|(start, _)| *start <= offset);
for (_, index) in self.member_by_range_start[..idx].iter().rev() {
let member = &self.members[*index];
if member
.id
.member_key_range()
.is_some_and(|range| range.contains(offset))
// A positional table field has no key token: its range is its value's, which isn't a key.
let is_positional =
member.value_syntax.map(|value| value.get_range()) == member.id.member_key_range();
if !is_positional
&& member
.id
.member_key_range()
.is_some_and(|range| range.contains(offset))
{
return Some(member);
}
Expand Down Expand Up @@ -1982,7 +1986,13 @@ impl FactsBuilder {
let statement_owner = self.current_owner_syntax;
self.current_owner_syntax = Some(closure.get_syntax_id());
self.collect_params(closure);
self.collect_signature(closure, statement_owner);
// A doc comment above a table field is owned by the field, whatever statement holds the table.
let doc_owner = closure
.get_parent::<LuaTableField>()
.map(|field| field.get_syntax_id())
.filter(|field| self.doc_comment_owners.contains(field))
.or(statement_owner);
self.collect_signature(closure, doc_owner);
}
LuaAst::LuaNameExpr(name_expr) => {
if let Some(name) = name_expr.get_name_text() {
Expand Down
11 changes: 5 additions & 6 deletions crates/emmylua_code_analysis/src/semantic_model/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ pub(crate) use std::collections::HashSet;
pub(crate) use std::rc::Rc;

pub(crate) use emmylua_parser::{
LuaAssignStat, LuaAstNode, LuaCallExpr, LuaChunk, LuaClosureExpr, LuaCommentOwner,
LuaDocConditionalType, LuaDocNameType, LuaDocObjectFieldKey, LuaDocTag, LuaDocTagAlias,
LuaDocTagClass, LuaDocType, LuaExpr, LuaForRangeStat, LuaIndexExpr, LuaLiteralExpr,
LuaLiteralToken, LuaParseError, LuaSyntaxId, LuaSyntaxKind, LuaSyntaxNode, LuaSyntaxToken,
LuaSyntaxTree, LuaTableField, LuaTypeBinaryOperator, LuaTypeUnaryOperator, LuaVersionNumber,
NumberResult, VisibilityKind,
LuaAssignStat, LuaAstNode, LuaCallExpr, LuaChunk, LuaClosureExpr, LuaDocConditionalType,
LuaDocNameType, LuaDocObjectFieldKey, LuaDocTagAlias, LuaDocTagClass, LuaDocType, LuaExpr,
LuaForRangeStat, LuaIndexExpr, LuaLiteralExpr, LuaLiteralToken, LuaParseError, LuaSyntaxId,
LuaSyntaxKind, LuaSyntaxNode, LuaSyntaxToken, LuaSyntaxTree, LuaTypeBinaryOperator,
LuaTypeUnaryOperator, LuaVersionNumber, NumberResult, VisibilityKind,
};
pub(crate) use hashbrown::HashMap;
pub(crate) use rowan::TextSize;
Expand Down
77 changes: 0 additions & 77 deletions crates/emmylua_code_analysis/src/semantic_model/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -909,72 +909,6 @@ impl<'db> SemanticModel<'db> {
}
Some(out)
}
/// `---@param` / `---@return` annotations on table-literal fields override the closure's bare signature.
/// semantic currently does not merge these field-level docs into `Signature.docs`, but `setmetatable`'s
/// `__call` / `__index` metamethod fields depend on them to preserve the function signature.
pub(crate) fn table_field_signature_override(
&self,
file_id: FileId,
closure_syntax: LuaSyntaxId,
mut params: Vec<(String, Option<LuaType>)>,
mut ret: LuaType,
) -> Option<(Vec<(String, Option<LuaType>)>, LuaType)> {
let facts = self.file_facts_of(file_id)?;
facts
.members
.iter()
.find(|member| member.value_syntax == Some(closure_syntax))?;
let tree = self.syntax_tree_of(file_id)?;
let node = closure_syntax.to_node_from_root(&tree.get_red_root())?;
let field = node.ancestors().find_map(LuaTableField::cast)?;
let mut has_param = false;
let mut has_return = false;
let mut returns = Vec::new();
for comment in field.get_comments() {
for tag in comment.get_doc_tags() {
match tag {
LuaDocTag::Param(param) => {
if let Some(name_token) = param.get_name_token()
&& let Some(doc_ty) = param.get_type()
{
let mut ty =
self.project_doc_type(file_id, doc_ty.get_syntax_id(), &[]);
if param.is_nullable() {
ty = LuaType::from_vec(vec![ty, LuaType::Nil]);
}
let name = name_token.get_name_text().to_string();
if let Some(slot) = params.iter_mut().find(|(n, _)| n == &name) {
slot.1 = Some(ty);
has_param = true;
}
}
}
LuaDocTag::Return(return_tag) => {
has_return = true;
for doc_ty in return_tag.get_types() {
let ty = self.project_doc_type(file_id, doc_ty.get_syntax_id(), &[]);
if !matches!(ty, LuaType::Unknown) {
returns.push(ty);
}
}
}
_ => {}
}
}
}
if has_return && !returns.is_empty() {
ret = if returns.len() == 1 {
returns.pop()?
} else {
LuaType::Variadic(Rc::new(VariadicType::Multi(returns)))
};
}
if has_param || has_return {
Some((params, ret))
} else {
None
}
}
/// Signature structure of a closure in any file (used for cross-file member/global function signature resolution).
pub fn type_of_signature_in_file(
&self,
Expand Down Expand Up @@ -1037,17 +971,6 @@ impl<'db> SemanticModel<'db> {
ret = inferred;
}
}
if signature.docs.is_none()
&& let Some((new_params, new_ret)) = self.table_field_signature_override(
file_id,
closure_syntax,
params.clone(),
ret.clone(),
)
{
params = new_params;
ret = new_ret;
}
let is_variadic = signature.is_variadic;
let async_state = signature
.docs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ pub(crate) fn function_param_pairs(
}
// A repeated caller tail can be empty. A fixed implementation slot
// beyond the caller's prefix must also accept a missing argument.
let target_param = if index < fixed_source_count && index >= fixed_target_count {
// An untyped target tail like `fun(t, ...)` accepts anything, so it needs no `nil` added.
let target_param = if index < fixed_source_count
&& index >= fixed_target_count
&& !matches!(target_param, LuaType::Any | LuaType::Unknown)
{
LuaType::from_vec(vec![target_param.clone(), LuaType::Nil])
} else {
target_param.clone()
Expand Down
22 changes: 22 additions & 0 deletions crates/emmylua_ls/src/handlers/test/definition_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1140,4 +1140,26 @@ function g_config.get() end
));
Ok(())
}

/// A positional table field has no key, so tokens inside its value are not on a member key.
#[gtest]
fn test_name_inside_positional_field_value() -> Result<()> {
let mut ws = ProviderVirtualWorkspace::new();
check!(ws.check_definition(
r#"
local t = {
{
f = function(opts)
local _ = <??>opts
end,
},
}
"#,
vec![Expected {
file: "".to_string(),
line: 3,
}],
));
Ok(())
}
}
25 changes: 25 additions & 0 deletions crates/emmylua_ls/src/handlers/test/hover_function_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,4 +1088,29 @@ mod tests {
);
Ok(())
}

/// Hover on a `---@param` parameter of a function in a table field, at the
/// declaration and in the body, for each table position.
#[gtest]
fn test_table_field_param_hover() -> Result<()> {
for template in [
"local t = {\n---@param opts Opts\nf = function(%DECL%opts) local _ = %USE%opts end,\n}",
"local t = {\n{\n---@param opts Opts\nf = function(%DECL%opts) local _ = %USE%opts end,\n},\n}",
"print({\n---@param opts Opts\nf = function(%DECL%opts) local _ = %USE%opts end,\n})",
"return {\n---@param opts Opts\nf = function(%DECL%opts) local _ = %USE%opts end,\n}",
] {
for (cursor, other) in [("%DECL%", "%USE%"), ("%USE%", "%DECL%")] {
let mut ws = ProviderVirtualWorkspace::new();
ws.def("---@class Opts\n---@field name string\n");
let source = template.replace(cursor, "<??>").replace(other, "");
check!(ws.check_hover(
&source,
VirtualHoverResult {
value: "```lua\n(parameter) opts: Opts\n```".to_string(),
},
));
}
}
Ok(())
}
}
Loading