Repository navigation
fix(flow): a guard on a member no longer turns its memo off - #1372
Conversation
`if o.w == 'a' then o.w = fn end` reported expected `"a"`: the checker took the target from `type_of_member_at`, the narrowed read. A guard narrows reads, not what a write may store. The walk for a target now follows the member's writes and casts and skips guards, as a local's target does. It keeps its own memo states. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG
`trace_member` served its memo only to an empty path. A guard on the member leaves a narrowing on the path, so every later read walked both sides of every earlier guard: 2^n routes. `if h.b then print(1) end; print(h.b)` 20 times never finishes; 0.25.1 and a local are fine. The memo now holds the state for an empty path, and what the path collected applies to that state. Guards after a write now apply to the written value on reads, as they do for a local. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG
There was a problem hiding this comment.
Code Review
Summary
The change introduces a new type_of_member_assign_target_at API that computes a member's type for write targets, deliberately ignoring conditional narrowing (guards) while still applying casts. It also fixes a performance regression in the member flow memo by caching the "empty path" state separately from the path-collected narrowings/casts. The intent is sound: a guard narrows reads, not the contract a write must satisfy.
Issues & Suggestions
1. ignore_guards is not propagated through trace_member_uncached's recursive calls (potential correctness bug)
In trace_member_uncached, the assign_path for FlowNodeKind::Assign is built as:
let assign_path = PathState {
narrowings: Vec::new(),
casts: path.casts.clone(),
ignore_guards: path.ignore_guards,
};This correctly propagates the flag. However, verify that all other PathState constructions inside trace_member_uncached (e.g. for FlowNodeKind::Branch/merge handling, Loop handling, and any path.clone()-like sites) also carry ignore_guards. The diff only shows the Assign site. If any branch/merge path constructs a fresh PathState::default() or omits the field, the guard-ignoring behavior will silently revert to guard-respecting on that route, producing inconsistent results depending on control flow. Please audit every PathState { ... } literal in flow.rs.
2. trace_decl_uncached hard-codes ignore_guards: false
let assign_path = PathState {
narrowings,
casts: path.casts.clone(),
ignore_guards: false,
};This is fine if decl tracing never needs the flag, but it's a latent trap: if type_of_decl_before_at ever gains an "assign target" variant, this will be wrong. Consider propagating path.ignore_guards here too (it will be false in all current call sites, so behavior is unchanged) to keep the invariant uniform and avoid a future footgun.
3. Memo key now includes ignore_guards, but the early-return path bypasses the cache
In trace_member:
if !path.narrowings.is_empty() || !path.casts.is_empty() {
let state = trace_member(..., &mut PathState { ignore_guards: path.ignore_guards, ..Default::default() })?;
return Some(finalize(model, state, path));
}This is the core fix and looks correct: it recurses with an empty path (which will hit the memo, keyed by ignore_guards), then applies the collected path via finalize. Two things to confirm:
visitedis shared between the outer call and the inner empty-path call. Since the inner call starts from the sameflow_id, and the outer call already insertedflow_idintovisitedbefore this point (presumably), the inner call may immediately hit the "already visited" cycle guard and returnNone, causing?to bail out. Verify the ordering: thevisited.insert(flow_id)must happen after this early-return block, or the inner recursion must use a freshvisited. This is the most likely place for a subtle regression.finalizesemantics: confirmfinalize(model, state, path)applies narrowings/casts in the correct order relative to the memoized base state, and thatignore_guardsdoesn't causefinalizeto skip casts it should apply.
4. Correlated narrowing check is now the only reason to bypass the memo
if tree.is_loop_reachable(flow_id)
|| path.narrowings.iter().any(|n| matches!(narrowing, Narrowing::Correlated { .. }))Previously any non-empty narrowings bypassed the memo. Now only Correlated does, and plain narrowings go through the empty-path + finalize route. This is the intended optimization, but it assumes finalize can faithfully replay all non-correlated narrowing kinds (equality, truthiness, type guards, etc.) against the memoized base state. If any narrowing kind is order-sensitive or depends on the sequence of prior narrowings in a way finalize doesn't reproduce (e.g., narrowing A then B vs. B then A yielding different results), this will produce wrong types. The new test test_member_write_target_ignores_guards covers only equality guards; consider adding a test with mixed guard kinds (truthiness + type guard + equality) on the same member to validate finalize replay.
5. Test test_member_write_target_ignores_guards — expected values need justification
for (write, expected) in [("function() return '' end", 0), ("1", 1)] {The field is string|fun():string. Writing a function is valid (0 diagnostics); writing 1 is invalid (1 diagnostic). This is correct, but the test name says "ignores guards" while the loop also varies prefix (prior writes). The prefix variations test that prior writes don't leak into the target type — good, but the test name undersells it. Consider renaming to reflect both aspects, or splitting into two tests. Minor.
6. test_undeclared_member_write_target_ignores_guards — opts.w == nil guard
The first guard is opts.w == nil, then opts.w = function() .... With ignore_guards, the target is any (from table<string, any>), so no diagnostic — correct. But note: without the fix, the nil guard would narrow opts.w to nil, and assigning a function would flag a mismatch. This test is a good regression guard. No issue.
7. Performance test bound is loose but acceptable
let bound = 64 * (n as u64) * (n as u64) + 256;Quadratic bound for n up to 16. The comment says "must stay polynomial" — quadratic is fine. However, the test only measures type_of_expr_at on LuaIndexExpr descendants; if the regression were in type_of_member_at called from a different entry point (e.g., the checker), this test wouldn't catch it. The assign_type_mismatch_test.rs additions cover the checker path functionally but not performance. Consider whether a checker-level perf test is warranted; likely overkill, but note the gap.
8. Doc comment placement
/// Flow-sensitive type of the member at `offset` (member assignment flow + `---@cast t.x +T` widening).
/// Target type for a member write: its writes and casts, without guards. ...
pub fn type_of_member_assign_target_at(...)The first doc line ("Flow-sensitive type of the member at offset...") was the original doc for type_of_member_at and now sits above type_of_member_assign_target_at, which is misleading. Move it down to type_of_member_at and give type_of_member_assign_target_at its own clean doc. Minor but worth fixing for readability.
9. Naming consistency
type_of_member_assign_target_at vs. existing type_of_member_at / type_of_decl_before_at. The new name is descriptive but long. Given the codebase already uses _before_at for the assignment-check variant, consider type_of_member_assign_target_at → consistent enough. No action needed, just noting.
Verdict
The design is correct and the memo fix addresses a real exponential blowup. The main risks are (1) incomplete ignore_guards propagation through all PathState construction sites in trace_member_uncached, and (3) the shared visited set potentially causing the inner empty-path recursion to bail early. Both should be verified with targeted tests (mixed guard kinds, nested branches, loops) before merge.
From the bot review: a test for the memo replaying mixed guards, the doc line of `type_of_member_at` back on it, and `ignore_guards` carried in the decl walk too. No behaviour change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG
|
Thanks. Applied in 586ea33, no behaviour change:
Checked:
Not applied: splitting or renaming the target test, and a checker-level step test. The corpus diff in the description covers the checker path. Written with help from Claude Code. |
Port of EmmyLuaLs#1372's rule. The fork took the flow-insensitive type for a member write's target, and with a `---@cast` anywhere in the file fell back to the narrowed read, so `if o.w == 'a' then o.w = fn end` reported expected `"a"` there. The target now walks with `ignore_guards` on `PathState`, part of the member memo key, as EmmyLuaLs#1372 does. Corpus against 1f7c158, with the next commit: 12 false assign-type-mismatch gone (guard-narrowed targets: `true` vs `false`, `"list"` vs `"tree"`, neovim's `formatexpr = nil` after its guard). Added: refactoring's `start_col = space_start - 1` (`integer?` arithmetic, as for a local) and vendored luarocks `MT = getenv() or nil` after `or "mt"` (every build flags the shape). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURuoSufkUL6bLjXoS7
`merge_types` drops a component that another one is broader than, and `type_is_broader` listed both `(Integer, Number)` and `(Number, Integer)`, so whichever came first won: `integer|number` read after an `if` was `integer`. A declared `integer|number` local then passed into `integer`, and the fork's write target, which follows the flow since the EmmyLuaLs#1372 port, held `R.c = s - 1` to `integer` though `R.c` is declared by that write alone (refactoring.nvim `debug/utils.lua:101`). Upstream main has the same pair (`narrow_intersect_types` rightly maps the pair to `integer`; the union side copied it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURuoSufkUL6bLjXoS7
|
Still reproduces on current main Written with help from Claude Code. |
…emo, EmmyLuaLs#1373 short callback vs variadic tail) into marek-main-fixes Both PRs are this fork's own fixes, merged upstream in their reviewed form. - vm.rs: take upstream's clamped `start` (EmmyLuaLs#1373 review) over the fork's `.get(..).unwrap_or_default()`; same behavior for `arg_index` past the end. - flow.rs: keep the fork's side; it already carries EmmyLuaLs#1372 (ported in d16b712) plus the `access` base and cast positions upstream lacks. Result = fork's file. - assign_type_mismatch_test.rs: keep the fork's side; upstream's three tests are present, the fork's `test_member_write_target_ignores_guards` has one more case (a cast in the file). - param_type_check_test.rs: keep the fork's side and add upstream's boundary test `test_callback_at_and_past_variadic_prefix`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUNXDZoFif8q99ttrdb
Summary
A guard on a member, then a read of it, repeated, never finishes. 20 repeats are enough, and
emmylua_checkondiffs.nvimruns past 60 s (0.25.1: 1 s):trace_memberserved its memo only to an empty path. A guard on the member leaves a narrowing on the path, so each read walked both sides of every earlier guard, 2^n routes. The memo now holds the state for an empty path, and what the path collected applies to that state:The walk used to drop guards when it reached a write. Now they apply, which is right for reads and matches locals, but it would have narrowed write targets. Those were already wrong:
if o.w == 'a' then o.w = fn endreports expected"a"onmain, and 0.25.1 doesn't. So the first commit gives a write target its own walk, which follows the member's writes and casts and skips guards.Evidence
flow_member_guard_chain_keeps_the_memo: 289 steps at 4 guards, 5329 at 8. The 4 lines above repeated 30 times: killed at 10 s.diffs.nvim: killed at 60 s.test_member_write_target_ignores_guards: 1 falseassign-type-mismatch.After: the same 4 lines: 0.16 s.
diffs.nvim: 23 s. Both tests pass, with 1706 passed, 0 failed inemmylua_code_analysis.test_undeclared_member_write_target_ignores_guardspasses onmaintoo: it fails with the memo change alone, so it pins why the target needs its own walk.diffs.nvimis still slower than it should be: what remains is intrace_decl. With #1360 merged on top it takes about 4.5 s.Merge Danger
Door: two-way
Revert restores the old behaviour. No API or config change.
Blast Radius: diagnostics
emmylua_checkfrommainand from this branch, per file and line, on 59 Neovim plugins andruntime/, 55 of them comparable: 48839 to 48830 diagnostics, allassign-type-mismatch.if self.state == "pending" then self.state = state end. Six are inruntime/.mainreports the same kind of hit on these writes without the guard, so the guard was hiding them. flash'sstate.lua:123is a true mismatch. lazy'sconfig.lua:239(twice, one vendored copy) and LazyVim'sfzf.lua:32are false, and this PR doesn't fix them: the first resolves a nested field by name tofunction M.hererocks, and I haven't traced the second.async.nvimandtuis.nvimoverflow the stack on both sides (fix(semantic): a closure parameter's evaluation inherits the cycle guard #1370),mason.nvimruns out of time on both (fix(semantic): a binding that mentions a bound generic does not enter the function solver #1371),grug-far.nvimpanics on both, andmaindoesn't finishdiffs.nvim.Written with help from Claude Code.
🤖 Generated with Claude Code
https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG