]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/utils.rs
Move some utils to ty_utils
[rust.git] / clippy_lints / src / transmute / utils.rs
1 use crate::utils::{last_path_segment, snippet};
2 use clippy_utils::ty::is_normalizable;
3 use if_chain::if_chain;
4 use rustc_hir::{Expr, GenericArg, QPath, TyKind};
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, 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(ref 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     let empty_param_env = ty::ParamEnv::empty();
37     // check if `from` and `to` are normalizable to avoid ICE (#4968)
38     if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
39         return false;
40     }
41     let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
42     let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
43     if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
44         from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
45     } else {
46         // no idea about layout, so don't lint
47         false
48     }
49 }
50
51 /// Check if the type conversion can be expressed as a pointer cast, instead of
52 /// a transmute. In certain cases, including some invalid casts from array
53 /// references to pointers, this may cause additional errors to be emitted and/or
54 /// ICE error messages. This function will panic if that occurs.
55 pub(super) fn can_be_expressed_as_pointer_cast<'tcx>(
56     cx: &LateContext<'tcx>,
57     e: &'tcx Expr<'_>,
58     from_ty: Ty<'tcx>,
59     to_ty: Ty<'tcx>,
60 ) -> bool {
61     use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
62     matches!(
63         check_cast(cx, e, from_ty, to_ty),
64         Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast)
65     )
66 }
67
68 /// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of
69 /// the cast. In certain cases, including some invalid casts from array references
70 /// to pointers, this may cause additional errors to be emitted and/or ICE error
71 /// messages. This function will panic if that occurs.
72 fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option<CastKind> {
73     let hir_id = e.hir_id;
74     let local_def_id = hir_id.owner;
75
76     Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
77         let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id);
78
79         // If we already have errors, we can't be sure we can pointer cast.
80         assert!(
81             !fn_ctxt.errors_reported_since_creation(),
82             "Newly created FnCtxt contained errors"
83         );
84
85         if let Ok(check) = CastCheck::new(
86             &fn_ctxt, e, from_ty, to_ty,
87             // We won't show any error to the user, so we don't care what the span is here.
88             DUMMY_SP, DUMMY_SP,
89         ) {
90             let res = check.do_check(&fn_ctxt);
91
92             // do_check's documentation says that it might return Ok and create
93             // errors in the fcx instead of returing Err in some cases. Those cases
94             // should be filtered out before getting here.
95             assert!(
96                 !fn_ctxt.errors_reported_since_creation(),
97                 "`fn_ctxt` contained errors after cast check!"
98             );
99
100             res.ok()
101         } else {
102             None
103         }
104     })
105 }