rustc_trait_selection/error_reporting/infer/nice_region_error/
util.rs

1//! Helper functions corresponding to lifetime errors due to
2//! anonymous regions.
3
4use rustc_hir as hir;
5use rustc_hir::def_id::{DefId, LocalDefId};
6use rustc_middle::ty::fold::fold_regions;
7use rustc_middle::ty::{self, Binder, Region, Ty, TyCtxt, TypeFoldable};
8use rustc_span::Span;
9use tracing::instrument;
10
11use crate::error_reporting::infer::nice_region_error::NiceRegionError;
12
13/// Information about the anonymous region we are searching for.
14#[derive(Debug)]
15pub struct AnonymousParamInfo<'tcx> {
16    /// The parameter corresponding to the anonymous region.
17    pub param: &'tcx hir::Param<'tcx>,
18    /// The type corresponding to the anonymous region parameter.
19    pub param_ty: Ty<'tcx>,
20    /// The `ty::LateParamRegionKind` corresponding to the anonymous region.
21    pub kind: ty::LateParamRegionKind,
22    /// The `Span` of the parameter type.
23    pub param_ty_span: Span,
24    /// Signals that the argument is the first parameter in the declaration.
25    pub is_first: bool,
26}
27
28// This method walks the Type of the function body parameters using
29// `fold_regions()` function and returns the
30// &hir::Param of the function parameter corresponding to the anonymous
31// region and the Ty corresponding to the named region.
32// Currently only the case where the function declaration consists of
33// one named region and one anonymous region is handled.
34// Consider the example `fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32`
35// Here, we would return the hir::Param for y, we return the type &'a
36// i32, which is the type of y but with the anonymous region replaced
37// with 'a, the corresponding bound region and is_first which is true if
38// the hir::Param is the first parameter in the function declaration.
39#[instrument(skip(tcx), level = "debug")]
40pub fn find_param_with_region<'tcx>(
41    tcx: TyCtxt<'tcx>,
42    generic_param_scope: LocalDefId,
43    anon_region: Region<'tcx>,
44    replace_region: Region<'tcx>,
45) -> Option<AnonymousParamInfo<'tcx>> {
46    let (id, kind) = match *anon_region {
47        ty::ReLateParam(late_param) => (late_param.scope, late_param.kind),
48        ty::ReEarlyParam(ebr) => {
49            let region_def = tcx.generics_of(generic_param_scope).region_param(ebr, tcx).def_id;
50            (tcx.parent(region_def), ty::LateParamRegionKind::Named(region_def, ebr.name))
51        }
52        _ => return None, // not a free region
53    };
54
55    let hir = &tcx.hir();
56    let def_id = id.as_local()?;
57
58    // FIXME: use def_kind
59    // Don't perform this on closures
60    match tcx.hir_node_by_def_id(generic_param_scope) {
61        hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
62            return None;
63        }
64        _ => {}
65    }
66
67    let body = hir.maybe_body_owned_by(def_id)?;
68
69    let owner_id = hir.body_owner(body.id());
70    let fn_decl = hir.fn_decl_by_hir_id(owner_id)?;
71    let poly_fn_sig = tcx.fn_sig(id).instantiate_identity();
72
73    let fn_sig = tcx.liberate_late_bound_regions(id, poly_fn_sig);
74    body.params
75        .iter()
76        .take(if fn_sig.c_variadic {
77            fn_sig.inputs().len()
78        } else {
79            assert_eq!(fn_sig.inputs().len(), body.params.len());
80            body.params.len()
81        })
82        .enumerate()
83        .find_map(|(index, param)| {
84            // May return None; sometimes the tables are not yet populated.
85            let ty = fn_sig.inputs()[index];
86            let mut found_anon_region = false;
87            let new_param_ty = fold_regions(tcx, ty, |r, _| {
88                if r == anon_region {
89                    found_anon_region = true;
90                    replace_region
91                } else {
92                    r
93                }
94            });
95            found_anon_region.then(|| {
96                let ty_hir_id = fn_decl.inputs[index].hir_id;
97                let param_ty_span = hir.span(ty_hir_id);
98                let is_first = index == 0;
99                AnonymousParamInfo { param, param_ty: new_param_ty, param_ty_span, kind, is_first }
100            })
101        })
102}
103
104impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
105    pub(super) fn find_param_with_region(
106        &self,
107        anon_region: Region<'tcx>,
108        replace_region: Region<'tcx>,
109    ) -> Option<AnonymousParamInfo<'tcx>> {
110        find_param_with_region(self.tcx(), self.generic_param_scope, anon_region, replace_region)
111    }
112
113    // Here, we check for the case where the anonymous region
114    // is in the return type as written by the user.
115    // FIXME(#42703) - Need to handle certain cases here.
116    pub(super) fn is_return_type_anon(
117        &self,
118        scope_def_id: LocalDefId,
119        region_def_id: DefId,
120        hir_sig: &hir::FnSig<'_>,
121    ) -> Option<Span> {
122        let fn_ty = self.tcx().type_of(scope_def_id).instantiate_identity();
123        if let ty::FnDef(_, _) = fn_ty.kind() {
124            let ret_ty = fn_ty.fn_sig(self.tcx()).output();
125            let span = hir_sig.decl.output.span();
126            let future_output = if hir_sig.header.is_async() {
127                ret_ty.map_bound(|ty| self.cx.get_impl_future_output_ty(ty)).transpose()
128            } else {
129                None
130            };
131            return match future_output {
132                Some(output) if self.includes_region(output, region_def_id) => Some(span),
133                None if self.includes_region(ret_ty, region_def_id) => Some(span),
134                _ => None,
135            };
136        }
137        None
138    }
139
140    fn includes_region(
141        &self,
142        ty: Binder<'tcx, impl TypeFoldable<TyCtxt<'tcx>>>,
143        region_def_id: DefId,
144    ) -> bool {
145        let late_bound_regions = self.tcx().collect_referenced_late_bound_regions(ty);
146        // We are only checking is any region meets the condition so order doesn't matter
147        #[allow(rustc::potential_query_instability)]
148        late_bound_regions.iter().any(|r| match *r {
149            ty::BoundRegionKind::Named(def_id, _) => def_id == region_def_id,
150            _ => false,
151        })
152    }
153
154    // Here we check for the case where anonymous region
155    // corresponds to self and if yes, we display E0312.
156    // FIXME(#42700) - Need to format self properly to
157    // enable E0621 for it.
158    pub(super) fn is_self_anon(&self, is_first: bool, scope_def_id: LocalDefId) -> bool {
159        is_first
160            && self
161                .tcx()
162                .opt_associated_item(scope_def_id.to_def_id())
163                .is_some_and(|i| i.fn_has_self_parameter)
164    }
165}