Skip to content

Commit aa72cac

Browse files
committed
Improve cast_ptr_alignment lint
* print alignment in bytes in the lint message * ignore ZST left-hand types
1 parent 8744e8e commit aa72cac

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

clippy_lints/src/types.rs

+12-4
Original file line numberDiff line numberDiff line change
@@ -1210,17 +1210,25 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
12101210
if_chain! {
12111211
if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
12121212
if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
1213-
if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi);
1214-
if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi);
1215-
if from_align < to_align;
1213+
if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1214+
if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1215+
if from_layout.align.abi < to_layout.align.abi;
12161216
// with c_void, we inherently need to trust the user
12171217
if !is_c_void(cx, from_ptr_ty.ty);
1218+
// when casting from a ZST, we don't know enough to properly lint
1219+
if !from_layout.is_zst();
12181220
then {
12191221
span_lint(
12201222
cx,
12211223
CAST_PTR_ALIGNMENT,
12221224
expr.span,
1223-
&format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1225+
&format!(
1226+
"casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1227+
cast_from,
1228+
cast_to,
1229+
from_layout.align.abi.bytes(),
1230+
to_layout.align.abi.bytes(),
1231+
),
12241232
);
12251233
}
12261234
}

tests/ui/cast_alignment.rs

+2
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,6 @@ fn main() {
2222
// For c_void, we should trust the user. See #2677
2323
(&1u32 as *const u32 as *const std::os::raw::c_void) as *const u32;
2424
(&1u32 as *const u32 as *const libc::c_void) as *const u32;
25+
// For ZST, we should trust the user. See #4256
26+
(&1u32 as *const u32 as *const ()) as *const u32;
2527
}

tests/ui/cast_alignment.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`)
1+
error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes)
22
--> $DIR/cast_alignment.rs:12:5
33
|
44
LL | (&1u8 as *const u8) as *const u16;
55
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66
|
77
= note: `-D clippy::cast-ptr-alignment` implied by `-D warnings`
88

9-
error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`)
9+
error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 < 2 bytes)
1010
--> $DIR/cast_alignment.rs:13:5
1111
|
1212
LL | (&mut 1u8 as *mut u8) as *mut u16;

0 commit comments

Comments
 (0)