Skip to content

Commit 077475f

Browse files
authored
ptr_cast_constness: show snippet from the right context (#14622)
changelog: [`ptr_cast_constness`]: do not replace suggestion by content of macro Fixes #14621
2 parents 781fdab + 5dc239a commit 077475f

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

clippy_lints/src/casts/ptr_cast_constness.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ pub(super) fn check<'tcx>(
5353
}
5454

5555
if msrv.meets(cx, msrvs::POINTER_CAST_CONSTNESS) {
56-
let sugg = Sugg::hir(cx, cast_expr, "_");
56+
let mut app = Applicability::MachineApplicable;
57+
let sugg = Sugg::hir_with_context(cx, cast_expr, expr.span.ctxt(), "_", &mut app);
5758
let constness = match *to_mutbl {
5859
Mutability::Not => "const",
5960
Mutability::Mut => "mut",
@@ -66,7 +67,7 @@ pub(super) fn check<'tcx>(
6667
"`as` casting between raw pointers while changing only its constness",
6768
format!("try `pointer::cast_{constness}`, a safer alternative"),
6869
format!("{}.cast_{constness}()", sugg.maybe_paren()),
69-
Applicability::MachineApplicable,
70+
app,
7071
);
7172
}
7273
}

tests/ui/ptr_cast_constness.fixed

+6
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,9 @@ fn null_pointers() {
100100
let _ = external!(ptr::null::<u32>() as *mut u32);
101101
let _ = external!(ptr::null::<u32>().cast_mut());
102102
}
103+
104+
fn issue14621() {
105+
let mut local = 4;
106+
let _ = std::ptr::addr_of_mut!(local).cast_const();
107+
//~^ ptr_cast_constness
108+
}

tests/ui/ptr_cast_constness.rs

+6
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,9 @@ fn null_pointers() {
100100
let _ = external!(ptr::null::<u32>() as *mut u32);
101101
let _ = external!(ptr::null::<u32>().cast_mut());
102102
}
103+
104+
fn issue14621() {
105+
let mut local = 4;
106+
let _ = std::ptr::addr_of_mut!(local) as *const _;
107+
//~^ ptr_cast_constness
108+
}

tests/ui/ptr_cast_constness.stderr

+7-1
Original file line numberDiff line numberDiff line change
@@ -83,5 +83,11 @@ LL | let _ = inline!(ptr::null::<u32>().cast_mut());
8383
|
8484
= note: this error originates in the macro `__inline_mac_fn_null_pointers` (in Nightly builds, run with -Z macro-backtrace for more info)
8585

86-
error: aborting due to 13 previous errors
86+
error: `as` casting between raw pointers while changing only its constness
87+
--> tests/ui/ptr_cast_constness.rs:106:13
88+
|
89+
LL | let _ = std::ptr::addr_of_mut!(local) as *const _;
90+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast_const`, a safer alternative: `std::ptr::addr_of_mut!(local).cast_const()`
91+
92+
error: aborting due to 14 previous errors
8793

0 commit comments

Comments
 (0)