Invert suggestion if pointer is tested for non-nullness

This commit is contained in:
Samuel Tardieu 2025-06-08 10:23:55 +02:00
parent 0138c79f76
commit f397a302a9
No known key found for this signature in database
GPG key ID: BDDC3208C6FEAFA8
4 changed files with 21 additions and 2 deletions

View file

@ -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,
);
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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