From f25197ac44553a297c93c29e99f99808964df710 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Fri, 20 Nov 2026 21:11:33 +0100 Subject: [PATCH 1/4] fix(flow): a member read in the function that writes it starts from the 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 Claude-Session: https://claude.ai/code/session_018NxUUSGcaeYGoYHckFhhm8 --- .../src/semantic_model/flow.rs | 68 ++++++++++- .../semantic_model/infer/legacy_tests/flow.rs | 115 ++++++++++++++++++ 2 files changed, 178 insertions(+), 5 deletions(-) diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 8da2de74f..0fbd6add1 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -547,6 +547,60 @@ fn flow_member_value_type(model: &SemanticModel, member: &SemanticId) -> Option< } } +/// The member's type where backtracking found none of its writes. A runtime member's own value +/// is a write that has not happened yet: the read's flow-insensitive type (the declared field, +/// or that same value for an undeclared table) is what the path holds there. +fn member_entry_type( + model: &SemanticModel, + member: &SemanticId, + access: Option<&LuaIndexExpr>, +) -> Option { + let member_file = match member { + SemanticId::Member(key) => key.file_id, + _ => model.file_id(), + }; + if let Some(access) = access + && model + .file_facts_of(member_file) + .and_then(|facts| facts.member_by_id(member)) + .is_some_and(|def| matches!(def.owner, SemanticId::Decl(_))) + && written_in_closure_of(model, member, access) + { + // A bare `nil` is the VM's answer for a member the owner doesn't declare, not a field type. + let ty = model.type_of_expr(access.get_syntax_id()); + if !matches!(ty, LuaType::Unknown | LuaType::Nil) { + return Some(ty); + } + } + flow_member_value_type(model, member) +} + +/// Whether `member` is written in the function that reads it through `access`. Only then does +/// "none of its writes precede the read" mean the read runs before the write: a method body may +/// run after a chunk-level `function M:m()` or a write in another method. +fn written_in_closure_of( + model: &SemanticModel, + member: &SemanticId, + access: &LuaIndexExpr, +) -> bool { + let SemanticId::Member(key) = member else { + return false; + }; + if key.file_id != model.file_id() { + return false; + } + let Some(tree) = model.syntax_tree() else { + return false; + }; + let written = match tree.get_red_root().covering_element(key.key_range) { + rowan::NodeOrToken::Node(node) => Some(node), + rowan::NodeOrToken::Token(token) => token.parent(), + }; + written.is_some_and(|node| { + LuaClosureId::from_node(&node) == LuaClosureId::from_node(access.syntax()) + }) +} + /// Nullable members declared with `---@field x? T` should also carry nil in flow queries. fn apply_field_nullable(model: &SemanticModel, member: &SemanticId, ty: LuaType) -> LuaType { let member_file = match member { @@ -586,7 +640,7 @@ fn member_type_at( ignore_guards: bool, access: Option<&LuaIndexExpr>, ) -> LuaType { - let fallback = || flow_member_value_type(model, member).unwrap_or(LuaType::Unknown); + let fallback = || member_entry_type(model, member, access).unwrap_or(LuaType::Unknown); let Some(tree) = model.flow_tree() else { return fallback(); }; @@ -813,7 +867,9 @@ pub(crate) fn type_of_expr_at_node( &mut HashSet::new(), &mut PathState::default(), ) - .unwrap_or_else(|| type_of_member_at(model, &member_id, offset)) + .unwrap_or_else(|| { + member_type_at(model, &member_id, offset, false, Some(index_expr)) + }) } else { member_type_at(model, &member_id, offset, false, Some(index_expr)) } @@ -2810,14 +2866,16 @@ fn trace_member_uncached( } } FlowNodeKind::Start | FlowNodeKind::Unreachable => { - return flow_member_value_type(model, member).map(|ty| finalize(model, ty, path)); + return member_entry_type(model, member, access) + .map(|ty| finalize(model, ty, path)); } _ => {} } match &node.antecedent { None => { - return flow_member_value_type(model, member).map(|ty| finalize(model, ty, path)); + return member_entry_type(model, member, access) + .map(|ty| finalize(model, ty, path)); } Some(FlowAntecedent::Single(next)) => { current = *next; @@ -6237,7 +6295,7 @@ fn walk_member( ) -> Option { match antecedent { // Backtracked to the start: use the member's declaration type as the base and apply cast widening collected on the path. - None => flow_member_value_type(model, member).map(|ty| finalize(model, ty, path)), + None => member_entry_type(model, member, access).map(|ty| finalize(model, ty, path)), Some(FlowAntecedent::Single(next)) => { trace_member(model, member, access, tree, *next, visited, path) } diff --git a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs index 2f80fd8cc..ad985330d 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs @@ -4943,4 +4943,119 @@ _ = a[2] let ty = ws.expr_ty("B"); assert_eq!(ws.humanize_type(ty), "string"); } + + #[test] + fn test_runtime_member_read_before_its_write_keeps_declared_field() { + let mut ws = VirtualWorkspace::new(); + let mut emmyrc = ws.get_emmyrc(); + emmyrc.strict.array_index = true; + ws.update_emmyrc(emmyrc); + ws.def( + r#" + ---@class EntryContainer + ---@field items string[] + "#, + ); + // `t.items[1] = nil` comes later: before it, the element is the declared `string?`. + for body in [ + "---@type nil\nlocal _n = t.items[1]\nt.items[1] = nil", + "if _flag then return end\n---@type nil\nlocal _n = t.items[1]\nt.items[1] = nil", + ] { + assert!( + !ws.has_no_diagnostic( + DiagnosticCode::AssignTypeMismatch, + &format!( + "---@param t EntryContainer\n---@param _flag boolean\nlocal function f(t, _flag)\n{body}\nend" + ), + ), + "{body}" + ); + } + } + + #[test] + fn test_conditional_member_write_keeps_the_path_that_skips_it() { + // `if c then s.desc = "x" end`: on the path where `c` is false no write ran, so the read + // holds the declared `string?`, not the write's value. + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + let file = ws.def( + r#" + ---@class CondS + ---@field desc? string + + ---@param c boolean + ---@param s CondS + local function cond(c, s) + if c then s.desc = "x" end + local skipped = s.desc + print(skipped) + end + ---@param c boolean + ---@param s CondS + local function cond_nil(c, s) + if c then s.desc = nil end + local skipped_nil = s.desc + print(skipped_nil) + end + cond(true, {}) + cond_nil(true, {}) + "#, + ); + let ty = |name| ws.humanize_type(last_name_expr_type(&ws, file, name)); + assert_eq!([ty("skipped"), ty("skipped_nil")], ["string?", "string?"]); + } + + #[test] + fn test_method_read_does_not_start_before_a_chunk_level_definition() { + // `function M:expand()` is defined at chunk level, after `children` in the file, but the + // body of `children` runs later: its read must not start from the inherited `expand?`. + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + assert!(ws.has_no_diagnostic( + DiagnosticCode::NeedCheckNil, + r#" + ---@class GBase + ---@field expand? fun(self: GBase): integer + + ---@class GNode: GBase + local M = {} + + function M:children() + return self:expand() + 1 + end + + function M:expand() + return 1 + end + return M + "#, + )); + } + + #[test] + fn test_read_before_a_write_to_an_undeclared_member_is_not_nil() { + // `args` is untyped, so the VM reads the undeclared `args[1]` as a bare `nil`: that is + // no field type to start from before the later `args[1] = missing`. + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + assert!(ws.has_no_diagnostic( + DiagnosticCode::AssignTypeMismatch, + r#" + local function holes(args, arr) + local length = args[1] + if length == nil then + length = 0 + for i in pairs(arr) do + if type(i) == "number" then + length = i + end + end + end + local missing + for i = 1, length do + end + args[1] = missing + end + return holes + "#, + )); + } } From 2c009e2043b16f1ee1c696b44f096d38ab249b16 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Fri, 20 Nov 2026 21:42:15 +0100 Subject: [PATCH 2/4] flow: document why the entry base is safe; assert the read type in the 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 Claude-Session: https://claude.ai/code/session_018NxUUSGcaeYGoYHckFhhm8 --- .../src/semantic_model/flow.rs | 27 +++++++++----- .../semantic_model/infer/legacy_tests/flow.rs | 37 +++++++++++-------- 2 files changed, 40 insertions(+), 24 deletions(-) diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 0fbd6add1..84b3be7bf 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -547,9 +547,13 @@ fn flow_member_value_type(model: &SemanticModel, member: &SemanticId) -> Option< } } -/// The member's type where backtracking found none of its writes. A runtime member's own value -/// is a write that has not happened yet: the read's flow-insensitive type (the declared field, -/// or that same value for an undeclared table) is what the path holds there. +/// The member's type where backtracking found none of its writes. +/// +/// A member owned by a local or param (`s.desc = v`) is a runtime member: its identity is that one +/// write site, and its own value is the write's value, which this path has not run. Declared +/// `---@field`s are owned by their class and never take the first branch. For a runtime member, +/// the read's flow-insensitive type (the declared field, or that same value for an undeclared +/// table) is what the path holds before the write. fn member_entry_type( model: &SemanticModel, member: &SemanticId, @@ -564,9 +568,11 @@ fn member_entry_type( .file_facts_of(member_file) .and_then(|facts| facts.member_by_id(member)) .is_some_and(|def| matches!(def.owner, SemanticId::Decl(_))) - && written_in_closure_of(model, member, access) + && write_site_in_closure_of(model, member, access) { - // A bare `nil` is the VM's answer for a member the owner doesn't declare, not a field type. + // `type_of_expr` is memoized with an in-progress marker, so a query that re-enters this + // read gets `Unknown` and keeps the old base. A bare `nil` is the VM's answer for a member + // the owner doesn't declare, not a field type. let ty = model.type_of_expr(access.get_syntax_id()); if !matches!(ty, LuaType::Unknown | LuaType::Nil) { return Some(ty); @@ -575,10 +581,11 @@ fn member_entry_type( flow_member_value_type(model, member) } -/// Whether `member` is written in the function that reads it through `access`. Only then does -/// "none of its writes precede the read" mean the read runs before the write: a method body may -/// run after a chunk-level `function M:m()` or a write in another method. -fn written_in_closure_of( +/// Whether the write site that is `member` (a runtime member's identity, see `member_entry_type`) +/// sits in the closure that reads it through `access`. Only then does "no write precedes the read" +/// mean the read runs before the write: a method body or a callback (a lambda is its own closure) +/// may run after a chunk-level `function M:m()` or after a write in another function. +fn write_site_in_closure_of( model: &SemanticModel, member: &SemanticId, access: &LuaIndexExpr, @@ -586,6 +593,8 @@ fn written_in_closure_of( let SemanticId::Member(key) = member else { return false; }; + // `key_range` is a range in `key.file_id`. A local's members are written in the local's own + // file, so another file's member is never this function's write. if key.file_id != model.file_id() { return false; } diff --git a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs index ad985330d..0c61e88e4 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs @@ -4956,21 +4956,28 @@ _ = a[2] ---@field items string[] "#, ); - // `t.items[1] = nil` comes later: before it, the element is the declared `string?`. - for body in [ - "---@type nil\nlocal _n = t.items[1]\nt.items[1] = nil", - "if _flag then return end\n---@type nil\nlocal _n = t.items[1]\nt.items[1] = nil", - ] { - assert!( - !ws.has_no_diagnostic( - DiagnosticCode::AssignTypeMismatch, - &format!( - "---@param t EntryContainer\n---@param _flag boolean\nlocal function f(t, _flag)\n{body}\nend" - ), - ), - "{body}" - ); - } + // `t.items[1] = nil` comes later: before it, the element is the declared `string?`, not + // the later write's `nil`, with or without an earlier exit on the path. + let file = ws.def( + r#" + ---@param t EntryContainer + local function plain(t) + local before = t.items[1] + print(before) + t.items[1] = nil + end + ---@param t EntryContainer + ---@param flag boolean + local function after_exit(t, flag) + if flag then return end + local before_guarded = t.items[1] + print(before_guarded) + t.items[1] = nil + end + "#, + ); + let ty = |name| ws.humanize_type(last_name_expr_type(&ws, file, name)); + assert_eq!([ty("before"), ty("before_guarded")], ["string?", "string?"]); } #[test] From 76f8fb5000ab187af368d8d744b2bcbc40ab6bfc Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Fri, 20 Nov 2026 23:26:25 +0100 Subject: [PATCH 3/4] fix(flow): only a function statement keeps the old base, not every other 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 Claude-Session: https://claude.ai/code/session_018NxUUSGcaeYGoYHckFhhm8 --- .../src/semantic_model/flow.rs | 42 +++++++++---------- .../semantic_model/infer/legacy_tests/flow.rs | 23 ++++++++++ 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 84b3be7bf..d49a6dd6a 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -568,7 +568,7 @@ fn member_entry_type( .file_facts_of(member_file) .and_then(|facts| facts.member_by_id(member)) .is_some_and(|def| matches!(def.owner, SemanticId::Decl(_))) - && write_site_in_closure_of(model, member, access) + && !defines_a_function(model, member) { // `type_of_expr` is memoized with an in-progress marker, so a query that re-enters this // read gets `Unknown` and keeps the old base. A bare `nil` is the VM's answer for a member @@ -582,32 +582,32 @@ fn member_entry_type( } /// Whether the write site that is `member` (a runtime member's identity, see `member_entry_type`) -/// sits in the closure that reads it through `access`. Only then does "no write precedes the read" -/// mean the read runs before the write: a method body or a callback (a lambda is its own closure) -/// may run after a chunk-level `function M:m()` or after a write in another function. -fn write_site_in_closure_of( - model: &SemanticModel, - member: &SemanticId, - access: &LuaIndexExpr, -) -> bool { +/// is a function statement, `function M:m()` or `function M.f()`. That defines the member rather +/// than changing its state, so a read that no definition precedes (another method's body, which +/// runs after the module has loaded) holds the function, not an inherited `m?` field. An assignment +/// (`t.cb = function() end`) is a state change like any other write. +fn defines_a_function(model: &SemanticModel, member: &SemanticId) -> bool { let SemanticId::Member(key) = member else { return false; }; - // `key_range` is a range in `key.file_id`. A local's members are written in the local's own - // file, so another file's member is never this function's write. - if key.file_id != model.file_id() { - return false; - } - let Some(tree) = model.syntax_tree() else { + let Some(def) = model + .file_facts_of(key.file_id) + .and_then(|facts| facts.member_by_id(member)) + else { return false; }; - let written = match tree.get_red_root().covering_element(key.key_range) { - rowan::NodeOrToken::Node(node) => Some(node), - rowan::NodeOrToken::Token(token) => token.parent(), + let Some(value_syntax) = def.value_syntax else { + return false; }; - written.is_some_and(|node| { - LuaClosureId::from_node(&node) == LuaClosureId::from_node(access.syntax()) - }) + model + .syntax_tree_of(key.file_id) + .and_then(|tree| value_syntax.to_node_from_root(&tree.get_red_root())) + .is_some_and(|node| { + emmylua_parser::LuaClosureExpr::cast(node.clone()).is_some() + && node + .parent() + .is_some_and(|parent| emmylua_parser::LuaFuncStat::cast(parent).is_some()) + }) } /// Nullable members declared with `---@field x? T` should also carry nil in flow queries. diff --git a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs index 0c61e88e4..2c1b2267e 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs @@ -5065,4 +5065,27 @@ _ = a[2] "#, )); } + + #[test] + fn test_wrapping_an_optional_callback_reads_it_before_the_wrapper() { + // `self.args.on_exit = function() end` assigns a function: a state change like any other + // write, so the read before it is not that function (lualine `utils/job.lua`). + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + assert!(ws.has_no_diagnostic( + DiagnosticCode::UnnecessaryIf, + r#" + local Job = { + wrap_on_exit = function(self) + local original_cb = self.args.on_exit + if original_cb then + self.args.on_exit = function() + return original_cb() + end + end + end, + } + return Job + "#, + )); + } } From a9affd2dc9351eccf45ce2ff8bce1c2ca4628e28 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Sat, 21 Nov 2026 01:31:30 +0100 Subject: [PATCH 4/4] test(flow): a nested function reads the declared field, not a later write in its parent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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 2c009e20; 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 Claude-Session: https://claude.ai/code/session_018NxUURTC4DUybydaqMS5Lu --- .../semantic_model/infer/legacy_tests/flow.rs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs index 2c1b2267e..b20e00733 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/infer/legacy_tests/flow.rs @@ -5088,4 +5088,44 @@ _ = a[2] "#, )); } + + #[test] + fn test_a_nested_function_reads_the_field_not_a_later_write_in_its_parent() { + // `f` and `s` can run before the conditional write, so they read the declared `name?`. Main + // took the write's value in both when the write carries `---@type` (a plain write reads the + // field); + // a rule that kept the write's value for reads in the writing function's closures did too + // (tuis `uis/*.lua`: `assert(ctx.state)` in `refresh`, a mount-only `ctx.state = …`). + let mut ws = VirtualWorkspace::new_with_init_std_lib(); + assert!(ws.has_no_diagnostic( + DiagnosticCode::UnnecessaryAssert, + r#" + ---@class Ctx + ---@field name? string + + ---@param ctx Ctx + ---@param c boolean + local function App(ctx, c) + local function f() + return assert(ctx.name) + end + if c then + ctx.name = "x" ---@type string + end + return f + end + + ---@param ctx Ctx + ---@param c boolean + local function Straight(ctx, c) + local s = assert(ctx.name) + if c then + ctx.name = "x" ---@type string + end + return s + end + return { App, Straight } + "#, + )); + } }