Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 68 additions & 5 deletions crates/emmylua_code_analysis/src/semantic_model/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,69 @@ fn flow_member_value_type(model: &SemanticModel, member: &SemanticId) -> Option<
}
}

/// 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,
access: Option<&LuaIndexExpr>,
) -> Option<LuaType> {
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(_)))
&& !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
// 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 the write site that is `member` (a runtime member's identity, see `member_entry_type`)
/// 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;
};
let Some(def) = model
.file_facts_of(key.file_id)
.and_then(|facts| facts.member_by_id(member))
else {
return false;
};
let Some(value_syntax) = def.value_syntax else {
return false;
};
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.
fn apply_field_nullable(model: &SemanticModel, member: &SemanticId, ty: LuaType) -> LuaType {
let member_file = match member {
Expand Down Expand Up @@ -627,7 +690,7 @@ fn member_type_at(
ignore_guards: bool,
access: Option<&LuaIndexExpr>,
) -> Result<LuaType, DeferredMemberRead> {
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 Ok(fallback());
};
Expand Down Expand Up @@ -903,7 +966,7 @@ pub(super) fn type_of_expr_at_node(
)?;
match traced {
Some(ty) => ty,
None => member_type_at(model, &member_id, offset, false, None)?,
None => member_type_at(model, &member_id, offset, false, Some(index_expr))?,
}
} else {
member_type_at(model, &member_id, offset, false, Some(index_expr))?
Expand Down Expand Up @@ -3084,7 +3147,7 @@ fn trace_member_uncached(
}
FlowNodeKind::Start | FlowNodeKind::Unreachable => {
return Ok(
flow_member_value_type(model, member).map(|ty| finalize(model, ty, path))
member_entry_type(model, member, access).map(|ty| finalize(model, ty, path))
);
}
_ => {}
Expand All @@ -3093,7 +3156,7 @@ fn trace_member_uncached(
match &node.antecedent {
None => {
return Ok(
flow_member_value_type(model, member).map(|ty| finalize(model, ty, path))
member_entry_type(model, member, access).map(|ty| finalize(model, ty, path))
);
}
Some(FlowAntecedent::Single(next)) => {
Expand Down Expand Up @@ -6491,7 +6554,7 @@ fn walk_member(
) -> MemberTrace {
match antecedent {
// Backtracked to the start: use the member's declaration type as the base and apply cast widening collected on the path.
None => Ok(flow_member_value_type(model, member).map(|ty| finalize(model, ty, path))),
None => Ok(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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4973,4 +4973,189 @@ _ = 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?`, 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]
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
"#,
));
}

#[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
"#,
));
}

#[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 }
"#,
));
}
}
Loading