Skip to content

Commit

Permalink
Improve cast_ptr_alignment lint
Browse files Browse the repository at this point in the history
* print alignment in bytes in the lint message
* ignore ZST left-hand types
  • Loading branch information
skade committed Jul 6, 2019
1 parent 8744e8e commit b290106
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 3 deletions.
4 changes: 3 additions & 1 deletion clippy_lints/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1215,12 +1215,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
if from_align < to_align;
// with c_void, we inherently need to trust the user
if !is_c_void(cx, from_ptr_ty.ty);
// when casting from a ZST, we don't know enough to properly lint
if !(Some(true) == cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.is_zst()));
then {
span_lint(
cx,
CAST_PTR_ALIGNMENT,
expr.span,
&format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
&format!("casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {})", cast_from, cast_to, from_align.bytes(), to_align.bytes())
);
}
}
Expand Down
2 changes: 2 additions & 0 deletions tests/ui/cast_alignment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ fn main() {
// For c_void, we should trust the user. See #2677
(&1u32 as *const u32 as *const std::os::raw::c_void) as *const u32;
(&1u32 as *const u32 as *const libc::c_void) as *const u32;
// For ZST, we should trust the user. See #4256
(&1u32 as *const u32 as *const ()) as *const u32;
}
4 changes: 2 additions & 2 deletions tests/ui/cast_alignment.stderr
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`)
error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2)
--> $DIR/cast_alignment.rs:12:5
|
LL | (&1u8 as *const u8) as *const u16;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `-D clippy::cast-ptr-alignment` implied by `-D warnings`

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

0 comments on commit b290106

Please sign in to comment.