1 mod crosspointer_transmute;
2 mod transmute_int_to_char;
3 mod transmute_ptr_to_ptr;
4 mod transmute_ptr_to_ref;
5 mod transmute_ref_to_ref;
13 in_constant, match_def_path, paths, snippet, span_lint, span_lint_and_sugg, span_lint_and_then, sugg,
15 use if_chain::if_chain;
17 use rustc_errors::Applicability;
18 use rustc_hir::{Expr, ExprKind, Mutability, UnOp};
19 use rustc_lint::{LateContext, LateLintPass};
21 use rustc_session::{declare_lint_pass, declare_tool_lint};
24 declare_clippy_lint! {
25 /// **What it does:** Checks for transmutes that can't ever be correct on any
28 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
30 /// **Known problems:** When accessing C, users might want to store pointer
31 /// sized objects in `extradata` arguments to save an allocation.
35 /// let ptr: *const T = core::intrinsics::transmute('x')
39 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
42 // FIXME: Move this to `complexity` again, after #5343 is fixed
43 declare_clippy_lint! {
44 /// **What it does:** Checks for transmutes to the original type of the object
45 /// and transmutes that could be a cast.
47 /// **Why is this bad?** Readability. The code tricks people into thinking that
48 /// something complex is going on.
50 /// **Known problems:** None.
54 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
56 pub USELESS_TRANSMUTE,
58 "transmutes that have the same to and from types or could be a cast/coercion"
61 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
62 declare_clippy_lint! {
63 /// **What it does:**Checks for transmutes that could be a pointer cast.
65 /// **Why is this bad?** Readability. The code tricks people into thinking that
66 /// something complex is going on.
68 /// **Known problems:** None.
73 /// # let p: *const [i32] = &[];
74 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
78 /// # let p: *const [i32] = &[];
79 /// p as *const [u16];
81 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
83 "transmutes that could be a pointer cast"
86 declare_clippy_lint! {
87 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
89 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
90 /// pointer to that type.
92 /// **Known problems:** None.
96 /// core::intrinsics::transmute(t) // where the result type is the same as
99 pub CROSSPOINTER_TRANSMUTE,
101 "transmutes that have to or from types that are a pointer to the other"
104 declare_clippy_lint! {
105 /// **What it does:** Checks for transmutes from a pointer to a reference.
107 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
109 /// **Known problems:**
110 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
111 /// while dereferencing raw pointer is not stable yet.
112 /// If you need to do this in those places,
113 /// you would have to use `transmute` instead.
118 /// let _: &T = std::mem::transmute(p); // where p: *const T
121 /// // can be written:
124 pub TRANSMUTE_PTR_TO_REF,
126 "transmutes from a pointer to a reference type"
129 declare_clippy_lint! {
130 /// **What it does:** Checks for transmutes from an integer to a `char`.
132 /// **Why is this bad?** Not every integer is a Unicode scalar value.
134 /// **Known problems:**
135 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
136 /// as it needs to validate the input.
137 /// If you are certain that the input is always a valid Unicode scalar value,
138 /// use [`from_u32_unchecked`] which is as fast as `transmute`
139 /// but has a semantically meaningful name.
140 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
142 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
143 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
149 /// let _: char = std::mem::transmute(x); // where x: u32
153 /// let _ = std::char::from_u32(x).unwrap();
155 pub TRANSMUTE_INT_TO_CHAR,
157 "transmutes from an integer to a `char`"
160 declare_clippy_lint! {
161 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
163 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
165 /// **Known problems:**
166 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
167 /// as it needs to validate the input.
168 /// If you are certain that the input is always a valid UTF-8,
169 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
170 /// but has a semantically meaningful name.
171 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
173 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
174 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
178 /// let b: &[u8] = &[1_u8, 2_u8];
180 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
184 /// let _ = std::str::from_utf8(b).unwrap();
186 pub TRANSMUTE_BYTES_TO_STR,
188 "transmutes from a `&[u8]` to a `&str`"
191 declare_clippy_lint! {
192 /// **What it does:** Checks for transmutes from an integer to a `bool`.
194 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
196 /// **Known problems:** None.
202 /// let _: bool = std::mem::transmute(x); // where x: u8
206 /// let _: bool = x != 0;
208 pub TRANSMUTE_INT_TO_BOOL,
210 "transmutes from an integer to a `bool`"
213 declare_clippy_lint! {
214 /// **What it does:** Checks for transmutes from an integer to a float.
216 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
219 /// **Known problems:** None.
224 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
228 /// let _: f32 = f32::from_bits(1_u32);
230 pub TRANSMUTE_INT_TO_FLOAT,
232 "transmutes from an integer to a float"
235 declare_clippy_lint! {
236 /// **What it does:** Checks for transmutes from a float to an integer.
238 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
241 /// **Known problems:** None.
246 /// let _: u32 = std::mem::transmute(1f32);
250 /// let _: u32 = 1f32.to_bits();
252 pub TRANSMUTE_FLOAT_TO_INT,
254 "transmutes from a float to an integer"
257 declare_clippy_lint! {
258 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
259 /// from a reference to a reference.
261 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
262 /// written as casts.
264 /// **Known problems:** None.
268 /// let ptr = &1u32 as *const u32;
270 /// // pointer-to-pointer transmute
271 /// let _: *const f32 = std::mem::transmute(ptr);
272 /// // ref-ref transmute
273 /// let _: &f32 = std::mem::transmute(&1u32);
275 /// // These can be respectively written:
276 /// let _ = ptr as *const f32;
277 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
279 pub TRANSMUTE_PTR_TO_PTR,
281 "transmutes from a pointer to a pointer / a reference to a reference"
284 declare_clippy_lint! {
285 /// **What it does:** Checks for transmutes between collections whose
286 /// types have different ABI, size or alignment.
288 /// **Why is this bad?** This is undefined behavior.
290 /// **Known problems:** Currently, we cannot know whether a type is a
291 /// collection, so we just lint the ones that come with `std`.
295 /// // different size, therefore likely out-of-bounds memory access
296 /// // You absolutely do not want this in your code!
298 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
302 /// You must always iterate, map and collect the values:
305 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
307 pub UNSOUND_COLLECTION_TRANSMUTE,
309 "transmute between collections of layout-incompatible types"
312 declare_lint_pass!(Transmute => [
313 CROSSPOINTER_TRANSMUTE,
314 TRANSMUTE_PTR_TO_REF,
315 TRANSMUTE_PTR_TO_PTR,
318 TRANSMUTE_INT_TO_CHAR,
319 TRANSMUTE_BYTES_TO_STR,
320 TRANSMUTE_INT_TO_BOOL,
321 TRANSMUTE_INT_TO_FLOAT,
322 TRANSMUTE_FLOAT_TO_INT,
323 UNSOUND_COLLECTION_TRANSMUTE,
324 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
327 // used to check for UNSOUND_COLLECTION_TRANSMUTE
328 static COLLECTIONS: &[&[&str]] = &[
338 impl<'tcx> LateLintPass<'tcx> for Transmute {
339 #[allow(clippy::similar_names, clippy::too_many_lines)]
340 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
342 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
343 if let ExprKind::Path(ref qpath) = path_expr.kind;
344 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
345 if match_def_path(cx, def_id, &paths::TRANSMUTE);
347 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
348 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
349 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
350 let const_context = in_constant(cx, e.hir_id);
352 let from_ty = cx.typeck_results().expr_ty(&args[0]);
353 let to_ty = cx.typeck_results().expr_ty(e);
355 let triggered = useless_transmute::check(cx, e, from_ty, to_ty, args);
359 let triggered = wrong_transmute::check(cx, e, from_ty, to_ty);
363 let triggered = crosspointer_transmute::check(cx, e, from_ty, to_ty);
367 let triggered = transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
371 let triggered = transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
375 let triggered = transmute_ref_to_ref::check(cx, e, from_ty, to_ty, args, const_context);
379 let triggered = transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, args);
384 match (&from_ty.kind(), &to_ty.kind()) {
385 (ty::Int(ty::IntTy::I8) | ty::Uint(ty::UintTy::U8), ty::Bool) => {
388 TRANSMUTE_INT_TO_BOOL,
390 &format!("transmute from a `{}` to a `bool`", from_ty),
392 let arg = sugg::Sugg::hir(cx, &args[0], "..");
393 let zero = sugg::Sugg::NonParen(Cow::from("0"));
394 diag.span_suggestion(
397 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
398 Applicability::Unspecified,
403 (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
405 TRANSMUTE_INT_TO_FLOAT,
407 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
409 let arg = sugg::Sugg::hir(cx, &args[0], "..");
410 let arg = if let ty::Int(int_ty) = from_ty.kind() {
413 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
418 diag.span_suggestion(
421 format!("{}::from_bits({})", to_ty, arg.to_string()),
422 Applicability::Unspecified,
426 (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
428 TRANSMUTE_FLOAT_TO_INT,
430 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
432 let mut expr = &args[0];
433 let mut arg = sugg::Sugg::hir(cx, expr, "..");
435 if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
440 // if the expression is a float literal and it is unsuffixed then
441 // add a suffix so the suggestion is valid and unambiguous
442 let op = format!("{}{}", arg, float_ty.name_str()).into();
443 if let ExprKind::Lit(lit) = &expr.kind;
444 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
447 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
448 _ => arg = sugg::Sugg::NonParen(op)
453 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
455 // cast the result of `to_bits` if `to_ty` is signed
456 arg = if let ty::Int(int_ty) = to_ty.kind() {
457 arg.as_ty(int_ty.name_str().to_string())
462 diag.span_suggestion(
466 Applicability::Unspecified,
470 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
471 if from_adt.did != to_adt.did ||
472 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
475 if from_substs.types().zip(to_substs.types())
476 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
479 UNSOUND_COLLECTION_TRANSMUTE,
482 "transmute from `{}` to `{}` with mismatched layout is unsound",
489 (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
491 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
494 "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
499 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
500 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
501 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);