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 clippy_utils::in_constant;
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};
20 use rustc_span::symbol::sym;
22 declare_clippy_lint! {
23 /// **What it does:** Checks for transmutes that can't ever be correct on any
26 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
28 /// **Known problems:** When accessing C, users might want to store pointer
29 /// sized objects in `extradata` arguments to save an allocation.
33 /// let ptr: *const T = core::intrinsics::transmute('x')
37 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
40 // FIXME: Move this to `complexity` again, after #5343 is fixed
41 declare_clippy_lint! {
42 /// **What it does:** Checks for transmutes to the original type of the object
43 /// and transmutes that could be a cast.
45 /// **Why is this bad?** Readability. The code tricks people into thinking that
46 /// something complex is going on.
48 /// **Known problems:** None.
52 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
54 pub USELESS_TRANSMUTE,
56 "transmutes that have the same to and from types or could be a cast/coercion"
59 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
60 declare_clippy_lint! {
61 /// **What it does:**Checks for transmutes that could be a pointer cast.
63 /// **Why is this bad?** Readability. The code tricks people into thinking that
64 /// something complex is going on.
66 /// **Known problems:** None.
71 /// # let p: *const [i32] = &[];
72 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
76 /// # let p: *const [i32] = &[];
77 /// p as *const [u16];
79 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
81 "transmutes that could be a pointer cast"
84 declare_clippy_lint! {
85 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
87 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
88 /// pointer to that type.
90 /// **Known problems:** None.
94 /// core::intrinsics::transmute(t) // where the result type is the same as
97 pub CROSSPOINTER_TRANSMUTE,
99 "transmutes that have to or from types that are a pointer to the other"
102 declare_clippy_lint! {
103 /// **What it does:** Checks for transmutes from a pointer to a reference.
105 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
107 /// **Known problems:**
108 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
109 /// while dereferencing raw pointer is not stable yet.
110 /// If you need to do this in those places,
111 /// you would have to use `transmute` instead.
116 /// let _: &T = std::mem::transmute(p); // where p: *const T
119 /// // can be written:
122 pub TRANSMUTE_PTR_TO_REF,
124 "transmutes from a pointer to a reference type"
127 declare_clippy_lint! {
128 /// **What it does:** Checks for transmutes from an integer to a `char`.
130 /// **Why is this bad?** Not every integer is a Unicode scalar value.
132 /// **Known problems:**
133 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
134 /// as it needs to validate the input.
135 /// If you are certain that the input is always a valid Unicode scalar value,
136 /// use [`from_u32_unchecked`] which is as fast as `transmute`
137 /// but has a semantically meaningful name.
138 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
140 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
141 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
147 /// let _: char = std::mem::transmute(x); // where x: u32
151 /// let _ = std::char::from_u32(x).unwrap();
153 pub TRANSMUTE_INT_TO_CHAR,
155 "transmutes from an integer to a `char`"
158 declare_clippy_lint! {
159 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
161 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
163 /// **Known problems:**
164 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
165 /// as it needs to validate the input.
166 /// If you are certain that the input is always a valid UTF-8,
167 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
168 /// but has a semantically meaningful name.
169 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
171 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
172 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
176 /// let b: &[u8] = &[1_u8, 2_u8];
178 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
182 /// let _ = std::str::from_utf8(b).unwrap();
184 pub TRANSMUTE_BYTES_TO_STR,
186 "transmutes from a `&[u8]` to a `&str`"
189 declare_clippy_lint! {
190 /// **What it does:** Checks for transmutes from an integer to a `bool`.
192 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
194 /// **Known problems:** None.
200 /// let _: bool = std::mem::transmute(x); // where x: u8
204 /// let _: bool = x != 0;
206 pub TRANSMUTE_INT_TO_BOOL,
208 "transmutes from an integer to a `bool`"
211 declare_clippy_lint! {
212 /// **What it does:** Checks for transmutes from an integer to a float.
214 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
217 /// **Known problems:** None.
222 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
226 /// let _: f32 = f32::from_bits(1_u32);
228 pub TRANSMUTE_INT_TO_FLOAT,
230 "transmutes from an integer to a float"
233 declare_clippy_lint! {
234 /// **What it does:** Checks for transmutes from a float to an integer.
236 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
239 /// **Known problems:** None.
244 /// let _: u32 = std::mem::transmute(1f32);
248 /// let _: u32 = 1f32.to_bits();
250 pub TRANSMUTE_FLOAT_TO_INT,
252 "transmutes from a float to an integer"
255 declare_clippy_lint! {
256 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
257 /// from a reference to a reference.
259 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
260 /// written as casts.
262 /// **Known problems:** None.
266 /// let ptr = &1u32 as *const u32;
268 /// // pointer-to-pointer transmute
269 /// let _: *const f32 = std::mem::transmute(ptr);
270 /// // ref-ref transmute
271 /// let _: &f32 = std::mem::transmute(&1u32);
273 /// // These can be respectively written:
274 /// let _ = ptr as *const f32;
275 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
277 pub TRANSMUTE_PTR_TO_PTR,
279 "transmutes from a pointer to a pointer / a reference to a reference"
282 declare_clippy_lint! {
283 /// **What it does:** Checks for transmutes between collections whose
284 /// types have different ABI, size or alignment.
286 /// **Why is this bad?** This is undefined behavior.
288 /// **Known problems:** Currently, we cannot know whether a type is a
289 /// collection, so we just lint the ones that come with `std`.
293 /// // different size, therefore likely out-of-bounds memory access
294 /// // You absolutely do not want this in your code!
296 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
300 /// You must always iterate, map and collect the values:
303 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
305 pub UNSOUND_COLLECTION_TRANSMUTE,
307 "transmute between collections of layout-incompatible types"
310 declare_lint_pass!(Transmute => [
311 CROSSPOINTER_TRANSMUTE,
312 TRANSMUTE_PTR_TO_REF,
313 TRANSMUTE_PTR_TO_PTR,
316 TRANSMUTE_INT_TO_CHAR,
317 TRANSMUTE_BYTES_TO_STR,
318 TRANSMUTE_INT_TO_BOOL,
319 TRANSMUTE_INT_TO_FLOAT,
320 TRANSMUTE_FLOAT_TO_INT,
321 UNSOUND_COLLECTION_TRANSMUTE,
322 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
325 impl<'tcx> LateLintPass<'tcx> for Transmute {
326 #[allow(clippy::similar_names, clippy::too_many_lines)]
327 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
329 if let ExprKind::Call(path_expr, args) = e.kind;
330 if let ExprKind::Path(ref qpath) = path_expr.kind;
331 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
332 if cx.tcx.is_diagnostic_item(sym::transmute, def_id);
334 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
335 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
336 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
337 let const_context = in_constant(cx, e.hir_id);
339 let from_ty = cx.typeck_results().expr_ty(&args[0]);
340 let to_ty = cx.typeck_results().expr_ty(e);
342 // If useless_transmute is triggered, the other lints can be skipped.
343 if useless_transmute::check(cx, e, from_ty, to_ty, args) {
347 let mut linted = wrong_transmute::check(cx, e, from_ty, to_ty);
348 linted |= crosspointer_transmute::check(cx, e, from_ty, to_ty);
349 linted |= transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
350 linted |= transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
351 linted |= transmute_ref_to_ref::check(cx, e, from_ty, to_ty, args, const_context);
352 linted |= transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, args);
353 linted |= transmute_int_to_bool::check(cx, e, from_ty, to_ty, args);
354 linted |= transmute_int_to_float::check(cx, e, from_ty, to_ty, args, const_context);
355 linted |= transmute_float_to_int::check(cx, e, from_ty, to_ty, args, const_context);
356 linted |= unsound_collection_transmute::check(cx, e, from_ty, to_ty);
359 transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, args);