diff options
| author | Samuel Tardieu <sam@rfc1149.net> | 2025-06-08 10:23:55 +0200 |
|---|---|---|
| committer | Samuel Tardieu <sam@rfc1149.net> | 2025-06-08 10:29:30 +0200 |
| commit | f397a302a968344e8a9403206119d146bcdff7b2 (patch) | |
| tree | 031cd9e7e73656903bf4415009e0135e59681acb | |
| parent | 0138c79f7695aea2fdc9abaa1ecea662217efce2 (diff) | |
| download | rust-f397a302a968344e8a9403206119d146bcdff7b2.tar.gz rust-f397a302a968344e8a9403206119d146bcdff7b2.zip | |
Invert suggestion if pointer is tested for non-nullness
| -rw-r--r-- | clippy_lints/src/ptr.rs | 3 | ||||
| -rw-r--r-- | tests/ui/cmp_null.fixed | 6 | ||||
| -rw-r--r-- | tests/ui/cmp_null.rs | 6 | ||||
| -rw-r--r-- | 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 92a912bfff8..94cdcf00054 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 140ddb10aeb..04b8ec50160 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 16ed17765da..6f7762e6ae8 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 6821846d046..8a75b050111 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 |
