Skip to content

fix(infer): a member missing from an unresolved name or an alias of a union is unknown, not nil - #1451

Open
mareklangiewicz wants to merge 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-missing-member-of-unresolved-type
Open

mareklangiewicz wants to merge 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-missing-member-of-unresolved-type

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Reading a key that is missing from a Ref/Def owner returns nil for every such owner, though the comment above the rule says "declared class instances". A name with no declaration (---@param m Missing, or uv.fs_stat.result when the luv types are not loaded) knows nothing about its members. Reading m.kind as nil turns the one type-not-found into follow-up false hits wherever the value flows: need-check-nil, param-type-mismatch, unnecessary-if, assign-type-mismatch. 0.25.1 reads such a member as unknown, and member_missing_in_union already skips such a component in a union.

The same rule was wrong for an alias: ---@alias Item Missing|{ text?: string } read it.kind as nil, while the inline union reads unknown.

New missing_member_is_known (vm.rs): a declared class or enum is known, so nil stays. An object or a table literal with members is known as before. An alias reads like its target. A name with no declaration reads unknown. undefined-field still reports each of these reads.

-let missing_is_known = match &owner.ty {
-    LuaType::TableConst(_) => Self::table_literal_has_members(self.model, &owner.ty),
-    LuaType::Ref(_) | LuaType::Def(_) | LuaType::Object(_) => true,
-    _ => false,
-};
-if missing_is_known {
+if Self::missing_member_is_known(self.model, &owner.ty, &mut Vec::new()) {
     return Value::plain(LuaType::Nil);
 }

Evidence

---@param m Missing
local function h(m)
    ---@type boolean
    local z = m.kind -- main: assign-type-mismatch (found nil); this PR, 0.25.1: none
    return z
end

---@alias ItemOfMissing Missing|{ text?: string }
---@type ItemOfMissing
local it
---@type boolean
local v = it.kind    -- main: assign-type-mismatch; this PR: none, like the inline union

---@class DeclaredClass
---@param d DeclaredClass
local function k(d)
    ---@type boolean
    local y = d.kind -- control: assign-type-mismatch (found nil) on both
    return y
end
  • Before: test_member_of_an_unresolved_type_is_unknown_not_nil (new, assign_type_mismatch_test.rs) fails on main's vm.rs: assign-type-mismatch on m.kind, a.kind (an alias of Missing), it.kind, d.kind, s.kind.
    After: only d.kind (a declared class) and s.kind (an alias of an object type) are reported, and undefined-field is still reported on all five reads. All emmylua_code_analysis tests pass, as do cargo fmt and clippy. The test uses a new texts_by_code helper, added next to count_by_code.
  • Plugin corpus (emmylua_check, empty config, the 54 Neovim plugin trees that finish on main): main 48ef52a → this branch, 57302 → 54436 hits (−2866). By code: need-check-nil −2797, param-type-mismatch +3 −29, assign-type-mismatch +5 −20, unnecessary-if +1 −20, return-type-mismatch +1 −6, unnecessary-assert −3, undefined-field −1. Of the 2831 changed lines, 2812 now report what 0.25.1 reports. Most are reads of luv/LSP types that do not resolve under an empty config, for example gitsigns.nvim fs_event.lua:28 stat.mtime may be nil (gitsigns −1724, grug-far.nvim −444).
  • Lines added:
    • nvim-treesitter-context context.lua:219 unnecessary-if: if end_col ~= 0 after both earlier branches set end_col = -1. This one looks true.
    • blink.cmp sources/lsp/completion.lua:79, oil.nvim trash/freedesktop.lua:600/628 and sidekick.nvim cli/context/quickfix.lua:54 are table literals checked against an expected type that reaches an undeclared name. They are false. On our fork, a reduced case of this shape traced to the whole-literal check in table_argument_mismatches: the comparison ends Unresolved and is reported as a mismatch. The four lines here are believed to share it, but were read rather than reduced one by one. On the fork, changing that check to report only a definite mismatch failed test_recursive_scalar_alias_rejects_table_arguments and two sibling tests, since a recursive alias also ends Unresolved. So it is left out of this PR.
    • blink.cmp config/sources.lua:80/81: main already reports about 30 false assign-type-mismatch in this one literal (its blink.cmp.DeduplicateConfig does not resolve). The messages on lines 76–81 vary between runs on main itself: in 4 runs of main 48ef52a, 1 differed from the other 3. Main 70dbcf4 was the same in 3 runs, and with this change 1 of 7 runs differed, both consistent with that rate. This is main's own noise, not this change.
    • The remaining 3 are assign-type-mismatch lines in diffview.nvim config.lua and nvim-lspconfig lsp/perlls.lua, files where main itself reports different lines from run to run.

Merge Danger

Door: two-way

One predicate. Reverting it restores nil for every named owner.

Blast Radius: inference

A member read on a type with no declaration infers unknown instead of nil, so every check downstream of such a read changes. Declared classes, enums, objects and table literals with members keep nil.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUUSjAWtbRaNWmmf1F3n

… union is unknown, not nil

A read of a key missing from a `Ref`/`Def` owner returned `nil` for every
such owner, though the comment above it says "declared class instances". A
name with no declaration (`---@PARAM m Missing`) knows nothing about its
members: 0.25.1 reads `m.kind` as `unknown`, and `member_missing_in_union`
already skips such a union component. Reading it as `nil` turned one
`type-not-found` into follow-up false hits wherever the value flows
(need-check-nil, param-type-mismatch, unnecessary-if, ...).

The same rule was wrong for an alias of a union holding such a name: the
alias read `nil` where the inline union reads `unknown`.

New `missing_member_is_known`: a declared class or enum is known (`nil`
stays), an alias reads like its target, an undeclared name is `unknown`.
`undefined-field` still reports every such read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUSjAWtbRaNWmmf1F3n

@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.

Review Summary

The change refactors missing_member_is_known into a helper that resolves aliases to their targets and treats unresolved names as "unknown" rather than "nil". Overall the logic is sound, but there are a few points worth addressing.


Issues

1. texts_by_code can panic on non-UTF-8 boundaries (low risk, but worth guard)

.map(|d| &source[d.range])

Diagnostic ranges are usually char-boundary aligned, but a defensive note or get(range) would be safer. Not blocking, but consider documenting the assumption.

2. Test coverage gap in test_member_of_an_unresolved_type_is_unknown_not_nil

  • The UndefinedField assertion ["kind"; 5] is order-dependent. If the diagnostic iteration order changes (e.g. sorting by line but ties broken differently), the test breaks for reasons unrelated to the fix. A count_by_code(...) == 5 assertion plus one representative check would be more robust — or at least the comment "One per read (the range is the key)" should be reconciled with why the reported order is m, a, it, d, s (source order).
  • The test doesn't cover the recursive alias cycle path (visited guard). An alias like ---@alias A A or A -> B -> A should be exercised, otherwise the cycle protection is untested.

3. visited cycle handling returns false (unknown) — verify intent

if visited.contains(id) {
    return false;
}

Treating a cyclic alias as "unknown" is reasonable, but the doc comment says nothing about cycles. Add a one-line note so future readers understand why self-referential aliases resolve to unknown rather than, say, propagating through the union.

4. Alias over a union: alias_target semantics
The test comment claims "An alias of a union holding an unresolved name reads like the inline union." The new helper resolves the alias to its target and recurses. For Missing|{...} (a LuaType::Union hit), the match falls into _ => false. That means unknown — correct per the test. But note the asymmetry:

  • AliasOfMissing → alias → Missing (a Ref/Def with no defs) → false → unknown ✓
  • ItemOfMissing = Missing|{text?} → alias → Union → _ => false → unknown ✓

That works, but it means any union (even {a: string}|{b: string} with all-resolved members) yields unknown for a missing key. Previously the code path for a Union owner also returned unknown (_ => false), so behavior is unchanged — just confirm this is intentional and documented, since it reads like an unintended side effect of the match arms rather than a deliberate rule.

5. defs.as_slice().first() ignores multiple defs

let Some(def) = defs.as_slice().first() else { return false; };

If a Ref/Def has multiple definitions (e.g. overloaded via ---@class augmentations), only the first is considered. If the first happens to be a non-alias but a later one is an alias — or vice versa — the result may be surprising. At minimum add a comment; ideally check whether emit relies on all defs of the same kind for aliases.

6. Naming
missing_member_is_known is a bit indirect. Since the function returns true for "read is definitively nil", consider a name like missing_member_reads_nil or member_set_is_closed. Minor.

7. No new diagnostics / no regression note
The removed inline comment block referenced issue 600. The new comment omits it. If issue 600 is still relevant, keep a reference so the regression intent isn't lost in git archaeology.


Style / Minor

  • The new helper is placed between table_missing_index_type and table_literal_has_members; ordering is fine, but grouping related comment ("empty {} … issue 600") with the helper would improve readability.
  • The test doc comment is thorough; nice. But texts_by_code(...) returning Vec<&str> makes equality assertions brittle to ordering — see point 2.

Suggestions (priority order)

  1. Add a cycle-alias test (e.g. ---@alias A A, ---@alias B C; ---@alias C B) to exercise visited.
  2. Add a comment in missing_member_is_known explaining the cycle → false choice, and the union → false behavior.
  3. Relax the UndefinedField order assertion to avoid future brittleness.
  4. Re-check defs.first() behavior for multi-def refs or add a comment.
  5. Optionally use source.get(range) in texts_by_code for panic safety.

@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I'm not changing this one. Item by item:

  1. Diagnostic ranges come from the syntax tree, so they fall on char boundaries.
  2. Alias cycles: I checked ---@alias A A and ---@alias B C + ---@alias C B, each with a member read. The check finishes and reports nothing on 0.25.1, upstream main and this branch. I haven't found a source whose read reaches the visited guard, so a test would not show it working. It stays as a cheap stop against a loop. The UndefinedField list is in source order, one entry per read. It compares the read texts so that a failure shows which read changed.
  3. A cycle gets unknown, the same answer as any other alias whose target can't be resolved.
  4. The union arm is unchanged: a union owner returned unknown before this change too.
  5. One name declared as both an alias and a class is not a valid program. Several defs of one class all have kind Class.
  6. The name is kept to match missing_is_known, which it replaces.
  7. Issue 600 is still referenced, on table_literal_has_members just below, which is where the empty-{} rule lives.

@mareklangiewicz
mareklangiewicz marked this pull request as ready for review November 23, 2026 15:01
Test-file conflicts only: main's version of the file, with this
branch's tests re-added at the end of the module and its test-helper
imports kept. The branch's changed lines are unchanged against main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUQZHt6a5njk8trY5BZ
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