]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/utils.rs
Auto merge of #8645 - Jarcho:manual_non_exhaustive_5714, r=Jarcho
[rust.git] / clippy_lints / src / transmute / utils.rs
1 use clippy_utils::last_path_segment;
2 use clippy_utils::source::snippet;
3 use if_chain::if_chain;
4 use rustc_hir::{Expr, GenericArg, QPath, TyKind};
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{cast::CastKind, Ty};
7 use rustc_span::DUMMY_SP;
8 use rustc_typeck::check::{cast::CastCheck, FnCtxt, Inherited};
9
10 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
11 /// not available , use
12 /// the type's `ToString` implementation. In weird cases it could lead to types
13 /// with invalid `'_`
14 /// lifetime, but it should be rare.
15 pub(super) fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
16     let seg = last_path_segment(path);
17     if_chain! {
18         if let Some(params) = seg.args;
19         if !params.parenthesized;
20         if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
21             GenericArg::Type(ty) => Some(ty),
22             _ => None,
23         }).nth(1);
24         if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
25         then {
26             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
27         }
28     }
29
30     to_ref_ty.to_string()
31 }
32
33 // check if the component types of the transmuted collection and the result have different ABI,
34 // size or alignment
35 pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
36     if let Ok(from) = cx.tcx.try_normalize_erasing_regions(cx.param_env, from)
37         && let Ok(to) = cx.tcx.try_normalize_erasing_regions(cx.param_env, to)
38         && let Ok(from_layout) = cx.tcx.layout_of(cx.param_env.and(from))
39         && let Ok(to_layout) = cx.tcx.layout_of(cx.param_env.and(to))
40     {
41         from_layout.size != to_layout.size || from_layout.align.abi != to_layout.align.abi
42     } else {
43         // no idea about layout, so don't lint
44         false
45     }
46 }
47
48 /// Check if the type conversion can be expressed as a pointer cast, instead of
49 /// a transmute. In certain cases, including some invalid casts from array
50 /// references to pointers, this may cause additional errors to be emitted and/or
51 /// ICE error messages. This function will panic if that occurs.
52 pub(super) fn can_be_expressed_as_pointer_cast<'tcx>(
53     cx: &LateContext<'tcx>,
54     e: &'tcx Expr<'_>,
55     from_ty: Ty<'tcx>,
56     to_ty: Ty<'tcx>,
57 ) -> bool {
58     use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
59     matches!(
60         check_cast(cx, e, from_ty, to_ty),
61         Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast)
62     )
63 }
64
65 /// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of
66 /// the cast. In certain cases, including some invalid casts from array references
67 /// to pointers, this may cause additional errors to be emitted and/or ICE error
68 /// messages. This function will panic if that occurs.
69 fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option<CastKind> {
70     let hir_id = e.hir_id;
71     let local_def_id = hir_id.owner;
72
73     Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
74         let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id);
75
76         // If we already have errors, we can't be sure we can pointer cast.
77         assert!(
78             !fn_ctxt.errors_reported_since_creation(),
79             "Newly created FnCtxt contained errors"
80         );
81
82         if let Ok(check) = CastCheck::new(
83             &fn_ctxt, e, from_ty, to_ty,
84             // We won't show any error to the user, so we don't care what the span is here.
85             DUMMY_SP, DUMMY_SP,
86         ) {
87             let res = check.do_check(&fn_ctxt);
88
89             // do_check's documentation says that it might return Ok and create
90             // errors in the fcx instead of returing Err in some cases. Those cases
91             // should be filtered out before getting here.
92             assert!(
93                 !fn_ctxt.errors_reported_since_creation(),
94                 "`fn_ctxt` contained errors after cast check!"
95             );
96
97             res.ok()
98         } else {
99             None
100         }
101     })
102 }