2021-03-12 08:30:50 -06:00
|
|
|
use super::USELESS_TRANSMUTE;
|
2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
|
|
|
|
use clippy_utils::sugg;
|
2021-03-12 08:30:50 -06:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir::Expr;
|
|
|
|
use rustc_lint::LateContext;
|
2023-02-21 20:18:40 -06:00
|
|
|
use rustc_middle::ty::{self, Ty, TypeVisitableExt};
|
2021-03-12 08:30:50 -06:00
|
|
|
|
|
|
|
/// Checks for `useless_transmute` 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>,
|
2022-02-10 11:40:06 -06:00
|
|
|
arg: &'tcx Expr<'_>,
|
2021-03-12 08:30:50 -06:00
|
|
|
) -> bool {
|
|
|
|
match (&from_ty.kind(), &to_ty.kind()) {
|
2022-06-04 06:34:07 -05:00
|
|
|
_ if from_ty == to_ty && !from_ty.has_erased_regions() => {
|
2021-03-12 08:30:50 -06:00
|
|
|
span_lint(
|
|
|
|
cx,
|
|
|
|
USELESS_TRANSMUTE,
|
|
|
|
e.span,
|
2022-10-06 02:44:38 -05:00
|
|
|
&format!("transmute from a type (`{from_ty}`) to itself"),
|
2021-03-12 08:30:50 -06:00
|
|
|
);
|
|
|
|
true
|
|
|
|
},
|
|
|
|
(ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => {
|
2022-06-04 06:34:07 -05:00
|
|
|
// No way to give the correct suggestion here. Avoid linting for now.
|
|
|
|
if !rty.has_erased_regions() {
|
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
USELESS_TRANSMUTE,
|
|
|
|
e.span,
|
|
|
|
"transmute from a reference to a pointer",
|
|
|
|
|diag| {
|
|
|
|
if let Some(arg) = sugg::Sugg::hir_opt(cx, arg) {
|
|
|
|
let rty_and_mut = ty::TypeAndMut {
|
|
|
|
ty: *rty,
|
|
|
|
mutbl: *rty_mutbl,
|
|
|
|
};
|
2021-03-12 08:30:50 -06:00
|
|
|
|
2022-06-04 06:34:07 -05:00
|
|
|
let sugg = if *ptr_ty == rty_and_mut {
|
|
|
|
arg.as_ty(to_ty)
|
|
|
|
} else {
|
2023-07-17 03:19:29 -05:00
|
|
|
arg.as_ty(Ty::new_ptr(cx.tcx, rty_and_mut)).as_ty(to_ty)
|
2022-06-04 06:34:07 -05:00
|
|
|
};
|
2021-03-12 08:30:50 -06:00
|
|
|
|
2022-06-13 01:48:40 -05:00
|
|
|
diag.span_suggestion(e.span, "try", sugg, Applicability::Unspecified);
|
2022-06-04 06:34:07 -05:00
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
2021-03-12 08:30:50 -06:00
|
|
|
true
|
|
|
|
},
|
|
|
|
(ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => {
|
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
USELESS_TRANSMUTE,
|
|
|
|
e.span,
|
|
|
|
"transmute from an integer to a pointer",
|
|
|
|
|diag| {
|
2022-02-10 11:40:06 -06:00
|
|
|
if let Some(arg) = sugg::Sugg::hir_opt(cx, arg) {
|
2022-12-29 07:28:34 -06:00
|
|
|
diag.span_suggestion(e.span, "try", arg.as_ty(to_ty.to_string()), Applicability::Unspecified);
|
2021-03-12 08:30:50 -06:00
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
true
|
|
|
|
},
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|