Move transmute_ptr_to_ref to its own module

This commit is contained in:
Yusuke Tanaka 2021-02-11 00:10:19 +09:00 committed by flip1995
parent afc9275928
commit 6442d45d3a
No known key found for this signature in database
GPG key ID: 1CA0DF2AF59D68A5
2 changed files with 61 additions and 31 deletions

View file

@ -1,4 +1,5 @@
mod crosspointer_transmute;
mod transmute_ptr_to_ref;
mod useless_transmute;
mod utils;
mod wrong_transmute;
@ -360,39 +361,12 @@ impl<'tcx> LateLintPass<'tcx> for Transmute {
if triggered {
return;
}
let triggered = transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
if triggered {
return;
}
match (&from_ty.kind(), &to_ty.kind()) {
(ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
cx,
TRANSMUTE_PTR_TO_REF,
e.span,
&format!(
"transmute from a pointer type (`{}`) to a reference type \
(`{}`)",
from_ty, to_ty
),
|diag| {
let arg = sugg::Sugg::hir(cx, &args[0], "..");
let (deref, cast) = if *mutbl == Mutability::Mut {
("&mut *", "*mut")
} else {
("&*", "*const")
};
let arg = if from_pty.ty == *to_ref_ty {
arg
} else {
arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
};
diag.span_suggestion(
e.span,
"try",
sugg::make_unop(deref, arg).to_string(),
Applicability::Unspecified,
);
},
),
(ty::Int(ty::IntTy::I32) | ty::Uint(ty::UintTy::U32), &ty::Char) => {
span_lint_and_then(
cx,

View file

@ -0,0 +1,56 @@
use super::utils::get_type_snippet;
use super::TRANSMUTE_PTR_TO_REF;
use crate::utils::{span_lint_and_then, sugg};
use rustc_errors::Applicability;
use rustc_hir::{Expr, Mutability, QPath};
use rustc_lint::LateContext;
use rustc_middle::ty;
use rustc_middle::ty::Ty;
/// Checks for `transmute_ptr_to_ref` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
e: &'tcx Expr<'_>,
from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
args: &'tcx [Expr<'_>],
qpath: &'tcx QPath<'_>,
) -> bool {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => {
span_lint_and_then(
cx,
TRANSMUTE_PTR_TO_REF,
e.span,
&format!(
"transmute from a pointer type (`{}`) to a reference type (`{}`)",
from_ty, to_ty
),
|diag| {
let arg = sugg::Sugg::hir(cx, &args[0], "..");
let (deref, cast) = if *mutbl == Mutability::Mut {
("&mut *", "*mut")
} else {
("&*", "*const")
};
let arg = if from_pty.ty == *to_ref_ty {
arg
} else {
arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
};
diag.span_suggestion(
e.span,
"try",
sugg::make_unop(deref, arg).to_string(),
Applicability::Unspecified,
);
},
);
true
},
_ => false,
}
}