Skip to content

fix(semantic): ---@param on a table-field function reaches its body - #1364

Draft
mareklangiewicz wants to merge 8 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-table-field-param-docs
Draft

mareklangiewicz wants to merge 8 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-table-field-param-docs

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A ---@param above 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 is unknown, so hover, completion and diagnostics stop working on it. Lazy.nvim specs have this shape:

---@class Opts
---@field name string

return {
  ---@param opts Opts
  f = function(opts)
    local _ = opts.nope   -- not reported, `opts` hovers as `unknown`
  end,
}

Three fix commits, one per cause, then a comment fix and tests pinning the behavior changes below. The second fix depends on the first.

 closure in a table field
-  looks for docs under the enclosing statement   (never finds them)
+  looks for docs under the field, if it has a comment
+  table_field_signature_override: no cases left, removed

 function_param_pairs, implementation slot past the caller's fixed prefix
-  must accept nil
+  must accept nil, unless the caller's tail is untyped (`...`, `...: any`)

 member_at_offset
-  a positional field's range is its whole value, so it claims every token inside
+  a positional field has no key token, so it claims none

The second change is needed because std declares __call as fun(t, ...), which rejected fun(_, arg: string) once the field's ---@param reached the signature. main already reports this for a named function, setmetatable({}, { __call = call }). The rule for typed tails like fun(...: string) is unchanged.

The third is the nested case: in { { f = function(opts) local _ = opts end } }, opts hovered as [1]: { f: fun(opts: Opts) } and go-to-definition jumped to the table.

Evidence

Same file, one annotated function per table position, opts.nope in each body:

table is undefined-field before after hover in the body before after
value of a local reported reported opts: Opts opts: Opts
nested in a table missed reported [1]: { f: fun(opts: Opts) } opts: Opts
call argument missed reported opts: unknown opts: Opts
return value missed reported opts: unknown opts: Opts
  • Before (new tests on main):

    • param_type_reaches_the_body_in_every_table_position: FAILED for nested, call argument and return
    • each_sibling_field_uses_its_own_docs: FAILED
    • return_type_is_still_inferred_without_a_return_tag: FAILED for nested
    • test_value_compatibility_across_assignment_argument_and_return, new fun(...) rows: FAILED
    • test_name_inside_positional_field_value: FAILED

    After: all pass, along with the existing __call tests in call_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(...) and fun(...: any) targets become more permissive. Hovering x in { x } now shows local x: integer rather 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: ---@param above return function(a) or a closure call argument is also lost, which is a different owner problem.


Written with help from Claude Code.

mareklangiewicz and others added 3 commits November 5, 2026 14:09
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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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; if member_key_range() ever returns None for positional fields (which is the semantically correct answer — there is no key), this comparison silently becomes false and 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_owners already 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 to statement_owner and 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 by docs_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 ---@return with multiple types via LuaType::Variadic(VariadicType::Multi(...)) and skipped Unknown types. Confirm the new collect_signature path produces identical results for:
    • multiple ---@return tags,
    • ---@return with Unknown types,
    • nullable ---@param (param.is_nullable() → T | nil).
  • 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 being Any/Unknown, not about the source being variadic. The comment and code don't quite line up — please clarify (e.g. "a target slot typed any/unknown accepts a missing argument, so don't widen it to T | nil").
  • Consider whether LuaType::Nil should also be excluded (a target slot already accepting nil doesn't need widening). Minor, but avoids redundant union construction.

5. Test quality

  • undefined_field_in returns !has_no_diagnostic(...) — the double negation is confusing. Consider renaming to has_undefined_field and returning !ws.has_no_diagnostic(...) directly, or invert the helper.
  • each_sibling_field_uses_its_own_docs asserts eq(true) for both wrong-field cases but doesn't distinguish which field triggered the diagnostic. If the implementation accidentally attributed both fields' docs to f, 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_tag uses ws.expr_ty("R") — good, but the direct/nested shapes don't cover the call argument / return value shapes used in SHAPES. Minor coverage gap.
  • test_table_field_param_hover builds source by 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. If member_key_range() is meant to return None for positional fields, fix it there instead.
  • undefined_field_test.rs: const OPTS is defined inside the test module but SHAPES uses Opts — fine, but consider moving OPTS next to SHAPES for locality.
  • func_type.rs: the added condition makes the if harder to scan; consider extracting let 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.

mareklangiewicz and others added 2 commits November 5, 2026 14:49
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
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Re item 1 of the bot review: member_key_range() returns Some for every member, so the suggested .is_none() would never be true. If it did return None for positional fields, member_at_offset would still skip them through its is_some_and, so the bug wouldn't come back. Keeping the range comparison and its comment; test_name_inside_positional_field_value covers it.


Written with help from Claude Code.

mareklangiewicz and others added 3 commits November 23, 2026 17:30
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
…-docs

# Conflicts:
#	crates/emmylua_ls/src/handlers/test/definition_test.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant