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