Repository navigation
fix(semantic): ---@param on a table-field function reaches its body - #1364
mareklangiewicz wants to merge 8 commits into
Conversation
function_param_pairs adds nil to an implementation slot past the caller's fixed prefix, because a repeated tail can be empty. That is right for fun(...: string), but it also made fun(t, ...) reject fun(_, arg: string), which is how std declares __call. An untyped tail promises nothing, so leave it unconstrained. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURPpemyuzYS6urQxCm
A doc comment above a table field is owned by the field, but the closure looked for its docs under the enclosing statement. Signature.docs was therefore always empty for these functions: params were unknown in the body unless the table was the direct value of a local or assignment, where expected_member_param_for_closure happened to fill them in. So nested tables, call arguments and returned tables lost hover, completion and diagnostics, which is the shape of a lazy.nvim spec. Use the field as the doc owner when it has a comment. Signature.docs now carries these docs, so table_field_signature_override has no remaining case and goes away. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURPpemyuzYS6urQxCm
A positional field has no key token, so its member key range falls back to
the whole field. member_at_offset then returned the [1] member for every
token inside the value, so in { { f = function(opts) return opts end } }
hover on opts showed the outer table and go-to-definition jumped there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUURPpemyuzYS6urQxCm
There was a problem hiding this comment.
Code Review
Summary
The change replaces a post-hoc "signature override" hack (table_field_signature_override) with proper doc-owner attribution during fact collection, so ---@param/---@return above a table field are attached to the closure directly. It also fixes member-key lookup for positional table fields and relaxes variadic-tail checking. Overall the direction is good, but there are a few issues worth addressing.
Issues & Recommendations
1. is_positional comparison is fragile (facts.rs)
let is_positional =
member.value_syntax.map(|value| value.get_range()) == member.id.member_key_range();- This relies on
member_key_range()returning the value's range for positional fields. That's an implicit invariant; ifmember_key_range()ever returnsNonefor positional fields (which is the semantically correct answer — there is no key), this comparison silently becomesfalseand the bug returns. - It also compares
Option<TextRange>by value; two distinct fields could theoretically share a range only if the invariant is broken, but the intent is unclear to a reader.
Recommendation: Prefer an explicit check, e.g. member.id.member_key_range().is_none() or a dedicated is_positional() helper on the member id. If the range-equality trick is required, add a comment explaining why member_key_range() returns the value range for positional fields (and consider fixing that at the source instead).
2. doc_comment_owners.contains(field) — verify population order (facts.rs)
let doc_owner = closure
.get_parent::<LuaTableField>()
.map(|field| field.get_syntax_id())
.filter(|field| self.doc_comment_owners.contains(field))
.or(statement_owner);- This depends on
doc_comment_ownersalready containing the field's id when the closure is visited. If the table field's doc owner is registered after its value is walked, the filter silently falls back tostatement_ownerand the fix regresses without any test failure in other shapes. Please confirm the traversal order (or add a comment noting the ordering assumption). get_parent::<LuaTableField>()only finds the immediate parent. A closure wrapped in a call (wrap(function() ... end)) correctly falls back (covered bydocs_stay_on_the_field_when_the_closure_is_wrapped), but a closure nested deeper inside the field value (e.g.f = (function() return function() end end)()) will also fall back. That's probably intended, but worth a comment.
3. Removed table_field_signature_override — check for other callers / behavior parity
- The deleted function handled
---@returnwith multiple types viaLuaType::Variadic(VariadicType::Multi(...))and skippedUnknowntypes. Confirm the newcollect_signaturepath produces identical results for:- multiple
---@returntags, ---@returnwithUnknowntypes,- nullable
---@param(param.is_nullable()→T | nil).
- multiple
- The old code only applied the override when
signature.docs.is_none(). If the new path now always merges field docs, behavior changes for closures that already had their own docs. Add a test for "field doc + closure doc" precedence.
4. func_type.rs — Any/Unknown in the tail
&& !matches!(target_param, LuaType::Any | LuaType::Unknown)- The comment says "An untyped tail like
fun(t, ...)promises nothing", but the condition is about the target parameter type beingAny/Unknown, not about the source being variadic. The comment and code don't quite line up — please clarify (e.g. "a target slot typedany/unknownaccepts a missing argument, so don't widen it toT | nil"). - Consider whether
LuaType::Nilshould also be excluded (a target slot already acceptingnildoesn't need widening). Minor, but avoids redundant union construction.
5. Test quality
undefined_field_inreturns!has_no_diagnostic(...)— the double negation is confusing. Consider renaming tohas_undefined_fieldand returning!ws.has_no_diagnostic(...)directly, or invert the helper.each_sibling_field_uses_its_own_docsassertseq(true)for both wrong-field cases but doesn't distinguish which field triggered the diagnostic. If the implementation accidentally attributed both fields' docs tof, the test would still pass. Consider asserting the diagnostic range/message, or at least that only one diagnostic is produced.return_type_is_still_inferred_without_a_return_tagusesws.expr_ty("R")— good, but thedirect/nestedshapes don't cover thecall argument/return valueshapes used inSHAPES. Minor coverage gap.test_table_field_param_hoverbuildssourceby replacing%DECL%/%USE%with<??>and the other with"". This works but is hard to read; a small helper that takes(decl_marker, use_marker)would be clearer.
6. prelude.rs — removed imports
LuaCommentOwner, LuaDocTag, LuaTableField were removed from the prelude. Verify no other module relied on them via prelude::* (the build will catch it, but worth noting the blast radius of prelude edits).
Nitpicks
facts.rs: the comment "A positional table field has no key token: its range is its value's, which isn't a key." is good, but the code reads as a workaround. Ifmember_key_range()is meant to returnNonefor positional fields, fix it there instead.undefined_field_test.rs:const OPTSis defined inside the test module butSHAPESusesOpts— fine, but consider movingOPTSnext toSHAPESfor locality.func_type.rs: the added condition makes theifharder to scan; consider extractinglet needs_nil_widening = ...;for readability.
Verdict
The refactor is a net improvement (removes a hack, fixes positional-field key lookup, adds good regression tests). Address items 1–3 before merging; 4–6 are recommended.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURPpemyuzYS6urQxCm
A field's docs now beat the statement's, and a trailing tag no longer types the closure. The deleted override honored one on fields only; no statement form ever did. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURPpemyuzYS6urQxCm
|
Re item 1 of the bot review: Written with help from Claude Code. |
Conflicts: main renamed doc_type_lua_rich_in to project_doc_type inside table_field_signature_override, which this branch removes; its three prelude imports were used only there. Both resolved to this branch's side. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUR6W6YykYLUWo9RTMQ
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUNhALyTAADUEzLeBUe
…-docs # Conflicts: # crates/emmylua_ls/src/handlers/test/definition_test.rs
Summary
A
---@paramabove a function in a table field is lost in the body unless the table is the direct value of a local or assignment. The parameter isunknown, so hover, completion and diagnostics stop working on it. Lazy.nvim specs have this shape:Three fix commits, one per cause, then a comment fix and tests pinning the behavior changes below. The second fix depends on the first.
The second change is needed because std declares
__callasfun(t, ...), which rejectedfun(_, arg: string)once the field's---@paramreached the signature.mainalready reports this for a named function,setmetatable({}, { __call = call }). The rule for typed tails likefun(...: string)is unchanged.The third is the nested case: in
{ { f = function(opts) local _ = opts end } },optshovered as[1]: { f: fun(opts: Opts) }and go-to-definition jumped to the table.Evidence
Same file, one annotated function per table position,
opts.nopein each body:undefined-fieldbeforeopts: Optsopts: Opts[1]: { f: fun(opts: Opts) }opts: Optsopts: unknownopts: Optsreturnvalueopts: unknownopts: OptsBefore (new tests on
main):param_type_reaches_the_body_in_every_table_position: FAILED for nested, call argument and returneach_sibling_field_uses_its_own_docs: FAILEDreturn_type_is_still_inferred_without_a_return_tag: FAILED for nestedtest_value_compatibility_across_assignment_argument_and_return, newfun(...)rows: FAILEDtest_name_inside_positional_field_value: FAILEDAfter: all pass, along with the existing
__calltests incall_non_callable_test.Merge Danger
Door: two-way
Blast Radius: diagnostics
Function bodies that were unchecked are now checked, so projects with these shapes will see new diagnostics in them. On our own config (three Lua repos) that was one new report, and it was a real bug.
fun(...)andfun(...: any)targets become more permissive. Hoveringxin{ x }now showslocal x: integerrather than(field) [1]: integer = 1.Docs on a table field now take precedence over docs on the enclosing statement. A trailing same-line tag (
f = function(a) end, ---@param a string) no longer types the closure. It only worked through the removed override; no statement form honors one, so fields now match. Both are pinned by tests.Not addressed here:
---@paramabovereturn function(a)or a closure call argument is also lost, which is a different owner problem.Written with help from Claude Code.