1 mod crosspointer_transmute;
2 mod transmute_int_to_bool;
3 mod transmute_int_to_char;
4 mod transmute_int_to_float;
5 mod transmute_ptr_to_ptr;
6 mod transmute_ptr_to_ref;
7 mod transmute_ref_to_ref;
15 in_constant, match_def_path, paths, snippet, span_lint, span_lint_and_sugg, span_lint_and_then, sugg,
17 use if_chain::if_chain;
19 use rustc_errors::Applicability;
20 use rustc_hir::{Expr, ExprKind, Mutability, UnOp};
21 use rustc_lint::{LateContext, LateLintPass};
23 use rustc_session::{declare_lint_pass, declare_tool_lint};
26 declare_clippy_lint! {
27 /// **What it does:** Checks for transmutes that can't ever be correct on any
30 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
32 /// **Known problems:** 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')
41 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
44 // FIXME: Move this to `complexity` again, after #5343 is fixed
45 declare_clippy_lint! {
46 /// **What it does:** Checks for transmutes to the original type of the object
47 /// and transmutes that could be a cast.
49 /// **Why is this bad?** Readability. The code tricks people into thinking that
50 /// something complex is going on.
52 /// **Known problems:** None.
56 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
58 pub USELESS_TRANSMUTE,
60 "transmutes that have the same to and from types or could be a cast/coercion"
63 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
64 declare_clippy_lint! {
65 /// **What it does:**Checks for transmutes that could be a pointer cast.
67 /// **Why is this bad?** Readability. The code tricks people into thinking that
68 /// something complex is going on.
70 /// **Known problems:** None.
75 /// # let p: *const [i32] = &[];
76 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
80 /// # let p: *const [i32] = &[];
81 /// p as *const [u16];
83 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
85 "transmutes that could be a pointer cast"
88 declare_clippy_lint! {
89 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
91 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
92 /// pointer to that type.
94 /// **Known problems:** None.
98 /// core::intrinsics::transmute(t) // where the result type is the same as
101 pub CROSSPOINTER_TRANSMUTE,
103 "transmutes that have to or from types that are a pointer to the other"
106 declare_clippy_lint! {
107 /// **What it does:** Checks for transmutes from a pointer to a reference.
109 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
111 /// **Known problems:**
112 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
113 /// while dereferencing raw pointer is not stable yet.
114 /// If you need to do this in those places,
115 /// you would have to use `transmute` instead.
120 /// let _: &T = std::mem::transmute(p); // where p: *const T
123 /// // can be written:
126 pub TRANSMUTE_PTR_TO_REF,
128 "transmutes from a pointer to a reference type"
131 declare_clippy_lint! {
132 /// **What it does:** Checks for transmutes from an integer to a `char`.
134 /// **Why is this bad?** Not every integer is a Unicode scalar value.
136 /// **Known problems:**
137 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
138 /// as it needs to validate the input.
139 /// If you are certain that the input is always a valid Unicode scalar value,
140 /// use [`from_u32_unchecked`] which is as fast as `transmute`
141 /// but has a semantically meaningful name.
142 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
144 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
145 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
151 /// let _: char = std::mem::transmute(x); // where x: u32
155 /// let _ = std::char::from_u32(x).unwrap();
157 pub TRANSMUTE_INT_TO_CHAR,
159 "transmutes from an integer to a `char`"
162 declare_clippy_lint! {
163 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
165 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
167 /// **Known problems:**
168 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
169 /// as it needs to validate the input.
170 /// If you are certain that the input is always a valid UTF-8,
171 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
172 /// but has a semantically meaningful name.
173 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
175 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
176 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
180 /// let b: &[u8] = &[1_u8, 2_u8];
182 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
186 /// let _ = std::str::from_utf8(b).unwrap();
188 pub TRANSMUTE_BYTES_TO_STR,
190 "transmutes from a `&[u8]` to a `&str`"
193 declare_clippy_lint! {
194 /// **What it does:** Checks for transmutes from an integer to a `bool`.
196 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
198 /// **Known problems:** None.
204 /// let _: bool = std::mem::transmute(x); // where x: u8
208 /// let _: bool = x != 0;
210 pub TRANSMUTE_INT_TO_BOOL,
212 "transmutes from an integer to a `bool`"
215 declare_clippy_lint! {
216 /// **What it does:** Checks for transmutes from an integer to a float.
218 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
221 /// **Known problems:** None.
226 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
230 /// let _: f32 = f32::from_bits(1_u32);
232 pub TRANSMUTE_INT_TO_FLOAT,
234 "transmutes from an integer to a float"
237 declare_clippy_lint! {
238 /// **What it does:** Checks for transmutes from a float to an integer.
240 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
243 /// **Known problems:** None.
248 /// let _: u32 = std::mem::transmute(1f32);
252 /// let _: u32 = 1f32.to_bits();
254 pub TRANSMUTE_FLOAT_TO_INT,
256 "transmutes from a float to an integer"
259 declare_clippy_lint! {
260 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
261 /// from a reference to a reference.
263 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
264 /// written as casts.
266 /// **Known problems:** None.
270 /// let ptr = &1u32 as *const u32;
272 /// // pointer-to-pointer transmute
273 /// let _: *const f32 = std::mem::transmute(ptr);
274 /// // ref-ref transmute
275 /// let _: &f32 = std::mem::transmute(&1u32);
277 /// // These can be respectively written:
278 /// let _ = ptr as *const f32;
279 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
281 pub TRANSMUTE_PTR_TO_PTR,
283 "transmutes from a pointer to a pointer / a reference to a reference"
286 declare_clippy_lint! {
287 /// **What it does:** Checks for transmutes between collections whose
288 /// types have different ABI, size or alignment.
290 /// **Why is this bad?** This is undefined behavior.
292 /// **Known problems:** Currently, we cannot know whether a type is a
293 /// collection, so we just lint the ones that come with `std`.
297 /// // different size, therefore likely out-of-bounds memory access
298 /// // You absolutely do not want this in your code!
300 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
304 /// You must always iterate, map and collect the values:
307 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
309 pub UNSOUND_COLLECTION_TRANSMUTE,
311 "transmute between collections of layout-incompatible types"
314 declare_lint_pass!(Transmute => [
315 CROSSPOINTER_TRANSMUTE,
316 TRANSMUTE_PTR_TO_REF,
317 TRANSMUTE_PTR_TO_PTR,
320 TRANSMUTE_INT_TO_CHAR,
321 TRANSMUTE_BYTES_TO_STR,
322 TRANSMUTE_INT_TO_BOOL,
323 TRANSMUTE_INT_TO_FLOAT,
324 TRANSMUTE_FLOAT_TO_INT,
325 UNSOUND_COLLECTION_TRANSMUTE,
326 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
329 // used to check for UNSOUND_COLLECTION_TRANSMUTE
330 static COLLECTIONS: &[&[&str]] = &[
340 impl<'tcx> LateLintPass<'tcx> for Transmute {
341 #[allow(clippy::similar_names, clippy::too_many_lines)]
342 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
344 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
345 if let ExprKind::Path(ref qpath) = path_expr.kind;
346 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
347 if match_def_path(cx, def_id, &paths::TRANSMUTE);
349 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
350 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
351 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
352 let const_context = in_constant(cx, e.hir_id);
354 let from_ty = cx.typeck_results().expr_ty(&args[0]);
355 let to_ty = cx.typeck_results().expr_ty(e);
357 let triggered = useless_transmute::check(cx, e, from_ty, to_ty, args);
361 let triggered = wrong_transmute::check(cx, e, from_ty, to_ty);
365 let triggered = crosspointer_transmute::check(cx, e, from_ty, to_ty);
369 let triggered = transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
373 let triggered = transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
377 let triggered = transmute_ref_to_ref::check(cx, e, from_ty, to_ty, args, const_context);
381 let triggered = transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, args);
385 let triggered = transmute_int_to_bool::check(cx, e, from_ty, to_ty, args);
389 let triggered = transmute_int_to_float::check(cx, e, from_ty, to_ty, args, const_context);
394 match (&from_ty.kind(), &to_ty.kind()) {
395 (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
397 TRANSMUTE_FLOAT_TO_INT,
399 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
401 let mut expr = &args[0];
402 let mut arg = sugg::Sugg::hir(cx, expr, "..");
404 if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
409 // if the expression is a float literal and it is unsuffixed then
410 // add a suffix so the suggestion is valid and unambiguous
411 let op = format!("{}{}", arg, float_ty.name_str()).into();
412 if let ExprKind::Lit(lit) = &expr.kind;
413 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
416 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
417 _ => arg = sugg::Sugg::NonParen(op)
422 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
424 // cast the result of `to_bits` if `to_ty` is signed
425 arg = if let ty::Int(int_ty) = to_ty.kind() {
426 arg.as_ty(int_ty.name_str().to_string())
431 diag.span_suggestion(
435 Applicability::Unspecified,
439 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
440 if from_adt.did != to_adt.did ||
441 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
444 if from_substs.types().zip(to_substs.types())
445 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
448 UNSOUND_COLLECTION_TRANSMUTE,
451 "transmute from `{}` to `{}` with mismatched layout is unsound",
458 (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
460 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
463 "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
468 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
469 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
470 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);