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_num_to_bytes;
7 mod transmute_ptr_to_ptr;
8 mod transmute_ptr_to_ref;
9 mod transmute_ref_to_ref;
10 mod transmutes_expressible_as_ptr_casts;
11 mod unsound_collection_transmute;
12 mod useless_transmute;
16 use clippy_utils::in_constant;
17 use if_chain::if_chain;
18 use rustc_hir::{Expr, ExprKind};
19 use rustc_lint::{LateContext, LateLintPass};
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::symbol::sym;
23 declare_clippy_lint! {
25 /// Checks for transmutes that can't ever be correct on any
28 /// ### Why is this bad?
29 /// It's basically guaranteed to be undefined behaviour.
31 /// ### Known problems
32 /// When accessing C, users might want to store pointer
33 /// sized objects in `extradata` arguments to save an allocation.
37 /// let ptr: *const T = core::intrinsics::transmute('x')
39 #[clippy::version = "pre 1.29.0"]
42 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
45 // FIXME: Move this to `complexity` again, after #5343 is fixed
46 declare_clippy_lint! {
48 /// Checks for transmutes to the original type of the object
49 /// and transmutes that could be a cast.
51 /// ### Why is this bad?
52 /// Readability. The code tricks people into thinking that
53 /// something complex is going on.
57 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
59 #[clippy::version = "pre 1.29.0"]
60 pub USELESS_TRANSMUTE,
62 "transmutes that have the same to and from types or could be a cast/coercion"
65 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
66 declare_clippy_lint! {
68 ///Checks for transmutes that could be a pointer cast.
70 /// ### Why is this bad?
71 /// Readability. The code tricks people into thinking that
72 /// something complex is going on.
77 /// # let p: *const [i32] = &[];
78 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
82 /// # let p: *const [i32] = &[];
83 /// p as *const [u16];
85 #[clippy::version = "1.47.0"]
86 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
88 "transmutes that could be a pointer cast"
91 declare_clippy_lint! {
93 /// Checks for transmutes between a type `T` and `*T`.
95 /// ### Why is this bad?
96 /// It's easy to mistakenly transmute between a type and a
97 /// pointer to that type.
101 /// core::intrinsics::transmute(t) // where the result type is the same as
102 /// // `*t` or `&t`'s
104 #[clippy::version = "pre 1.29.0"]
105 pub CROSSPOINTER_TRANSMUTE,
107 "transmutes that have to or from types that are a pointer to the other"
110 declare_clippy_lint! {
112 /// Checks for transmutes from a pointer to a reference.
114 /// ### Why is this bad?
115 /// This can always be rewritten with `&` and `*`.
117 /// ### Known problems
118 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
119 /// while dereferencing raw pointer is not stable yet.
120 /// If you need to do this in those places,
121 /// you would have to use `transmute` instead.
126 /// let _: &T = std::mem::transmute(p); // where p: *const T
129 /// // can be written:
132 #[clippy::version = "pre 1.29.0"]
133 pub TRANSMUTE_PTR_TO_REF,
135 "transmutes from a pointer to a reference type"
138 declare_clippy_lint! {
140 /// Checks for transmutes from an integer to a `char`.
142 /// ### Why is this bad?
143 /// Not every integer is a Unicode scalar value.
145 /// ### Known problems
146 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
147 /// as it needs to validate the input.
148 /// If you are certain that the input is always a valid Unicode scalar value,
149 /// use [`from_u32_unchecked`] which is as fast as `transmute`
150 /// but has a semantically meaningful name.
151 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
153 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
154 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
160 /// let _: char = std::mem::transmute(x); // where x: u32
164 /// let _ = std::char::from_u32(x).unwrap();
166 #[clippy::version = "pre 1.29.0"]
167 pub TRANSMUTE_INT_TO_CHAR,
169 "transmutes from an integer to a `char`"
172 declare_clippy_lint! {
174 /// Checks for transmutes from a `&[u8]` to a `&str`.
176 /// ### Why is this bad?
177 /// Not every byte slice is a valid UTF-8 string.
179 /// ### Known problems
180 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
181 /// as it needs to validate the input.
182 /// If you are certain that the input is always a valid UTF-8,
183 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
184 /// but has a semantically meaningful name.
185 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
187 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
188 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
192 /// let b: &[u8] = &[1_u8, 2_u8];
194 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
198 /// let _ = std::str::from_utf8(b).unwrap();
200 #[clippy::version = "pre 1.29.0"]
201 pub TRANSMUTE_BYTES_TO_STR,
203 "transmutes from a `&[u8]` to a `&str`"
206 declare_clippy_lint! {
208 /// Checks for transmutes from an integer to a `bool`.
210 /// ### Why is this bad?
211 /// This might result in an invalid in-memory representation of a `bool`.
217 /// let _: bool = std::mem::transmute(x); // where x: u8
221 /// let _: bool = x != 0;
223 #[clippy::version = "pre 1.29.0"]
224 pub TRANSMUTE_INT_TO_BOOL,
226 "transmutes from an integer to a `bool`"
229 declare_clippy_lint! {
231 /// Checks for transmutes from an integer to a float.
233 /// ### Why is this bad?
234 /// Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
240 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
244 /// let _: f32 = f32::from_bits(1_u32);
246 #[clippy::version = "pre 1.29.0"]
247 pub TRANSMUTE_INT_TO_FLOAT,
249 "transmutes from an integer to a float"
252 declare_clippy_lint! {
254 /// Checks for transmutes from a float to an integer.
256 /// ### Why is this bad?
257 /// Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
263 /// let _: u32 = std::mem::transmute(1f32);
267 /// let _: u32 = 1f32.to_bits();
269 #[clippy::version = "1.41.0"]
270 pub TRANSMUTE_FLOAT_TO_INT,
272 "transmutes from a float to an integer"
275 declare_clippy_lint! {
277 /// Checks for transmutes from a number to an array of `u8`
279 /// ### Why this is bad?
280 /// Transmutes are dangerous and error-prone, whereas `to_ne_bytes`
281 /// is intuitive and safe.
286 /// let x: [u8; 8] = std::mem::transmute(1i64);
290 /// let x: [u8; 8] = 0i64.to_ne_bytes();
292 #[clippy::version = "1.58.0"]
293 pub TRANSMUTE_NUM_TO_BYTES,
295 "transmutes from a number to an array of `u8`"
298 declare_clippy_lint! {
300 /// Checks for transmutes from a pointer to a pointer, or
301 /// from a reference to a reference.
303 /// ### Why is this bad?
304 /// Transmutes are dangerous, and these can instead be
305 /// written as casts.
309 /// let ptr = &1u32 as *const u32;
311 /// // pointer-to-pointer transmute
312 /// let _: *const f32 = std::mem::transmute(ptr);
313 /// // ref-ref transmute
314 /// let _: &f32 = std::mem::transmute(&1u32);
316 /// // These can be respectively written:
317 /// let _ = ptr as *const f32;
318 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
320 #[clippy::version = "pre 1.29.0"]
321 pub TRANSMUTE_PTR_TO_PTR,
323 "transmutes from a pointer to a pointer / a reference to a reference"
326 declare_clippy_lint! {
328 /// Checks for transmutes between collections whose
329 /// types have different ABI, size or alignment.
331 /// ### Why is this bad?
332 /// This is undefined behavior.
334 /// ### Known problems
335 /// Currently, we cannot know whether a type is a
336 /// collection, so we just lint the ones that come with `std`.
340 /// // different size, therefore likely out-of-bounds memory access
341 /// // You absolutely do not want this in your code!
343 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
347 /// You must always iterate, map and collect the values:
350 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
352 #[clippy::version = "1.40.0"]
353 pub UNSOUND_COLLECTION_TRANSMUTE,
355 "transmute between collections of layout-incompatible types"
358 declare_lint_pass!(Transmute => [
359 CROSSPOINTER_TRANSMUTE,
360 TRANSMUTE_PTR_TO_REF,
361 TRANSMUTE_PTR_TO_PTR,
364 TRANSMUTE_INT_TO_CHAR,
365 TRANSMUTE_BYTES_TO_STR,
366 TRANSMUTE_INT_TO_BOOL,
367 TRANSMUTE_INT_TO_FLOAT,
368 TRANSMUTE_FLOAT_TO_INT,
369 TRANSMUTE_NUM_TO_BYTES,
370 UNSOUND_COLLECTION_TRANSMUTE,
371 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
374 impl<'tcx> LateLintPass<'tcx> for Transmute {
375 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
377 if let ExprKind::Call(path_expr, [arg]) = e.kind;
378 if let ExprKind::Path(ref qpath) = path_expr.kind;
379 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
380 if cx.tcx.is_diagnostic_item(sym::transmute, def_id);
382 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
383 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
384 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
385 let const_context = in_constant(cx, e.hir_id);
387 let from_ty = cx.typeck_results().expr_ty(arg);
388 let to_ty = cx.typeck_results().expr_ty(e);
390 // If useless_transmute is triggered, the other lints can be skipped.
391 if useless_transmute::check(cx, e, from_ty, to_ty, arg) {
395 let linted = wrong_transmute::check(cx, e, from_ty, to_ty)
396 | crosspointer_transmute::check(cx, e, from_ty, to_ty)
397 | transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, arg, qpath)
398 | transmute_int_to_char::check(cx, e, from_ty, to_ty, arg)
399 | transmute_ref_to_ref::check(cx, e, from_ty, to_ty, arg, const_context)
400 | transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, arg)
401 | transmute_int_to_bool::check(cx, e, from_ty, to_ty, arg)
402 | transmute_int_to_float::check(cx, e, from_ty, to_ty, arg, const_context)
403 | transmute_float_to_int::check(cx, e, from_ty, to_ty, arg, const_context)
404 | transmute_num_to_bytes::check(cx, e, from_ty, to_ty, arg, const_context)
405 | unsound_collection_transmute::check(cx, e, from_ty, to_ty);
408 transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, arg);