Repository navigation
fix(flow): a member read before its write starts from the declared field - #1447
mareklangiewicz wants to merge 5 commits into
Conversation
…he declared field When backtracking a runtime member (`s.desc = v` on a local or param) reaches the flow start without meeting any of its writes, the base was the member's own value: a write the path never ran. So after `if c then s.desc = "x" end` the read was `string`, not `string?`, and after `if c then s.desc = nil end` it was `nil`. The base is now the read's flow-insensitive type (the declared field), but only where that is what the path holds before the write: - the member is written in the function that reads it; a method body runs after a chunk-level `function M:m()` or a write in another method, so those keep the old base; - the read is not the VM's bare `nil` for a member the owner doesn't declare. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUSGcaeYGoYHckFhhm8
There was a problem hiding this comment.
Review Summary
The change introduces member_entry_type as a smarter fallback for flow-analysis path roots, plus a helper written_in_closure_of. The intent is sound, but there are several correctness and robustness concerns.
Potential Issues
-
written_in_closure_ofconflates "written" with "declared"- The function name says "written", but the body only compares the closure of the member definition node against the closure of the access. It does not check whether the member is actually assigned in that closure. If a member is declared via
---@fieldinside a class definition (always at chunk level) but is written inside the function being analyzed, the code does not detect the write — it just detects "definition is in a different closure". This is a subtle semantic mismatch that will confuse future maintainers and may produce the wrong branch in edge cases (e.g., a member declared inside the same closure but assigned elsewhere).
Suggestion: Rename to
defined_outside_closureor actually scan the closure body for a write tomember, matching the stated intent. - The function name says "written", but the body only compares the closure of the member definition node against the closure of the access. It does not check whether the member is actually assigned in that closure. If a member is declared via
-
Cross-file early return may hide the intended fix
if key.file_id != model.file_id() { return false; }silently disables the new behavior for members whose key was declared in another file (e.g., a shared type file). In those cases the declared field type is exactly the fallback that should be used, and the current gate returnsflow_member_value_typeonly — but this is inconsistent with intent. If the fix is meant to apply to cross-file declared members (a common pattern:---@classin types.lua, implementation elsewhere), this is a bug.
Suggestion: Clarify whether cross-file members are intentionally excluded. If not, drop this guard or document why.
-
covering_element(key.key_range)on the model's own tree is fragilekey.key_rangebelongs tokey.file_id. After thekey.file_id != model.file_id()guard this is OK today, but the guard is easy to forget and the code depends on it for safety. Thecovering_elementcall also assumes the range is usable; a zero-width or out-of-bounds range may returnNoneand producefalsesilently. Consider asserting/clarifying the invariant.
-
access.syntax()traversal may cross closures unrelated to the memberLuaClosureId::from_node(access.syntax())walks up to the nearest closure — correct — butaccess.syntax()here is aLuaIndexExpr; if the access is nested in a lambda passed to a call, the "reading closure" will be the lambda, not the enclosing function. That is arguably correct, but the comment ("written in the function that reads it") should mention lambdas.
-
model.type_of_expr(access.get_syntax_id())insidemember_entry_typerisks recursionmember_entry_typeis called frommember_type_at, which is called fromtype_of_expr_at_node(whenflow_treeis absent, or viaunwrap_or_else).type_of_exprat the same access node may re-enter the member flow analysis, potentially causing unbounded recursion or a stack overflow on hostile inputs. The new call site attype_of_expr_at_node(unwrap_or_else(|| member_type_at(..., Some(index_expr)))) makes this more likely: the fallback path callsmember_type_at, which callsmember_entry_type, which callstype_of_expr(access)— the same expression that just failed.- The
!matches!(ty, Unknown | Nil)guard helps, but only after the call has already been made. AUnknownresult from a self-read could easily be the outcome of re-entering; it's guard-by-accident.
Suggestion: Add a recursion guard (thread-local or a flag threaded through), or resolve the access expression via a sibling API that cannot re-enter
type_of_expr_at_node. -
Behavioral regression risk in
type_of_expr_at_node- The old fallback
type_of_member_at(model, &member_id, offset)presumably uses the current offset. The new code goes throughmember_type_at(model, ..., false, Some(index_expr))— this changes signature/semantics. Iftype_of_member_atdid not honoraccessor the flow tree differently, this subtle change may alter results beyond the new test cases. Confirmtype_of_member_atwas simply a thin wrapper and is now redundant.
- The old fallback
-
Comment on
member_entry_typeis slightly wrong- "A runtime member's own value is a write that has not happened yet" — but for declared fields the "value" isn't a write at all; it's the type annotation. The comment mixes the two cases. Consider splitting the explanation.
-
Test quality
test_runtime_member_read_before_its_write_keeps_declared_fieldusesassert!(!ws.has_no_diagnostic(...))— a negative assertion that a diagnostic exists. This is easy to break (any new diagnostic changes the test). Prefer asserting the inferred type directly ifws.expr_tycan reach the read site.test_conditional_member_write_keeps_the_path_that_skips_itexpects"string?"for bothskippedandskipped_nil— but forskipped_nil, ifcis true the write isnil, if false the entry isstring?; the union is stillstring?. The test asserts the same value for two genuinely different scenarios; consider assertingstring?for one and, e.g.,nilon a guarded branch for the other, to actually exercise the path.last_name_expr_typeis used but not imported/defined in the diff — confirm it is visible (test would not compile otherwise, but flagging for completeness).
Minor / Style
- The
written.is_some_and(|node| LuaClosureId::from_node(&node) == ...)compares closure IDs; ifLuaClosureIddoes not implementEqconsistently across files (does it encodefile_id?), this is a silent cross-file footgun. Verify. member_entry_typetakesaccess: Option<&LuaIndexExpr>but every new caller passesSomeexceptmember_type_at's own fallback closure which capturesaccess. Fine, but theOptionis redundant with the two new call sites intrace_member_uncached/walk_member— those also passaccess, so theNonecase there is now only reachable whenaccessitself isNoneat trace time. OK.- Consider extracting the guard
matches!(def.owner, SemanticId::Decl(_))lookup into a named helper; it's now duplicated withapply_field_nullable's pattern.
Recommended Actions (priority)
- Add recursion protection around
type_of_expr(access)inmember_entry_type(issue 5) — this is the most likely source of a real crash. - Decide and document whether cross-file declared members should trigger the new branch (issue 2).
- Fix or rename
written_in_closure_ofto match what it actually checks (issue 1). - Strengthen tests to assert positive types rather than diagnostic absence (issue 8).
…e test Review follow-up, no behaviour change: - `member_entry_type`: a local-owned member is one write site, and `---@field` members never take this branch; re-entry through `type_of_expr` is bounded by its in-progress marker and reads `Unknown`. - `written_in_closure_of` is now `write_site_in_closure_of`, and says that a lambda is its own closure and why another file's member is skipped. - `test_runtime_member_read_before_its_write_keeps_declared_field` asserts that the read is `string?` instead of that a diagnostic exists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUSGcaeYGoYHckFhhm8
|
Thanks for the review. 2c009e2 addresses it (doc comments and one test, no behaviour change):
|
…her closure "Written in the read's closure" was broader than the case it was for. A nested callback that reads a member its enclosing function writes on some paths (a mount-only `ctx.state`) can run before or after that write, so the declared field is its base too. What should keep the old base is a function statement: `function M:m()` defines the member, so another method's body, which runs after the module has loaded, holds that function and not an inherited `m?` field. An assignment like `self.args.on_exit = function() ... end` is a state change like any other write: the read before it is the callback being wrapped, not the wrapper. That is a false "Unnecessary `if`" on main as well; it now has a test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUSGcaeYGoYHckFhhm8
|
Update in 76f8fb5: the "written in the reading function" condition was broader than the case it was for, so it's replaced by a narrower one.
Numbers: the full suite passes (1986 tests), and |
…rite in its parent `f` may run before the conditional `ctx.name = "x" ---@type string`, so it reads the declared `name?`. main reports "Unnecessary assert" here, and so did the "written in the reading function" rule this branch had at 2c009e2; emmylua 0.25.1 does not. Reduced from tuis.nvim `uis/hacker_news.lua` (`assert(ctx.state)` in `refresh`, a mount-only `ctx.state = …`). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURTC4DUybydaqMS5Lu
Conflicts in flow.rs: upstream made the member walk return Result<_, DeferredMemberRead>. Kept that shape at all five spots and put this branch's member_entry_type where the walk reaches the start (Start/Unreachable, no antecedent, walk_member's None) and in member_type_at's fallback; the read's untraced case passes its access (Some(index_expr)) as before. Upstream's new owner-invalidation breaks (MemberWrite::Invalidates) keep flow_member_value_type: they are not a walk reaching the start. Main's flow.rs still fails 4 of this branch's 6 tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUQZHt6a5njk8trY5BZ
Summary
A member written on only some paths reads as if every path wrote it:
Each
s.desc = vis its own runtime member. When the backward walk for that member reaches the flow start without meeting the write, it took the member's own value as the base, which is the value of a write this path never ran. On code with a union receiver this surfaces as falseunnecessary-if("Impossibleif") andunnecessary-assertafter the conditional write.The base at the start is now the read's flow-insensitive type (the declared field), through a new
member_entry_typeused at the four places that fell back toflow_member_value_type:Two cases keep the old base:
function M:m()defines the member rather than changing its state. Another method's body runs after the module has loaded, soself:expand()beforefunction M:expand()reads the method, not an inheritedexpand?field. An assignment such asself.args.on_exit = function() … endis an ordinary write: the read before it is the callback being wrapped.nilread. That is what the VM gives a member the owner doesn't declare (an untypedargs[1]), not a field type.unknownmeans a re-entered query.Evidence
main70dbcf4):test_conditional_member_write_keeps_the_path_that_skips_it(["string", "nil"]instead of["string?", "string?"]) andtest_runtime_member_read_before_its_write_keeps_declared_fieldfail.After: both pass.
test_method_read_does_not_start_before_a_chunk_level_definition,test_read_before_a_write_to_an_undeclared_member_is_not_nilandtest_wrapping_an_optional_callback_reads_it_before_the_wrapperpin the two exceptions and the assigned-callback case.test_a_nested_function_reads_the_field_not_a_later_write_in_its_parentcovers a read beforectx.name = "x" ---@type string, from a nested function and on a straight line.mainreports "Unnecessary assert" on both, and the broader closure condition this branch had at 2c009e2 still reported the nested one: the test fails with 76f8fb5 reverted. Fullemmylua_code_analysissuite: 1987 passed.cargo fmtandclippyare clean.emmylua_checkwith an empty config on 60 Neovim plugin trees,mainvs this branch. 54 finished on both; the other six crash or are skipped on both builds. Total hits 57387 → 57376, 61 changed lines, 36 of which agree with emmylua 0.25.1.actions/diff.lua:581"Impossible assert" onassert(self.left_win)after a conditionalself.left_win = nil;:880"Unnecessaryif"; catppuccininit.lua:116"Impossibleif"; tenparam-type-mismatch … found nilin lualinecomponent.lua.need-check-nil, each on a path that really skips the write: snacksindent.lua:421(×2, theelsebranch only notifies), snacksdashboard.lua:561and:727, and nuiinput/init.lua:58(is_type("table", …)isn't a type guard). 0.25.1 reports all five.maincrashes on (tuis, neotest, bufferline, async.nvim, neovim-runtime): I checked the same rule on my fork, which runs them. An earlier, broader exception ("written in the reading function") gave 8 falseunnecessary-assertin tuis. With the current rule the fork's whole corpus loses 146 lines and gains none, all agreeing with 0.25.1.need-check-nil, almost all on method reads off un-annotated class tables (lualinerequire(...):extend()).Merge Danger
Door: two-way
Two helpers and four call sites. Reverting them restores the current base.
Blast Radius: narrowing
A member read on a path that skips its write keeps the declared type. Later
need-check-nil/param-type-mismatchon it can fire where they were missed before, andunnecessary-if/unnecessary-assertno longer fire on the written value alone.🤖 Generated with Claude Code
https://claude.ai/code/session_018NxUURTC4DUybydaqMS5Lu