Repository navigation
fix(semantic): index signature reads have the value type (#1334) - #1340
mareklangiewicz wants to merge 10 commits into
Conversation
There was a problem hiding this comment.
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 namedtable, or the builtin is renamed/aliased, this silently misbehaves. Prefer comparing against the known builtinTypeId(e.g. via a constant oris_builtin_table-style helper) rather thanget_name(). - The
Generic(_)arm also appears in the laterRef(_) | Def(_) | Generic(_)branch. The guard means non-tablegenerics fall through tomember_infos, which is probably intended, but the duplication is easy to get wrong later. Consider a comment or restructuring so the twoGenericcases 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 futureBooleanConst, or aLiteralwrapper) will silently start taking the index-signature path instead of the named-member path. Consider inverting to a positive predicate likeis_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.tyexclusion (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::Nameis used for botht.fooandt["foo"]. Mapping it toStringConstis fine fortype_checkagainststring, 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 confirmtype_checktreatsStringConstvsStringConstas exact equality and not as "both are strings".LuaMemberKey::Integer→IntegerConstsimilarly relies ontype_checkdistinguishingIntegerConst(1)fromIntegerConst(2). The test("---@param pt table<integer, integer>", "pt[1]", false)exercises the positive case; consider adding a negative case liketable<1, integer>withpt[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_testloop is good and readable. Theacceptednaming 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_callableasserts exactly1diagnostic. If the inference regresses toUnknown,CallNonCallablemay not fire and the count would be0— 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 theLuaType::TableGenericarm. Add at least one test for each to prevent dead-code drift.
6. Minor
index_signature_typeispub(crate)and used fromvm.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.
) 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
7c0aacb to
294d821
Compare
…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
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
…ts (EmmyLuaLs#1334) 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
|
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 ( Fix (6911ca1): Interleaved CPU against main, 5 rounds: gitsigns +0.9%, refactoring −1.1% (both noise), snacks +2.5%. All tests and clippy pass. |
…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
…ix-string-table-index-1334
…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
Fixes #1334.
Summary
A read with no named member never consulted index signatures, so it fell through to the missing-key fallback:
member::index_signature_typereturnsVof the first signature whose key domain accepts the key. Since the rebase onto 1b6df85 it is a thin wrapper overapplicable_index_infos(from e1cd626). Arrays and table literals are excluded, soT[]still readsT?:Named members still win (
---@field flag booleanbeside[string] integerkeepsboolean), and a literal key outside the domain is unchanged (table<'X', integer>read as.Y).member_infoitself 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. WithVtyped, a read through a variable key now carriesV's nil, so a guard or a write ont[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 ont[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 narrowingtest_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 anifsettle;k = j,t[j] = nil, a one-armedifor a nullable value do not.Evidence
1b6df859plus 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) andtest_index_signature_value_is_not_callable(call_non_callable_test.rs).After: they pass, and so do the
emmylua_code_analysis+emmylua_lstest suites. Before the rebase (main56267ead),emmylua_checkon the Regression on main: indexingtable<string, V>givesunknowninstead ofV#1334 repro reported only the control line without this PR and, with it,pt.X,pt[k](assign-type-mismatch) andpt.X()(call-non-callable):Not covered here (separate main behavior, same before and after this PR, checked on
56267ead):pt.X.yfrom the repro: main reports no undefined-field on anyintegerprefix (---@param i integer+i.yis silent too).---@param pt {[string]: integer}types the param as plaintable, so there is no index access to read. The same annotation on a---@typelocal is anObjectand is fixed here.Merge Danger
Door: two-way
Blast Radius: inference
Reads through
table<K, V>,{ [K]: V }and[K] Vclass signatures now produceVwhere they gaveunknown/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), andfound nilfor 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, andlocal x = niltreated as the variable's contract.Written with help from Claude Code.
🤖 Generated with Claude Code
https://claude.ai/code/session_017nze85evtQomp5n24iU7sV