Skip to content

Commit f397a30

Browse files
committed
Invert suggestion if pointer is tested for non-nullness
1 parent 0138c79 commit f397a30

File tree

4 files changed

+21
-2
lines changed

4 files changed

+21
-2
lines changed

clippy_lints/src/ptr.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,14 +268,15 @@ impl<'tcx> LateLintPass<'tcx> for Ptr {
268268
(false, false, true) if let Some(sugg) = Sugg::hir_opt(cx, l) => sugg.maybe_paren(),
269269
_ => return check_ptr_eq(cx, expr, op.node, l, r),
270270
};
271+
let invert = if op.node == BinOpKind::Eq { "" } else { "!" };
271272

272273
span_lint_and_sugg(
273274
cx,
274275
CMP_NULL,
275276
expr.span,
276277
"comparing with null is better expressed by the `.is_null()` method",
277278
"try",
278-
format!("{non_null_path_snippet}.is_null()"),
279+
format!("{invert}{non_null_path_snippet}.is_null()",),
279280
Applicability::MachineApplicable,
280281
);
281282
}

tests/ui/cmp_null.fixed

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,9 @@ fn main() {
3333
let _ = (x as *const ()).is_null();
3434
//~^ cmp_null
3535
}
36+
37+
fn issue15010() {
38+
let f: *mut i32 = std::ptr::null_mut();
39+
debug_assert!(!f.is_null());
40+
//~^ cmp_null
41+
}

tests/ui/cmp_null.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,9 @@ fn main() {
3333
let _ = x as *const () == ptr::null();
3434
//~^ cmp_null
3535
}
36+
37+
fn issue15010() {
38+
let f: *mut i32 = std::ptr::null_mut();
39+
debug_assert!(f != std::ptr::null_mut());
40+
//~^ cmp_null
41+
}

tests/ui/cmp_null.stderr

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,11 @@ error: comparing with null is better expressed by the `.is_null()` method
3131
LL | let _ = x as *const () == ptr::null();
3232
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(x as *const ()).is_null()`
3333

34-
error: aborting due to 5 previous errors
34+
error: comparing with null is better expressed by the `.is_null()` method
35+
--> tests/ui/cmp_null.rs:39:19
36+
|
37+
LL | debug_assert!(f != std::ptr::null_mut());
38+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `!f.is_null()`
39+
40+
error: aborting due to 6 previous errors
3541

0 commit comments

Comments
 (0)