Skip to content

fix(flow): a member read before its write starts from the declared field - #1447

Open
mareklangiewicz wants to merge 5 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:up-member-write-skip-path
Open

mareklangiewicz wants to merge 5 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:up-member-write-skip-path

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A member written on only some paths reads as if every path wrote it:

---@class S
---@field desc? string

---@param c boolean
---@param s S
local function f(c, s)
  if c then s.desc = "x" end
  local d = s.desc   -- main: `string`, should be `string?`
end

---@param c boolean
---@param s S
local function g(c, s)
  if c then s.desc = nil end
  local d = s.desc   -- main: `nil`, should be `string?`
end

Each s.desc = v is 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 false unnecessary-if ("Impossible if") and unnecessary-assert after the conditional write.

The base at the start is now the read's flow-insensitive type (the declared field), through a new member_entry_type used at the four places that fell back to flow_member_value_type:

 walk reaches the flow start, no write to this runtime member seen
-  base = the member's own written value
+  if the write is a function statement (`function M:m()`)   -- defines_a_function
+    base = the member's own written value
+  else if the read's type is not `nil` / `unknown`
+    base = the read's flow-insensitive type
+  else
+    base = the member's own written value

Two cases keep the old base:

  • A function statement. function M:m() defines the member rather than changing its state. Another method's body runs after the module has loaded, so self:expand() before function M:expand() reads the method, not an inherited expand? field. An assignment such as self.args.on_exit = function() … end is an ordinary write: the read before it is the callback being wrapped.
  • A bare nil read. That is what the VM gives a member the owner doesn't declare (an untyped args[1]), not a field type. unknown means a re-entered query.

Evidence

  • Before (plain main 70dbcf4): test_conditional_member_write_keeps_the_path_that_skips_it (["string", "nil"] instead of ["string?", "string?"]) and test_runtime_member_read_before_its_write_keeps_declared_field fail.
    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_nil and test_wrapping_an_optional_callback_reads_it_before_the_wrapper pin the two exceptions and the assigned-callback case. test_a_nested_function_reads_the_field_not_a_later_write_in_its_parent covers a read before ctx.name = "x" ---@type string, from a nested function and on a straight line. main reports "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. Full emmylua_code_analysis suite: 1987 passed. cargo fmt and clippy are clean.
  • On real code: emmylua_check with an empty config on 60 Neovim plugin trees, main vs 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.
    • Removed: gitsigns actions/diff.lua:581 "Impossible assert" on assert(self.left_win) after a conditional self.left_win = nil; :880 "Unnecessary if"; catppuccin init.lua:116 "Impossible if"; ten param-type-mismatch … found nil in lualine component.lua.
    • Added need-check-nil, each on a path that really skips the write: snacks indent.lua:421 (×2, the else branch only notifies), snacks dashboard.lua:561 and :727, and nui input/init.lua:58 (is_type("table", …) isn't a type guard). 0.25.1 reports all five.
    • The rest are mostly the same hits with a different message.
  • Trees main crashes 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 false unnecessary-assert in tuis. With the current rule the fork's whole corpus loses 146 lines and gains none, all agreeing with 0.25.1.
  • With neither exception, the corpus gained 183 need-check-nil, almost all on method reads off un-annotated class tables (lualine require(...):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-mismatch on it can fire where they were missed before, and unnecessary-if / unnecessary-assert no longer fire on the written value alone.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUURTC4DUybydaqMS5Lu

…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

@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.

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

  1. written_in_closure_of conflates "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 ---@field inside 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_closure or actually scan the closure body for a write to member, matching the stated intent.

  2. 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 returns flow_member_value_type only — but this is inconsistent with intent. If the fix is meant to apply to cross-file declared members (a common pattern: ---@class in 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.

  3. covering_element(key.key_range) on the model's own tree is fragile

    • key.key_range belongs to key.file_id. After the key.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. The covering_element call also assumes the range is usable; a zero-width or out-of-bounds range may return None and produce false silently. Consider asserting/clarifying the invariant.
  4. access.syntax() traversal may cross closures unrelated to the member

    • LuaClosureId::from_node(access.syntax()) walks up to the nearest closure — correct — but access.syntax() here is a LuaIndexExpr; 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.
  5. model.type_of_expr(access.get_syntax_id()) inside member_entry_type risks recursion

    • member_entry_type is called from member_type_at, which is called from type_of_expr_at_node (when flow_tree is absent, or via unwrap_or_else). type_of_expr at 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 at type_of_expr_at_node (unwrap_or_else(|| member_type_at(..., Some(index_expr)))) makes this more likely: the fallback path calls member_type_at, which calls member_entry_type, which calls type_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. A Unknown result 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.

  6. 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 through member_type_at(model, ..., false, Some(index_expr)) — this changes signature/semantics. If type_of_member_at did not honor access or the flow tree differently, this subtle change may alter results beyond the new test cases. Confirm type_of_member_at was simply a thin wrapper and is now redundant.
  7. Comment on member_entry_type is 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.
  8. Test quality

    • test_runtime_member_read_before_its_write_keeps_declared_field uses assert!(!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 if ws.expr_ty can reach the read site.
    • test_conditional_member_write_keeps_the_path_that_skips_it expects "string?" for both skipped and skipped_nil — but for skipped_nil, if c is true the write is nil, if false the entry is string?; the union is still string?. The test asserts the same value for two genuinely different scenarios; consider asserting string? for one and, e.g., nil on a guarded branch for the other, to actually exercise the path.
    • last_name_expr_type is 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; if LuaClosureId does not implement Eq consistently across files (does it encode file_id?), this is a silent cross-file footgun. Verify.
  • member_entry_type takes access: Option<&LuaIndexExpr> but every new caller passes Some except member_type_at's own fallback closure which captures access. Fine, but the Option is redundant with the two new call sites in trace_member_uncached/walk_member — those also pass access, so the None case there is now only reachable when access itself is None at trace time. OK.
  • Consider extracting the guard matches!(def.owner, SemanticId::Decl(_)) lookup into a named helper; it's now duplicated with apply_field_nullable's pattern.

Recommended Actions (priority)

  1. Add recursion protection around type_of_expr(access) in member_entry_type (issue 5) — this is the most likely source of a real crash.
  2. Decide and document whether cross-file declared members should trigger the new branch (issue 2).
  3. Fix or rename written_in_closure_of to match what it actually checks (issue 1).
  4. 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
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks for the review. 2c009e2 addresses it (doc comments and one test, no behaviour change):

  1. Written vs declared. member_entry_type only reaches this helper for a member owned by a local or param (the SemanticId::Decl owner check). Such a member is a runtime member: its identity is its member-key range, i.e. the one s.x = v write site. ---@field members are owned by their class and never get here. Renamed to write_site_in_closure_of, and the doc says so.
  2. Cross-file. Declared fields in a shared types file are excluded by the owner check above, so this guard doesn't drop them. A local's members are written in the local's own file. The guard only keeps key_range from being looked up in another file's tree. That's now a comment.
  3. covering_element. The same guard covers it, and a lookup that finds nothing returns false, which keeps the old base.
  4. Lambdas. Intended: a callback may run after the write, so it counts as its own closure. That's in the doc now.
  5. Recursion. type_of_expr goes through type_of_expr_cached (signature.rs), which marks the expression InProgress before inferring. A re-entry reads Unknown, and Unknown keeps the old base. That's now a comment. On the 54 corpus trees, this branch crashes on the same trees as main and nowhere else.
  6. The type_of_expr_at_node fallback. type_of_member_at is member_type_at(…, None). The fallback now passes the read's access, as the else branch right below it already does.
  7. Tests. test_runtime_member_read_before_its_write_keeps_declared_field now asserts that the read is string? (main: nil). skipped_nil is meant: nil where c is true and string? where it isn't join to string?, while main reads nil. last_name_expr_type is the test module's existing helper.

@mareklangiewicz
mareklangiewicz marked this pull request as ready for review November 20, 2026 20:53
…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
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

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.

  • What it got wrong: a nested callback that reads a member its enclosing function writes only on some paths (a ctx.state set on mount) can run before or after that write. Its base should also be the declared field, but the closure condition gave it the write's value. On the fork's corpus that meant 8 false "Unnecessary assert" in tuis.nvim (that tree crashes on main, so the earlier numbers here didn't show it).
  • New condition: the old base is kept only when the write is a function statement (function M:m()). That defines the member, so another method's body sees the method and not an inherited m? field. An assignment like self.args.on_exit = function() … end is an ordinary write. The read before it is the callback being wrapped, which main currently reports as "Unnecessary if" (lualine utils/job.lua:38). That case is now a test: test_wrapping_an_optional_callback_reads_it_before_the_wrapper.

Numbers: the full suite passes (1986 tests), and fmt/clippy are clean. On the same 54 corpus trees, the total goes from 57387 on main to 57376 (61 changed lines), and 36 of the changed lines agree with emmylua 0.25.1. The need-check-nil lines this branch adds are snacks indent.lua:421 (×2), snacks dashboard.lua:561 and :727, and nui input/init.lua:58. 0.25.1 reports all five.

@mareklangiewicz mareklangiewicz changed the title fix(flow): a member read in the function that writes it starts from the declared field fix(flow): a member read before its write starts from the declared field Nov 20, 2026
mareklangiewicz and others added 2 commits November 21, 2026 01:51
…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
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.

1 participant