1 // ignore-tidy-filelength
2 //! Name resolution for lifetimes.
4 //! Name resolution for lifetimes follows *much* simpler rules than the
5 //! full resolve. For example, lifetime names are never exported or
6 //! used between functions, and they operate in a purely top-down
7 //! way. Therefore, we break lifetime name resolution into a separate pass.
9 use crate::late::diagnostics::{ForLifetimeSpanType, MissingLifetimeSpot};
10 use rustc_ast::walk_list;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
12 use rustc_errors::struct_span_err;
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::{DefIdMap, LocalDefId};
16 use rustc_hir::hir_id::ItemLocalId;
17 use rustc_hir::intravisit::{self, Visitor};
18 use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName};
19 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet};
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::hir::nested_filter;
22 use rustc_middle::middle::resolve_lifetime::*;
23 use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
24 use rustc_middle::{bug, span_bug};
25 use rustc_span::def_id::DefId;
26 use rustc_span::symbol::{kw, sym, Ident};
33 use tracing::{debug, span, Level};
36 fn early(hir_map: Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
38 fn late(index: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
40 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region;
42 fn id(&self) -> Option<DefId>;
44 fn shifted(self, amount: u32) -> Region;
46 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
48 fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
50 L: Iterator<Item = &'a hir::Lifetime>;
53 impl RegionExt for Region {
54 fn early(hir_map: Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
57 let def_id = hir_map.local_def_id(param.hir_id);
58 debug!("Region::early: index={} def_id={:?}", i, def_id);
59 (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id()))
62 fn late(idx: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
63 let depth = ty::INNERMOST;
64 let def_id = hir_map.local_def_id(param.hir_id);
66 "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}",
67 idx, param, depth, def_id,
69 (param.name.normalize_to_macros_2_0(), Region::LateBound(depth, idx, def_id.to_def_id()))
72 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region {
75 let depth = ty::INNERMOST;
76 Region::LateBoundAnon(depth, named_late_bound_vars + i, i)
79 fn id(&self) -> Option<DefId> {
81 Region::Static | Region::LateBoundAnon(..) => None,
83 Region::EarlyBound(_, id) | Region::LateBound(_, _, id) | Region::Free(_, id) => {
89 fn shifted(self, amount: u32) -> Region {
91 Region::LateBound(debruijn, idx, id) => {
92 Region::LateBound(debruijn.shifted_in(amount), idx, id)
94 Region::LateBoundAnon(debruijn, index, anon_index) => {
95 Region::LateBoundAnon(debruijn.shifted_in(amount), index, anon_index)
101 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
103 Region::LateBound(debruijn, index, id) => {
104 Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id)
106 Region::LateBoundAnon(debruijn, index, anon_index) => {
107 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index, anon_index)
113 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
115 L: Iterator<Item = &'a hir::Lifetime>,
117 if let Region::EarlyBound(index, _) = self {
118 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
125 /// Maps the id of each lifetime reference to the lifetime decl
126 /// that it corresponds to.
128 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
129 /// actual use. It has the same data, but indexed by `LocalDefId`. This
131 #[derive(Debug, Default)]
132 struct NamedRegionMap {
133 // maps from every use of a named (not anonymous) lifetime to a
134 // `Region` describing how that region is bound
135 defs: HirIdMap<Region>,
137 // the set of lifetime def ids that are late-bound; a region can
138 // be late-bound if (a) it does NOT appear in a where-clause and
139 // (b) it DOES appear in the arguments.
140 late_bound: HirIdSet,
142 // Maps relevant hir items to the bound vars on them. These include:
144 // - function pointers
147 // - bound types (like `T` in `for<'a> T<'a>: Foo`)
148 late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
150 // maps `PathSegment` `HirId`s to lifetime scopes.
151 scope_for_path: Option<FxHashMap<LocalDefId, FxHashMap<ItemLocalId, LifetimeScopeForPath>>>,
154 pub(crate) struct LifetimeContext<'a, 'tcx> {
155 pub(crate) tcx: TyCtxt<'tcx>,
156 map: &'a mut NamedRegionMap,
159 /// Indicates that we only care about the definition of a trait. This should
160 /// be false if the `Item` we are resolving lifetimes for is not a trait or
161 /// we eventually need lifetimes resolve for trait items.
162 trait_definition_only: bool,
164 /// Cache for cross-crate per-definition object lifetime defaults.
165 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
167 /// When encountering an undefined named lifetime, we will suggest introducing it in these
169 pub(crate) missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
174 /// Declares lifetimes, and each can be early-bound or late-bound.
175 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
176 /// it should be shifted by the number of `Binder`s in between the
177 /// declaration `Binder` and the location it's referenced from.
179 /// We use an IndexMap here because we want these lifetimes in order
181 lifetimes: FxIndexMap<hir::ParamName, Region>,
183 /// if we extend this scope with another scope, what is the next index
184 /// we should use for an early-bound region?
185 next_early_index: u32,
187 /// Whether or not this binder would serve as the parent
188 /// binder for opaque types introduced within. For example:
191 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
194 /// Here, the opaque types we create for the `impl Trait`
195 /// and `impl Trait2` references will both have the `foo` item
196 /// as their parent. When we get to `impl Trait2`, we find
197 /// that it is nested within the `for<>` binder -- this flag
198 /// allows us to skip that when looking for the parent binder
199 /// of the resulting opaque type.
200 opaque_type_parent: bool,
202 scope_type: BinderScopeType,
204 /// The late bound vars for a given item are stored by `HirId` to be
205 /// queried later. However, if we enter an elision scope, we have to
206 /// later append the elided bound vars to the list and need to know what
212 /// In some cases not allowing late bounds allows us to avoid ICEs.
213 /// This is almost ways set to true.
214 allow_late_bound: bool,
217 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
218 /// if this is a fn body, otherwise the original definitions are used.
219 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
220 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
226 /// A scope which either determines unspecified lifetimes or errors
227 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
233 /// Use a specific lifetime (if `Some`) or leave it unset (to be
234 /// inferred in a function body or potentially error outside one),
235 /// for the default choice of lifetime in a trait object type.
236 ObjectLifetimeDefault {
237 lifetime: Option<Region>,
241 /// When we have nested trait refs, we concatenate late bound vars for inner
242 /// trait refs from outer ones. But we also need to include any HRTB
243 /// lifetimes encountered when identifying the trait that an associated type
246 lifetimes: Vec<ty::BoundVariableKind>,
257 #[derive(Copy, Clone, Debug)]
258 enum BinderScopeType {
259 /// Any non-concatenating binder scopes.
261 /// Within a syntactic trait ref, there may be multiple poly trait refs that
262 /// are nested (under the `associated_type_bounds` feature). The binders of
263 /// the inner poly trait refs are extended from the outer poly trait refs
264 /// and don't increase the late bound depth. If you had
265 /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
266 /// would be `Concatenating`. This also used in trait refs in where clauses
267 /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
268 /// out any lifetimes because they aren't needed to show the two scopes).
269 /// The inner `for<>` has a scope of `Concatenating`.
273 // A helper struct for debugging scopes without printing parent scopes
274 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
276 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 .debug_struct("Binder")
289 .field("lifetimes", lifetimes)
290 .field("next_early_index", next_early_index)
291 .field("opaque_type_parent", opaque_type_parent)
292 .field("scope_type", scope_type)
293 .field("hir_id", hir_id)
295 .field("allow_late_bound", allow_late_bound)
297 Scope::Body { id, s: _ } => {
298 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
300 Scope::Elision { elide, s: _ } => {
301 f.debug_struct("Elision").field("elide", elide).field("s", &"..").finish()
303 Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
304 .debug_struct("ObjectLifetimeDefault")
305 .field("lifetime", lifetime)
308 Scope::Supertrait { lifetimes, s: _ } => f
309 .debug_struct("Supertrait")
310 .field("lifetimes", lifetimes)
313 Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
314 Scope::Root => f.debug_struct("Root").finish(),
319 #[derive(Clone, Debug)]
321 /// Use a fresh anonymous late-bound lifetime each time, by
322 /// incrementing the counter to generate sequential indices. All
323 /// anonymous lifetimes must start *after* named bound vars.
324 FreshLateAnon(u32, Cell<u32>),
325 /// Always use this one lifetime.
327 /// Less or more than one lifetime were found, error on unspecified.
328 Error(Vec<ElisionFailureInfo>),
329 /// Forbid lifetime elision inside of a larger scope where it would be
330 /// permitted. For example, in let position impl trait.
334 #[derive(Clone, Debug)]
335 pub(crate) struct ElisionFailureInfo {
336 /// Where we can find the argument pattern.
337 pub(crate) parent: Option<hir::BodyId>,
338 /// The index of the argument in the original definition.
339 pub(crate) index: usize,
340 pub(crate) lifetime_count: usize,
341 pub(crate) have_bound_regions: bool,
342 pub(crate) span: Span,
345 type ScopeRef<'a> = &'a Scope<'a>;
347 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
349 pub fn provide(providers: &mut ty::query::Providers) {
350 *providers = ty::query::Providers {
351 resolve_lifetimes_trait_definition,
354 named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
356 object_lifetime_defaults: |tcx, id| match tcx.hir().find_by_def_id(id) {
357 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
360 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
361 lifetime_scope_map: |tcx, id| {
362 let item_id = item_for(tcx, id);
363 do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
370 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
371 /// Also does not generate any diagnostics.
373 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
374 /// resolves lifetimes only within the trait "header" -- that is, the trait
375 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
376 /// lifetimes within the trait and its items. There is room to refactor this,
377 /// for example to resolve lifetimes for each trait item in separate queries,
378 /// but it's convenient to do the entire trait at once because the lifetimes
379 /// from the trait definition are in scope within the trait items as well.
381 /// The reason for this separate call is to resolve what would otherwise
382 /// be a cycle. Consider this example:
384 /// ```ignore UNSOLVED (maybe @jackh726 knows what lifetime parameter to give Sub)
388 /// trait Sub<'b>: for<'a> Base<'a> {
389 /// type SubItem: Sub<BaseItem = &'b u32>;
393 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
394 /// To figure out the index of `'b`, we have to know about the supertraits
395 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
396 /// (This is because we -- currently at least -- flatten all the late-bound
397 /// lifetimes into a single binder.) This requires us to resolve the
398 /// *trait definition* of `Sub`; basically just enough lifetime information
399 /// to look at the supertraits.
400 #[tracing::instrument(level = "debug", skip(tcx))]
401 fn resolve_lifetimes_trait_definition(
403 local_def_id: LocalDefId,
404 ) -> ResolveLifetimes {
405 convert_named_region_map(tcx, do_resolve(tcx, local_def_id, true, false))
408 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
409 /// You should not read the result of this query directly, but rather use
410 /// `named_region_map`, `is_late_bound_map`, etc.
411 #[tracing::instrument(level = "debug", skip(tcx))]
412 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
413 convert_named_region_map(tcx, do_resolve(tcx, local_def_id, false, false))
418 local_def_id: LocalDefId,
419 trait_definition_only: bool,
420 with_scope_for_path: bool,
421 ) -> NamedRegionMap {
422 let item = tcx.hir().expect_item(local_def_id);
423 let mut named_region_map = NamedRegionMap {
424 defs: Default::default(),
425 late_bound: Default::default(),
426 late_bound_vars: Default::default(),
427 scope_for_path: with_scope_for_path.then(|| Default::default()),
429 let mut visitor = LifetimeContext {
431 map: &mut named_region_map,
433 trait_definition_only,
434 xcrate_object_lifetime_defaults: Default::default(),
435 missing_named_lifetime_spots: vec![],
437 visitor.visit_item(item);
442 fn convert_named_region_map(tcx: TyCtxt<'_>, named_region_map: NamedRegionMap) -> ResolveLifetimes {
443 let mut rl = ResolveLifetimes::default();
445 for (hir_id, v) in named_region_map.defs {
446 let map = rl.defs.entry(hir_id.owner).or_default();
447 map.insert(hir_id.local_id, v);
449 for hir_id in named_region_map.late_bound {
450 let map = rl.late_bound.entry(hir_id.owner).or_default();
451 let def_id = tcx.hir().local_def_id(hir_id);
454 for (hir_id, v) in named_region_map.late_bound_vars {
455 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
456 map.insert(hir_id.local_id, v);
463 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
464 /// There are two important things this does.
465 /// First, we have to resolve lifetimes for
466 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
467 /// where we can have relevant lifetimes.
468 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
469 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
470 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
471 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
472 /// `resolve_lifetimes`.
473 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
474 let item_id = item_for(tcx, def_id);
475 if item_id == def_id {
476 let item = tcx.hir().item(hir::ItemId { def_id: item_id });
478 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
479 _ => tcx.resolve_lifetimes(item_id),
482 tcx.resolve_lifetimes(item_id)
486 /// Finds the `Item` that contains the given `LocalDefId`
487 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
488 match tcx.hir().find_by_def_id(local_def_id) {
489 Some(Node::Item(item)) => {
495 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
496 let mut parent_iter = tcx.hir().parent_iter(hir_id);
498 let node = parent_iter.next().map(|n| n.1);
500 Some(hir::Node::Item(item)) => break item.def_id,
501 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
509 fn is_late_bound_map<'tcx>(
512 ) -> Option<(LocalDefId, &'tcx FxHashSet<LocalDefId>)> {
513 match tcx.def_kind(def_id) {
514 DefKind::AnonConst | DefKind::InlineConst => {
515 let mut def_id = tcx.local_parent(def_id);
516 // We search for the next outer anon const or fn here
517 // while skipping closures.
519 // Note that for `AnonConst` we still just recurse until we
520 // find a function body, but who cares :shrug:
521 while tcx.is_closure(def_id.to_def_id()) {
522 def_id = tcx.local_parent(def_id);
525 tcx.is_late_bound_map(def_id)
527 _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
531 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
532 /// We have to account for this when computing the index of the other generic parameters.
533 /// This function returns whether there is such an implicit parameter defined on the given item.
534 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
535 matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
538 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
540 Region::LateBound(_, _, def_id) => {
541 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
542 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
544 Region::LateBoundAnon(_, _, anon_idx) => {
545 ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
547 _ => bug!("{:?} is not a late region", region),
551 #[tracing::instrument(level = "debug")]
552 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
553 let mut available_lifetimes = vec![];
556 Scope::Binder { lifetimes, s, .. } => {
557 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
558 hir::ParamName::Plain(ident) => Some(ident.name),
563 Scope::Body { s, .. } => {
566 Scope::Elision { elide, s } => {
567 if let Elide::Exact(_) = elide {
568 return LifetimeScopeForPath::Elided;
573 Scope::ObjectLifetimeDefault { s, .. } => {
577 return LifetimeScopeForPath::NonElided(available_lifetimes);
579 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
586 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
587 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
588 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
589 let mut scope = self.scope;
590 let mut supertrait_lifetimes = vec![];
593 Scope::Body { .. } | Scope::Root => {
594 break (vec![], BinderScopeType::Normal);
597 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
601 Scope::Supertrait { s, lifetimes } => {
602 supertrait_lifetimes = lifetimes.clone();
606 Scope::TraitRefBoundary { .. } => {
607 // We should only see super trait lifetimes if there is a `Binder` above
608 assert!(supertrait_lifetimes.is_empty());
609 break (vec![], BinderScopeType::Normal);
612 Scope::Binder { hir_id, .. } => {
613 // Nested poly trait refs have the binders concatenated
614 let mut full_binders =
615 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
616 full_binders.extend(supertrait_lifetimes.into_iter());
617 break (full_binders, BinderScopeType::Concatenating);
623 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
624 type NestedFilter = nested_filter::All;
626 fn nested_visit_map(&mut self) -> Self::Map {
630 // We want to nest trait/impl items in their parent, but nothing else.
631 fn visit_nested_item(&mut self, _: hir::ItemId) {}
633 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
634 if !self.trait_definition_only {
635 intravisit::walk_trait_item_ref(self, ii)
639 fn visit_nested_body(&mut self, body: hir::BodyId) {
640 let body = self.tcx.hir().body(body);
641 self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
642 this.visit_body(body);
648 fk: intravisit::FnKind<'tcx>,
649 fd: &'tcx hir::FnDecl<'tcx>,
654 let name = match fk {
655 intravisit::FnKind::ItemFn(id, _, _) => id.name,
656 intravisit::FnKind::Method(id, _) => id.name,
657 intravisit::FnKind::Closure => sym::closure,
659 let name = name.as_str();
660 let span = span!(Level::DEBUG, "visit_fn", name);
661 let _enter = span.enter();
663 // Any `Binders` are handled elsewhere
664 intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
665 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
667 intravisit::FnKind::Closure => {
668 self.map.late_bound_vars.insert(hir_id, vec![]);
669 let scope = Scope::Binder {
671 lifetimes: FxIndexMap::default(),
672 next_early_index: self.next_early_index(),
674 opaque_type_parent: false,
675 scope_type: BinderScopeType::Normal,
676 allow_late_bound: true,
678 self.with(scope, move |this| intravisit::walk_fn(this, fk, fd, b, s, hir_id));
683 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
685 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
686 if let Some(of_trait) = of_trait {
687 self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
693 hir::ItemKind::Fn(ref sig, ref generics, _) => {
694 self.missing_named_lifetime_spots.push(generics.into());
695 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
696 intravisit::walk_item(this, item);
698 self.missing_named_lifetime_spots.pop();
701 hir::ItemKind::ExternCrate(_)
702 | hir::ItemKind::Use(..)
703 | hir::ItemKind::Macro(..)
704 | hir::ItemKind::Mod(..)
705 | hir::ItemKind::ForeignMod { .. }
706 | hir::ItemKind::GlobalAsm(..) => {
707 // These sorts of items have no lifetime parameters at all.
708 intravisit::walk_item(self, item);
710 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
711 // No lifetime parameters, but implied 'static.
712 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
713 self.with(scope, |this| intravisit::walk_item(this, item));
715 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
716 // Opaque types are visited when we visit the
717 // `TyKind::OpaqueDef`, so that they have the lifetimes from
718 // their parent opaque_ty in scope.
720 // The core idea here is that since OpaqueTys are generated with the impl Trait as
721 // their owner, we can keep going until we find the Item that owns that. We then
722 // conservatively add all resolved lifetimes. Otherwise we run into problems in
723 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
724 for (_hir_id, node) in
725 self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
728 hir::Node::Item(parent_item) => {
729 let resolved_lifetimes: &ResolveLifetimes =
730 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
731 // We need to add *all* deps, since opaque tys may want them from *us*
732 for (&owner, defs) in resolved_lifetimes.defs.iter() {
733 defs.iter().for_each(|(&local_id, region)| {
734 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
737 for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
738 late_bound.iter().for_each(|&id| {
739 let hir_id = self.tcx.local_def_id_to_hir_id(id);
740 debug_assert_eq!(owner, hir_id.owner);
741 self.map.late_bound.insert(hir_id);
744 for (&owner, late_bound_vars) in
745 resolved_lifetimes.late_bound_vars.iter()
747 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
748 self.map.late_bound_vars.insert(
749 hir::HirId { owner, local_id },
750 late_bound_vars.clone(),
756 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
761 hir::ItemKind::TyAlias(_, ref generics)
762 | hir::ItemKind::Enum(_, ref generics)
763 | hir::ItemKind::Struct(_, ref generics)
764 | hir::ItemKind::Union(_, ref generics)
765 | hir::ItemKind::Trait(_, _, ref generics, ..)
766 | hir::ItemKind::TraitAlias(ref generics, ..)
767 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
768 self.missing_named_lifetime_spots.push(generics.into());
770 // These kinds of items have only early-bound lifetime parameters.
771 let mut index = if sub_items_have_self_param(&item.kind) {
772 1 // Self comes before lifetimes
776 let mut non_lifetime_count = 0;
777 let lifetimes = generics
780 .filter_map(|param| match param.kind {
781 GenericParamKind::Lifetime { .. } => {
782 Some(Region::early(self.tcx.hir(), &mut index, param))
784 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
785 non_lifetime_count += 1;
790 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
791 let scope = Scope::Binder {
792 hir_id: item.hir_id(),
794 next_early_index: index + non_lifetime_count,
795 opaque_type_parent: true,
796 scope_type: BinderScopeType::Normal,
798 allow_late_bound: false,
800 self.with(scope, |this| {
801 let scope = Scope::TraitRefBoundary { s: this.scope };
802 this.with(scope, |this| {
803 intravisit::walk_item(this, item);
806 self.missing_named_lifetime_spots.pop();
811 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
813 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
814 self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
815 intravisit::walk_foreign_item(this, item);
818 hir::ForeignItemKind::Static(..) => {
819 intravisit::walk_foreign_item(self, item);
821 hir::ForeignItemKind::Type => {
822 intravisit::walk_foreign_item(self, item);
827 #[tracing::instrument(level = "debug", skip(self))]
828 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
830 hir::TyKind::BareFn(ref c) => {
831 let next_early_index = self.next_early_index();
832 let lifetime_span: Option<Span> =
833 c.generic_params.iter().rev().find_map(|param| match param.kind {
834 GenericParamKind::Lifetime { .. } => Some(param.span),
837 let (span, span_type) = if let Some(span) = lifetime_span {
838 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
840 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
842 self.missing_named_lifetime_spots
843 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
844 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
847 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
849 .map(|(late_bound_idx, param)| {
850 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
851 let r = late_region_as_bound_region(self.tcx, &pair.1);
855 self.map.late_bound_vars.insert(ty.hir_id, binders);
856 let scope = Scope::Binder {
861 opaque_type_parent: false,
862 scope_type: BinderScopeType::Normal,
863 allow_late_bound: true,
865 self.with(scope, |this| {
866 // a bare fn has no bounds, so everything
867 // contained within is scoped within its binder.
868 intravisit::walk_ty(this, ty);
870 self.missing_named_lifetime_spots.pop();
872 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
873 debug!(?bounds, ?lifetime, "TraitObject");
874 let scope = Scope::TraitRefBoundary { s: self.scope };
875 self.with(scope, |this| {
876 for bound in bounds {
877 this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
880 match lifetime.name {
881 LifetimeName::Implicit => {
882 // For types like `dyn Foo`, we should
883 // generate a special form of elided.
884 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
886 LifetimeName::ImplicitObjectLifetimeDefault => {
887 // If the user does not write *anything*, we
888 // use the object lifetime defaulting
889 // rules. So e.g., `Box<dyn Debug>` becomes
890 // `Box<dyn Debug + 'static>`.
891 self.resolve_object_lifetime_default(lifetime)
893 LifetimeName::Underscore => {
894 // If the user writes `'_`, we use the *ordinary* elision
895 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
896 // resolved the same as the `'_` in `&'_ Foo`.
899 self.resolve_elided_lifetimes(&[lifetime])
901 LifetimeName::Param(_) | LifetimeName::Static => {
902 // If the user wrote an explicit name, use that.
903 self.visit_lifetime(lifetime);
905 LifetimeName::Error => {}
908 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
909 self.visit_lifetime(lifetime_ref);
910 let scope = Scope::ObjectLifetimeDefault {
911 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
914 self.with(scope, |this| this.visit_ty(&mt.ty));
916 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
917 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
918 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
919 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
920 // ^ ^ this gets resolved in the scope of
921 // the opaque_ty generics
922 let opaque_ty = self.tcx.hir().item(item_id);
923 let (generics, bounds) = match opaque_ty.kind {
924 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
925 // This arm is for `impl Trait` in the types of statics, constants and locals.
926 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
927 origin: hir::OpaqueTyOrigin::TyAlias,
930 intravisit::walk_ty(self, ty);
932 // Elided lifetimes are not allowed in non-return
933 // position impl Trait
934 let scope = Scope::TraitRefBoundary { s: self.scope };
935 self.with(scope, |this| {
936 let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
937 this.with(scope, |this| {
938 intravisit::walk_item(this, opaque_ty);
944 // RPIT (return position impl trait)
945 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
946 origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
950 }) => (generics, bounds),
951 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
954 // Resolve the lifetimes that are applied to the opaque type.
955 // These are resolved in the current scope.
956 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
957 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
958 // ^ ^this gets resolved in the current scope
959 for lifetime in lifetimes {
960 let hir::GenericArg::Lifetime(lifetime) = lifetime else {
963 self.visit_lifetime(lifetime);
965 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
966 // and ban them. Type variables instantiated inside binders aren't
967 // well-supported at the moment, so this doesn't work.
968 // In the future, this should be fixed and this error should be removed.
969 let def = self.map.defs.get(&lifetime.hir_id).cloned();
970 let Some(Region::LateBound(_, _, def_id)) = def else {
973 let Some(def_id) = def_id.as_local() else {
976 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
977 // Ensure that the parent of the def is an item, not HRTB
978 let parent_id = self.tcx.hir().get_parent_node(hir_id);
979 if !parent_id.is_owner() {
980 if !self.trait_definition_only {
985 "`impl Trait` can only capture lifetimes \
986 bound at the fn or impl level"
990 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
992 if let hir::Node::Item(hir::Item {
993 kind: hir::ItemKind::OpaqueTy { .. }, ..
994 }) = self.tcx.hir().get(parent_id)
996 if !self.trait_definition_only {
997 let mut err = self.tcx.sess.struct_span_err(
999 "higher kinded lifetime bounds on nested opaque types are not supported yet",
1001 err.span_note(self.tcx.def_span(def_id), "lifetime declared here");
1004 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1008 // We want to start our early-bound indices at the end of the parent scope,
1009 // not including any parent `impl Trait`s.
1010 let mut index = self.next_early_index_for_opaque_type();
1013 let mut elision = None;
1014 let mut lifetimes = FxIndexMap::default();
1015 let mut non_lifetime_count = 0;
1016 for param in generics.params {
1018 GenericParamKind::Lifetime { .. } => {
1019 let (name, reg) = Region::early(self.tcx.hir(), &mut index, ¶m);
1020 if let hir::ParamName::Plain(Ident {
1021 name: kw::UnderscoreLifetime,
1025 // Pick the elided lifetime "definition" if one exists
1026 // and use it to make an elision scope.
1027 elision = Some(reg);
1029 lifetimes.insert(name, reg);
1032 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1033 non_lifetime_count += 1;
1037 let next_early_index = index + non_lifetime_count;
1038 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1040 if let Some(elision_region) = elision {
1042 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1043 self.with(scope, |this| {
1044 let scope = Scope::Binder {
1049 opaque_type_parent: false,
1050 scope_type: BinderScopeType::Normal,
1051 allow_late_bound: false,
1053 this.with(scope, |this| {
1054 this.visit_generics(generics);
1055 let scope = Scope::TraitRefBoundary { s: this.scope };
1056 this.with(scope, |this| {
1057 for bound in bounds {
1058 this.visit_param_bound(bound);
1064 let scope = Scope::Binder {
1069 opaque_type_parent: false,
1070 scope_type: BinderScopeType::Normal,
1071 allow_late_bound: false,
1073 self.with(scope, |this| {
1074 let scope = Scope::TraitRefBoundary { s: this.scope };
1075 this.with(scope, |this| {
1076 this.visit_generics(generics);
1077 for bound in bounds {
1078 this.visit_param_bound(bound);
1084 _ => intravisit::walk_ty(self, ty),
1088 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1089 use self::hir::TraitItemKind::*;
1090 match trait_item.kind {
1092 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1094 self.visit_early_late(
1095 Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1096 trait_item.hir_id(),
1098 &trait_item.generics,
1099 |this| intravisit::walk_trait_item(this, trait_item),
1101 self.missing_named_lifetime_spots.pop();
1103 Type(bounds, ref ty) => {
1104 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1105 let generics = &trait_item.generics;
1106 let mut index = self.next_early_index();
1107 debug!("visit_ty: index = {}", index);
1108 let mut non_lifetime_count = 0;
1109 let lifetimes = generics
1112 .filter_map(|param| match param.kind {
1113 GenericParamKind::Lifetime { .. } => {
1114 Some(Region::early(self.tcx.hir(), &mut index, param))
1116 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1117 non_lifetime_count += 1;
1122 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1123 let scope = Scope::Binder {
1124 hir_id: trait_item.hir_id(),
1126 next_early_index: index + non_lifetime_count,
1128 opaque_type_parent: true,
1129 scope_type: BinderScopeType::Normal,
1130 allow_late_bound: false,
1132 self.with(scope, |this| {
1133 let scope = Scope::TraitRefBoundary { s: this.scope };
1134 this.with(scope, |this| {
1135 this.visit_generics(generics);
1136 for bound in bounds {
1137 this.visit_param_bound(bound);
1139 if let Some(ty) = ty {
1144 self.missing_named_lifetime_spots.pop();
1147 // Only methods and types support generics.
1148 assert!(trait_item.generics.params.is_empty());
1149 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1150 intravisit::walk_trait_item(self, trait_item);
1151 self.missing_named_lifetime_spots.pop();
1156 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1157 use self::hir::ImplItemKind::*;
1158 match impl_item.kind {
1160 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1162 self.visit_early_late(
1163 Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1166 &impl_item.generics,
1167 |this| intravisit::walk_impl_item(this, impl_item),
1169 self.missing_named_lifetime_spots.pop();
1171 TyAlias(ref ty) => {
1172 let generics = &impl_item.generics;
1173 self.missing_named_lifetime_spots.push(generics.into());
1174 let mut index = self.next_early_index();
1175 let mut non_lifetime_count = 0;
1176 debug!("visit_ty: index = {}", index);
1177 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1180 .filter_map(|param| match param.kind {
1181 GenericParamKind::Lifetime { .. } => {
1182 Some(Region::early(self.tcx.hir(), &mut index, param))
1184 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1185 non_lifetime_count += 1;
1190 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1191 let scope = Scope::Binder {
1194 next_early_index: index + non_lifetime_count,
1196 opaque_type_parent: true,
1197 scope_type: BinderScopeType::Normal,
1198 allow_late_bound: true,
1200 self.with(scope, |this| {
1201 let scope = Scope::TraitRefBoundary { s: this.scope };
1202 this.with(scope, |this| {
1203 this.visit_generics(generics);
1207 self.missing_named_lifetime_spots.pop();
1210 // Only methods and types support generics.
1211 assert!(impl_item.generics.params.is_empty());
1212 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1213 intravisit::walk_impl_item(self, impl_item);
1214 self.missing_named_lifetime_spots.pop();
1219 #[tracing::instrument(level = "debug", skip(self))]
1220 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1221 if lifetime_ref.is_elided() {
1222 self.resolve_elided_lifetimes(&[lifetime_ref]);
1225 if lifetime_ref.is_static() {
1226 self.insert_lifetime(lifetime_ref, Region::Static);
1229 self.resolve_lifetime_ref(lifetime_ref);
1232 fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1233 let scope = self.scope;
1234 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1235 // We add lifetime scope information for `Ident`s in associated type bindings and use
1236 // the `HirId` of the type binding as the key in `LifetimeMap`
1237 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1238 let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1239 map.insert(type_binding.hir_id.local_id, lifetime_scope);
1241 hir::intravisit::walk_assoc_type_binding(self, type_binding);
1244 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1245 for (i, segment) in path.segments.iter().enumerate() {
1246 let depth = path.segments.len() - i - 1;
1247 if let Some(ref args) = segment.args {
1248 self.visit_segment_args(path.res, depth, args);
1251 let scope = self.scope;
1252 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1253 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1254 // here because that call would yield to resolution problems due to `walk_path_segment`
1255 // being called, which processes the path segments generic args, which we have already
1256 // processed using `visit_segment_args`.
1257 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1258 if let Some(hir_id) = segment.hir_id {
1259 let map = scope_for_path.entry(hir_id.owner).or_default();
1260 map.insert(hir_id.local_id, lifetime_scope);
1266 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1267 let scope = self.scope;
1268 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1269 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1270 if let Some(hir_id) = path_segment.hir_id {
1271 let map = scope_for_path.entry(hir_id.owner).or_default();
1272 map.insert(hir_id.local_id, lifetime_scope);
1276 intravisit::walk_path_segment(self, path_span, path_segment);
1279 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1280 let output = match fd.output {
1281 hir::FnRetTy::DefaultReturn(_) => None,
1282 hir::FnRetTy::Return(ref ty) => Some(&**ty),
1284 self.visit_fn_like_elision(&fd.inputs, output);
1287 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1288 let scope = Scope::TraitRefBoundary { s: self.scope };
1289 self.with(scope, |this| {
1290 for param in generics.params {
1292 GenericParamKind::Lifetime { .. } => {}
1293 GenericParamKind::Type { ref default, .. } => {
1294 if let Some(ref ty) = default {
1298 GenericParamKind::Const { ref ty, default } => {
1300 if let Some(default) = default {
1301 this.visit_body(this.tcx.hir().body(default.body));
1306 for predicate in generics.predicates {
1308 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1311 ref bound_generic_params,
1314 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1315 bound_generic_params
1318 matches!(param.kind, GenericParamKind::Lifetime { .. })
1321 .map(|(late_bound_idx, param)| {
1323 Region::late(late_bound_idx as u32, this.tcx.hir(), param);
1324 let r = late_region_as_bound_region(this.tcx, &pair.1);
1328 this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1329 let next_early_index = this.next_early_index();
1330 // Even if there are no lifetimes defined here, we still wrap it in a binder
1331 // scope. If there happens to be a nested poly trait ref (an error), that
1332 // will be `Concatenating` anyways, so we don't have to worry about the depth
1334 let scope = Scope::Binder {
1335 hir_id: bounded_ty.hir_id,
1339 opaque_type_parent: false,
1340 scope_type: BinderScopeType::Normal,
1341 allow_late_bound: true,
1343 this.with(scope, |this| {
1344 this.visit_ty(&bounded_ty);
1345 walk_list!(this, visit_param_bound, bounds);
1348 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1353 this.visit_lifetime(lifetime);
1354 walk_list!(this, visit_param_bound, bounds);
1356 if lifetime.name != hir::LifetimeName::Static {
1357 for bound in bounds {
1358 let hir::GenericBound::Outlives(ref lt) = bound else {
1361 if lt.name != hir::LifetimeName::Static {
1364 this.insert_lifetime(lt, Region::Static);
1370 "unnecessary lifetime parameter `{}`",
1371 lifetime.name.ident(),
1375 "you can use the `'static` lifetime directly, in place of `{}`",
1376 lifetime.name.ident(),
1382 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1387 this.visit_ty(lhs_ty);
1388 this.visit_ty(rhs_ty);
1395 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1397 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1398 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1399 // through the regular poly trait ref code, so we don't get another
1400 // chance to introduce a binder. For now, I'm keeping the existing logic
1401 // of "if there isn't a Binder scope above us, add one", but I
1402 // imagine there's a better way to go about this.
1403 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1405 self.map.late_bound_vars.insert(*hir_id, binders);
1406 let scope = Scope::Binder {
1408 lifetimes: FxIndexMap::default(),
1410 next_early_index: self.next_early_index(),
1411 opaque_type_parent: false,
1413 allow_late_bound: true,
1415 self.with(scope, |this| {
1416 intravisit::walk_param_bound(this, bound);
1419 _ => intravisit::walk_param_bound(self, bound),
1423 fn visit_poly_trait_ref(
1425 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1426 _modifier: hir::TraitBoundModifier,
1428 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1430 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1432 let next_early_index = self.next_early_index();
1433 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1435 let initial_bound_vars = binders.len() as u32;
1436 let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1437 let binders_iter = trait_ref
1438 .bound_generic_params
1440 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1442 .map(|(late_bound_idx, param)| {
1444 Region::late(initial_bound_vars + late_bound_idx as u32, self.tcx.hir(), param);
1445 let r = late_region_as_bound_region(self.tcx, &pair.1);
1446 lifetimes.insert(pair.0, pair.1);
1449 binders.extend(binders_iter);
1452 self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1454 // Always introduce a scope here, even if this is in a where clause and
1455 // we introduced the binders around the bounded Ty. In that case, we
1456 // just reuse the concatenation functionality also present in nested trait
1458 let scope = Scope::Binder {
1459 hir_id: trait_ref.trait_ref.hir_ref_id,
1463 opaque_type_parent: false,
1465 allow_late_bound: true,
1467 self.with(scope, |this| {
1468 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1469 this.visit_trait_ref(&trait_ref.trait_ref);
1472 if should_pop_missing_lt {
1473 self.missing_named_lifetime_spots.pop();
1478 fn compute_object_lifetime_defaults<'tcx>(
1480 item: &hir::Item<'_>,
1481 ) -> Option<&'tcx [ObjectLifetimeDefault]> {
1483 hir::ItemKind::Struct(_, ref generics)
1484 | hir::ItemKind::Union(_, ref generics)
1485 | hir::ItemKind::Enum(_, ref generics)
1486 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1488 origin: hir::OpaqueTyOrigin::TyAlias,
1491 | hir::ItemKind::TyAlias(_, ref generics)
1492 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1493 let result = object_lifetime_defaults_for_item(tcx, generics);
1496 let attrs = tcx.hir().attrs(item.hir_id());
1497 if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1498 let object_lifetime_default_reprs: String = result
1500 .map(|set| match *set {
1501 Set1::Empty => "BaseDefault".into(),
1502 Set1::One(Region::Static) => "'static".into(),
1503 Set1::One(Region::EarlyBound(mut i, _)) => generics
1506 .find_map(|param| match param.kind {
1507 GenericParamKind::Lifetime { .. } => {
1509 return Some(param.name.ident().to_string().into());
1517 Set1::One(_) => bug!(),
1518 Set1::Many => "Ambiguous".into(),
1520 .collect::<Vec<Cow<'static, str>>>()
1522 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1531 /// Scan the bounds and where-clauses on parameters to extract bounds
1532 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1533 /// for each type parameter.
1534 fn object_lifetime_defaults_for_item<'tcx>(
1536 generics: &hir::Generics<'_>,
1537 ) -> &'tcx [ObjectLifetimeDefault] {
1538 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1539 for bound in bounds {
1540 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1541 set.insert(lifetime.name.normalize_to_macros_2_0());
1546 let process_param = |param: &hir::GenericParam<'_>| match param.kind {
1547 GenericParamKind::Lifetime { .. } => None,
1548 GenericParamKind::Type { .. } => {
1549 let mut set = Set1::Empty;
1551 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1552 for predicate in generics.predicates {
1553 // Look for `type: ...` where clauses.
1554 let hir::WherePredicate::BoundPredicate(ref data) = *predicate else { continue };
1556 // Ignore `for<'a> type: ...` as they can change what
1557 // lifetimes mean (although we could "just" handle it).
1558 if !data.bound_generic_params.is_empty() {
1562 let res = match data.bounded_ty.kind {
1563 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1567 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1568 add_bounds(&mut set, &data.bounds);
1573 Set1::Empty => Set1::Empty,
1574 Set1::One(name) => {
1575 if name == hir::LifetimeName::Static {
1576 Set1::One(Region::Static)
1581 .filter_map(|param| match param.kind {
1582 GenericParamKind::Lifetime { .. } => {
1583 Some((param.hir_id, hir::LifetimeName::Param(param.name)))
1588 .find(|&(_, (_, lt_name))| lt_name == name)
1589 .map_or(Set1::Many, |(i, (id, _))| {
1590 let def_id = tcx.hir().local_def_id(id);
1591 Set1::One(Region::EarlyBound(i as u32, def_id.to_def_id()))
1595 Set1::Many => Set1::Many,
1598 GenericParamKind::Const { .. } => {
1599 // Generic consts don't impose any constraints.
1601 // We still store a dummy value here to allow generic parameters
1602 // in an arbitrary order.
1607 tcx.arena.alloc_from_iter(generics.params.iter().filter_map(process_param))
1610 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1611 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1613 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1615 let LifetimeContext { tcx, map, .. } = self;
1616 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1617 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1618 let mut this = LifetimeContext {
1622 trait_definition_only: self.trait_definition_only,
1623 xcrate_object_lifetime_defaults,
1624 missing_named_lifetime_spots,
1626 let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1628 let _enter = span.enter();
1631 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1632 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1635 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1637 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1638 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1639 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1643 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1645 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1646 /// lifetimes may be interspersed together.
1648 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1649 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1650 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1651 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1652 /// ordering is not important there.
1653 fn visit_early_late<F>(
1655 parent_id: Option<LocalDefId>,
1657 decl: &'tcx hir::FnDecl<'tcx>,
1658 generics: &'tcx hir::Generics<'tcx>,
1661 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1663 insert_late_bound_lifetimes(self.map, decl, generics);
1665 // Find the start of nested early scopes, e.g., in methods.
1666 let mut next_early_index = 0;
1667 if let Some(parent_id) = parent_id {
1668 let parent = self.tcx.hir().expect_item(parent_id);
1669 if sub_items_have_self_param(&parent.kind) {
1670 next_early_index += 1; // Self comes before lifetimes
1673 hir::ItemKind::Trait(_, _, ref generics, ..)
1674 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
1675 next_early_index += generics.params.len() as u32;
1681 let mut non_lifetime_count = 0;
1682 let mut named_late_bound_vars = 0;
1683 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1686 .filter_map(|param| match param.kind {
1687 GenericParamKind::Lifetime { .. } => {
1688 if self.map.late_bound.contains(¶m.hir_id) {
1689 let late_bound_idx = named_late_bound_vars;
1690 named_late_bound_vars += 1;
1691 Some(Region::late(late_bound_idx, self.tcx.hir(), param))
1693 Some(Region::early(self.tcx.hir(), &mut next_early_index, param))
1696 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1697 non_lifetime_count += 1;
1702 let next_early_index = next_early_index + non_lifetime_count;
1704 let binders: Vec<_> = generics
1708 matches!(param.kind, GenericParamKind::Lifetime { .. })
1709 && self.map.late_bound.contains(¶m.hir_id)
1712 .map(|(late_bound_idx, param)| {
1713 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
1714 late_region_as_bound_region(self.tcx, &pair.1)
1717 self.map.late_bound_vars.insert(hir_id, binders);
1718 let scope = Scope::Binder {
1723 opaque_type_parent: true,
1724 scope_type: BinderScopeType::Normal,
1725 allow_late_bound: true,
1727 self.with(scope, walk);
1730 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1731 let mut scope = self.scope;
1734 Scope::Root => return 0,
1736 Scope::Binder { next_early_index, opaque_type_parent, .. }
1737 if (!only_opaque_type_parent || opaque_type_parent) =>
1739 return next_early_index;
1742 Scope::Binder { s, .. }
1743 | Scope::Body { s, .. }
1744 | Scope::Elision { s, .. }
1745 | Scope::ObjectLifetimeDefault { s, .. }
1746 | Scope::Supertrait { s, .. }
1747 | Scope::TraitRefBoundary { s, .. } => scope = s,
1752 /// Returns the next index one would use for an early-bound-region
1753 /// if extending the current scope.
1754 fn next_early_index(&self) -> u32 {
1755 self.next_early_index_helper(true)
1758 /// Returns the next index one would use for an `impl Trait` that
1759 /// is being converted into an opaque type alias `impl Trait`. This will be the
1760 /// next early index from the enclosing item, for the most
1761 /// part. See the `opaque_type_parent` field for more info.
1762 fn next_early_index_for_opaque_type(&self) -> u32 {
1763 self.next_early_index_helper(false)
1766 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1767 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1769 // If we've already reported an error, just ignore `lifetime_ref`.
1770 if let LifetimeName::Error = lifetime_ref.name {
1774 // Walk up the scope chain, tracking the number of fn scopes
1775 // that we pass through, until we find a lifetime with the
1776 // given name or we run out of scopes.
1778 let mut late_depth = 0;
1779 let mut scope = self.scope;
1780 let mut outermost_body = None;
1783 Scope::Body { id, s } => {
1784 outermost_body = Some(id);
1792 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
1793 match lifetime_ref.name {
1794 LifetimeName::Param(param_name) => {
1795 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
1797 break Some(def.shifted(late_depth));
1800 _ => bug!("expected LifetimeName::Param"),
1803 BinderScopeType::Normal => late_depth += 1,
1804 BinderScopeType::Concatenating => {}
1809 Scope::Elision { s, .. }
1810 | Scope::ObjectLifetimeDefault { s, .. }
1811 | Scope::Supertrait { s, .. }
1812 | Scope::TraitRefBoundary { s, .. } => {
1818 if let Some(mut def) = result {
1819 if let Region::EarlyBound(..) = def {
1820 // Do not free early-bound regions, only late-bound ones.
1821 } else if let Some(body_id) = outermost_body {
1822 let fn_id = self.tcx.hir().body_owner(body_id);
1823 match self.tcx.hir().get(fn_id) {
1824 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1825 | Node::TraitItem(&hir::TraitItem {
1826 kind: hir::TraitItemKind::Fn(..), ..
1828 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
1829 let scope = self.tcx.hir().local_def_id(fn_id);
1830 def = Region::Free(scope.to_def_id(), def.id().unwrap());
1836 self.insert_lifetime(lifetime_ref, def);
1838 self.tcx.sess.delay_span_bug(
1840 &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
1845 fn visit_segment_args(
1849 generic_args: &'tcx hir::GenericArgs<'tcx>,
1852 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1853 res, depth, generic_args,
1856 if generic_args.parenthesized {
1857 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1861 let mut elide_lifetimes = true;
1862 let lifetimes: Vec<_> = generic_args
1865 .filter_map(|arg| match arg {
1866 hir::GenericArg::Lifetime(lt) => {
1867 if !lt.is_elided() {
1868 elide_lifetimes = false;
1875 // We short-circuit here if all are elided in order to pluralize
1877 if elide_lifetimes {
1878 self.resolve_elided_lifetimes(&lifetimes);
1880 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1883 // Figure out if this is a type/trait segment,
1884 // which requires object lifetime defaults.
1885 let parent_def_id = |this: &mut Self, def_id: DefId| {
1886 let def_key = this.tcx.def_key(def_id);
1887 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1889 let type_def_id = match res {
1890 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1891 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1899 ) if depth == 0 => Some(def_id),
1903 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1905 // Compute a vector of defaults, one for each type parameter,
1906 // per the rules given in RFCs 599 and 1156. Example:
1909 // struct Foo<'a, T: 'a, U> { }
1912 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1913 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1914 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1917 // Therefore, we would compute `object_lifetime_defaults` to a
1918 // vector like `['x, 'static]`. Note that the vector only
1919 // includes type parameters.
1920 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
1922 let mut scope = self.scope;
1925 Scope::Root => break false,
1927 Scope::Body { .. } => break true,
1929 Scope::Binder { s, .. }
1930 | Scope::Elision { s, .. }
1931 | Scope::ObjectLifetimeDefault { s, .. }
1932 | Scope::Supertrait { s, .. }
1933 | Scope::TraitRefBoundary { s, .. } => {
1940 let map = &self.map;
1941 let set_to_region = |set: &ObjectLifetimeDefault| match *set {
1946 Some(Region::Static)
1950 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1951 GenericArg::Lifetime(lt) => Some(lt),
1954 r.subst(lifetimes, map)
1958 if let Some(def_id) = def_id.as_local() {
1959 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1961 .object_lifetime_defaults(id.owner)
1968 self.xcrate_object_lifetime_defaults
1970 .or_insert_with(|| {
1971 tcx.generics_of(def_id)
1974 .filter_map(|param| match param.kind {
1975 GenericParamDefKind::Type { object_lifetime_default, .. } => {
1976 Some(object_lifetime_default)
1978 GenericParamDefKind::Const { .. } => Some(Set1::Empty),
1979 GenericParamDefKind::Lifetime => None,
1989 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
1992 for arg in generic_args.args {
1994 GenericArg::Lifetime(_) => {}
1995 GenericArg::Type(ty) => {
1996 if let Some(<) = object_lifetime_defaults.get(i) {
1997 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1998 self.with(scope, |this| this.visit_ty(ty));
2004 GenericArg::Const(ct) => {
2005 self.visit_anon_const(&ct.value);
2008 GenericArg::Infer(inf) => {
2009 self.visit_id(inf.hir_id);
2015 // Hack: when resolving the type `XX` in binding like `dyn
2016 // Foo<'b, Item = XX>`, the current object-lifetime default
2017 // would be to examine the trait `Foo` to check whether it has
2018 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2019 // declared like so, then the default object lifetime bound in
2020 // `XX` should be `'b`:
2028 // but if we just have `type Item;`, then it would be
2029 // `'static`. However, we don't get all of this logic correct.
2031 // Instead, we do something hacky: if there are no lifetime parameters
2032 // to the trait, then we simply use a default object lifetime
2033 // bound of `'static`, because there is no other possibility. On the other hand,
2034 // if there ARE lifetime parameters, then we require the user to give an
2035 // explicit bound for now.
2037 // This is intended to leave room for us to implement the
2038 // correct behavior in the future.
2039 let has_lifetime_parameter =
2040 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2042 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2043 // in the trait ref `YY<...>` in `Item: YY<...>`.
2044 for binding in generic_args.bindings {
2045 let scope = Scope::ObjectLifetimeDefault {
2046 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2049 if let Some(type_def_id) = type_def_id {
2050 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2055 self.with(scope, |this| {
2056 let scope = Scope::Supertrait {
2057 lifetimes: lifetimes.unwrap_or_default(),
2060 this.with(scope, |this| this.visit_assoc_type_binding(binding));
2063 self.with(scope, |this| this.visit_assoc_type_binding(binding));
2068 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2069 /// associated type name and starting trait.
2070 /// For example, imagine we have
2071 /// ```ignore (illustrative)
2072 /// trait Foo<'a, 'b> {
2075 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2076 /// trait Bar: for<'b> Bar<'b> {}
2078 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2079 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2080 fn supertrait_hrtb_lifetimes(
2084 ) -> Option<Vec<ty::BoundVariableKind>> {
2085 let trait_defines_associated_type_named = |trait_def_id: DefId| {
2086 tcx.associated_items(trait_def_id)
2087 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2091 use smallvec::{smallvec, SmallVec};
2092 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2093 smallvec![(def_id, smallvec![])];
2094 let mut visited: FxHashSet<DefId> = FxHashSet::default();
2096 let Some((def_id, bound_vars)) = stack.pop() else {
2099 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2100 // there being no supertrait HRTBs.
2101 match tcx.def_kind(def_id) {
2102 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2106 if trait_defines_associated_type_named(def_id) {
2107 break Some(bound_vars.into_iter().collect());
2110 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2111 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2112 let bound_predicate = pred.kind();
2113 match bound_predicate.skip_binder() {
2114 ty::PredicateKind::Trait(data) => {
2115 // The order here needs to match what we would get from `subst_supertrait`
2116 let pred_bound_vars = bound_predicate.bound_vars();
2117 let mut all_bound_vars = bound_vars.clone();
2118 all_bound_vars.extend(pred_bound_vars.iter());
2119 let super_def_id = data.trait_ref.def_id;
2120 Some((super_def_id, all_bound_vars))
2126 let obligations = obligations.filter(|o| visited.insert(o.0));
2127 stack.extend(obligations);
2131 #[tracing::instrument(level = "debug", skip(self))]
2132 fn visit_fn_like_elision(
2134 inputs: &'tcx [hir::Ty<'tcx>],
2135 output: Option<&'tcx hir::Ty<'tcx>>,
2137 debug!("visit_fn_like_elision: enter");
2138 let mut scope = &*self.scope;
2141 Scope::Binder { hir_id, allow_late_bound: true, .. } => {
2144 Scope::ObjectLifetimeDefault { ref s, .. }
2145 | Scope::Elision { ref s, .. }
2146 | Scope::Supertrait { ref s, .. }
2147 | Scope::TraitRefBoundary { ref s, .. } => {
2151 | Scope::Body { .. }
2152 | Scope::Binder { allow_late_bound: false, .. } => {
2153 // See issues #83907 and #83693. Just bail out from looking inside.
2154 // See the issue #95023 for not allowing late bound
2155 self.tcx.sess.delay_span_bug(
2156 rustc_span::DUMMY_SP,
2157 "In fn_like_elision without appropriate scope above",
2163 // While not strictly necessary, we gather anon lifetimes *before* actually
2164 // visiting the argument types.
2165 let mut gather = GatherAnonLifetimes { anon_count: 0 };
2166 for input in inputs {
2167 gather.visit_ty(input);
2169 trace!(?gather.anon_count);
2170 let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2171 let named_late_bound_vars = late_bound_vars.len() as u32;
2172 late_bound_vars.extend(
2173 (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2175 let arg_scope = Scope::Elision {
2176 elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2179 self.with(arg_scope, |this| {
2180 for input in inputs {
2181 this.visit_ty(input);
2185 let Some(output) = output else { return };
2187 debug!("determine output");
2189 // Figure out if there's a body we can get argument names from,
2190 // and whether there's a `self` argument (treated specially).
2191 let mut assoc_item_kind = None;
2192 let mut impl_self = None;
2193 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2194 let body = match self.tcx.hir().get(parent) {
2195 // `fn` definitions and methods.
2196 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2198 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2199 if let hir::ItemKind::Trait(.., ref trait_items) =
2200 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2203 trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2206 hir::TraitFn::Required(_) => None,
2207 hir::TraitFn::Provided(body) => Some(body),
2211 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2212 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2213 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2215 impl_self = Some(self_ty);
2217 items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2222 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2223 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2224 // Everything else (only closures?) doesn't
2225 // actually enjoy elision in return types.
2227 self.visit_ty(output);
2232 let has_self = match assoc_item_kind {
2233 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2237 // In accordance with the rules for lifetime elision, we can determine
2238 // what region to use for elision in the output type in two ways.
2239 // First (determined here), if `self` is by-reference, then the
2240 // implied output region is the region of the self parameter.
2242 struct SelfVisitor<'a> {
2243 map: &'a NamedRegionMap,
2244 impl_self: Option<&'a hir::TyKind<'a>>,
2245 lifetime: Set1<Region>,
2248 impl SelfVisitor<'_> {
2249 // Look for `self: &'a Self` - also desugared from `&'a self`,
2250 // and if that matches, use it for elision and return early.
2251 fn is_self_ty(&self, res: Res) -> bool {
2252 if let Res::SelfTy { .. } = res {
2256 // Can't always rely on literal (or implied) `Self` due
2257 // to the way elision rules were originally specified.
2258 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2262 // Permit the types that unambiguously always
2263 // result in the same type constructor being used
2264 // (it can't differ between `Self` and `self`).
2265 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2266 | Res::PrimTy(_) => return res == path.res,
2275 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2276 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2277 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2278 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2280 if self.is_self_ty(path.res) {
2281 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2282 self.lifetime.insert(*lifetime);
2287 intravisit::walk_ty(self, ty)
2291 let mut visitor = SelfVisitor {
2293 impl_self: impl_self.map(|ty| &ty.kind),
2294 lifetime: Set1::Empty,
2296 visitor.visit_ty(&inputs[0]);
2297 if let Set1::One(lifetime) = visitor.lifetime {
2298 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2299 self.with(scope, |this| this.visit_ty(output));
2304 // Second, if there was exactly one lifetime (either a substitution or a
2305 // reference) in the arguments, then any anonymous regions in the output
2306 // have that lifetime.
2307 let mut possible_implied_output_region = None;
2308 let mut lifetime_count = 0;
2309 let arg_lifetimes = inputs
2312 .skip(has_self as usize)
2314 let mut gather = GatherLifetimes {
2316 outer_index: ty::INNERMOST,
2317 have_bound_regions: false,
2318 lifetimes: Default::default(),
2320 gather.visit_ty(input);
2322 lifetime_count += gather.lifetimes.len();
2324 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2325 // there's a chance that the unique lifetime of this
2326 // iteration will be the appropriate lifetime for output
2327 // parameters, so lets store it.
2328 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2331 ElisionFailureInfo {
2334 lifetime_count: gather.lifetimes.len(),
2335 have_bound_regions: gather.have_bound_regions,
2341 let elide = if lifetime_count == 1 {
2342 Elide::Exact(possible_implied_output_region.unwrap())
2344 Elide::Error(arg_lifetimes)
2349 let scope = Scope::Elision { elide, s: self.scope };
2350 self.with(scope, |this| this.visit_ty(output));
2352 struct GatherLifetimes<'a> {
2353 map: &'a NamedRegionMap,
2354 outer_index: ty::DebruijnIndex,
2355 have_bound_regions: bool,
2356 lifetimes: FxHashSet<Region>,
2359 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2360 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2361 if let hir::TyKind::BareFn(_) = ty.kind {
2362 self.outer_index.shift_in(1);
2365 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2366 for bound in bounds {
2367 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2370 // Stay on the safe side and don't include the object
2371 // lifetime default (which may not end up being used).
2372 if !lifetime.is_elided() {
2373 self.visit_lifetime(lifetime);
2377 intravisit::walk_ty(self, ty);
2380 if let hir::TyKind::BareFn(_) = ty.kind {
2381 self.outer_index.shift_out(1);
2385 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2386 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2387 // FIXME(eddyb) Do we want this? It only makes a difference
2388 // if this `for<'a>` lifetime parameter is never used.
2389 self.have_bound_regions = true;
2392 intravisit::walk_generic_param(self, param);
2395 fn visit_poly_trait_ref(
2397 trait_ref: &hir::PolyTraitRef<'_>,
2398 modifier: hir::TraitBoundModifier,
2400 self.outer_index.shift_in(1);
2401 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2402 self.outer_index.shift_out(1);
2405 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2406 if let hir::GenericBound::LangItemTrait { .. } = bound {
2407 self.outer_index.shift_in(1);
2408 intravisit::walk_param_bound(self, bound);
2409 self.outer_index.shift_out(1);
2411 intravisit::walk_param_bound(self, bound);
2415 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2416 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2418 Region::LateBound(debruijn, _, _)
2419 | Region::LateBoundAnon(debruijn, _, _)
2420 if debruijn < self.outer_index =>
2422 self.have_bound_regions = true;
2425 // FIXME(jackh726): nested trait refs?
2426 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2433 struct GatherAnonLifetimes {
2436 impl<'v> Visitor<'v> for GatherAnonLifetimes {
2437 #[instrument(skip(self), level = "trace")]
2438 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2439 // If we enter a `BareFn`, then we enter a *new* binding scope
2440 if let hir::TyKind::BareFn(_) = ty.kind {
2443 intravisit::walk_ty(self, ty);
2446 fn visit_generic_args(
2449 generic_args: &'v hir::GenericArgs<'v>,
2451 // parenthesized args enter a new elision scope
2452 if generic_args.parenthesized {
2455 intravisit::walk_generic_args(self, path_span, generic_args)
2458 #[instrument(skip(self), level = "trace")]
2459 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2460 if lifetime_ref.is_elided() {
2461 self.anon_count += 1;
2467 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
2468 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2470 if lifetime_refs.is_empty() {
2474 let mut late_depth = 0;
2475 let mut scope = self.scope;
2476 let mut lifetime_names = FxHashSet::default();
2477 let mut lifetime_spans = vec![];
2480 // Do not assign any resolution, it will be inferred.
2481 Scope::Body { .. } => return,
2483 Scope::Root => break None,
2485 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
2486 // collect named lifetimes for suggestions
2487 for name in lifetimes.keys() {
2488 if let hir::ParamName::Plain(name) = name {
2489 lifetime_names.insert(name.name);
2490 lifetime_spans.push(name.span);
2494 BinderScopeType::Normal => late_depth += 1,
2495 BinderScopeType::Concatenating => {}
2501 elide: Elide::FreshLateAnon(named_late_bound_vars, ref counter),
2504 for lifetime_ref in lifetime_refs {
2506 Region::late_anon(named_late_bound_vars, counter).shifted(late_depth);
2508 self.insert_lifetime(lifetime_ref, lifetime);
2513 Scope::Elision { elide: Elide::Exact(l), .. } => {
2514 let lifetime = l.shifted(late_depth);
2515 for lifetime_ref in lifetime_refs {
2516 self.insert_lifetime(lifetime_ref, lifetime);
2521 Scope::Elision { elide: Elide::Error(ref e), ref s, .. } => {
2525 Scope::Binder { ref lifetimes, s, .. } => {
2526 // Collect named lifetimes for suggestions.
2527 for name in lifetimes.keys() {
2528 if let hir::ParamName::Plain(name) = name {
2529 lifetime_names.insert(name.name);
2530 lifetime_spans.push(name.span);
2535 Scope::ObjectLifetimeDefault { ref s, .. }
2536 | Scope::Elision { ref s, .. }
2537 | Scope::TraitRefBoundary { ref s, .. } => {
2546 Scope::Elision { elide: Elide::Forbid, .. } => break None,
2548 Scope::ObjectLifetimeDefault { s, .. }
2549 | Scope::Supertrait { s, .. }
2550 | Scope::TraitRefBoundary { s, .. } => {
2556 // If we specifically need the `scope_for_path` map, then we're in the
2557 // diagnostic pass and we don't want to emit more errors.
2558 if self.map.scope_for_path.is_some() {
2559 self.tcx.sess.delay_span_bug(
2560 rustc_span::DUMMY_SP,
2561 "Encountered unexpected errors during diagnostics related part",
2566 let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
2568 let mut spans_dedup = spans.clone();
2569 spans_dedup.dedup();
2570 let spans_with_counts: Vec<_> = spans_dedup
2572 .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
2575 let mut err = self.report_missing_lifetime_specifiers(spans.clone(), lifetime_refs.len());
2577 if let Some(params) = error {
2578 // If there's no lifetime available, suggest `'static`.
2579 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
2580 lifetime_names.insert(kw::StaticLifetime);
2584 self.add_missing_lifetime_specifiers_label(
2589 error.unwrap_or(&[]),
2594 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2595 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2596 let mut late_depth = 0;
2597 let mut scope = self.scope;
2598 let lifetime = loop {
2600 Scope::Binder { s, scope_type, .. } => {
2602 BinderScopeType::Normal => late_depth += 1,
2603 BinderScopeType::Concatenating => {}
2608 Scope::Root | Scope::Elision { .. } => break Region::Static,
2610 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2612 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2614 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
2619 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2622 #[tracing::instrument(level = "debug", skip(self))]
2623 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2625 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2626 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
2628 self.map.defs.insert(lifetime_ref.hir_id, def);
2631 /// Sometimes we resolve a lifetime, but later find that it is an
2632 /// error (esp. around impl trait). In that case, we remove the
2633 /// entry into `map.defs` so as not to confuse later code.
2634 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2635 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2636 assert_eq!(old_value, Some(bad_def));
2640 /// Detects late-bound lifetimes and inserts them into
2641 /// `map.late_bound`.
2643 /// A region declared on a fn is **late-bound** if:
2644 /// - it is constrained by an argument type;
2645 /// - it does not appear in a where-clause.
2647 /// "Constrained" basically means that it appears in any type but
2648 /// not amongst the inputs to a projection. In other words, `<&'a
2649 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2650 #[tracing::instrument(level = "debug", skip(map))]
2651 fn insert_late_bound_lifetimes(
2652 map: &mut NamedRegionMap,
2653 decl: &hir::FnDecl<'_>,
2654 generics: &hir::Generics<'_>,
2656 let mut constrained_by_input = ConstrainedCollector::default();
2657 for arg_ty in decl.inputs {
2658 constrained_by_input.visit_ty(arg_ty);
2661 let mut appears_in_output = AllCollector::default();
2662 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2664 debug!(?constrained_by_input.regions);
2666 // Walk the lifetimes that appear in where clauses.
2668 // Subtle point: because we disallow nested bindings, we can just
2669 // ignore binders here and scrape up all names we see.
2670 let mut appears_in_where_clause = AllCollector::default();
2671 appears_in_where_clause.visit_generics(generics);
2672 debug!(?appears_in_where_clause.regions);
2674 // Late bound regions are those that:
2675 // - appear in the inputs
2676 // - do not appear in the where-clauses
2677 // - are not implicitly captured by `impl Trait`
2678 for param in generics.params {
2680 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2682 // Neither types nor consts are late-bound.
2683 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2686 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
2687 // appears in the where clauses? early-bound.
2688 if appears_in_where_clause.regions.contains(<_name) {
2692 // does not appear in the inputs, but appears in the return type? early-bound.
2693 if !constrained_by_input.regions.contains(<_name)
2694 && appears_in_output.regions.contains(<_name)
2699 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
2701 let inserted = map.late_bound.insert(param.hir_id);
2702 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2708 struct ConstrainedCollector {
2709 regions: FxHashSet<hir::LifetimeName>,
2712 impl<'v> Visitor<'v> for ConstrainedCollector {
2713 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2716 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2718 // ignore lifetimes appearing in associated type
2719 // projections, as they are not *constrained*
2723 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2724 // consider only the lifetimes on the final
2725 // segment; I am not sure it's even currently
2726 // valid to have them elsewhere, but even if it
2727 // is, those would be potentially inputs to
2729 if let Some(last_segment) = path.segments.last() {
2730 self.visit_path_segment(path.span, last_segment);
2735 intravisit::walk_ty(self, ty);
2740 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2741 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
2746 struct AllCollector {
2747 regions: FxHashSet<hir::LifetimeName>,
2750 impl<'v> Visitor<'v> for AllCollector {
2751 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2752 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());