1 mod crosspointer_transmute;
2 mod transmute_float_to_int;
3 mod transmute_int_to_bool;
4 mod transmute_int_to_char;
5 mod transmute_int_to_float;
6 mod transmute_ptr_to_ptr;
7 mod transmute_ptr_to_ref;
8 mod transmute_ref_to_ref;
9 mod transmutes_expressible_as_ptr_casts;
10 mod unsound_collection_transmute;
11 mod useless_transmute;
15 use crate::utils::{in_constant, match_def_path, paths};
16 use if_chain::if_chain;
17 use rustc_hir::{Expr, ExprKind};
18 use rustc_lint::{LateContext, LateLintPass};
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 declare_clippy_lint! {
22 /// **What it does:** Checks for transmutes that can't ever be correct on any
25 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
27 /// **Known problems:** When accessing C, users might want to store pointer
28 /// sized objects in `extradata` arguments to save an allocation.
32 /// let ptr: *const T = core::intrinsics::transmute('x')
36 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
39 // FIXME: Move this to `complexity` again, after #5343 is fixed
40 declare_clippy_lint! {
41 /// **What it does:** Checks for transmutes to the original type of the object
42 /// and transmutes that could be a cast.
44 /// **Why is this bad?** Readability. The code tricks people into thinking that
45 /// something complex is going on.
47 /// **Known problems:** None.
51 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
53 pub USELESS_TRANSMUTE,
55 "transmutes that have the same to and from types or could be a cast/coercion"
58 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
59 declare_clippy_lint! {
60 /// **What it does:**Checks for transmutes that could be a pointer cast.
62 /// **Why is this bad?** Readability. The code tricks people into thinking that
63 /// something complex is going on.
65 /// **Known problems:** None.
70 /// # let p: *const [i32] = &[];
71 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
75 /// # let p: *const [i32] = &[];
76 /// p as *const [u16];
78 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
80 "transmutes that could be a pointer cast"
83 declare_clippy_lint! {
84 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
86 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
87 /// pointer to that type.
89 /// **Known problems:** None.
93 /// core::intrinsics::transmute(t) // where the result type is the same as
96 pub CROSSPOINTER_TRANSMUTE,
98 "transmutes that have to or from types that are a pointer to the other"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for transmutes from a pointer to a reference.
104 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
106 /// **Known problems:**
107 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
108 /// while dereferencing raw pointer is not stable yet.
109 /// If you need to do this in those places,
110 /// you would have to use `transmute` instead.
115 /// let _: &T = std::mem::transmute(p); // where p: *const T
118 /// // can be written:
121 pub TRANSMUTE_PTR_TO_REF,
123 "transmutes from a pointer to a reference type"
126 declare_clippy_lint! {
127 /// **What it does:** Checks for transmutes from an integer to a `char`.
129 /// **Why is this bad?** Not every integer is a Unicode scalar value.
131 /// **Known problems:**
132 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
133 /// as it needs to validate the input.
134 /// If you are certain that the input is always a valid Unicode scalar value,
135 /// use [`from_u32_unchecked`] which is as fast as `transmute`
136 /// but has a semantically meaningful name.
137 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
139 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
140 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
146 /// let _: char = std::mem::transmute(x); // where x: u32
150 /// let _ = std::char::from_u32(x).unwrap();
152 pub TRANSMUTE_INT_TO_CHAR,
154 "transmutes from an integer to a `char`"
157 declare_clippy_lint! {
158 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
160 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
162 /// **Known problems:**
163 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
164 /// as it needs to validate the input.
165 /// If you are certain that the input is always a valid UTF-8,
166 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
167 /// but has a semantically meaningful name.
168 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
170 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
171 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
175 /// let b: &[u8] = &[1_u8, 2_u8];
177 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
181 /// let _ = std::str::from_utf8(b).unwrap();
183 pub TRANSMUTE_BYTES_TO_STR,
185 "transmutes from a `&[u8]` to a `&str`"
188 declare_clippy_lint! {
189 /// **What it does:** Checks for transmutes from an integer to a `bool`.
191 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
193 /// **Known problems:** None.
199 /// let _: bool = std::mem::transmute(x); // where x: u8
203 /// let _: bool = x != 0;
205 pub TRANSMUTE_INT_TO_BOOL,
207 "transmutes from an integer to a `bool`"
210 declare_clippy_lint! {
211 /// **What it does:** Checks for transmutes from an integer to a float.
213 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
216 /// **Known problems:** None.
221 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
225 /// let _: f32 = f32::from_bits(1_u32);
227 pub TRANSMUTE_INT_TO_FLOAT,
229 "transmutes from an integer to a float"
232 declare_clippy_lint! {
233 /// **What it does:** Checks for transmutes from a float to an integer.
235 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
238 /// **Known problems:** None.
243 /// let _: u32 = std::mem::transmute(1f32);
247 /// let _: u32 = 1f32.to_bits();
249 pub TRANSMUTE_FLOAT_TO_INT,
251 "transmutes from a float to an integer"
254 declare_clippy_lint! {
255 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
256 /// from a reference to a reference.
258 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
259 /// written as casts.
261 /// **Known problems:** None.
265 /// let ptr = &1u32 as *const u32;
267 /// // pointer-to-pointer transmute
268 /// let _: *const f32 = std::mem::transmute(ptr);
269 /// // ref-ref transmute
270 /// let _: &f32 = std::mem::transmute(&1u32);
272 /// // These can be respectively written:
273 /// let _ = ptr as *const f32;
274 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
276 pub TRANSMUTE_PTR_TO_PTR,
278 "transmutes from a pointer to a pointer / a reference to a reference"
281 declare_clippy_lint! {
282 /// **What it does:** Checks for transmutes between collections whose
283 /// types have different ABI, size or alignment.
285 /// **Why is this bad?** This is undefined behavior.
287 /// **Known problems:** Currently, we cannot know whether a type is a
288 /// collection, so we just lint the ones that come with `std`.
292 /// // different size, therefore likely out-of-bounds memory access
293 /// // You absolutely do not want this in your code!
295 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
299 /// You must always iterate, map and collect the values:
302 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
304 pub UNSOUND_COLLECTION_TRANSMUTE,
306 "transmute between collections of layout-incompatible types"
309 declare_lint_pass!(Transmute => [
310 CROSSPOINTER_TRANSMUTE,
311 TRANSMUTE_PTR_TO_REF,
312 TRANSMUTE_PTR_TO_PTR,
315 TRANSMUTE_INT_TO_CHAR,
316 TRANSMUTE_BYTES_TO_STR,
317 TRANSMUTE_INT_TO_BOOL,
318 TRANSMUTE_INT_TO_FLOAT,
319 TRANSMUTE_FLOAT_TO_INT,
320 UNSOUND_COLLECTION_TRANSMUTE,
321 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
324 impl<'tcx> LateLintPass<'tcx> for Transmute {
325 #[allow(clippy::similar_names, clippy::too_many_lines)]
326 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
328 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
329 if let ExprKind::Path(ref qpath) = path_expr.kind;
330 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
331 if match_def_path(cx, def_id, &paths::TRANSMUTE);
333 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
334 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
335 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
336 let const_context = in_constant(cx, e.hir_id);
338 let from_ty = cx.typeck_results().expr_ty(&args[0]);
339 let to_ty = cx.typeck_results().expr_ty(e);
341 // If useless_transmute is triggered, the other lints can be skipped.
342 if useless_transmute::check(cx, e, from_ty, to_ty, args) {
346 let mut linted = wrong_transmute::check(cx, e, from_ty, to_ty);
347 linted |= crosspointer_transmute::check(cx, e, from_ty, to_ty);
348 linted |= transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
349 linted |= transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
350 linted |= transmute_ref_to_ref::check(cx, e, from_ty, to_ty, args, const_context);
351 linted |= transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, args);
352 linted |= transmute_int_to_bool::check(cx, e, from_ty, to_ty, args);
353 linted |= transmute_int_to_float::check(cx, e, from_ty, to_ty, args, const_context);
354 linted |= transmute_float_to_int::check(cx, e, from_ty, to_ty, args, const_context);
355 linted |= unsound_collection_transmute::check(cx, e, from_ty, to_ty);
358 transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, args);