1 //! Resolution of early vs late bound lifetimes.
3 //! Name resolution for lifetimes is performed on the AST and embedded into HIR. From this
4 //! information, typechecking needs to transform the lifetime parameters into bound lifetimes.
5 //! Lifetimes can be early-bound or late-bound. Construction of typechecking terms needs to visit
6 //! the types in HIR to identify late-bound lifetimes and assign their Debruijn indices. This file
7 //! is also responsible for assigning their semantics to implicit lifetimes in trait objects.
9 use rustc_ast::walk_list;
10 use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
11 use rustc_errors::struct_span_err;
13 use rustc_hir::def::{DefKind, Res};
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_hir::intravisit::{self, Visitor};
16 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, HirIdMap, LifetimeName, Node};
17 use rustc_middle::bug;
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::hir::nested_filter;
20 use rustc_middle::middle::resolve_lifetime::*;
21 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
22 use rustc_span::def_id::DefId;
23 use rustc_span::symbol::{sym, Ident};
28 fn early(hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region);
30 fn late(index: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region);
32 fn id(&self) -> Option<DefId>;
34 fn shifted(self, amount: u32) -> Region;
37 impl RegionExt for Region {
38 fn early(hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region) {
39 let def_id = hir_map.local_def_id(param.hir_id);
40 debug!("Region::early: def_id={:?}", def_id);
41 (def_id, Region::EarlyBound(def_id.to_def_id()))
44 fn late(idx: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region) {
45 let depth = ty::INNERMOST;
46 let def_id = hir_map.local_def_id(param.hir_id);
48 "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}",
49 idx, param, depth, def_id,
51 (def_id, Region::LateBound(depth, idx, def_id.to_def_id()))
54 fn id(&self) -> Option<DefId> {
56 Region::Static => None,
58 Region::EarlyBound(id) | Region::LateBound(_, _, id) | Region::Free(_, id) => Some(id),
62 fn shifted(self, amount: u32) -> Region {
64 Region::LateBound(debruijn, idx, id) => {
65 Region::LateBound(debruijn.shifted_in(amount), idx, id)
72 /// Maps the id of each lifetime reference to the lifetime decl
73 /// that it corresponds to.
75 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
76 /// actual use. It has the same data, but indexed by `LocalDefId`. This
78 #[derive(Debug, Default)]
79 struct NamedRegionMap {
80 // maps from every use of a named (not anonymous) lifetime to a
81 // `Region` describing how that region is bound
82 defs: HirIdMap<Region>,
84 // Maps relevant hir items to the bound vars on them. These include:
86 // - function pointers
89 // - bound types (like `T` in `for<'a> T<'a>: Foo`)
90 late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
93 struct LifetimeContext<'a, 'tcx> {
95 map: &'a mut NamedRegionMap,
98 /// Indicates that we only care about the definition of a trait. This should
99 /// be false if the `Item` we are resolving lifetimes for is not a trait or
100 /// we eventually need lifetimes resolve for trait items.
101 trait_definition_only: bool,
106 /// Declares lifetimes, and each can be early-bound or late-bound.
107 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
108 /// it should be shifted by the number of `Binder`s in between the
109 /// declaration `Binder` and the location it's referenced from.
111 /// We use an IndexMap here because we want these lifetimes in order
113 lifetimes: FxIndexMap<LocalDefId, Region>,
115 scope_type: BinderScopeType,
117 /// The late bound vars for a given item are stored by `HirId` to be
118 /// queried later. However, if we enter an elision scope, we have to
119 /// later append the elided bound vars to the list and need to know what
125 /// If this binder comes from a where clause, specify how it was created.
126 /// This is used to diagnose inaccessible lifetimes in APIT:
127 /// ```ignore (illustrative)
128 /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
130 where_bound_origin: Option<hir::PredicateOrigin>,
133 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
134 /// if this is a fn body, otherwise the original definitions are used.
135 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
136 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
142 /// A scope which either determines unspecified lifetimes or errors
143 /// on them (e.g., due to ambiguity).
148 /// Use a specific lifetime (if `Some`) or leave it unset (to be
149 /// inferred in a function body or potentially error outside one),
150 /// for the default choice of lifetime in a trait object type.
151 ObjectLifetimeDefault {
152 lifetime: Option<Region>,
156 /// When we have nested trait refs, we concatenate late bound vars for inner
157 /// trait refs from outer ones. But we also need to include any HRTB
158 /// lifetimes encountered when identifying the trait that an associated type
161 lifetimes: Vec<ty::BoundVariableKind>,
172 #[derive(Copy, Clone, Debug)]
173 enum BinderScopeType {
174 /// Any non-concatenating binder scopes.
176 /// Within a syntactic trait ref, there may be multiple poly trait refs that
177 /// are nested (under the `associated_type_bounds` feature). The binders of
178 /// the inner poly trait refs are extended from the outer poly trait refs
179 /// and don't increase the late bound depth. If you had
180 /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
181 /// would be `Concatenating`. This also used in trait refs in where clauses
182 /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
183 /// out any lifetimes because they aren't needed to show the two scopes).
184 /// The inner `for<>` has a scope of `Concatenating`.
188 // A helper struct for debugging scopes without printing parent scopes
189 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
191 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 Scope::Binder { lifetimes, scope_type, hir_id, where_bound_origin, s: _ } => f
195 .debug_struct("Binder")
196 .field("lifetimes", lifetimes)
197 .field("scope_type", scope_type)
198 .field("hir_id", hir_id)
199 .field("where_bound_origin", where_bound_origin)
202 Scope::Body { id, s: _ } => {
203 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
205 Scope::Elision { s: _ } => f.debug_struct("Elision").field("s", &"..").finish(),
206 Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
207 .debug_struct("ObjectLifetimeDefault")
208 .field("lifetime", lifetime)
211 Scope::Supertrait { lifetimes, s: _ } => f
212 .debug_struct("Supertrait")
213 .field("lifetimes", lifetimes)
216 Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
217 Scope::Root => f.debug_struct("Root").finish(),
222 type ScopeRef<'a> = &'a Scope<'a>;
224 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
226 pub(crate) fn provide(providers: &mut ty::query::Providers) {
227 *providers = ty::query::Providers {
228 resolve_lifetimes_trait_definition,
231 named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
233 object_lifetime_default,
234 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
240 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
241 /// Also does not generate any diagnostics.
243 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
244 /// resolves lifetimes only within the trait "header" -- that is, the trait
245 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
246 /// lifetimes within the trait and its items. There is room to refactor this,
247 /// for example to resolve lifetimes for each trait item in separate queries,
248 /// but it's convenient to do the entire trait at once because the lifetimes
249 /// from the trait definition are in scope within the trait items as well.
251 /// The reason for this separate call is to resolve what would otherwise
252 /// be a cycle. Consider this example:
254 /// ```ignore UNSOLVED (maybe @jackh726 knows what lifetime parameter to give Sub)
258 /// trait Sub<'b>: for<'a> Base<'a> {
259 /// type SubItem: Sub<BaseItem = &'b u32>;
263 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
264 /// To figure out the index of `'b`, we have to know about the supertraits
265 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
266 /// (This is because we -- currently at least -- flatten all the late-bound
267 /// lifetimes into a single binder.) This requires us to resolve the
268 /// *trait definition* of `Sub`; basically just enough lifetime information
269 /// to look at the supertraits.
270 #[instrument(level = "debug", skip(tcx))]
271 fn resolve_lifetimes_trait_definition(
273 local_def_id: LocalDefId,
274 ) -> ResolveLifetimes {
275 convert_named_region_map(do_resolve(tcx, local_def_id, true))
278 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
279 /// You should not read the result of this query directly, but rather use
280 /// `named_region_map`, `is_late_bound_map`, etc.
281 #[instrument(level = "debug", skip(tcx))]
282 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
283 convert_named_region_map(do_resolve(tcx, local_def_id, false))
288 local_def_id: LocalDefId,
289 trait_definition_only: bool,
290 ) -> NamedRegionMap {
291 let item = tcx.hir().expect_item(local_def_id);
292 let mut named_region_map =
293 NamedRegionMap { defs: Default::default(), late_bound_vars: Default::default() };
294 let mut visitor = LifetimeContext {
296 map: &mut named_region_map,
298 trait_definition_only,
300 visitor.visit_item(item);
305 fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes {
306 let mut rl = ResolveLifetimes::default();
308 for (hir_id, v) in named_region_map.defs {
309 let map = rl.defs.entry(hir_id.owner).or_default();
310 map.insert(hir_id.local_id, v);
312 for (hir_id, v) in named_region_map.late_bound_vars {
313 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
314 map.insert(hir_id.local_id, v);
318 debug!(?rl.late_bound_vars);
322 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
323 /// There are two important things this does.
324 /// First, we have to resolve lifetimes for
325 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
326 /// where we can have relevant lifetimes.
327 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
328 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
329 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
330 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
331 /// `resolve_lifetimes`.
332 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: hir::OwnerId) -> &'tcx ResolveLifetimes {
333 let item_id = item_for(tcx, def_id.def_id);
334 let local_def_id = item_id.def_id.def_id;
335 if item_id.def_id == def_id {
336 let item = tcx.hir().item(item_id);
338 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(local_def_id),
339 _ => tcx.resolve_lifetimes(local_def_id),
342 tcx.resolve_lifetimes(local_def_id)
346 /// Finds the `Item` that contains the given `LocalDefId`
347 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> hir::ItemId {
348 match tcx.hir().find_by_def_id(local_def_id) {
349 Some(Node::Item(item)) => {
350 return item.item_id();
355 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
356 let mut parent_iter = tcx.hir().parent_iter(hir_id);
358 let node = parent_iter.next().map(|n| n.1);
360 Some(hir::Node::Item(item)) => break item.item_id(),
361 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
369 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
371 Region::LateBound(_, _, def_id) => {
372 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
373 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
375 _ => bug!("{:?} is not a late region", region),
379 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
380 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
381 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
382 let mut scope = self.scope;
383 let mut supertrait_lifetimes = vec![];
386 Scope::Body { .. } | Scope::Root => {
387 break (vec![], BinderScopeType::Normal);
390 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
394 Scope::Supertrait { s, lifetimes } => {
395 supertrait_lifetimes = lifetimes.clone();
399 Scope::TraitRefBoundary { .. } => {
400 // We should only see super trait lifetimes if there is a `Binder` above
401 assert!(supertrait_lifetimes.is_empty());
402 break (vec![], BinderScopeType::Normal);
405 Scope::Binder { hir_id, .. } => {
406 // Nested poly trait refs have the binders concatenated
407 let mut full_binders =
408 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
409 full_binders.extend(supertrait_lifetimes.into_iter());
410 break (full_binders, BinderScopeType::Concatenating);
416 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
417 type NestedFilter = nested_filter::All;
419 fn nested_visit_map(&mut self) -> Self::Map {
423 // We want to nest trait/impl items in their parent, but nothing else.
424 fn visit_nested_item(&mut self, _: hir::ItemId) {}
426 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
427 if !self.trait_definition_only {
428 intravisit::walk_trait_item_ref(self, ii)
432 fn visit_nested_body(&mut self, body: hir::BodyId) {
433 let body = self.tcx.hir().body(body);
434 self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
435 this.visit_body(body);
439 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
440 if let hir::ExprKind::Closure(hir::Closure {
441 binder, bound_generic_params, fn_decl, ..
444 if let &hir::ClosureBinder::For { span: for_sp, .. } = binder {
445 fn span_of_infer(ty: &hir::Ty<'_>) -> Option<Span> {
446 struct V(Option<Span>);
448 impl<'v> Visitor<'v> for V {
449 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
451 _ if self.0.is_some() => (),
452 hir::TyKind::Infer => {
453 self.0 = Some(t.span);
455 _ => intravisit::walk_ty(self, t),
465 let infer_in_rt_sp = match fn_decl.output {
466 hir::FnRetTy::DefaultReturn(sp) => Some(sp),
467 hir::FnRetTy::Return(ty) => span_of_infer(ty),
470 let infer_spans = fn_decl
473 .filter_map(span_of_infer)
474 .chain(infer_in_rt_sp)
475 .collect::<Vec<_>>();
477 if !infer_spans.is_empty() {
481 "implicit types in closure signatures are forbidden when `for<...>` is present",
483 .span_label(for_sp, "`for<...>` is here")
488 let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) =
491 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
493 .map(|(late_bound_idx, param)| {
494 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
495 let r = late_region_as_bound_region(self.tcx, &pair.1);
500 self.record_late_bound_vars(e.hir_id, binders);
501 let scope = Scope::Binder {
505 scope_type: BinderScopeType::Normal,
506 where_bound_origin: None,
509 self.with(scope, |this| {
510 // a closure has no bounds, so everything
511 // contained within is scoped within its binder.
512 intravisit::walk_expr(this, e)
515 intravisit::walk_expr(self, e)
519 #[instrument(level = "debug", skip(self))]
520 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
522 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
523 if let Some(of_trait) = of_trait {
524 self.record_late_bound_vars(of_trait.hir_ref_id, Vec::default());
530 hir::ItemKind::Fn(_, ref generics, _) => {
531 self.visit_early_late(item.hir_id(), generics, |this| {
532 intravisit::walk_item(this, item);
536 hir::ItemKind::ExternCrate(_)
537 | hir::ItemKind::Use(..)
538 | hir::ItemKind::Macro(..)
539 | hir::ItemKind::Mod(..)
540 | hir::ItemKind::ForeignMod { .. }
541 | hir::ItemKind::GlobalAsm(..) => {
542 // These sorts of items have no lifetime parameters at all.
543 intravisit::walk_item(self, item);
545 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
546 // No lifetime parameters, but implied 'static.
547 self.with(Scope::Elision { s: self.scope }, |this| {
548 intravisit::walk_item(this, item)
551 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
552 // Opaque types are visited when we visit the
553 // `TyKind::OpaqueDef`, so that they have the lifetimes from
554 // their parent opaque_ty in scope.
556 // The core idea here is that since OpaqueTys are generated with the impl Trait as
557 // their owner, we can keep going until we find the Item that owns that. We then
558 // conservatively add all resolved lifetimes. Otherwise we run into problems in
559 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
560 for (_hir_id, node) in self.tcx.hir().parent_iter(item.def_id.into()) {
562 hir::Node::Item(parent_item) => {
563 let resolved_lifetimes: &ResolveLifetimes = self.tcx.resolve_lifetimes(
564 item_for(self.tcx, parent_item.def_id.def_id).def_id.def_id,
566 // We need to add *all* deps, since opaque tys may want them from *us*
567 for (&owner, defs) in resolved_lifetimes.defs.iter() {
568 defs.iter().for_each(|(&local_id, region)| {
569 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
572 for (&owner, late_bound_vars) in
573 resolved_lifetimes.late_bound_vars.iter()
575 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
576 self.record_late_bound_vars(
577 hir::HirId { owner, local_id },
578 late_bound_vars.clone(),
584 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
589 hir::ItemKind::TyAlias(_, ref generics)
590 | hir::ItemKind::Enum(_, ref generics)
591 | hir::ItemKind::Struct(_, ref generics)
592 | hir::ItemKind::Union(_, ref generics)
593 | hir::ItemKind::Trait(_, _, ref generics, ..)
594 | hir::ItemKind::TraitAlias(ref generics, ..)
595 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
596 // These kinds of items have only early-bound lifetime parameters.
597 let lifetimes = generics
600 .filter_map(|param| match param.kind {
601 GenericParamKind::Lifetime { .. } => {
602 Some(Region::early(self.tcx.hir(), param))
604 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None,
607 self.record_late_bound_vars(item.hir_id(), vec![]);
608 let scope = Scope::Binder {
609 hir_id: item.hir_id(),
611 scope_type: BinderScopeType::Normal,
613 where_bound_origin: None,
615 self.with(scope, |this| {
616 let scope = Scope::TraitRefBoundary { s: this.scope };
617 this.with(scope, |this| {
618 intravisit::walk_item(this, item);
625 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
627 hir::ForeignItemKind::Fn(_, _, ref generics) => {
628 self.visit_early_late(item.hir_id(), generics, |this| {
629 intravisit::walk_foreign_item(this, item);
632 hir::ForeignItemKind::Static(..) => {
633 intravisit::walk_foreign_item(self, item);
635 hir::ForeignItemKind::Type => {
636 intravisit::walk_foreign_item(self, item);
641 #[instrument(level = "debug", skip(self))]
642 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
644 hir::TyKind::BareFn(ref c) => {
645 let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) = c
648 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
650 .map(|(late_bound_idx, param)| {
651 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
652 let r = late_region_as_bound_region(self.tcx, &pair.1);
656 self.record_late_bound_vars(ty.hir_id, binders);
657 let scope = Scope::Binder {
661 scope_type: BinderScopeType::Normal,
662 where_bound_origin: None,
664 self.with(scope, |this| {
665 // a bare fn has no bounds, so everything
666 // contained within is scoped within its binder.
667 intravisit::walk_ty(this, ty);
670 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
671 debug!(?bounds, ?lifetime, "TraitObject");
672 let scope = Scope::TraitRefBoundary { s: self.scope };
673 self.with(scope, |this| {
674 for bound in bounds {
675 this.visit_poly_trait_ref(bound);
678 match lifetime.name {
679 LifetimeName::ImplicitObjectLifetimeDefault => {
680 // If the user does not write *anything*, we
681 // use the object lifetime defaulting
682 // rules. So e.g., `Box<dyn Debug>` becomes
683 // `Box<dyn Debug + 'static>`.
684 self.resolve_object_lifetime_default(lifetime)
686 LifetimeName::Infer => {
687 // If the user writes `'_`, we use the *ordinary* elision
688 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
689 // resolved the same as the `'_` in `&'_ Foo`.
693 LifetimeName::Param(..) | LifetimeName::Static => {
694 // If the user wrote an explicit name, use that.
695 self.visit_lifetime(lifetime);
697 LifetimeName::Error => {}
700 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
701 self.visit_lifetime(lifetime_ref);
702 let scope = Scope::ObjectLifetimeDefault {
703 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
706 self.with(scope, |this| this.visit_ty(&mt.ty));
708 hir::TyKind::OpaqueDef(item_id, lifetimes, _in_trait) => {
709 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
710 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
711 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
712 // ^ ^ this gets resolved in the scope of
713 // the opaque_ty generics
714 let opaque_ty = self.tcx.hir().item(item_id);
715 let (generics, bounds) = match opaque_ty.kind {
716 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
717 origin: hir::OpaqueTyOrigin::TyAlias,
720 intravisit::walk_ty(self, ty);
722 // Elided lifetimes are not allowed in non-return
723 // position impl Trait
724 let scope = Scope::TraitRefBoundary { s: self.scope };
725 self.with(scope, |this| {
726 let scope = Scope::Elision { s: this.scope };
727 this.with(scope, |this| {
728 intravisit::walk_item(this, opaque_ty);
734 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
735 origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
739 }) => (generics, bounds),
740 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
743 // Resolve the lifetimes that are applied to the opaque type.
744 // These are resolved in the current scope.
745 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
746 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
747 // ^ ^this gets resolved in the current scope
748 for lifetime in lifetimes {
749 let hir::GenericArg::Lifetime(lifetime) = lifetime else {
752 self.visit_lifetime(lifetime);
754 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
755 // and ban them. Type variables instantiated inside binders aren't
756 // well-supported at the moment, so this doesn't work.
757 // In the future, this should be fixed and this error should be removed.
758 let def = self.map.defs.get(&lifetime.hir_id).cloned();
759 let Some(Region::LateBound(_, _, def_id)) = def else {
762 let Some(def_id) = def_id.as_local() else {
765 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
766 // Ensure that the parent of the def is an item, not HRTB
767 let parent_id = self.tcx.hir().get_parent_node(hir_id);
768 if !parent_id.is_owner() {
769 if !self.trait_definition_only {
774 "`impl Trait` can only capture lifetimes \
775 bound at the fn or impl level"
779 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
781 if let hir::Node::Item(hir::Item {
782 kind: hir::ItemKind::OpaqueTy { .. }, ..
783 }) = self.tcx.hir().get(parent_id)
785 if !self.trait_definition_only {
786 let mut err = self.tcx.sess.struct_span_err(
788 "higher kinded lifetime bounds on nested opaque types are not supported yet",
790 err.span_note(self.tcx.def_span(def_id), "lifetime declared here");
793 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
797 // We want to start our early-bound indices at the end of the parent scope,
798 // not including any parent `impl Trait`s.
799 let mut lifetimes = FxIndexMap::default();
800 debug!(?generics.params);
801 for param in generics.params {
803 GenericParamKind::Lifetime { .. } => {
804 let (def_id, reg) = Region::early(self.tcx.hir(), ¶m);
805 lifetimes.insert(def_id, reg);
807 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {}
810 self.record_late_bound_vars(ty.hir_id, vec![]);
812 let scope = Scope::Binder {
816 scope_type: BinderScopeType::Normal,
817 where_bound_origin: None,
819 self.with(scope, |this| {
820 let scope = Scope::TraitRefBoundary { s: this.scope };
821 this.with(scope, |this| {
822 this.visit_generics(generics);
823 for bound in bounds {
824 this.visit_param_bound(bound);
829 _ => intravisit::walk_ty(self, ty),
833 #[instrument(level = "debug", skip(self))]
834 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
835 use self::hir::TraitItemKind::*;
836 match trait_item.kind {
838 self.visit_early_late(trait_item.hir_id(), &trait_item.generics, |this| {
839 intravisit::walk_trait_item(this, trait_item)
842 Type(bounds, ref ty) => {
843 let generics = &trait_item.generics;
844 let lifetimes = generics
847 .filter_map(|param| match param.kind {
848 GenericParamKind::Lifetime { .. } => {
849 Some(Region::early(self.tcx.hir(), param))
851 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None,
854 self.record_late_bound_vars(trait_item.hir_id(), vec![]);
855 let scope = Scope::Binder {
856 hir_id: trait_item.hir_id(),
859 scope_type: BinderScopeType::Normal,
860 where_bound_origin: None,
862 self.with(scope, |this| {
863 let scope = Scope::TraitRefBoundary { s: this.scope };
864 this.with(scope, |this| {
865 this.visit_generics(generics);
866 for bound in bounds {
867 this.visit_param_bound(bound);
869 if let Some(ty) = ty {
876 // Only methods and types support generics.
877 assert!(trait_item.generics.params.is_empty());
878 intravisit::walk_trait_item(self, trait_item);
883 #[instrument(level = "debug", skip(self))]
884 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
885 use self::hir::ImplItemKind::*;
886 match impl_item.kind {
887 Fn(..) => self.visit_early_late(impl_item.hir_id(), &impl_item.generics, |this| {
888 intravisit::walk_impl_item(this, impl_item)
891 let generics = &impl_item.generics;
892 let lifetimes: FxIndexMap<LocalDefId, Region> = generics
895 .filter_map(|param| match param.kind {
896 GenericParamKind::Lifetime { .. } => {
897 Some(Region::early(self.tcx.hir(), param))
899 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => None,
902 self.record_late_bound_vars(impl_item.hir_id(), vec![]);
903 let scope = Scope::Binder {
904 hir_id: impl_item.hir_id(),
907 scope_type: BinderScopeType::Normal,
908 where_bound_origin: None,
910 self.with(scope, |this| {
911 let scope = Scope::TraitRefBoundary { s: this.scope };
912 this.with(scope, |this| {
913 this.visit_generics(generics);
919 // Only methods and types support generics.
920 assert!(impl_item.generics.params.is_empty());
921 intravisit::walk_impl_item(self, impl_item);
926 #[instrument(level = "debug", skip(self))]
927 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
928 match lifetime_ref.name {
929 hir::LifetimeName::Static => self.insert_lifetime(lifetime_ref, Region::Static),
930 hir::LifetimeName::Param(param_def_id, _) => {
931 self.resolve_lifetime_ref(param_def_id, lifetime_ref)
933 // If we've already reported an error, just ignore `lifetime_ref`.
934 hir::LifetimeName::Error => {}
935 // Those will be resolved by typechecking.
936 hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Infer => {}
940 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
941 for (i, segment) in path.segments.iter().enumerate() {
942 let depth = path.segments.len() - i - 1;
943 if let Some(ref args) = segment.args {
944 self.visit_segment_args(path.res, depth, args);
951 fk: intravisit::FnKind<'tcx>,
952 fd: &'tcx hir::FnDecl<'tcx>,
953 body_id: hir::BodyId,
957 let output = match fd.output {
958 hir::FnRetTy::DefaultReturn(_) => None,
959 hir::FnRetTy::Return(ref ty) => Some(&**ty),
961 self.visit_fn_like_elision(&fd.inputs, output, matches!(fk, intravisit::FnKind::Closure));
962 intravisit::walk_fn_kind(self, fk);
963 self.visit_nested_body(body_id)
966 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
967 let scope = Scope::TraitRefBoundary { s: self.scope };
968 self.with(scope, |this| {
969 for param in generics.params {
971 GenericParamKind::Lifetime { .. } => {}
972 GenericParamKind::Type { ref default, .. } => {
973 if let Some(ref ty) = default {
977 GenericParamKind::Const { ref ty, default } => {
979 if let Some(default) = default {
980 this.visit_body(this.tcx.hir().body(default.body));
985 for predicate in generics.predicates {
987 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
991 ref bound_generic_params,
995 let lifetimes: FxIndexMap<LocalDefId, Region> =
999 matches!(param.kind, GenericParamKind::Lifetime { .. })
1002 .map(|(late_bound_idx, param)| {
1003 Region::late(late_bound_idx as u32, this.tcx.hir(), param)
1006 let binders: Vec<_> =
1009 .map(|(_, region)| {
1010 late_region_as_bound_region(this.tcx, region)
1013 this.record_late_bound_vars(hir_id, binders.clone());
1014 // Even if there are no lifetimes defined here, we still wrap it in a binder
1015 // scope. If there happens to be a nested poly trait ref (an error), that
1016 // will be `Concatenating` anyways, so we don't have to worry about the depth
1018 let scope = Scope::Binder {
1022 scope_type: BinderScopeType::Normal,
1023 where_bound_origin: Some(origin),
1025 this.with(scope, |this| {
1026 this.visit_ty(&bounded_ty);
1027 walk_list!(this, visit_param_bound, bounds);
1030 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1035 this.visit_lifetime(lifetime);
1036 walk_list!(this, visit_param_bound, bounds);
1038 if lifetime.name != hir::LifetimeName::Static {
1039 for bound in bounds {
1040 let hir::GenericBound::Outlives(ref lt) = bound else {
1043 if lt.name != hir::LifetimeName::Static {
1046 this.insert_lifetime(lt, Region::Static);
1052 "unnecessary lifetime parameter `{}`",
1053 lifetime.name.ident(),
1057 "you can use the `'static` lifetime directly, in place of `{}`",
1058 lifetime.name.ident(),
1064 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1069 this.visit_ty(lhs_ty);
1070 this.visit_ty(rhs_ty);
1077 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1079 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1080 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1081 // through the regular poly trait ref code, so we don't get another
1082 // chance to introduce a binder. For now, I'm keeping the existing logic
1083 // of "if there isn't a Binder scope above us, add one", but I
1084 // imagine there's a better way to go about this.
1085 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1087 self.record_late_bound_vars(*hir_id, binders);
1088 let scope = Scope::Binder {
1090 lifetimes: FxIndexMap::default(),
1093 where_bound_origin: None,
1095 self.with(scope, |this| {
1096 intravisit::walk_param_bound(this, bound);
1099 _ => intravisit::walk_param_bound(self, bound),
1103 fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) {
1104 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1106 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1108 let initial_bound_vars = binders.len() as u32;
1109 let mut lifetimes: FxIndexMap<LocalDefId, Region> = FxIndexMap::default();
1110 let binders_iter = trait_ref
1111 .bound_generic_params
1113 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1115 .map(|(late_bound_idx, param)| {
1117 Region::late(initial_bound_vars + late_bound_idx as u32, self.tcx.hir(), param);
1118 let r = late_region_as_bound_region(self.tcx, &pair.1);
1119 lifetimes.insert(pair.0, pair.1);
1122 binders.extend(binders_iter);
1125 self.record_late_bound_vars(trait_ref.trait_ref.hir_ref_id, binders);
1127 // Always introduce a scope here, even if this is in a where clause and
1128 // we introduced the binders around the bounded Ty. In that case, we
1129 // just reuse the concatenation functionality also present in nested trait
1131 let scope = Scope::Binder {
1132 hir_id: trait_ref.trait_ref.hir_ref_id,
1136 where_bound_origin: None,
1138 self.with(scope, |this| {
1139 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1140 this.visit_trait_ref(&trait_ref.trait_ref);
1145 fn object_lifetime_default<'tcx>(tcx: TyCtxt<'tcx>, param_def_id: DefId) -> ObjectLifetimeDefault {
1146 debug_assert_eq!(tcx.def_kind(param_def_id), DefKind::TyParam);
1147 let param_def_id = param_def_id.expect_local();
1148 let parent_def_id = tcx.local_parent(param_def_id);
1149 let generics = tcx.hir().get_generics(parent_def_id).unwrap();
1150 let param_hir_id = tcx.local_def_id_to_hir_id(param_def_id);
1151 let param = generics.params.iter().find(|p| p.hir_id == param_hir_id).unwrap();
1153 // Scan the bounds and where-clauses on parameters to extract bounds
1154 // of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1155 // for each type parameter.
1157 GenericParamKind::Type { .. } => {
1158 let mut set = Set1::Empty;
1160 // Look for `type: ...` where clauses.
1161 for bound in generics.bounds_for_param(param_def_id) {
1162 // Ignore `for<'a> type: ...` as they can change what
1163 // lifetimes mean (although we could "just" handle it).
1164 if !bound.bound_generic_params.is_empty() {
1168 for bound in bound.bounds {
1169 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1170 set.insert(lifetime.name.normalize_to_macros_2_0());
1176 Set1::Empty => ObjectLifetimeDefault::Empty,
1177 Set1::One(hir::LifetimeName::Static) => ObjectLifetimeDefault::Static,
1178 Set1::One(hir::LifetimeName::Param(param_def_id, _)) => {
1179 ObjectLifetimeDefault::Param(param_def_id.to_def_id())
1181 _ => ObjectLifetimeDefault::Ambiguous,
1185 bug!("object_lifetime_default_raw must only be called on a type parameter")
1190 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1191 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1193 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1195 let LifetimeContext { tcx, map, .. } = self;
1196 let mut this = LifetimeContext {
1200 trait_definition_only: self.trait_definition_only,
1202 let span = debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1204 let _enter = span.enter();
1209 fn record_late_bound_vars(&mut self, hir_id: hir::HirId, binder: Vec<ty::BoundVariableKind>) {
1210 if let Some(old) = self.map.late_bound_vars.insert(hir_id, binder) {
1212 "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}",
1213 self.map.late_bound_vars[&hir_id]
1218 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1220 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1221 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1222 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1226 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1228 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1229 /// lifetimes may be interspersed together.
1231 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1232 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1233 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1234 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1235 /// ordering is not important there.
1236 fn visit_early_late<F>(
1239 generics: &'tcx hir::Generics<'tcx>,
1242 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1244 let mut named_late_bound_vars = 0;
1245 let lifetimes: FxIndexMap<LocalDefId, Region> = generics
1248 .filter_map(|param| match param.kind {
1249 GenericParamKind::Lifetime { .. } => {
1250 if self.tcx.is_late_bound(param.hir_id) {
1251 let late_bound_idx = named_late_bound_vars;
1252 named_late_bound_vars += 1;
1253 Some(Region::late(late_bound_idx, self.tcx.hir(), param))
1255 Some(Region::early(self.tcx.hir(), param))
1258 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None,
1262 let binders: Vec<_> = generics
1266 matches!(param.kind, GenericParamKind::Lifetime { .. })
1267 && self.tcx.is_late_bound(param.hir_id)
1270 .map(|(late_bound_idx, param)| {
1271 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
1272 late_region_as_bound_region(self.tcx, &pair.1)
1275 self.record_late_bound_vars(hir_id, binders);
1276 let scope = Scope::Binder {
1280 scope_type: BinderScopeType::Normal,
1281 where_bound_origin: None,
1283 self.with(scope, walk);
1286 #[instrument(level = "debug", skip(self))]
1287 fn resolve_lifetime_ref(
1289 region_def_id: LocalDefId,
1290 lifetime_ref: &'tcx hir::Lifetime,
1292 // Walk up the scope chain, tracking the number of fn scopes
1293 // that we pass through, until we find a lifetime with the
1294 // given name or we run out of scopes.
1296 let mut late_depth = 0;
1297 let mut scope = self.scope;
1298 let mut outermost_body = None;
1301 Scope::Body { id, s } => {
1302 outermost_body = Some(id);
1310 Scope::Binder { ref lifetimes, scope_type, s, where_bound_origin, .. } => {
1311 if let Some(&def) = lifetimes.get(®ion_def_id) {
1312 break Some(def.shifted(late_depth));
1315 BinderScopeType::Normal => late_depth += 1,
1316 BinderScopeType::Concatenating => {}
1318 // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in
1320 if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
1321 && let hir::LifetimeName::Param(_, hir::ParamName::Fresh) = lifetime_ref.name
1322 && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id)
1323 && !self.tcx.features().anonymous_lifetime_in_impl_trait
1325 let mut diag = rustc_session::parse::feature_err(
1326 &self.tcx.sess.parse_sess,
1327 sym::anonymous_lifetime_in_impl_trait,
1329 "anonymous lifetimes in `impl Trait` are unstable",
1332 match self.tcx.hir().get_generics(lifetime_ref.hir_id.owner.def_id) {
1335 let new_param_sugg_tuple;
1337 new_param_sugg_tuple = match generics.span_for_param_suggestion() {
1339 Some((self.tcx.sess.source_map().span_through_char(generics.span, '<').shrink_to_hi(), "'a, ".to_owned()))
1341 None => Some((generics.span, "<'a>".to_owned()))
1344 let mut multi_sugg_vec = vec![(lifetime_ref.span.shrink_to_hi(), "'a ".to_owned())];
1346 if let Some(new_tuple) = new_param_sugg_tuple{
1347 multi_sugg_vec.push(new_tuple);
1350 diag.span_label(lifetime_ref.span, "expected named lifetime parameter");
1351 diag.multipart_suggestion("consider introducing a named lifetime parameter",
1353 rustc_errors::Applicability::MaybeIncorrect);
1365 Scope::Elision { s, .. }
1366 | Scope::ObjectLifetimeDefault { s, .. }
1367 | Scope::Supertrait { s, .. }
1368 | Scope::TraitRefBoundary { s, .. } => {
1374 if let Some(mut def) = result {
1375 if let Region::EarlyBound(..) = def {
1376 // Do not free early-bound regions, only late-bound ones.
1377 } else if let Some(body_id) = outermost_body {
1378 let fn_id = self.tcx.hir().body_owner(body_id);
1379 match self.tcx.hir().get(fn_id) {
1380 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1381 | Node::TraitItem(&hir::TraitItem {
1382 kind: hir::TraitItemKind::Fn(..), ..
1384 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
1385 let scope = self.tcx.hir().local_def_id(fn_id);
1386 def = Region::Free(scope.to_def_id(), def.id().unwrap());
1392 self.insert_lifetime(lifetime_ref, def);
1396 // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT.
1397 // AST-based resolution does not care for impl-trait desugaring, which are the
1398 // responibility of lowering. This may create a mismatch between the resolution
1399 // AST found (`region_def_id`) which points to HRTB, and what HIR allows.
1401 // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
1404 // In such case, walk back the binders to diagnose it properly.
1405 let mut scope = self.scope;
1409 where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1411 let mut err = self.tcx.sess.struct_span_err(
1413 "`impl Trait` can only mention lifetimes bound at the fn or impl level",
1415 err.span_note(self.tcx.def_span(region_def_id), "lifetime declared here");
1419 Scope::Root => break,
1420 Scope::Binder { s, .. }
1421 | Scope::Body { s, .. }
1422 | Scope::Elision { s, .. }
1423 | Scope::ObjectLifetimeDefault { s, .. }
1424 | Scope::Supertrait { s, .. }
1425 | Scope::TraitRefBoundary { s, .. } => {
1431 self.tcx.sess.delay_span_bug(
1433 &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
1437 #[instrument(level = "debug", skip(self))]
1438 fn visit_segment_args(
1442 generic_args: &'tcx hir::GenericArgs<'tcx>,
1444 if generic_args.parenthesized {
1445 self.visit_fn_like_elision(
1446 generic_args.inputs(),
1447 Some(generic_args.bindings[0].ty()),
1453 for arg in generic_args.args {
1454 if let hir::GenericArg::Lifetime(lt) = arg {
1455 self.visit_lifetime(lt);
1459 // Figure out if this is a type/trait segment,
1460 // which requires object lifetime defaults.
1461 let type_def_id = match res {
1462 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(self.tcx.parent(def_id)),
1463 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(self.tcx.parent(def_id)),
1471 ) if depth == 0 => Some(def_id),
1475 debug!(?type_def_id);
1477 // Compute a vector of defaults, one for each type parameter,
1478 // per the rules given in RFCs 599 and 1156. Example:
1481 // struct Foo<'a, T: 'a, U> { }
1484 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1485 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1486 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1489 // Therefore, we would compute `object_lifetime_defaults` to a
1490 // vector like `['x, 'static]`. Note that the vector only
1491 // includes type parameters.
1492 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
1494 let mut scope = self.scope;
1497 Scope::Root => break false,
1499 Scope::Body { .. } => break true,
1501 Scope::Binder { s, .. }
1502 | Scope::Elision { s, .. }
1503 | Scope::ObjectLifetimeDefault { s, .. }
1504 | Scope::Supertrait { s, .. }
1505 | Scope::TraitRefBoundary { s, .. } => {
1512 let map = &self.map;
1513 let generics = self.tcx.generics_of(def_id);
1515 // `type_def_id` points to an item, so there is nothing to inherit generics from.
1516 debug_assert_eq!(generics.parent_count, 0);
1518 let set_to_region = |set: ObjectLifetimeDefault| match set {
1519 ObjectLifetimeDefault::Empty => {
1523 Some(Region::Static)
1526 ObjectLifetimeDefault::Static => Some(Region::Static),
1527 ObjectLifetimeDefault::Param(param_def_id) => {
1528 // This index can be used with `generic_args` since `parent_count == 0`.
1529 let index = generics.param_def_id_to_index[¶m_def_id] as usize;
1530 generic_args.args.get(index).and_then(|arg| match arg {
1531 GenericArg::Lifetime(lt) => map.defs.get(<.hir_id).copied(),
1535 ObjectLifetimeDefault::Ambiguous => None,
1540 .filter_map(|param| {
1541 match self.tcx.def_kind(param.def_id) {
1542 // Generic consts don't impose any constraints.
1544 // We still store a dummy value here to allow generic parameters
1545 // in an arbitrary order.
1546 DefKind::ConstParam => Some(ObjectLifetimeDefault::Empty),
1547 DefKind::TyParam => Some(self.tcx.object_lifetime_default(param.def_id)),
1548 // We may also get a `Trait` or `TraitAlias` because of how generics `Self` parameter
1549 // works. Ignore it because it can't have a meaningful lifetime default.
1550 DefKind::LifetimeParam | DefKind::Trait | DefKind::TraitAlias => None,
1551 dk => bug!("unexpected def_kind {:?}", dk),
1558 debug!(?object_lifetime_defaults);
1561 for arg in generic_args.args {
1563 GenericArg::Lifetime(_) => {}
1564 GenericArg::Type(ty) => {
1565 if let Some(<) = object_lifetime_defaults.get(i) {
1566 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1567 self.with(scope, |this| this.visit_ty(ty));
1573 GenericArg::Const(ct) => {
1574 self.visit_anon_const(&ct.value);
1577 GenericArg::Infer(inf) => {
1578 self.visit_id(inf.hir_id);
1584 // Hack: when resolving the type `XX` in binding like `dyn
1585 // Foo<'b, Item = XX>`, the current object-lifetime default
1586 // would be to examine the trait `Foo` to check whether it has
1587 // a lifetime bound declared on `Item`. e.g., if `Foo` is
1588 // declared like so, then the default object lifetime bound in
1589 // `XX` should be `'b`:
1597 // but if we just have `type Item;`, then it would be
1598 // `'static`. However, we don't get all of this logic correct.
1600 // Instead, we do something hacky: if there are no lifetime parameters
1601 // to the trait, then we simply use a default object lifetime
1602 // bound of `'static`, because there is no other possibility. On the other hand,
1603 // if there ARE lifetime parameters, then we require the user to give an
1604 // explicit bound for now.
1606 // This is intended to leave room for us to implement the
1607 // correct behavior in the future.
1608 let has_lifetime_parameter =
1609 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
1611 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
1612 // in the trait ref `YY<...>` in `Item: YY<...>`.
1613 for binding in generic_args.bindings {
1614 let scope = Scope::ObjectLifetimeDefault {
1615 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
1618 if let Some(type_def_id) = type_def_id {
1619 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
1624 self.with(scope, |this| {
1625 let scope = Scope::Supertrait {
1626 lifetimes: lifetimes.unwrap_or_default(),
1629 this.with(scope, |this| this.visit_assoc_type_binding(binding));
1632 self.with(scope, |this| this.visit_assoc_type_binding(binding));
1637 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
1638 /// associated type name and starting trait.
1639 /// For example, imagine we have
1640 /// ```ignore (illustrative)
1641 /// trait Foo<'a, 'b> {
1644 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
1645 /// trait Bar: for<'b> Bar<'b> {}
1647 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
1648 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
1649 fn supertrait_hrtb_lifetimes(
1653 ) -> Option<Vec<ty::BoundVariableKind>> {
1654 let trait_defines_associated_type_named = |trait_def_id: DefId| {
1655 tcx.associated_items(trait_def_id)
1656 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
1660 use smallvec::{smallvec, SmallVec};
1661 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
1662 smallvec![(def_id, smallvec![])];
1663 let mut visited: FxHashSet<DefId> = FxHashSet::default();
1665 let Some((def_id, bound_vars)) = stack.pop() else {
1668 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
1669 // there being no supertrait HRTBs.
1670 match tcx.def_kind(def_id) {
1671 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
1675 if trait_defines_associated_type_named(def_id) {
1676 break Some(bound_vars.into_iter().collect());
1679 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
1680 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
1681 let bound_predicate = pred.kind();
1682 match bound_predicate.skip_binder() {
1683 ty::PredicateKind::Trait(data) => {
1684 // The order here needs to match what we would get from `subst_supertrait`
1685 let pred_bound_vars = bound_predicate.bound_vars();
1686 let mut all_bound_vars = bound_vars.clone();
1687 all_bound_vars.extend(pred_bound_vars.iter());
1688 let super_def_id = data.trait_ref.def_id;
1689 Some((super_def_id, all_bound_vars))
1695 let obligations = obligations.filter(|o| visited.insert(o.0));
1696 stack.extend(obligations);
1700 #[instrument(level = "debug", skip(self))]
1701 fn visit_fn_like_elision(
1703 inputs: &'tcx [hir::Ty<'tcx>],
1704 output: Option<&'tcx hir::Ty<'tcx>>,
1707 self.with(Scope::Elision { s: self.scope }, |this| {
1708 for input in inputs {
1709 this.visit_ty(input);
1711 if !in_closure && let Some(output) = output {
1712 this.visit_ty(output);
1715 if in_closure && let Some(output) = output {
1716 self.visit_ty(output);
1720 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1721 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
1722 let mut late_depth = 0;
1723 let mut scope = self.scope;
1724 let lifetime = loop {
1726 Scope::Binder { s, scope_type, .. } => {
1728 BinderScopeType::Normal => late_depth += 1,
1729 BinderScopeType::Concatenating => {}
1734 Scope::Root | Scope::Elision { .. } => break Region::Static,
1736 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
1738 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
1740 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
1745 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
1748 #[instrument(level = "debug", skip(self))]
1749 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
1751 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
1752 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
1754 self.map.defs.insert(lifetime_ref.hir_id, def);
1757 /// Sometimes we resolve a lifetime, but later find that it is an
1758 /// error (esp. around impl trait). In that case, we remove the
1759 /// entry into `map.defs` so as not to confuse later code.
1760 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
1761 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
1762 assert_eq!(old_value, Some(bad_def));
1766 /// Detects late-bound lifetimes and inserts them into
1769 /// A region declared on a fn is **late-bound** if:
1770 /// - it is constrained by an argument type;
1771 /// - it does not appear in a where-clause.
1773 /// "Constrained" basically means that it appears in any type but
1774 /// not amongst the inputs to a projection. In other words, `<&'a
1775 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
1776 fn is_late_bound_map(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<&FxIndexSet<LocalDefId>> {
1777 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1778 let decl = tcx.hir().fn_decl_by_hir_id(hir_id)?;
1779 let generics = tcx.hir().get_generics(def_id)?;
1781 let mut late_bound = FxIndexSet::default();
1783 let mut constrained_by_input = ConstrainedCollector::default();
1784 for arg_ty in decl.inputs {
1785 constrained_by_input.visit_ty(arg_ty);
1788 let mut appears_in_output = AllCollector::default();
1789 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
1791 debug!(?constrained_by_input.regions);
1793 // Walk the lifetimes that appear in where clauses.
1795 // Subtle point: because we disallow nested bindings, we can just
1796 // ignore binders here and scrape up all names we see.
1797 let mut appears_in_where_clause = AllCollector::default();
1798 appears_in_where_clause.visit_generics(generics);
1799 debug!(?appears_in_where_clause.regions);
1801 // Late bound regions are those that:
1802 // - appear in the inputs
1803 // - do not appear in the where-clauses
1804 // - are not implicitly captured by `impl Trait`
1805 for param in generics.params {
1807 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
1809 // Neither types nor consts are late-bound.
1810 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
1813 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1815 // appears in the where clauses? early-bound.
1816 if appears_in_where_clause.regions.contains(¶m_def_id) {
1820 // does not appear in the inputs, but appears in the return type? early-bound.
1821 if !constrained_by_input.regions.contains(¶m_def_id)
1822 && appears_in_output.regions.contains(¶m_def_id)
1827 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
1829 let inserted = late_bound.insert(param_def_id);
1830 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
1833 debug!(?late_bound);
1834 return Some(tcx.arena.alloc(late_bound));
1837 struct ConstrainedCollector {
1838 regions: FxHashSet<LocalDefId>,
1841 impl<'v> Visitor<'v> for ConstrainedCollector {
1842 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1845 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
1847 // ignore lifetimes appearing in associated type
1848 // projections, as they are not *constrained*
1852 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1853 // consider only the lifetimes on the final
1854 // segment; I am not sure it's even currently
1855 // valid to have them elsewhere, but even if it
1856 // is, those would be potentially inputs to
1858 if let Some(last_segment) = path.segments.last() {
1859 self.visit_path_segment(last_segment);
1864 intravisit::walk_ty(self, ty);
1869 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
1870 if let hir::LifetimeName::Param(def_id, _) = lifetime_ref.name {
1871 self.regions.insert(def_id);
1877 struct AllCollector {
1878 regions: FxHashSet<LocalDefId>,
1881 impl<'v> Visitor<'v> for AllCollector {
1882 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
1883 if let hir::LifetimeName::Param(def_id, _) = lifetime_ref.name {
1884 self.regions.insert(def_id);