From f397a302a968344e8a9403206119d146bcdff7b2 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Sun, 8 Jun 2025 10:23:55 +0200 Subject: [PATCH] Invert suggestion if pointer is tested for non-nullness --- clippy_lints/src/ptr.rs | 3 ++- tests/ui/cmp_null.fixed | 6 ++++++ tests/ui/cmp_null.rs | 6 ++++++ tests/ui/cmp_null.stderr | 8 +++++++- 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/ptr.rs b/clippy_lints/src/ptr.rs index 92a912bfff8f..94cdcf000548 100644 --- a/clippy_lints/src/ptr.rs +++ b/clippy_lints/src/ptr.rs @@ -268,6 +268,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { (false, false, true) if let Some(sugg) = Sugg::hir_opt(cx, l) => sugg.maybe_paren(), _ => return check_ptr_eq(cx, expr, op.node, l, r), }; + let invert = if op.node == BinOpKind::Eq { "" } else { "!" }; span_lint_and_sugg( cx, @@ -275,7 +276,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { expr.span, "comparing with null is better expressed by the `.is_null()` method", "try", - format!("{non_null_path_snippet}.is_null()"), + format!("{invert}{non_null_path_snippet}.is_null()",), Applicability::MachineApplicable, ); } diff --git a/tests/ui/cmp_null.fixed b/tests/ui/cmp_null.fixed index 140ddb10aeb8..04b8ec50160b 100644 --- a/tests/ui/cmp_null.fixed +++ b/tests/ui/cmp_null.fixed @@ -33,3 +33,9 @@ fn main() { let _ = (x as *const ()).is_null(); //~^ cmp_null } + +fn issue15010() { + let f: *mut i32 = std::ptr::null_mut(); + debug_assert!(!f.is_null()); + //~^ cmp_null +} diff --git a/tests/ui/cmp_null.rs b/tests/ui/cmp_null.rs index 16ed17765dac..6f7762e6ae83 100644 --- a/tests/ui/cmp_null.rs +++ b/tests/ui/cmp_null.rs @@ -33,3 +33,9 @@ fn main() { let _ = x as *const () == ptr::null(); //~^ cmp_null } + +fn issue15010() { + let f: *mut i32 = std::ptr::null_mut(); + debug_assert!(f != std::ptr::null_mut()); + //~^ cmp_null +} diff --git a/tests/ui/cmp_null.stderr b/tests/ui/cmp_null.stderr index 6821846d0466..8a75b0501119 100644 --- a/tests/ui/cmp_null.stderr +++ b/tests/ui/cmp_null.stderr @@ -31,5 +31,11 @@ error: comparing with null is better expressed by the `.is_null()` method LL | let _ = x as *const () == ptr::null(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(x as *const ()).is_null()` -error: aborting due to 5 previous errors +error: comparing with null is better expressed by the `.is_null()` method + --> tests/ui/cmp_null.rs:39:19 + | +LL | debug_assert!(f != std::ptr::null_mut()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `!f.is_null()` + +error: aborting due to 6 previous errors