Skip to content

fix(flow): a guard on a member no longer turns its memo off - #1372

Merged
CppCXY merged 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-member-guard-memo
Nov 9, 2026
Merged

CppCXY merged 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-member-guard-memo

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A guard on a member, then a read of it, repeated, never finishes. 20 repeats are enough, and emmylua_check on diffs.nvim runs past 60 s (0.25.1: 1 s):

---@class H
---@field b integer?

---@param h H
local function f(h)
  if h.b then print(1) end
  print(h.b)
  -- ...the same two lines again
end

trace_member served 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:

 trace_member(flow_id, path)
-  if path has narrowings or casts
-    walk on, uncached
+  if path has correlated narrowings
+    walk on, uncached
+  if path has narrowings or casts
+    state = trace_member(flow_id, empty path)   # memoized
+    return finalize(state, path)

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 end reports expected "a" on main, 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

  • Before: 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 false assign-type-mismatch.
    After: the same 4 lines: 0.16 s. diffs.nvim: 23 s. Both tests pass, with 1706 passed, 0 failed in emmylua_code_analysis.

test_undeclared_member_write_target_ignores_guards passes on main too: it fails with the memo change alone, so it pins why the target needs its own walk.

diffs.nvim is still slower than it should be: what remains is in trace_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_check from main and from this branch, per file and line, on 59 Neovim plugins and runtime/, 55 of them comparable: 48839 to 48830 diagnostics, all assign-type-mismatch.


Written with help from Claude Code.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG

mareklangiewicz and others added 2 commits November 6, 2026 14:33
`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

@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

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:

  • visited is shared between the outer call and the inner empty-path call. Since the inner call starts from the same flow_id, and the outer call already inserted flow_id into visited before this point (presumably), the inner call may immediately hit the "already visited" cycle guard and return None, causing ? to bail out. Verify the ordering: the visited.insert(flow_id) must happen after this early-return block, or the inner recursion must use a fresh visited. This is the most likely place for a subtle regression.
  • finalize semantics: confirm finalize(model, state, path) applies narrowings/casts in the correct order relative to the memoized base state, and that ignore_guards doesn't cause finalize to 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
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks. Applied in 586ea33, no behaviour change:

  • The doc line of type_of_member_at is back on it.
  • ignore_guards is carried in the decl walk too, so the field has no hard-coded site.
  • New test_mixed_member_guards_apply_to_the_memoized_state: truthiness, equality and type() guards on one member, read past their merges. It passes on main as well, so it pins that the memo replay gives what the old walk gave.

Checked:

  • PathState literals: on the member path, member_type_at, the empty-path call in trace_member, the write in trace_member_uncached and clone_path all carry the flag. The remaining PathState::default() sites are decl walks, which never set it.
  • visited: trace_member does not insert. Only trace_member_uncached does, so the empty-path call starts from the set the caller had.
  • finalize applies casts regardless of ignore_guards, and with the flag set no narrowing is collected.

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.

@mareklangiewicz
mareklangiewicz marked this pull request as ready for review November 6, 2026 13:57
mareklangiewicz added a commit to mareklangiewicz/emmylua-analyzer-rust that referenced this pull request Nov 8, 2026
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
mareklangiewicz added a commit to mareklangiewicz/emmylua-analyzer-rust that referenced this pull request Nov 8, 2026
`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
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Still reproduces on current main b889a2d1: emmylua_check on diffs.nvim does not finish in 120 s. Memory stays flat, and the stack is walk_member ↔ trace_member_uncached. With this PR on top of b889a2d1 (plus #1365, #1370, #1371 and the variadic-callback panic fix), it finishes in about 3 s. 0.25.1 finishes in 0.2 s.


Written with help from Claude Code.

@CppCXY
CppCXY merged commit 3b6d73f into EmmyLuaLs:main Nov 9, 2026
16 checks passed
mareklangiewicz added a commit to mareklangiewicz/emmylua-analyzer-rust that referenced this pull request Nov 10, 2026
…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
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.

2 participants