Repository navigation
fix(infer): a member missing from an unresolved name or an alias of a union is unknown, not nil - #1451
Conversation
… 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
There was a problem hiding this comment.
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
UndefinedFieldassertion["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. Acount_by_code(...) == 5assertion 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 ism, a, it, d, s(source order). - The test doesn't cover the recursive alias cycle path (
visitedguard). An alias like---@alias A AorA -> B -> Ashould 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(aRef/Defwith 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_typeandtable_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(...)returningVec<&str>makes equality assertions brittle to ordering — see point 2.
Suggestions (priority order)
- Add a cycle-alias test (e.g.
---@alias A A,---@alias B C; ---@alias C B) to exercisevisited. - Add a comment in
missing_member_is_knownexplaining the cycle →falsechoice, and the union →falsebehavior. - Relax the
UndefinedFieldorder assertion to avoid future brittleness. - Re-check
defs.first()behavior for multi-def refs or add a comment. - Optionally use
source.get(range)intexts_by_codefor panic safety.
|
Thanks for the review. I'm not changing this one. Item by item:
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUR6W6YykYLUWo9RTMQ
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
Summary
Reading a key that is missing from a
Ref/Defowner returnsnilfor every such owner, though the comment above the rule says "declared class instances". A name with no declaration (---@param m Missing, oruv.fs_stat.resultwhen the luv types are not loaded) knows nothing about its members. Readingm.kindasnilturns the onetype-not-foundinto 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 asunknown, andmember_missing_in_unionalready skips such a component in a union.The same rule was wrong for an alias:
---@alias Item Missing|{ text?: string }readit.kindasnil, while the inline union readsunknown.New
missing_member_is_known(vm.rs): a declared class or enum is known, sonilstays. An object or a table literal with members is known as before. An alias reads like its target. A name with no declaration readsunknown.undefined-fieldstill reports each of these reads.Evidence
test_member_of_an_unresolved_type_is_unknown_not_nil(new,assign_type_mismatch_test.rs) fails on main'svm.rs:assign-type-mismatchonm.kind,a.kind(an alias ofMissing),it.kind,d.kind,s.kind.After: only
d.kind(a declared class) ands.kind(an alias of an object type) are reported, andundefined-fieldis still reported on all five reads. Allemmylua_code_analysistests pass, as docargo fmtandclippy. The test uses a newtexts_by_codehelper, added next tocount_by_code.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.nvimfs_event.lua:28stat.mtime may be nil(gitsigns −1724, grug-far.nvim −444).context.lua:219unnecessary-if:if end_col ~= 0after both earlier branches setend_col = -1. This one looks true.sources/lsp/completion.lua:79, oil.nvimtrash/freedesktop.lua:600/628and sidekick.nvimcli/context/quickfix.lua:54are 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 intable_argument_mismatches: the comparison endsUnresolvedand 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 failedtest_recursive_scalar_alias_rejects_table_argumentsand two sibling tests, since a recursive alias also endsUnresolved. So it is left out of this PR.config/sources.lua:80/81: main already reports about 30 falseassign-type-mismatchin this one literal (itsblink.cmp.DeduplicateConfigdoes 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.assign-type-mismatchlines in diffview.nvimconfig.luaand nvim-lspconfiglsp/perlls.lua, files where main itself reports different lines from run to run.Merge Danger
Door: two-way
One predicate. Reverting it restores
nilfor every named owner.Blast Radius: inference
A member read on a type with no declaration infers
unknowninstead ofnil, so every check downstream of such a read changes. Declared classes, enums, objects and table literals with members keepnil.🤖 Generated with Claude Code
https://claude.ai/code/session_018NxUUSjAWtbRaNWmmf1F3n