From 37f94e44109ca5cea4934ff4a15d0e8b24025266 Mon Sep 17 00:00:00 2001 From: phanium <91544758+phanen@users.noreply.github.com> Date: Sat, 27 Dec 2025 10:58:15 +0800 Subject: [PATCH] fix(diagnostics): compare non-nil with nil --- .../test/unnecessary_assert_test.rs | 17 +++++++++++++++ .../diagnostic/test/unnecessary_if_test.rs | 21 +++++++++++++++++++ .../src/semantic/infer/infer_binary/mod.rs | 10 +++++++++ 3 files changed, 48 insertions(+) diff --git a/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_assert_test.rs b/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_assert_test.rs index 1706d87e3..e7ee8e7e8 100644 --- a/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_assert_test.rs +++ b/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_assert_test.rs @@ -127,4 +127,21 @@ mod test { "# )); } + + #[test] + fn test_nonnli_with_nil() { + let mut ws = VirtualWorkspace::new(); + assert!(!ws.check_code_for( + DiagnosticCode::UnnecessaryAssert, + r#" + assert("abc" ~= nil) + "# + )); + assert!(!ws.check_code_for( + DiagnosticCode::UnnecessaryAssert, + r#" + assert(1 == nil) + "# + )); + } } diff --git a/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_if_test.rs b/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_if_test.rs index e16a652bb..f027e2ebb 100644 --- a/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_if_test.rs +++ b/crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_if_test.rs @@ -26,4 +26,25 @@ mod test { "# )); } + + #[test] + fn test_nonnil_with_nil() { + let mut ws = VirtualWorkspace::new(); + assert!(!ws.check_code_for( + DiagnosticCode::UnnecessaryIf, + r#" + if 1 ~= nil then + error("Impossible") + end + "# + )); + assert!(!ws.check_code_for( + DiagnosticCode::UnnecessaryIf, + r#" + if "abc" == nil then + error("Impossible") + end + "# + )); + } } diff --git a/crates/emmylua_code_analysis/src/semantic/infer/infer_binary/mod.rs b/crates/emmylua_code_analysis/src/semantic/infer/infer_binary/mod.rs index 7b033d03a..cbe0f63f3 100644 --- a/crates/emmylua_code_analysis/src/semantic/infer/infer_binary/mod.rs +++ b/crates/emmylua_code_analysis/src/semantic/infer/infer_binary/mod.rs @@ -506,6 +506,16 @@ fn infer_cmp_expr(_: &DbIndex, left: LuaType, right: LuaType, op: BinaryOperator BinaryOperator::OpNe => Ok(LuaType::BooleanConst(i != j)), _ => Ok(LuaType::Boolean), }, + (LuaType::Nil, right) if right.is_const() => match op { + BinaryOperator::OpEq => Ok(LuaType::BooleanConst(false)), + BinaryOperator::OpNe => Ok(LuaType::BooleanConst(true)), + _ => Ok(LuaType::Boolean), + }, + (left, LuaType::Nil) if left.is_const() => match op { + BinaryOperator::OpEq => Ok(LuaType::BooleanConst(false)), + BinaryOperator::OpNe => Ok(LuaType::BooleanConst(true)), + _ => Ok(LuaType::Boolean), + }, (left, right) if left.is_const() && right.is_const() => Ok(LuaType::BooleanConst(false)), _ => Ok(LuaType::Boolean), }