]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/transmute_ptr_to_ref.rs
f14eef936453114abb3b4814fafe2cfe09c95826
[rust.git] / clippy_lints / src / transmute / transmute_ptr_to_ref.rs
1 use super::utils::get_type_snippet;
2 use super::TRANSMUTE_PTR_TO_REF;
3 use clippy_utils::diagnostics::span_lint_and_then;
4 use clippy_utils::sugg;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, Mutability, QPath};
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::{self, Ty};
9
10 /// Checks for `transmute_ptr_to_ref` lint.
11 /// Returns `true` if it's triggered, otherwise returns `false`.
12 pub(super) fn check<'tcx>(
13     cx: &LateContext<'tcx>,
14     e: &'tcx Expr<'_>,
15     from_ty: Ty<'tcx>,
16     to_ty: Ty<'tcx>,
17     args: &'tcx [Expr<'_>],
18     qpath: &'tcx QPath<'_>,
19 ) -> bool {
20     match (&from_ty.kind(), &to_ty.kind()) {
21         (ty::RawPtr(from_ptr_ty), ty::Ref(_, to_ref_ty, mutbl)) => {
22             span_lint_and_then(
23                 cx,
24                 TRANSMUTE_PTR_TO_REF,
25                 e.span,
26                 &format!(
27                     "transmute from a pointer type (`{}`) to a reference type (`{}`)",
28                     from_ty, to_ty
29                 ),
30                 |diag| {
31                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
32                     let (deref, cast) = if *mutbl == Mutability::Mut {
33                         ("&mut *", "*mut")
34                     } else {
35                         ("&*", "*const")
36                     };
37
38                     let arg = if from_ptr_ty.ty == *to_ref_ty {
39                         arg
40                     } else {
41                         arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
42                     };
43
44                     diag.span_suggestion(
45                         e.span,
46                         "try",
47                         sugg::make_unop(deref, arg).to_string(),
48                         Applicability::Unspecified,
49                     );
50                 },
51             );
52             true
53         },
54         _ => false,
55     }
56 }