2 #![warn(clippy::transmutes_expressible_as_ptr_casts)]
3 // These two warnings currrently cover the cases transmutes_expressible_as_ptr_casts
4 // would otherwise be responsible for
5 #![warn(clippy::useless_transmute)]
6 #![warn(clippy::transmute_ptr_to_ptr)]
7 #![allow(unused_unsafe)]
10 use std::mem::{size_of, transmute};
12 // rustc_typeck::check::cast contains documentation about when a cast `e as U` is
13 // valid, which we quote from below.
15 // We should see an error message for each transmute, and no error messages for
16 // the casts, since the casts are the recommended fixes.
18 // e is an integer and U is *U_0, while U_0: Sized; addr-ptr-cast
19 let _ptr_i32_transmute = unsafe {
20 usize::MAX as *const i32
22 let ptr_i32 = usize::MAX as *const i32;
24 // e has type *T, U is *U_0, and either U_0: Sized ...
25 let _ptr_i8_transmute = unsafe {
28 let _ptr_i8 = ptr_i32 as *const i8;
30 let slice_ptr = &[0,1,2,3] as *const [i32];
32 // ... or pointer_kind(T) = pointer_kind(U_0); ptr-ptr-cast
33 let _ptr_to_unsized_transmute = unsafe {
34 slice_ptr as *const [u16]
36 let _ptr_to_unsized = slice_ptr as *const [u16];
37 // TODO: We could try testing vtable casts here too, but maybe
38 // we should wait until std::raw::TraitObject is stabilized?
40 // e has type *T and U is a numeric type, while T: Sized; ptr-addr-cast
41 let _usize_from_int_ptr_transmute = unsafe {
44 let _usize_from_int_ptr = ptr_i32 as usize;
46 let array_ref: &[i32; 4] = &[1,2,3,4];
48 // e has type &[T; n] and U is *const T; array-ptr-cast
49 let _array_ptr_transmute = unsafe {
50 array_ref as *const [i32; 4]
52 let _array_ptr = array_ref as *const [i32; 4];
54 fn foo(_: usize) -> u8 { 42 }
56 // e is a function pointer type and U has type *T, while T: Sized; fptr-ptr-cast
57 let _usize_ptr_transmute = unsafe {
60 let _usize_ptr_transmute = foo as *const usize;
62 // e is a function pointer type and U is an integer; fptr-addr-cast
63 let _usize_from_fn_ptr_transmute = unsafe {
66 let _usize_from_fn_ptr = foo as *const usize;
69 // If a ref-to-ptr cast of this form where the pointer type points to a type other
70 // than the referenced type, calling `CastCheck::do_check` has been observed to
71 // cause an ICE error message. `do_check` is currently called inside the
72 // `transmutes_expressible_as_ptr_casts` check, but other, more specific lints
73 // currently prevent it from being called in these cases. This test is meant to
74 // fail if the ordering of the checks ever changes enough to cause these cases to
75 // fall through into `do_check`.
76 fn trigger_do_check_to_emit_error(in_param: &[i32; 1]) -> *const u8 {
77 unsafe { in_param as *const [i32; 1] as *const u8 }
84 struct Pair(u32, u32);
86 fn cannot_be_expressed_as_pointer_cast(in_param: Single) -> Pair {
87 assert_eq!(size_of::<Single>(), size_of::<Pair>());
89 unsafe { transmute::<Single, Pair>(in_param) }