Skip to content

fix(semantic): index signature reads have the value type (#1334) - #1340

Open
mareklangiewicz wants to merge 10 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-string-table-index-1334
Open

mareklangiewicz wants to merge 10 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-string-table-index-1334

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1334.

Summary

A read with no named member never consulted index signatures, so it fell through to the missing-key fallback:

 InferVm::index_member_impl(owner, key)
   named member (owner identity / type-side @field)  -> its type
+  index_signature_type(owner, key literal type)     -> V
   missing key -> Nil (Ref / Def / Object), Unknown (Generic table<K, V>)

 InferVm::index_member_dynamic(owner, key)
+  non-literal key (`pt[k]`, k: string)
+    index_signature_type(owner, key type)          -> V
   literal / union keys -> index_member (above)

member::index_signature_type returns V of the first signature whose key domain accepts the key. Since the rebase onto 1b6df85 it is a thin wrapper over applicable_index_infos (from e1cd626). Arrays and table literals are excluded, so T[] still reads T?:

table<K, V> / TableGeneric [K, V]   key ⊆ K  -> V
{ [K]: V }  (Object index access)   key ⊆ K  -> V
---@field [K] V  (incl. inherited)   key ⊆ K  -> V

Named members still win (---@field flag boolean beside [string] integer keeps boolean), and a literal key outside the domain is unchanged (table<'X', integer> read as .Y). member_info itself is untouched, so checkers that rely on "no named member" (undefined-field, inject-field) see the same results as before.

Stacked on #1517 (merged in, with main 2d2374fa): review and merge that one first, and this diff shrinks to its own commits. With V typed, a read through a variable key now carries V's nil, so a guard or a write on t[k] has to narrow it. On main alone, this PR made ~100 false need-check-nil / param hits over ~60 Neovim plugin trees (if cache[b] then cache[b].x, timers[id] = timers[id] or …; timers[id]:start()). #1517 makes a guard on t[k] hold. The last commit here makes a write settle the next read:

 guarded_index_type(t[k]): on every path back to the read
   a guard that reads the same t[k]          -> narrowed       (#1517)
+  a write to the same t[k] (same keys)      -> the written value's type
   any other write to t[k] or to k           -> no narrowing

test_dynamic_key_write_establishes_the_read (need_check_nil_test.rs) fails without that commit and passes with it: t[k] = t[k] or {} / t[k] = {} / both arms of an if settle; k = j, t[j] = nil, a one-armed if or a nullable value do not.

Evidence

  • Before (main 1b6df859 plus only this PR's tests): the new tests fail: test_index_signature_read_has_value_type, test_object_index_signature_read_has_value_type (assign_type_mismatch_test.rs) and test_index_signature_value_is_not_callable (call_non_callable_test.rs).
    After: they pass, and so do the emmylua_code_analysis + emmylua_ls test suites. Before the rebase (main 56267ead), emmylua_check on the Regression on main: indexing table<string, V> gives unknown instead of V #1334 repro reported only the control line without this PR and, with it, pt.X, pt[k] (assign-type-mismatch) and pt.X() (call-non-callable):
test_index_signature_read_has_value_type
  ---@type boolean
  local a = <read>      -- mismatch expected (V = integer)
    table<string, integer>   pt.X  pt['X']  pt[k]
    table<integer, integer>  pt[1]
    ---@field [string] integer   pt.X  pt[k]
  no mismatch expected:
    table<'X', integer>  pt.Y          -- key outside the domain
    class `flag: boolean` + `[string] integer`  pt.flag   -- named field wins

Not covered here (separate main behavior, same before and after this PR, checked on 56267ead):

  • pt.X.y from the repro: main reports no undefined-field on any integer prefix (---@param i integer + i.y is silent too).
  • ---@param pt {[string]: integer} types the param as plain table, so there is no index access to read. The same annotation on a ---@type local is an Object and is fixed here.

Merge Danger

Door: two-way

Blast Radius: inference

Reads through table<K, V>, { [K]: V } and [K] V class signatures now produce V where they gave unknown/nil, so diagnostics that were silent on such reads (assign/param/return mismatch, call-non-callable) can start firing in user code. That is the regression being fixed (0.25.1 reported them).

Against main, many of the hits that remain come from main gaps that typed reads expose, each fixed by an open PR: a member of an undeclared type reading nil (#1451), and found nil for a param that accepts nil (#1423). Two more have no PR yet: a new key on an annotated table literal checked against the literal's shape, and local x = nil treated as the variable's contract.

Written with help from Claude Code.

🤖 Generated with Claude Code

https://claude.ai/code/session_017nze85evtQomp5n24iU7sV

@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: Index Signature Read Type Inference

Summary

The change adds index-signature-aware type inference for reads through table<K, V>, { [K]: V }, and ---@field [K] V. Overall the implementation is reasonable and well-tested. A few concerns below.

Issues & Suggestions

1. index_signature_type — Generic arm is overly broad / fragile (member.rs)

LuaType::Generic(generic) if generic.get_base_type_id().get_name() == "table" => { ... }
  • Matching by name string "table" is brittle. If a user defines a class/alias named table, or the builtin is renamed/aliased, this silently misbehaves. Prefer comparing against the known builtin TypeId (e.g. via a constant or is_builtin_table-style helper) rather than get_name().
  • The Generic(_) arm also appears in the later Ref(_) | Def(_) | Generic(_) branch. The guard means non-table generics fall through to member_infos, which is probably intended, but the duplication is easy to get wrong later. Consider a comment or restructuring so the two Generic cases are clearly mutually exclusive.

2. index_member_dynamic — the exclusion list is easy to drift (vm.rs)

if !matches!(
    &key.ty,
    LuaType::StringConst(_) | LuaType::DocStringConst(_)
        | LuaType::IntegerConst(_) | LuaType::DocIntegerConst(_)
        | LuaType::Union(_)
) && !matches!(&owner.ty, LuaType::TableConst(_) | LuaType::Array(_))
    && let Some(ty) = index_signature_type(...)
  • This is a negative list of "literal-ish" key types. Any new literal type added to LuaType (e.g. a future BooleanConst, or a Literal wrapper) will silently start taking the index-signature path instead of the named-member path. Consider inverting to a positive predicate like is_literal_key(&key.ty) / is_named_member_key(&key.ty) so new variants default to the safe path.
  • The Union(_) exclusion is coarse: a union of literals like "X" | "Y" is excluded (good), but a union containing a non-literal (e.g. string | "X") is also excluded from the index-signature path. Worth a comment or a narrower check (e.g. "all members are literals").
  • The owner.ty exclusion (TableConst / Array) is unexplained. Add a comment on why table literals and arrays are excluded here (presumably they have their own member resolution), otherwise this is a future footgun.

3. index_member — key type construction may lose precision (vm.rs)

let key_ty = match key {
    LuaMemberKey::Name(name) => Some(LuaType::StringConst(name.clone().into())),
    LuaMemberKey::Integer(i) => Some(LuaType::IntegerConst(*i)),
    LuaMemberKey::None => None,
};
  • LuaMemberKey::Name is used for both t.foo and t["foo"]. Mapping it to StringConst is fine for type_check against string, but be aware that if a signature's key domain is a literal like 'X', type_check(StringConst("foo"), StringConst("X")) must correctly reject non-matching literals. The test ("---@param pt table<'X', integer>", "pt.Y", true) covers this — good — but confirm type_check treats StringConst vs StringConst as exact equality and not as "both are strings".
  • LuaMemberKey::Integer → IntegerConst similarly relies on type_check distinguishing IntegerConst(1) from IntegerConst(2). The test ("---@param pt table<integer, integer>", "pt[1]", false) exercises the positive case; consider adding a negative case like table<1, integer> with pt[2] to lock in literal-key rejection.

4. Ordering: named member vs. index signature

The new code runs after the named-member lookup in index_member, which matches the documented intent ("a named field beats the signature") and the test ("---@param pt I1334", "pt.flag", true). Good. However, in index_member_dynamic the index-signature path runs before the match &key.ty block. Verify this doesn't shadow any existing behavior for non-literal keys on types that also have named members — the tests don't cover a table<string, V> with an additional named field accessed via a dynamic key. Worth a test.

5. Test quality

  • The assign_type_mismatch_test loop is good and readable. The accepted naming is slightly confusing (it means "no diagnostic expected"), but the assertion message includes the source, so failures are debuggable.
  • test_index_signature_value_is_not_callable asserts exactly 1 diagnostic. If the inference regresses to Unknown, CallNonCallable may not fire and the count would be 0 — that's the intended signal, but consider also asserting the inferred type directly (if the test harness supports it) for a clearer failure mode.
  • Missing coverage: { [K]: V } table-literal form (mentioned in the doc comment but not tested), and the LuaType::TableGeneric arm. Add at least one test for each to prevent dead-code drift.

6. Minor

  • index_signature_type is pub(crate) and used from vm.rs; fine. The doc comment is clear.
  • In index_member_dynamic, the && let Some(ty) = ... chain is a bit dense; splitting into a named boolean or early-return helper would improve readability.

Verdict

Functionally sound and well-tested for the main paths. The main risks are (a) the brittle "table" name check, (b) the negative-list key-type filter that will silently misbehave as LuaType grows, and (c) missing tests for TableGeneric / { [K]: V } and literal-key rejection. Recommend addressing (a) and (b) before merge.

mareklangiewicz and others added 2 commits October 31, 2026 15:38
)

A read with no named member fell through to `Unknown` (`table<K, V>`)
or `Nil` (`{ [K]: V }`, `---@field [K] V`), so `pt.X`, `pt['X']` and
`pt[k]` lost `V`: no assign/param mismatch, and calling or indexing the
result was allowed.

`index_signature_type` returns `V` of the first signature whose key
domain accepts the key (via `applicable_index_infos`); the VM consults
it before the missing-key fallback and for non-literal dynamic keys.
Arrays and table literals keep their own rules (`T[]` still reads `T?`). Named members still win, and
a literal key outside the domain (`table<'X', V>` read as `.Y`) is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017nze85evtQomp5n24iU7sV
Claude-Session: https://claude.ai/code/session_018NxUURS1MVzowfNDjH6GGy
…mmyLuaLs#1334)

Review follow-up: the object index-signature form had no test (a
`---@param` of it is still a plain `table`, so it goes through a typed
local), and literal-key rejection was only covered for string literals.
The new object test fails on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLZMsNstzyced8VdU76TeY
@mareklangiewicz
mareklangiewicz force-pushed the fix-string-table-index-1334 branch from 7c0aacb to 294d821 Compare October 31, 2026 15:04
mareklangiewicz added a commit to mareklangiewicz/emmylua-analyzer-rust that referenced this pull request Oct 31, 2026
…mmyLuaLs#1340 (tree unchanged)

The four PR branches were rebased onto upstream main 1b6df85 (b44c70c, 0ffb918,
9b307e9, 294d821). Their content is already here: the old heads were merged
earlier and later fork commits reworked several of them, so a content merge
only duplicated moved tests and re-conflicted reworked code. -s ours records
the new heads as ancestors. The one substantive rebase change (EmmyLuaLs#1338 dropping
expand_generic_alias) is ported separately in 0cb957b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUURS1MVzowfNDjH6GGy
mareklangiewicz and others added 3 commits November 26, 2026 14:57
Conflicts: vm.rs imports (main renamed table_metatable_type to metatable_type and
added table_metatable_index_info), member.rs (index_signature_type sits beside the
renamed function), assign_type_mismatch_test.rs (both sides appended tests; both kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUNhALyTAADUEzLeBUe
…n undeclared type

The missing-member fallback asked every owner for an index signature. For an
undeclared name (neovim's `vim.Range`, `TSNode` under an empty config: 9931 reads
on refactoring.nvim) the collection marks the query incomplete, so the lookup
ended in `Err` (no signature) after sweeping the query caches, once per read:
gitsigns.nvim +77% CPU, refactoring.nvim +91%, snacks.nvim +32% against main.

`names_undeclared_type` answers that `None` up front, for the type itself, a
union or intersection component, a generic's base and an instance's base. The
lookup's own answer is unchanged, but the enclosing queries now stay complete:
the corpus loses 43 hits that only the sweep produced (a table literal whose
fields read `unknown`, then a param/assign/return mismatch), none of them on
main or 0.25.1, and CPU is back within noise of main.

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

Copy link
Copy Markdown
Contributor Author

Merged main (4c18e8e) and fixed a slowdown this PR caused.

Cost: when a member is missing, the fallback looks for an index signature on the owner. For an undeclared type (vim.Range, TSNode when no neovim library is configured), collecting signatures marks the query incomplete, so the lookup returns no signature but sweeps the query caches first. That happened once per such read, 9931 times on refactoring.nvim. Measured against main: gitsigns.nvim +77% CPU, refactoring.nvim +91%, snacks.nvim +32%.

Fix (6911ca1): names_undeclared_type returns None before the lookup when the owner, one of its union or intersection components, or a generic's base is undeclared. The lookup's answer is the same, and the enclosing queries now stay complete. That also removes 43 hits that only the sweep produced: a table literal whose fields read unknown, then a param/assign/return mismatch. None of them appear on main.

test_missing_member_of_an_undeclared_type_keeps_the_cache_complete
  ---@param r vim.Range ... local a = r.start_row
  assert cache revision unchanged by infer(r.start_row)   # fails before 6911ca11, passes on main and now

Interleaved CPU against main, 5 rounds: gitsigns +0.9%, refactoring −1.1% (both noise), snacks +2.5%. All tests and clippy pass.

mareklangiewicz and others added 5 commits December 5, 2026 18:03
…or a length

`toks[k] and toks[k].line`, `if toks[k] ~= nil then toks[k].line` and
`stages[#stages] and stages[#stages].final` reported need-check-nil: an index
access with a dynamic key had a `None` key in its path, and a `None` key never
established a guard, so only literal keys narrowed.

A dynamic key is now identified by what it reads (`DynamicKey`): the access path
of a name or field, or the length of one. Guard and use match when their
syntactic access paths match and their dynamic keys read the same thing; aliases
are not expanded for such accesses. The guard is lost on a write to the access
(a dynamic target key matches any written key: `k` may be `1`, so `toks[1] = nil`
kills `toks[k]`), on a write to the key's path, or, for a length, on a write
anywhere below it.

`path_write_affects` gains the "dynamic target key matches any write" rule; its
other callers only become more conservative (`t.x = v` now invalidates a read of
`t[k]`).

Port of fork cd052a7 onto main 2d2374f, kept on main's `Option` access in
`narrow_index_condition`.

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

With index signature reads typed (`table<K, V?>` reads `V?`), `t[k] = t[k] or {}; local b = t[k]`
read `b` as the declared `V?`: nothing tied the read to the write just before. The guarded-read
walk now lets an assignment settle a path: a write to the exact access (same path, same dynamic
keys) gives that path the assigned value's type. Any other write to the access or to a key it
reads still fails the walk, so `k = j`, `t[j] = nil`, a one-armed `if`, or a nullable value keep
the nil.

Literal-key writes stay with the member flow. The walker's "no conditions, no guard" shortcut
moves to the array-length caller, the only one that needs a condition.

Port of fork 6ccc474. Needs the index-signature read rule (upstream PR 1340) to be observable:
on main alone the test's `t[k]` reads are untyped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUPShUGSKvreGzsLevH
… what they prove

- IndexTarget { owner, keys: Vec<TargetKey> } with TargetKey::{Member, Dynamic} replaces the
  access path plus a parallel Vec<DynamicKey> that had to line up with its unknown keys.
  IndexTarget::changed_by and path_write_affects share one wildcard rule (path_write_affects
  takes any key iterator).
- guarded_on_all_paths returns each path's proof instead of its caller mutating captured
  state; guarded_index_type picks NotNil when any path proved it, as before.

No behaviour change intended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUScwhfgvPtvJni3rpf
…3eb13) into fix-string-table-index-1334

Resolution: guarded_on_all_paths returns PathProofs { guards, assigned } (AssignStep carries
the assigned type), so guarded_index_type needs no guarded flag or captured state; its result
is as before (the guards' narrowing once, then each assigned type, unioned).

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

Regression on main: indexing table<string, V> gives unknown instead of V

1 participant