Skip to content

Commit 032b195

Browse files
committed
fix flow: self 删除 nil
1 parent e53fd20 commit 032b195

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

crates/emmylua_code_analysis/src/compilation/test/flow.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1258,4 +1258,30 @@ end
12581258
"#,
12591259
));
12601260
}
1261+
1262+
#[test]
1263+
fn test_self_1() {
1264+
let mut ws = VirtualWorkspace::new();
1265+
ws.def(
1266+
r#"
1267+
---@class Node
1268+
---@field parent? Node
1269+
1270+
---@class Subject<T>: Node
1271+
---@field package root? Node
1272+
Subject = {}
1273+
"#,
1274+
);
1275+
ws.def(
1276+
r#"
1277+
function Subject:add()
1278+
if self == self.parent then
1279+
A = self
1280+
end
1281+
end
1282+
"#,
1283+
);
1284+
let a = ws.expr_ty("A");
1285+
assert_eq!(ws.humanize_type(a), "Node");
1286+
}
12611287
}

crates/emmylua_code_analysis/src/semantic/infer/narrow/condition_flow/binary_flow.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,16 @@ fn maybe_var_eq_narrow(
237237
}
238238

239239
let right_expr_type = infer_expr(db, cache, right_expr)?;
240+
240241
let result_type = match condition_flow {
241-
InferConditionFlow::TrueCondition => right_expr_type,
242+
InferConditionFlow::TrueCondition => {
243+
// self 是特殊的, 我们删除其 nil 类型
244+
if var_ref_id.is_self_ref() && !right_expr_type.is_nil() {
245+
TypeOps::Remove.apply(db, &right_expr_type, &LuaType::Nil)
246+
} else {
247+
right_expr_type
248+
}
249+
}
242250
InferConditionFlow::FalseCondition => {
243251
let antecedent_flow_id = get_single_antecedent(tree, flow_node)?;
244252
let antecedent_type =

crates/emmylua_code_analysis/src/semantic/infer/narrow/var_ref_id.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ impl VarRefId {
6161
}
6262
}
6363
}
64+
65+
pub fn is_self_ref(&self) -> bool {
66+
match self {
67+
VarRefId::SelfRef(_) => true,
68+
_ => false,
69+
}
70+
}
6471
}
6572

6673
fn get_call_expr_var_ref_id(

0 commit comments

Comments
 (0)