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 transmute_undefined_repr;
11 mod transmutes_expressible_as_ptr_casts;
12 mod unsound_collection_transmute;
13 mod useless_transmute;
17 use clippy_utils::in_constant;
18 use if_chain::if_chain;
19 use rustc_hir::{Expr, ExprKind};
20 use rustc_lint::{LateContext, LateLintPass};
21 use rustc_session::{declare_lint_pass, declare_tool_lint};
22 use rustc_span::symbol::sym;
24 declare_clippy_lint! {
26 /// Checks for transmutes that can't ever be correct on any
29 /// ### Why is this bad?
30 /// It's basically guaranteed to be undefined behaviour.
32 /// ### Known problems
33 /// When accessing C, users might want to store pointer
34 /// sized objects in `extradata` arguments to save an allocation.
38 /// let ptr: *const T = core::intrinsics::transmute('x')
40 #[clippy::version = "pre 1.29.0"]
43 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
46 // FIXME: Move this to `complexity` again, after #5343 is fixed
47 declare_clippy_lint! {
49 /// Checks for transmutes to the original type of the object
50 /// and transmutes that could be a cast.
52 /// ### Why is this bad?
53 /// Readability. The code tricks people into thinking that
54 /// something complex is going on.
58 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
60 #[clippy::version = "pre 1.29.0"]
61 pub USELESS_TRANSMUTE,
63 "transmutes that have the same to and from types or could be a cast/coercion"
66 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
67 declare_clippy_lint! {
69 ///Checks for transmutes that could be a pointer cast.
71 /// ### Why is this bad?
72 /// Readability. The code tricks people into thinking that
73 /// something complex is going on.
78 /// # let p: *const [i32] = &[];
79 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
83 /// # let p: *const [i32] = &[];
84 /// p as *const [u16];
86 #[clippy::version = "1.47.0"]
87 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
89 "transmutes that could be a pointer cast"
92 declare_clippy_lint! {
94 /// Checks for transmutes between a type `T` and `*T`.
96 /// ### Why is this bad?
97 /// It's easy to mistakenly transmute between a type and a
98 /// pointer to that type.
102 /// core::intrinsics::transmute(t) // where the result type is the same as
103 /// // `*t` or `&t`'s
105 #[clippy::version = "pre 1.29.0"]
106 pub CROSSPOINTER_TRANSMUTE,
108 "transmutes that have to or from types that are a pointer to the other"
111 declare_clippy_lint! {
113 /// Checks for transmutes from a pointer to a reference.
115 /// ### Why is this bad?
116 /// This can always be rewritten with `&` and `*`.
118 /// ### Known problems
119 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
120 /// while dereferencing raw pointer is not stable yet.
121 /// If you need to do this in those places,
122 /// you would have to use `transmute` instead.
127 /// let _: &T = std::mem::transmute(p); // where p: *const T
130 /// // can be written:
133 #[clippy::version = "pre 1.29.0"]
134 pub TRANSMUTE_PTR_TO_REF,
136 "transmutes from a pointer to a reference type"
139 declare_clippy_lint! {
141 /// Checks for transmutes from an integer to a `char`.
143 /// ### Why is this bad?
144 /// Not every integer is a Unicode scalar value.
146 /// ### Known problems
147 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
148 /// as it needs to validate the input.
149 /// If you are certain that the input is always a valid Unicode scalar value,
150 /// use [`from_u32_unchecked`] which is as fast as `transmute`
151 /// but has a semantically meaningful name.
152 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
154 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
155 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
161 /// let _: char = std::mem::transmute(x); // where x: u32
165 /// let _ = std::char::from_u32(x).unwrap();
167 #[clippy::version = "pre 1.29.0"]
168 pub TRANSMUTE_INT_TO_CHAR,
170 "transmutes from an integer to a `char`"
173 declare_clippy_lint! {
175 /// Checks for transmutes from a `&[u8]` to a `&str`.
177 /// ### Why is this bad?
178 /// Not every byte slice is a valid UTF-8 string.
180 /// ### Known problems
181 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
182 /// as it needs to validate the input.
183 /// If you are certain that the input is always a valid UTF-8,
184 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
185 /// but has a semantically meaningful name.
186 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
188 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
189 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
193 /// let b: &[u8] = &[1_u8, 2_u8];
195 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
199 /// let _ = std::str::from_utf8(b).unwrap();
201 #[clippy::version = "pre 1.29.0"]
202 pub TRANSMUTE_BYTES_TO_STR,
204 "transmutes from a `&[u8]` to a `&str`"
207 declare_clippy_lint! {
209 /// Checks for transmutes from an integer to a `bool`.
211 /// ### Why is this bad?
212 /// This might result in an invalid in-memory representation of a `bool`.
218 /// let _: bool = std::mem::transmute(x); // where x: u8
222 /// let _: bool = x != 0;
224 #[clippy::version = "pre 1.29.0"]
225 pub TRANSMUTE_INT_TO_BOOL,
227 "transmutes from an integer to a `bool`"
230 declare_clippy_lint! {
232 /// Checks for transmutes from an integer to a float.
234 /// ### Why is this bad?
235 /// Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
241 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
245 /// let _: f32 = f32::from_bits(1_u32);
247 #[clippy::version = "pre 1.29.0"]
248 pub TRANSMUTE_INT_TO_FLOAT,
250 "transmutes from an integer to a float"
253 declare_clippy_lint! {
255 /// Checks for transmutes from a float to an integer.
257 /// ### Why is this bad?
258 /// Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
264 /// let _: u32 = std::mem::transmute(1f32);
268 /// let _: u32 = 1f32.to_bits();
270 #[clippy::version = "1.41.0"]
271 pub TRANSMUTE_FLOAT_TO_INT,
273 "transmutes from a float to an integer"
276 declare_clippy_lint! {
278 /// Checks for transmutes from a number to an array of `u8`
280 /// ### Why this is bad?
281 /// Transmutes are dangerous and error-prone, whereas `to_ne_bytes`
282 /// is intuitive and safe.
287 /// let x: [u8; 8] = std::mem::transmute(1i64);
291 /// let x: [u8; 8] = 0i64.to_ne_bytes();
293 #[clippy::version = "1.58.0"]
294 pub TRANSMUTE_NUM_TO_BYTES,
296 "transmutes from a number to an array of `u8`"
299 declare_clippy_lint! {
301 /// Checks for transmutes from a pointer to a pointer, or
302 /// from a reference to a reference.
304 /// ### Why is this bad?
305 /// Transmutes are dangerous, and these can instead be
306 /// written as casts.
310 /// let ptr = &1u32 as *const u32;
312 /// // pointer-to-pointer transmute
313 /// let _: *const f32 = std::mem::transmute(ptr);
314 /// // ref-ref transmute
315 /// let _: &f32 = std::mem::transmute(&1u32);
317 /// // These can be respectively written:
318 /// let _ = ptr as *const f32;
319 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
321 #[clippy::version = "pre 1.29.0"]
322 pub TRANSMUTE_PTR_TO_PTR,
324 "transmutes from a pointer to a pointer / a reference to a reference"
327 declare_clippy_lint! {
329 /// Checks for transmutes between collections whose
330 /// types have different ABI, size or alignment.
332 /// ### Why is this bad?
333 /// This is undefined behavior.
335 /// ### Known problems
336 /// Currently, we cannot know whether a type is a
337 /// collection, so we just lint the ones that come with `std`.
341 /// // different size, therefore likely out-of-bounds memory access
342 /// // You absolutely do not want this in your code!
344 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
348 /// You must always iterate, map and collect the values:
351 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
353 #[clippy::version = "1.40.0"]
354 pub UNSOUND_COLLECTION_TRANSMUTE,
356 "transmute between collections of layout-incompatible types"
359 declare_clippy_lint! {
361 /// Checks for transmutes between types which do not have a representation defined relative to
364 /// ### Why is this bad?
365 /// The results of such a transmute are not defined.
367 /// ### Known problems
368 /// This lint has had multiple problems in the past and was moved to `nursery`. See issue
369 /// [#8496](https://github.com/rust-lang/rust-clippy/issues/8496) for more details.
373 /// struct Foo<T>(u32, T);
374 /// let _ = unsafe { core::mem::transmute::<Foo<u32>, Foo<i32>>(Foo(0u32, 0u32)) };
379 /// struct Foo<T>(u32, T);
380 /// let _ = unsafe { core::mem::transmute::<Foo<u32>, Foo<i32>>(Foo(0u32, 0u32)) };
382 #[clippy::version = "1.60.0"]
383 pub TRANSMUTE_UNDEFINED_REPR,
385 "transmute to or from a type with an undefined representation"
388 declare_lint_pass!(Transmute => [
389 CROSSPOINTER_TRANSMUTE,
390 TRANSMUTE_PTR_TO_REF,
391 TRANSMUTE_PTR_TO_PTR,
394 TRANSMUTE_INT_TO_CHAR,
395 TRANSMUTE_BYTES_TO_STR,
396 TRANSMUTE_INT_TO_BOOL,
397 TRANSMUTE_INT_TO_FLOAT,
398 TRANSMUTE_FLOAT_TO_INT,
399 TRANSMUTE_NUM_TO_BYTES,
400 UNSOUND_COLLECTION_TRANSMUTE,
401 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
402 TRANSMUTE_UNDEFINED_REPR,
405 impl<'tcx> LateLintPass<'tcx> for Transmute {
406 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
408 if let ExprKind::Call(path_expr, [arg]) = e.kind;
409 if let ExprKind::Path(ref qpath) = path_expr.kind;
410 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
411 if cx.tcx.is_diagnostic_item(sym::transmute, def_id);
413 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
414 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
415 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
416 let const_context = in_constant(cx, e.hir_id);
418 let from_ty = cx.typeck_results().expr_ty_adjusted(arg);
419 // Adjustments for `to_ty` happen after the call to `transmute`, so don't use them.
420 let to_ty = cx.typeck_results().expr_ty(e);
422 // If useless_transmute is triggered, the other lints can be skipped.
423 if useless_transmute::check(cx, e, from_ty, to_ty, arg) {
427 let linted = wrong_transmute::check(cx, e, from_ty, to_ty)
428 | crosspointer_transmute::check(cx, e, from_ty, to_ty)
429 | transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, arg, qpath)
430 | transmute_int_to_char::check(cx, e, from_ty, to_ty, arg)
431 | transmute_ref_to_ref::check(cx, e, from_ty, to_ty, arg, const_context)
432 | transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, arg)
433 | transmute_int_to_bool::check(cx, e, from_ty, to_ty, arg)
434 | transmute_int_to_float::check(cx, e, from_ty, to_ty, arg, const_context)
435 | transmute_float_to_int::check(cx, e, from_ty, to_ty, arg, const_context)
436 | transmute_num_to_bytes::check(cx, e, from_ty, to_ty, arg, const_context)
438 unsound_collection_transmute::check(cx, e, from_ty, to_ty)
439 || transmute_undefined_repr::check(cx, e, from_ty, to_ty)
443 transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, arg);