Skip to content

Commit 21e835d

Browse files
committed
fix some semantic for safe nav
1 parent 903caa3 commit 21e835d

3 files changed

Lines changed: 26 additions & 6 deletions

File tree

crates/emmylua_code_analysis/src/diagnostic/checker/need_check_nil.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ fn check_index_expr(
5858
semantic_model: &SemanticModel,
5959
index_expr: LuaIndexExpr,
6060
) -> Option<()> {
61+
if index_expr.is_safe_index() {
62+
return None;
63+
}
64+
6165
let prefix = index_expr.get_prefix_expr()?;
6266
let prefix_type = semantic_model.infer_expr(prefix.clone()).ok()?;
6367
if prefix_type.is_nullable() {

crates/emmylua_code_analysis/src/semantic/infer/infer_index/mod.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,17 +88,17 @@ pub fn infer_index_expr(
8888
&InferGuard::new(),
8989
)?;
9090

91-
let result_type = if is_safe && prefix_type.is_nullable() {
92-
TypeOps::Union.apply(db, &member_type, &LuaType::Nil)
91+
let mut result_type = if pass_flow {
92+
infer_member_type_pass_flow(db, cache, index_expr, member_type)?
9393
} else {
9494
member_type
9595
};
9696

97-
if pass_flow {
98-
infer_member_type_pass_flow(db, cache, index_expr, result_type)
99-
} else {
100-
Ok(result_type)
97+
if is_safe && prefix_type.is_optional() {
98+
result_type = TypeOps::Union.apply(db, &result_type, &LuaType::Nil);
10199
}
100+
101+
Ok(result_type)
102102
}
103103

104104
pub fn infer_ternary_expr(

crates/emmylua_code_analysis/src/semantic/infer/test.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,20 @@ mod test {
228228

229229
assert_eq!(ws.expr_ty("c"), ws.ty("any"));
230230
}
231+
232+
#[test]
233+
fn test_safe_nav() {
234+
let mut ws = VirtualWorkspace::new();
235+
ws.def(
236+
r#"
237+
--- @class MyClass
238+
--- @field public myField? string
239+
local MyClass = {}
240+
241+
a = MyClass.myField?.byte
242+
"#,
243+
);
244+
245+
assert!(ws.expr_ty("a").is_nullable());
246+
}
231247
}

0 commit comments

Comments
 (0)