]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs
New upstream version 1.66.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / transmute / unsound_collection_transmute.rs
1 use super::utils::is_layout_incompatible;
2 use super::UNSOUND_COLLECTION_TRANSMUTE;
3 use clippy_utils::diagnostics::span_lint;
4 use rustc_hir::Expr;
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, Ty};
7 use rustc_span::symbol::sym;
8
9 /// Checks for `unsound_collection_transmute` lint.
10 /// Returns `true` if it's triggered, otherwise returns `false`.
11 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool {
12 match (&from_ty.kind(), &to_ty.kind()) {
13 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
14 if from_adt.did() != to_adt.did() {
15 return false;
16 }
17 if !matches!(
18 cx.tcx.get_diagnostic_name(to_adt.did()),
19 Some(
20 sym::BTreeMap
21 | sym::BTreeSet
22 | sym::BinaryHeap
23 | sym::HashMap
24 | sym::HashSet
25 | sym::Vec
26 | sym::VecDeque
27 )
28 ) {
29 return false;
30 }
31 if from_substs
32 .types()
33 .zip(to_substs.types())
34 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty))
35 {
36 span_lint(
37 cx,
38 UNSOUND_COLLECTION_TRANSMUTE,
39 e.span,
40 &format!("transmute from `{from_ty}` to `{to_ty}` with mismatched layout is unsound"),
41 );
42 true
43 } else {
44 false
45 }
46 },
47 _ => false,
48 }
49 }