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