Skip to main content

rustc_lint/
utils.rs

1use rustc_hir::{Expr, ExprKind};
2use rustc_span::sym;
3
4use crate::LateContext;
5
6/// Given an expression, peel all of casts (`<expr> as ...`, `<expr>.cast{,_mut,_const}()`,
7/// `ptr::from_ref(<expr>)`, ...) and init expressions.
8///
9/// Returns the innermost expression.
10pub(crate) fn peel_casts<'tcx>(
11    cx: &LateContext<'tcx>,
12    mut e: &'tcx Expr<'tcx>,
13) -> &'tcx Expr<'tcx> {
14    loop {
15        e = e.peel_blocks();
16        // <expr> as ...
17        e = if let ExprKind::Cast(expr, _) = e.kind {
18            expr
19        // <expr>.cast(), <expr>.cast_mut() or <expr>.cast_const()
20        } else if let ExprKind::MethodCall(_, expr, [], _) = e.kind
21            && let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
22            && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
    {
    Some(sym::ptr_cast | sym::const_ptr_cast | sym::ptr_cast_mut |
        sym::ptr_cast_const) => true,
    _ => false,
}matches!(
23                cx.tcx.get_diagnostic_name(def_id),
24                Some(sym::ptr_cast | sym::const_ptr_cast | sym::ptr_cast_mut | sym::ptr_cast_const)
25            )
26        {
27            expr
28        // ptr::from_ref(<expr>), UnsafeCell::raw_get(<expr>) or mem::transmute<_, _>(<expr>)
29        } else if let ExprKind::Call(path, [arg]) = e.kind
30            && let ExprKind::Path(ref qpath) = path.kind
31            && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
32            && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
    {
    Some(sym::ptr_from_ref | sym::unsafe_cell_raw_get | sym::transmute) =>
        true,
    _ => false,
}matches!(
33                cx.tcx.get_diagnostic_name(def_id),
34                Some(sym::ptr_from_ref | sym::unsafe_cell_raw_get | sym::transmute)
35            )
36        {
37            arg
38        } else {
39            let init = cx.expr_or_init(e);
40            if init.hir_id != e.hir_id {
41                init
42            } else {
43                break;
44            }
45        };
46    }
47
48    e
49}