rustc_trait_selection/error_reporting/infer/nice_region_error/
find_anon_type.rs

1use core::ops::ControlFlow;
2
3use rustc_hir::def_id::{DefId, LocalDefId};
4use rustc_hir::intravisit::{self, Visitor, VisitorExt};
5use rustc_hir::{self as hir, AmbigArg};
6use rustc_middle::hir::map::Map;
7use rustc_middle::hir::nested_filter;
8use rustc_middle::middle::resolve_bound_vars as rbv;
9use rustc_middle::ty::{self, Region, TyCtxt};
10use tracing::debug;
11
12/// This function calls the `visit_ty` method for the parameters
13/// corresponding to the anonymous regions. The `nested_visitor.found_type`
14/// contains the anonymous type.
15///
16/// # Arguments
17/// region - the anonymous region corresponding to the anon_anon conflict
18/// br - the bound region corresponding to the above region which is of type `BrAnon(_)`
19///
20/// # Example
21/// ```compile_fail
22/// fn foo(x: &mut Vec<&u8>, y: &u8)
23///    { x.push(y); }
24/// ```
25/// The function returns the nested type corresponding to the anonymous region
26/// for e.g., `&u8` and `Vec<&u8>`.
27pub fn find_anon_type<'tcx>(
28    tcx: TyCtxt<'tcx>,
29    generic_param_scope: LocalDefId,
30    region: Region<'tcx>,
31) -> Option<(&'tcx hir::Ty<'tcx>, &'tcx hir::FnSig<'tcx>)> {
32    let anon_reg = tcx.is_suitable_region(generic_param_scope, region)?;
33    let fn_sig = tcx.hir_node_by_def_id(anon_reg.scope).fn_sig()?;
34
35    fn_sig
36        .decl
37        .inputs
38        .iter()
39        .find_map(|arg| find_component_for_bound_region(tcx, arg, anon_reg.region_def_id))
40        .map(|ty| (ty, fn_sig))
41}
42
43// This method creates a FindNestedTypeVisitor which returns the type corresponding
44// to the anonymous region.
45fn find_component_for_bound_region<'tcx>(
46    tcx: TyCtxt<'tcx>,
47    arg: &'tcx hir::Ty<'tcx>,
48    region_def_id: DefId,
49) -> Option<&'tcx hir::Ty<'tcx>> {
50    FindNestedTypeVisitor { tcx, region_def_id, current_index: ty::INNERMOST }
51        .visit_ty_unambig(arg)
52        .break_value()
53}
54
55// The FindNestedTypeVisitor captures the corresponding `hir::Ty` of the
56// anonymous region. The example above would lead to a conflict between
57// the two anonymous lifetimes for &u8 in x and y respectively. This visitor
58// would be invoked twice, once for each lifetime, and would
59// walk the types like &mut Vec<&u8> and &u8 looking for the HIR
60// where that lifetime appears. This allows us to highlight the
61// specific part of the type in the error message.
62struct FindNestedTypeVisitor<'tcx> {
63    tcx: TyCtxt<'tcx>,
64    // The `DefId` of the region we're looking for.
65    region_def_id: DefId,
66    current_index: ty::DebruijnIndex,
67}
68
69impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> {
70    type Result = ControlFlow<&'tcx hir::Ty<'tcx>>;
71    type NestedFilter = nested_filter::OnlyBodies;
72
73    fn nested_visit_map(&mut self) -> Self::Map {
74        self.tcx.hir()
75    }
76
77    fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
78        match arg.kind {
79            hir::TyKind::BareFn(_) => {
80                self.current_index.shift_in(1);
81                intravisit::walk_ty(self, arg);
82                self.current_index.shift_out(1);
83                return ControlFlow::Continue(());
84            }
85
86            hir::TyKind::TraitObject(bounds, ..) => {
87                for bound in bounds {
88                    self.current_index.shift_in(1);
89                    self.visit_poly_trait_ref(bound);
90                    self.current_index.shift_out(1);
91                }
92            }
93
94            hir::TyKind::Ref(lifetime, _) => {
95                // the lifetime of the Ref
96                let hir_id = lifetime.hir_id;
97                match self.tcx.named_bound_var(hir_id) {
98                    // Find the index of the named region that was part of the
99                    // error. We will then search the function parameters for a bound
100                    // region at the right depth with the same index
101                    Some(rbv::ResolvedArg::EarlyBound(id)) => {
102                        debug!("EarlyBound id={:?}", id);
103                        if id.to_def_id() == self.region_def_id {
104                            return ControlFlow::Break(arg.as_unambig_ty());
105                        }
106                    }
107
108                    // Find the index of the named region that was part of the
109                    // error. We will then search the function parameters for a bound
110                    // region at the right depth with the same index
111                    Some(rbv::ResolvedArg::LateBound(debruijn_index, _, id)) => {
112                        debug!(
113                            "FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}",
114                            debruijn_index
115                        );
116                        debug!("LateBound id={:?}", id);
117                        if debruijn_index == self.current_index
118                            && id.to_def_id() == self.region_def_id
119                        {
120                            return ControlFlow::Break(arg.as_unambig_ty());
121                        }
122                    }
123
124                    Some(
125                        rbv::ResolvedArg::StaticLifetime
126                        | rbv::ResolvedArg::Free(_, _)
127                        | rbv::ResolvedArg::Error(_),
128                    )
129                    | None => {
130                        debug!("no arg found");
131                    }
132                }
133            }
134            // Checks if it is of type `hir::TyKind::Path` which corresponds to a struct.
135            hir::TyKind::Path(_) => {
136                // Prefer using the lifetime in type arguments rather than lifetime arguments.
137                intravisit::walk_ty(self, arg)?;
138
139                // Call `walk_ty` as `visit_ty` is empty.
140                return if intravisit::walk_ty(
141                    &mut TyPathVisitor {
142                        tcx: self.tcx,
143                        region_def_id: self.region_def_id,
144                        current_index: self.current_index,
145                    },
146                    arg,
147                )
148                .is_break()
149                {
150                    ControlFlow::Break(arg.as_unambig_ty())
151                } else {
152                    ControlFlow::Continue(())
153                };
154            }
155            _ => {}
156        }
157        // walk the embedded contents: e.g., if we are visiting `Vec<&Foo>`,
158        // go on to visit `&Foo`
159        intravisit::walk_ty(self, arg)
160    }
161}
162
163// The visitor captures the corresponding `hir::Ty` of the anonymous region
164// in the case of structs ie. `hir::TyKind::Path`.
165// This visitor would be invoked for each lifetime corresponding to a struct,
166// and would walk the types like Vec<Ref> in the above example and Ref looking for the HIR
167// where that lifetime appears. This allows us to highlight the
168// specific part of the type in the error message.
169struct TyPathVisitor<'tcx> {
170    tcx: TyCtxt<'tcx>,
171    region_def_id: DefId,
172    current_index: ty::DebruijnIndex,
173}
174
175impl<'tcx> Visitor<'tcx> for TyPathVisitor<'tcx> {
176    type Result = ControlFlow<()>;
177    type NestedFilter = nested_filter::OnlyBodies;
178
179    fn nested_visit_map(&mut self) -> Map<'tcx> {
180        self.tcx.hir()
181    }
182
183    fn visit_lifetime(&mut self, lifetime: &hir::Lifetime) -> Self::Result {
184        match self.tcx.named_bound_var(lifetime.hir_id) {
185            // the lifetime of the TyPath!
186            Some(rbv::ResolvedArg::EarlyBound(id)) => {
187                debug!("EarlyBound id={:?}", id);
188                if id.to_def_id() == self.region_def_id {
189                    return ControlFlow::Break(());
190                }
191            }
192
193            Some(rbv::ResolvedArg::LateBound(debruijn_index, _, id)) => {
194                debug!("FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}", debruijn_index,);
195                debug!("id={:?}", id);
196                if debruijn_index == self.current_index && id.to_def_id() == self.region_def_id {
197                    return ControlFlow::Break(());
198                }
199            }
200
201            Some(
202                rbv::ResolvedArg::StaticLifetime
203                | rbv::ResolvedArg::Free(_, _)
204                | rbv::ResolvedArg::Error(_),
205            )
206            | None => {
207                debug!("no arg found");
208            }
209        }
210        ControlFlow::Continue(())
211    }
212
213    fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
214        // ignore nested types
215        //
216        // If you have a type like `Foo<'a, &Ty>` we
217        // are only interested in the immediate lifetimes ('a).
218        //
219        // Making `visit_ty` empty will ignore the `&Ty` embedded
220        // inside, it will get reached by the outer visitor.
221        debug!("`Ty` corresponding to a struct is {:?}", arg);
222        ControlFlow::Continue(())
223    }
224}