1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
11 use crate::utils::{opt_def_id, sugg};
12 use if_chain::if_chain;
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::ty::{self, Ty};
16 use rustc::{declare_tool_lint, lint_array};
17 use rustc_errors::Applicability;
21 /// **What it does:** Checks for transmutes that can't ever be correct on any
24 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
26 /// **Known problems:** When accessing C, users might want to store pointer
27 /// sized objects in `extradata` arguments to save an allocation.
31 /// let ptr: *const T = core::intrinsics::transmute('x')
33 declare_clippy_lint! {
36 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
39 /// **What it does:** Checks for transmutes to the original type of the object
40 /// and transmutes that could be a cast.
42 /// **Why is this bad?** Readability. The code tricks people into thinking that
43 /// something complex is going on.
45 /// **Known problems:** None.
49 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
51 declare_clippy_lint! {
52 pub USELESS_TRANSMUTE,
54 "transmutes that have the same to and from types or could be a cast/coercion"
57 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
59 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
60 /// pointer to that type.
62 /// **Known problems:** None.
66 /// core::intrinsics::transmute(t) // where the result type is the same as
69 declare_clippy_lint! {
70 pub CROSSPOINTER_TRANSMUTE,
72 "transmutes that have to or from types that are a pointer to the other"
75 /// **What it does:** Checks for transmutes from a pointer to a reference.
77 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
79 /// **Known problems:** None.
83 /// let _: &T = std::mem::transmute(p); // where p: *const T
85 /// // can be written:
88 declare_clippy_lint! {
89 pub TRANSMUTE_PTR_TO_REF,
91 "transmutes from a pointer to a reference type"
94 /// **What it does:** Checks for transmutes from an integer to a `char`.
96 /// **Why is this bad?** Not every integer is a Unicode scalar value.
98 /// **Known problems:**
99 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
100 /// as it needs to validate the input.
101 /// If you are certain that the input is always a valid Unicode scalar value,
102 /// use [`from_u32_unchecked`] which is as fast as `transmute`
103 /// but has a semantically meaningful name.
104 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
106 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
107 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
111 /// let _: char = std::mem::transmute(x); // where x: u32
114 /// let _ = std::char::from_u32(x).unwrap();
116 declare_clippy_lint! {
117 pub TRANSMUTE_INT_TO_CHAR,
119 "transmutes from an integer to a `char`"
122 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
124 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
126 /// **Known problems:**
127 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
128 /// as it needs to validate the input.
129 /// If you are certain that the input is always a valid UTF-8,
130 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
131 /// but has a semantically meaningful name.
132 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
134 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
135 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
139 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
142 /// let _ = std::str::from_utf8(b).unwrap();
144 declare_clippy_lint! {
145 pub TRANSMUTE_BYTES_TO_STR,
147 "transmutes from a `&[u8]` to a `&str`"
150 /// **What it does:** Checks for transmutes from an integer to a `bool`.
152 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
154 /// **Known problems:** None.
158 /// let _: bool = std::mem::transmute(x); // where x: u8
161 /// let _: bool = x != 0;
163 declare_clippy_lint! {
164 pub TRANSMUTE_INT_TO_BOOL,
166 "transmutes from an integer to a `bool`"
169 /// **What it does:** Checks for transmutes from an integer to a float.
171 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
173 /// **Known problems:** None.
177 /// let _: f32 = std::mem::transmute(x); // where x: u32
180 /// let _: f32 = f32::from_bits(x);
182 declare_clippy_lint! {
183 pub TRANSMUTE_INT_TO_FLOAT,
185 "transmutes from an integer to a float"
188 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
189 /// from a reference to a reference.
191 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
192 /// written as casts.
194 /// **Known problems:** None.
198 /// let ptr = &1u32 as *const u32;
200 /// // pointer-to-pointer transmute
201 /// let _: *const f32 = std::mem::transmute(ptr);
202 /// // ref-ref transmute
203 /// let _: &f32 = std::mem::transmute(&1u32);
205 /// // These can be respectively written:
206 /// let _ = ptr as *const f32
207 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
209 declare_clippy_lint! {
210 pub TRANSMUTE_PTR_TO_PTR,
212 "transmutes from a pointer to a pointer / a reference to a reference"
215 pub struct Transmute;
217 impl LintPass for Transmute {
218 fn get_lints(&self) -> LintArray {
220 CROSSPOINTER_TRANSMUTE,
221 TRANSMUTE_PTR_TO_REF,
222 TRANSMUTE_PTR_TO_PTR,
225 TRANSMUTE_INT_TO_CHAR,
226 TRANSMUTE_BYTES_TO_STR,
227 TRANSMUTE_INT_TO_BOOL,
228 TRANSMUTE_INT_TO_FLOAT,
233 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
234 #[allow(clippy::similar_names)]
235 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
236 if let ExprKind::Call(ref path_expr, ref args) = e.node {
237 if let ExprKind::Path(ref qpath) = path_expr.node {
238 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
239 if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
240 let from_ty = cx.tables.expr_ty(&args[0]);
241 let to_ty = cx.tables.expr_ty(e);
243 match (&from_ty.sty, &to_ty.sty) {
244 _ if from_ty == to_ty => span_lint(
248 &format!("transmute from a type (`{}`) to itself", from_ty),
250 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
254 "transmute from a reference to a pointer",
256 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
257 let rty_and_mut = ty::TypeAndMut {
262 let sugg = if ptr_ty == rty_and_mut {
265 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
268 db.span_suggestion_with_applicability(
272 Applicability::Unspecified,
277 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
281 "transmute from an integer to a pointer",
283 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
284 db.span_suggestion_with_applicability(
287 arg.as_ty(&to_ty.to_string()).to_string(),
288 Applicability::Unspecified,
293 (&ty::Float(_), &ty::Ref(..))
294 | (&ty::Float(_), &ty::RawPtr(_))
295 | (&ty::Char, &ty::Ref(..))
296 | (&ty::Char, &ty::RawPtr(_)) => span_lint(
300 &format!("transmute from a `{}` to a pointer", from_ty),
302 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
304 CROSSPOINTER_TRANSMUTE,
307 "transmute from a type (`{}`) to the type that it points to (`{}`)",
311 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
313 CROSSPOINTER_TRANSMUTE,
316 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
320 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
322 TRANSMUTE_PTR_TO_REF,
325 "transmute from a pointer type (`{}`) to a reference type \
330 let arg = sugg::Sugg::hir(cx, &args[0], "..");
331 let (deref, cast) = if mutbl == Mutability::MutMutable {
337 let arg = if from_pty.ty == to_ref_ty {
340 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
343 db.span_suggestion_with_applicability(
346 sugg::make_unop(deref, arg).to_string(),
347 Applicability::Unspecified,
351 (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
354 TRANSMUTE_INT_TO_CHAR,
356 &format!("transmute from a `{}` to a `char`", from_ty),
358 let arg = sugg::Sugg::hir(cx, &args[0], "..");
359 let arg = if let ty::Int(_) = from_ty.sty {
360 arg.as_ty(ty::Uint(ast::UintTy::U32))
364 db.span_suggestion_with_applicability(
367 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
368 Applicability::Unspecified,
373 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
375 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.sty, &ty_to.sty);
376 if let ty::Uint(ast::UintTy::U8) = slice_ty.sty;
377 if from_mutbl == to_mutbl;
379 let postfix = if from_mutbl == Mutability::MutMutable {
387 TRANSMUTE_BYTES_TO_STR,
389 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
391 db.span_suggestion_with_applicability(
395 "std::str::from_utf8{}({}).unwrap()",
397 snippet(cx, args[0].span, ".."),
399 Applicability::Unspecified,
404 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
407 TRANSMUTE_PTR_TO_PTR,
409 "transmute from a reference to a reference",
410 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
411 let ty_from_and_mut = ty::TypeAndMut {
415 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
417 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
418 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
419 let sugg = if to_mutbl == Mutability::MutMutable {
420 sugg_paren.mut_addr_deref()
422 sugg_paren.addr_deref()
424 db.span_suggestion_with_applicability(
428 Applicability::Unspecified,
436 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
438 TRANSMUTE_PTR_TO_PTR,
440 "transmute from a pointer to a pointer",
442 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
443 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
444 db.span_suggestion_with_applicability(
448 Applicability::Unspecified,
453 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
456 TRANSMUTE_INT_TO_BOOL,
458 &format!("transmute from a `{}` to a `bool`", from_ty),
460 let arg = sugg::Sugg::hir(cx, &args[0], "..");
461 let zero = sugg::Sugg::NonParen(Cow::from("0"));
462 db.span_suggestion_with_applicability(
465 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
466 Applicability::Unspecified,
471 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
473 TRANSMUTE_INT_TO_FLOAT,
475 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
477 let arg = sugg::Sugg::hir(cx, &args[0], "..");
478 let arg = if let ty::Int(int_ty) = from_ty.sty {
481 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
486 db.span_suggestion_with_applicability(
489 format!("{}::from_bits({})", to_ty, arg.to_string()),
490 Applicability::Unspecified,
503 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
504 /// not available , use
505 /// the type's `ToString` implementation. In weird cases it could lead to types
506 /// with invalid `'_`
507 /// lifetime, but it should be rare.
508 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
509 let seg = last_path_segment(path);
511 if let Some(ref params) = seg.args;
512 if !params.parenthesized;
513 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
514 GenericArg::Type(ty) => Some(ty),
515 GenericArg::Lifetime(_) => None,
517 if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
519 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
523 to_ref_ty.to_string()