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, Applicability, DiagnosticBuilder};
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, QPath};
19 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
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_session::lint;
26 use rustc_span::def_id::DefId;
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
34 use tracing::{debug, span, Level};
36 // This counts the no of times a lifetime is used
37 #[derive(Clone, Copy, Debug)]
38 pub enum LifetimeUseSet<'tcx> {
39 One(&'tcx hir::Lifetime),
44 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
46 fn late(index: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
48 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region;
50 fn id(&self) -> Option<DefId>;
52 fn shifted(self, amount: u32) -> Region;
54 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
56 fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
58 L: Iterator<Item = &'a hir::Lifetime>;
61 impl RegionExt for Region {
62 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
65 let def_id = hir_map.local_def_id(param.hir_id);
66 let origin = LifetimeDefOrigin::from_param(param);
67 debug!("Region::early: index={} def_id={:?}", i, def_id);
68 (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id(), origin))
71 fn late(idx: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
72 let depth = ty::INNERMOST;
73 let def_id = hir_map.local_def_id(param.hir_id);
74 let origin = LifetimeDefOrigin::from_param(param);
76 "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?} origin={:?}",
77 idx, param, depth, def_id, origin,
80 param.name.normalize_to_macros_2_0(),
81 Region::LateBound(depth, idx, def_id.to_def_id(), origin),
85 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region {
88 let depth = ty::INNERMOST;
89 Region::LateBoundAnon(depth, named_late_bound_vars + i, i)
92 fn id(&self) -> Option<DefId> {
94 Region::Static | Region::LateBoundAnon(..) => None,
96 Region::EarlyBound(_, id, _) | Region::LateBound(_, _, id, _) | Region::Free(_, id) => {
102 fn shifted(self, amount: u32) -> Region {
104 Region::LateBound(debruijn, idx, id, origin) => {
105 Region::LateBound(debruijn.shifted_in(amount), idx, id, origin)
107 Region::LateBoundAnon(debruijn, index, anon_index) => {
108 Region::LateBoundAnon(debruijn.shifted_in(amount), index, anon_index)
114 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
116 Region::LateBound(debruijn, index, id, origin) => {
117 Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id, origin)
119 Region::LateBoundAnon(debruijn, index, anon_index) => {
120 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index, anon_index)
126 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
128 L: Iterator<Item = &'a hir::Lifetime>,
130 if let Region::EarlyBound(index, _, _) = self {
131 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
138 /// Maps the id of each lifetime reference to the lifetime decl
139 /// that it corresponds to.
141 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
142 /// actual use. It has the same data, but indexed by `LocalDefId`. This
144 #[derive(Debug, Default)]
145 struct NamedRegionMap {
146 // maps from every use of a named (not anonymous) lifetime to a
147 // `Region` describing how that region is bound
148 defs: HirIdMap<Region>,
150 // the set of lifetime def ids that are late-bound; a region can
151 // be late-bound if (a) it does NOT appear in a where-clause and
152 // (b) it DOES appear in the arguments.
153 late_bound: HirIdSet,
155 // Maps relevant hir items to the bound vars on them. These include:
157 // - function pointers
160 // - bound types (like `T` in `for<'a> T<'a>: Foo`)
161 late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
163 // maps `PathSegment` `HirId`s to lifetime scopes.
164 scope_for_path: Option<FxHashMap<LocalDefId, FxHashMap<ItemLocalId, LifetimeScopeForPath>>>,
167 crate struct LifetimeContext<'a, 'tcx> {
168 crate tcx: TyCtxt<'tcx>,
169 map: &'a mut NamedRegionMap,
172 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
173 is_in_fn_syntax: bool,
175 is_in_const_generic: bool,
177 /// Indicates that we only care about the definition of a trait. This should
178 /// be false if the `Item` we are resolving lifetimes for is not a trait or
179 /// we eventually need lifetimes resolve for trait items.
180 trait_definition_only: bool,
182 /// List of labels in the function/method currently under analysis.
183 labels_in_fn: Vec<Ident>,
185 /// Cache for cross-crate per-definition object lifetime defaults.
186 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
188 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
190 /// When encountering an undefined named lifetime, we will suggest introducing it in these
192 crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
197 /// Declares lifetimes, and each can be early-bound or late-bound.
198 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
199 /// it should be shifted by the number of `Binder`s in between the
200 /// declaration `Binder` and the location it's referenced from.
202 /// We use an IndexMap here because we want these lifetimes in order
204 lifetimes: FxIndexMap<hir::ParamName, Region>,
206 /// if we extend this scope with another scope, what is the next index
207 /// we should use for an early-bound region?
208 next_early_index: u32,
210 /// Flag is set to true if, in this binder, `'_` would be
211 /// equivalent to a "single-use region". This is true on
212 /// impls, but not other kinds of items.
213 track_lifetime_uses: bool,
215 /// Whether or not this binder would serve as the parent
216 /// binder for opaque types introduced within. For example:
219 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
222 /// Here, the opaque types we create for the `impl Trait`
223 /// and `impl Trait2` references will both have the `foo` item
224 /// as their parent. When we get to `impl Trait2`, we find
225 /// that it is nested within the `for<>` binder -- this flag
226 /// allows us to skip that when looking for the parent binder
227 /// of the resulting opaque type.
228 opaque_type_parent: bool,
230 scope_type: BinderScopeType,
232 /// The late bound vars for a given item are stored by `HirId` to be
233 /// queried later. However, if we enter an elision scope, we have to
234 /// later append the elided bound vars to the list and need to know what
241 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
242 /// if this is a fn body, otherwise the original definitions are used.
243 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
244 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
250 /// A scope which either determines unspecified lifetimes or errors
251 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
257 /// Use a specific lifetime (if `Some`) or leave it unset (to be
258 /// inferred in a function body or potentially error outside one),
259 /// for the default choice of lifetime in a trait object type.
260 ObjectLifetimeDefault {
261 lifetime: Option<Region>,
265 /// When we have nested trait refs, we concanetate late bound vars for inner
266 /// trait refs from outer ones. But we also need to include any HRTB
267 /// lifetimes encountered when identifying the trait that an associated type
270 lifetimes: Vec<ty::BoundVariableKind>,
281 #[derive(Copy, Clone, Debug)]
282 enum BinderScopeType {
283 /// Any non-concatenating binder scopes.
285 /// Within a syntactic trait ref, there may be multiple poly trait refs that
286 /// are nested (under the `associcated_type_bounds` feature). The binders of
287 /// the innner poly trait refs are extended from the outer poly trait refs
288 /// and don't increase the late bound depth. If you had
289 /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
290 /// would be `Concatenating`. This also used in trait refs in where clauses
291 /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
292 /// out any lifetimes because they aren't needed to show the two scopes).
293 /// The inner `for<>` has a scope of `Concatenating`.
297 // A helper struct for debugging scopes without printing parent scopes
298 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
300 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 .debug_struct("Binder")
313 .field("lifetimes", lifetimes)
314 .field("next_early_index", next_early_index)
315 .field("track_lifetime_uses", track_lifetime_uses)
316 .field("opaque_type_parent", opaque_type_parent)
317 .field("scope_type", scope_type)
318 .field("hir_id", hir_id)
321 Scope::Body { id, s: _ } => {
322 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
324 Scope::Elision { elide, s: _ } => {
325 f.debug_struct("Elision").field("elide", elide).field("s", &"..").finish()
327 Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
328 .debug_struct("ObjectLifetimeDefault")
329 .field("lifetime", lifetime)
332 Scope::Supertrait { lifetimes, s: _ } => f
333 .debug_struct("Supertrait")
334 .field("lifetimes", lifetimes)
337 Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
338 Scope::Root => f.debug_struct("Root").finish(),
343 #[derive(Clone, Debug)]
345 /// Use a fresh anonymous late-bound lifetime each time, by
346 /// incrementing the counter to generate sequential indices. All
347 /// anonymous lifetimes must start *after* named bound vars.
348 FreshLateAnon(u32, Cell<u32>),
349 /// Always use this one lifetime.
351 /// Less or more than one lifetime were found, error on unspecified.
352 Error(Vec<ElisionFailureInfo>),
353 /// Forbid lifetime elision inside of a larger scope where it would be
354 /// permitted. For example, in let position impl trait.
358 #[derive(Clone, Debug)]
359 crate struct ElisionFailureInfo {
360 /// Where we can find the argument pattern.
361 crate parent: Option<hir::BodyId>,
362 /// The index of the argument in the original definition.
364 crate lifetime_count: usize,
365 crate have_bound_regions: bool,
369 type ScopeRef<'a> = &'a Scope<'a>;
371 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
373 pub fn provide(providers: &mut ty::query::Providers) {
374 *providers = ty::query::Providers {
375 resolve_lifetimes_trait_definition,
378 named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
380 object_lifetime_defaults_map: |tcx, id| match tcx.hir().find_by_def_id(id) {
381 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
384 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
385 lifetime_scope_map: |tcx, id| {
386 let item_id = item_for(tcx, id);
387 do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
394 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
395 /// Also does not generate any diagnostics.
397 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
398 /// resolves lifetimes only within the trait "header" -- that is, the trait
399 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
400 /// lifetimes within the trait and its items. There is room to refactor this,
401 /// for example to resolve lifetimes for each trait item in separate queries,
402 /// but it's convenient to do the entire trait at once because the lifetimes
403 /// from the trait definition are in scope within the trait items as well.
405 /// The reason for this separate call is to resolve what would otherwise
406 /// be a cycle. Consider this example:
412 /// trait Sub<'b>: for<'a> Base<'a> {
413 /// type SubItem: Sub<BaseItem = &'b u32>;
417 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
418 /// To figure out the index of `'b`, we have to know about the supertraits
419 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
420 /// (This is because we -- currently at least -- flatten all the late-bound
421 /// lifetimes into a single binder.) This requires us to resolve the
422 /// *trait definition* of `Sub`; basically just enough lifetime information
423 /// to look at the supertraits.
424 #[tracing::instrument(level = "debug", skip(tcx))]
425 fn resolve_lifetimes_trait_definition(
427 local_def_id: LocalDefId,
428 ) -> ResolveLifetimes {
429 convert_named_region_map(do_resolve(tcx, local_def_id, true, false))
432 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
433 /// You should not read the result of this query directly, but rather use
434 /// `named_region_map`, `is_late_bound_map`, etc.
435 #[tracing::instrument(level = "debug", skip(tcx))]
436 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
437 convert_named_region_map(do_resolve(tcx, local_def_id, false, false))
442 local_def_id: LocalDefId,
443 trait_definition_only: bool,
444 with_scope_for_path: bool,
445 ) -> NamedRegionMap {
446 let item = tcx.hir().expect_item(local_def_id);
447 let mut named_region_map = NamedRegionMap {
448 defs: Default::default(),
449 late_bound: Default::default(),
450 late_bound_vars: Default::default(),
451 scope_for_path: with_scope_for_path.then(|| Default::default()),
453 let mut visitor = LifetimeContext {
455 map: &mut named_region_map,
457 is_in_fn_syntax: false,
458 is_in_const_generic: false,
459 trait_definition_only,
460 labels_in_fn: vec![],
461 xcrate_object_lifetime_defaults: Default::default(),
462 lifetime_uses: &mut Default::default(),
463 missing_named_lifetime_spots: vec![],
465 visitor.visit_item(item);
470 fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes {
471 let mut rl = ResolveLifetimes::default();
473 for (hir_id, v) in named_region_map.defs {
474 let map = rl.defs.entry(hir_id.owner).or_default();
475 map.insert(hir_id.local_id, v);
477 for hir_id in named_region_map.late_bound {
478 let map = rl.late_bound.entry(hir_id.owner).or_default();
479 map.insert(hir_id.local_id);
481 for (hir_id, v) in named_region_map.late_bound_vars {
482 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
483 map.insert(hir_id.local_id, v);
490 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
491 /// There are two important things this does.
492 /// First, we have to resolve lifetimes for
493 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
494 /// where we can have relevant lifetimes.
495 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
496 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
497 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
498 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
499 /// `resolve_lifetimes`.
500 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
501 let item_id = item_for(tcx, def_id);
502 if item_id == def_id {
503 let item = tcx.hir().item(hir::ItemId { def_id: item_id });
505 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
506 _ => tcx.resolve_lifetimes(item_id),
509 tcx.resolve_lifetimes(item_id)
513 /// Finds the `Item` that contains the given `LocalDefId`
514 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
515 match tcx.hir().find_by_def_id(local_def_id) {
516 Some(Node::Item(item)) => {
522 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
523 let mut parent_iter = tcx.hir().parent_iter(hir_id);
525 let node = parent_iter.next().map(|n| n.1);
527 Some(hir::Node::Item(item)) => break item.def_id,
528 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
536 fn is_late_bound_map<'tcx>(
539 ) -> Option<(LocalDefId, &'tcx FxHashSet<ItemLocalId>)> {
540 match tcx.def_kind(def_id) {
541 DefKind::AnonConst | DefKind::InlineConst => {
543 .parent(def_id.to_def_id())
544 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
545 // We search for the next outer anon const or fn here
546 // while skipping closures.
548 // Note that for `AnonConst` we still just recurse until we
549 // find a function body, but who cares :shrug:
550 while tcx.is_closure(def_id) {
553 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
556 tcx.is_late_bound_map(def_id.expect_local())
558 _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
562 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
563 /// We have to account for this when computing the index of the other generic parameters.
564 /// This function returns whether there is such an implicit parameter defined on the given item.
565 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
566 matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
569 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
571 Region::LateBound(_, _, def_id, _) => {
572 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
573 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
575 Region::LateBoundAnon(_, _, anon_idx) => {
576 ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
578 _ => bug!("{:?} is not a late region", region),
582 #[tracing::instrument(level = "debug")]
583 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
584 let mut available_lifetimes = vec![];
587 Scope::Binder { lifetimes, s, .. } => {
588 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
589 hir::ParamName::Plain(ident) => Some(ident.name.to_string()),
594 Scope::Body { s, .. } => {
597 Scope::Elision { elide, s } => {
598 if let Elide::Exact(_) = elide {
599 return LifetimeScopeForPath::Elided;
604 Scope::ObjectLifetimeDefault { s, .. } => {
608 return LifetimeScopeForPath::NonElided(available_lifetimes);
610 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
617 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
618 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
619 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
620 let mut scope = self.scope;
621 let mut supertrait_lifetimes = vec![];
624 Scope::Body { .. } | Scope::Root => {
625 break (vec![], BinderScopeType::Normal);
628 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
632 Scope::Supertrait { s, lifetimes } => {
633 supertrait_lifetimes = lifetimes.clone();
637 Scope::TraitRefBoundary { .. } => {
638 // We should only see super trait lifetimes if there is a `Binder` above
639 assert!(supertrait_lifetimes.is_empty());
640 break (vec![], BinderScopeType::Normal);
643 Scope::Binder { hir_id, .. } => {
644 // Nested poly trait refs have the binders concatenated
645 let mut full_binders =
646 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
647 full_binders.extend(supertrait_lifetimes.into_iter());
648 break (full_binders, BinderScopeType::Concatenating);
654 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
655 type NestedFilter = nested_filter::All;
657 fn nested_visit_map(&mut self) -> Self::Map {
661 // We want to nest trait/impl items in their parent, but nothing else.
662 fn visit_nested_item(&mut self, _: hir::ItemId) {}
664 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
665 if !self.trait_definition_only {
666 intravisit::walk_trait_item_ref(self, ii)
670 fn visit_nested_body(&mut self, body: hir::BodyId) {
671 // Each body has their own set of labels, save labels.
672 let saved = take(&mut self.labels_in_fn);
673 let body = self.tcx.hir().body(body);
674 extract_labels(self, body);
675 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
676 this.visit_body(body);
678 self.labels_in_fn = saved;
683 fk: intravisit::FnKind<'tcx>,
684 fd: &'tcx hir::FnDecl<'tcx>,
689 let name = match fk {
690 intravisit::FnKind::ItemFn(id, _, _, _) => id.name,
691 intravisit::FnKind::Method(id, _, _) => id.name,
692 intravisit::FnKind::Closure => sym::closure,
694 let name = name.as_str();
695 let span = span!(Level::DEBUG, "visit_fn", name);
696 let _enter = span.enter();
698 // Any `Binders` are handled elsewhere
699 intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
700 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
702 intravisit::FnKind::Closure => {
703 self.map.late_bound_vars.insert(hir_id, vec![]);
704 let scope = Scope::Binder {
706 lifetimes: FxIndexMap::default(),
707 next_early_index: self.next_early_index(),
709 track_lifetime_uses: true,
710 opaque_type_parent: false,
711 scope_type: BinderScopeType::Normal,
713 self.with(scope, move |_old_scope, this| {
714 intravisit::walk_fn(this, fk, fd, b, s, hir_id)
720 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
722 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
723 if let Some(of_trait) = of_trait {
724 self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
730 hir::ItemKind::Fn(ref sig, ref generics, _) => {
731 self.missing_named_lifetime_spots.push(generics.into());
732 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
733 intravisit::walk_item(this, item);
735 self.missing_named_lifetime_spots.pop();
738 hir::ItemKind::ExternCrate(_)
739 | hir::ItemKind::Use(..)
740 | hir::ItemKind::Macro(..)
741 | hir::ItemKind::Mod(..)
742 | hir::ItemKind::ForeignMod { .. }
743 | hir::ItemKind::GlobalAsm(..) => {
744 // These sorts of items have no lifetime parameters at all.
745 intravisit::walk_item(self, item);
747 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
748 // No lifetime parameters, but implied 'static.
749 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
750 self.with(scope, |_, this| intravisit::walk_item(this, item));
752 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
753 // Opaque types are visited when we visit the
754 // `TyKind::OpaqueDef`, so that they have the lifetimes from
755 // their parent opaque_ty in scope.
757 // The core idea here is that since OpaqueTys are generated with the impl Trait as
758 // their owner, we can keep going until we find the Item that owns that. We then
759 // conservatively add all resolved lifetimes. Otherwise we run into problems in
760 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
761 for (_hir_id, node) in
762 self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
765 hir::Node::Item(parent_item) => {
766 let resolved_lifetimes: &ResolveLifetimes =
767 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
768 // We need to add *all* deps, since opaque tys may want them from *us*
769 for (&owner, defs) in resolved_lifetimes.defs.iter() {
770 defs.iter().for_each(|(&local_id, region)| {
771 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
774 for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
775 late_bound.iter().for_each(|&local_id| {
776 self.map.late_bound.insert(hir::HirId { owner, local_id });
779 for (&owner, late_bound_vars) in
780 resolved_lifetimes.late_bound_vars.iter()
782 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
783 self.map.late_bound_vars.insert(
784 hir::HirId { owner, local_id },
785 late_bound_vars.clone(),
791 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
796 hir::ItemKind::TyAlias(_, ref generics)
797 | hir::ItemKind::Enum(_, ref generics)
798 | hir::ItemKind::Struct(_, ref generics)
799 | hir::ItemKind::Union(_, ref generics)
800 | hir::ItemKind::Trait(_, _, ref generics, ..)
801 | hir::ItemKind::TraitAlias(ref generics, ..)
802 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
803 self.missing_named_lifetime_spots.push(generics.into());
805 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
806 // This is not true for other kinds of items.
807 let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
808 // These kinds of items have only early-bound lifetime parameters.
809 let mut index = if sub_items_have_self_param(&item.kind) {
810 1 // Self comes before lifetimes
814 let mut non_lifetime_count = 0;
815 let lifetimes = generics
818 .filter_map(|param| match param.kind {
819 GenericParamKind::Lifetime { .. } => {
820 Some(Region::early(&self.tcx.hir(), &mut index, param))
822 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
823 non_lifetime_count += 1;
828 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
829 let scope = Scope::Binder {
830 hir_id: item.hir_id(),
832 next_early_index: index + non_lifetime_count,
833 opaque_type_parent: true,
835 scope_type: BinderScopeType::Normal,
838 self.with(scope, |old_scope, this| {
839 this.check_lifetime_params(old_scope, &generics.params);
840 let scope = Scope::TraitRefBoundary { s: this.scope };
841 this.with(scope, |_, this| {
842 intravisit::walk_item(this, item);
845 self.missing_named_lifetime_spots.pop();
850 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
852 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
853 self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
854 intravisit::walk_foreign_item(this, item);
857 hir::ForeignItemKind::Static(..) => {
858 intravisit::walk_foreign_item(self, item);
860 hir::ForeignItemKind::Type => {
861 intravisit::walk_foreign_item(self, item);
866 #[tracing::instrument(level = "debug", skip(self))]
867 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
869 hir::TyKind::BareFn(ref c) => {
870 let next_early_index = self.next_early_index();
871 let was_in_fn_syntax = self.is_in_fn_syntax;
872 self.is_in_fn_syntax = true;
873 let lifetime_span: Option<Span> =
874 c.generic_params.iter().rev().find_map(|param| match param.kind {
875 GenericParamKind::Lifetime { .. } => Some(param.span),
878 let (span, span_type) = if let Some(span) = lifetime_span {
879 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
881 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
883 self.missing_named_lifetime_spots
884 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
885 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
888 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
890 .map(|(late_bound_idx, param)| {
891 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
892 let r = late_region_as_bound_region(self.tcx, &pair.1);
896 self.map.late_bound_vars.insert(ty.hir_id, binders);
897 let scope = Scope::Binder {
902 track_lifetime_uses: true,
903 opaque_type_parent: false,
904 scope_type: BinderScopeType::Normal,
906 self.with(scope, |old_scope, this| {
907 // a bare fn has no bounds, so everything
908 // contained within is scoped within its binder.
909 this.check_lifetime_params(old_scope, &c.generic_params);
910 intravisit::walk_ty(this, ty);
912 self.missing_named_lifetime_spots.pop();
913 self.is_in_fn_syntax = was_in_fn_syntax;
915 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
916 debug!(?bounds, ?lifetime, "TraitObject");
917 let scope = Scope::TraitRefBoundary { s: self.scope };
918 self.with(scope, |_, this| {
919 for bound in bounds {
920 this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
923 match lifetime.name {
924 LifetimeName::Implicit(_) => {
925 // For types like `dyn Foo`, we should
926 // generate a special form of elided.
927 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
929 LifetimeName::ImplicitObjectLifetimeDefault => {
930 // If the user does not write *anything*, we
931 // use the object lifetime defaulting
932 // rules. So e.g., `Box<dyn Debug>` becomes
933 // `Box<dyn Debug + 'static>`.
934 self.resolve_object_lifetime_default(lifetime)
936 LifetimeName::Underscore => {
937 // If the user writes `'_`, we use the *ordinary* elision
938 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
939 // resolved the same as the `'_` in `&'_ Foo`.
942 self.resolve_elided_lifetimes(&[lifetime])
944 LifetimeName::Param(_) | LifetimeName::Static => {
945 // If the user wrote an explicit name, use that.
946 self.visit_lifetime(lifetime);
948 LifetimeName::Error => {}
951 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
952 self.visit_lifetime(lifetime_ref);
953 let scope = Scope::ObjectLifetimeDefault {
954 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
957 self.with(scope, |_, this| this.visit_ty(&mt.ty));
959 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
960 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
961 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
962 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
963 // ^ ^ this gets resolved in the scope of
964 // the opaque_ty generics
965 let opaque_ty = self.tcx.hir().item(item_id);
966 let (generics, bounds) = match opaque_ty.kind {
967 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
968 // This arm is for `impl Trait` in the types of statics, constants and locals.
969 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
970 origin: hir::OpaqueTyOrigin::TyAlias,
973 intravisit::walk_ty(self, ty);
975 // Elided lifetimes are not allowed in non-return
976 // position impl Trait
977 let scope = Scope::TraitRefBoundary { s: self.scope };
978 self.with(scope, |_, this| {
979 let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
980 this.with(scope, |_, this| {
981 intravisit::walk_item(this, opaque_ty);
987 // RPIT (return position impl trait)
988 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
989 origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
993 }) => (generics, bounds),
994 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
997 // Resolve the lifetimes that are applied to the opaque type.
998 // These are resolved in the current scope.
999 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
1000 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
1001 // ^ ^this gets resolved in the current scope
1002 for lifetime in lifetimes {
1003 let hir::GenericArg::Lifetime(lifetime) = lifetime else {
1006 self.visit_lifetime(lifetime);
1008 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1009 // and ban them. Type variables instantiated inside binders aren't
1010 // well-supported at the moment, so this doesn't work.
1011 // In the future, this should be fixed and this error should be removed.
1012 let def = self.map.defs.get(&lifetime.hir_id).cloned();
1013 let Some(Region::LateBound(_, _, def_id, _)) = def else {
1016 let Some(def_id) = def_id.as_local() else {
1019 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1020 // Ensure that the parent of the def is an item, not HRTB
1021 let parent_id = self.tcx.hir().get_parent_node(hir_id);
1022 // FIXME(cjgillot) Can this check be replaced by
1023 // `let parent_is_item = parent_id.is_owner();`?
1024 let parent_is_item = if let Some(parent_def_id) = parent_id.as_owner() {
1025 matches!(self.tcx.hir().krate().owners.get(parent_def_id), Some(Some(_)),)
1030 if !parent_is_item {
1031 if !self.trait_definition_only {
1036 "`impl Trait` can only capture lifetimes \
1037 bound at the fn or impl level"
1041 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1045 // We want to start our early-bound indices at the end of the parent scope,
1046 // not including any parent `impl Trait`s.
1047 let mut index = self.next_early_index_for_opaque_type();
1050 let mut elision = None;
1051 let mut lifetimes = FxIndexMap::default();
1052 let mut non_lifetime_count = 0;
1053 for param in generics.params {
1055 GenericParamKind::Lifetime { .. } => {
1056 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
1057 let Region::EarlyBound(_, def_id, _) = reg else {
1060 // We cannot predict what lifetimes are unused in opaque type.
1061 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
1062 if let hir::ParamName::Plain(Ident {
1063 name: kw::UnderscoreLifetime,
1067 // Pick the elided lifetime "definition" if one exists
1068 // and use it to make an elision scope.
1069 elision = Some(reg);
1071 lifetimes.insert(name, reg);
1074 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1075 non_lifetime_count += 1;
1079 let next_early_index = index + non_lifetime_count;
1080 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1082 if let Some(elision_region) = elision {
1084 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1085 self.with(scope, |_old_scope, this| {
1086 let scope = Scope::Binder {
1091 track_lifetime_uses: true,
1092 opaque_type_parent: false,
1093 scope_type: BinderScopeType::Normal,
1095 this.with(scope, |_old_scope, this| {
1096 this.visit_generics(generics);
1097 let scope = Scope::TraitRefBoundary { s: this.scope };
1098 this.with(scope, |_, this| {
1099 for bound in bounds {
1100 this.visit_param_bound(bound);
1106 let scope = Scope::Binder {
1111 track_lifetime_uses: true,
1112 opaque_type_parent: false,
1113 scope_type: BinderScopeType::Normal,
1115 self.with(scope, |_old_scope, this| {
1116 let scope = Scope::TraitRefBoundary { s: this.scope };
1117 this.with(scope, |_, this| {
1118 this.visit_generics(generics);
1119 for bound in bounds {
1120 this.visit_param_bound(bound);
1126 _ => intravisit::walk_ty(self, ty),
1130 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1131 use self::hir::TraitItemKind::*;
1132 match trait_item.kind {
1134 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1136 self.visit_early_late(
1137 Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1138 trait_item.hir_id(),
1140 &trait_item.generics,
1141 |this| intravisit::walk_trait_item(this, trait_item),
1143 self.missing_named_lifetime_spots.pop();
1145 Type(bounds, ref ty) => {
1146 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1147 let generics = &trait_item.generics;
1148 let mut index = self.next_early_index();
1149 debug!("visit_ty: index = {}", index);
1150 let mut non_lifetime_count = 0;
1151 let lifetimes = generics
1154 .filter_map(|param| match param.kind {
1155 GenericParamKind::Lifetime { .. } => {
1156 Some(Region::early(&self.tcx.hir(), &mut index, param))
1158 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1159 non_lifetime_count += 1;
1164 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1165 let scope = Scope::Binder {
1166 hir_id: trait_item.hir_id(),
1168 next_early_index: index + non_lifetime_count,
1170 track_lifetime_uses: true,
1171 opaque_type_parent: true,
1172 scope_type: BinderScopeType::Normal,
1174 self.with(scope, |old_scope, this| {
1175 this.check_lifetime_params(old_scope, &generics.params);
1176 let scope = Scope::TraitRefBoundary { s: this.scope };
1177 this.with(scope, |_, this| {
1178 this.visit_generics(generics);
1179 for bound in bounds {
1180 this.visit_param_bound(bound);
1182 if let Some(ty) = ty {
1187 self.missing_named_lifetime_spots.pop();
1190 // Only methods and types support generics.
1191 assert!(trait_item.generics.params.is_empty());
1192 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1193 intravisit::walk_trait_item(self, trait_item);
1194 self.missing_named_lifetime_spots.pop();
1199 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1200 use self::hir::ImplItemKind::*;
1201 match impl_item.kind {
1203 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1205 self.visit_early_late(
1206 Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1209 &impl_item.generics,
1210 |this| intravisit::walk_impl_item(this, impl_item),
1212 self.missing_named_lifetime_spots.pop();
1214 TyAlias(ref ty) => {
1215 let generics = &impl_item.generics;
1216 self.missing_named_lifetime_spots.push(generics.into());
1217 let mut index = self.next_early_index();
1218 let mut non_lifetime_count = 0;
1219 debug!("visit_ty: index = {}", index);
1220 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1223 .filter_map(|param| match param.kind {
1224 GenericParamKind::Lifetime { .. } => {
1225 Some(Region::early(&self.tcx.hir(), &mut index, param))
1227 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1228 non_lifetime_count += 1;
1233 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1234 let scope = Scope::Binder {
1237 next_early_index: index + non_lifetime_count,
1239 track_lifetime_uses: true,
1240 opaque_type_parent: true,
1241 scope_type: BinderScopeType::Normal,
1243 self.with(scope, |old_scope, this| {
1244 this.check_lifetime_params(old_scope, &generics.params);
1245 let scope = Scope::TraitRefBoundary { s: this.scope };
1246 this.with(scope, |_, this| {
1247 this.visit_generics(generics);
1251 self.missing_named_lifetime_spots.pop();
1254 // Only methods and types support generics.
1255 assert!(impl_item.generics.params.is_empty());
1256 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1257 intravisit::walk_impl_item(self, impl_item);
1258 self.missing_named_lifetime_spots.pop();
1263 #[tracing::instrument(level = "debug", skip(self))]
1264 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1265 if lifetime_ref.is_elided() {
1266 self.resolve_elided_lifetimes(&[lifetime_ref]);
1269 if lifetime_ref.is_static() {
1270 self.insert_lifetime(lifetime_ref, Region::Static);
1273 if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
1274 self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
1277 self.resolve_lifetime_ref(lifetime_ref);
1280 fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1281 let scope = self.scope;
1282 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1283 // We add lifetime scope information for `Ident`s in associated type bindings and use
1284 // the `HirId` of the type binding as the key in `LifetimeMap`
1285 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1286 let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1287 map.insert(type_binding.hir_id.local_id, lifetime_scope);
1289 hir::intravisit::walk_assoc_type_binding(self, type_binding);
1292 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1293 for (i, segment) in path.segments.iter().enumerate() {
1294 let depth = path.segments.len() - i - 1;
1295 if let Some(ref args) = segment.args {
1296 self.visit_segment_args(path.res, depth, args);
1299 let scope = self.scope;
1300 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1301 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1302 // here because that call would yield to resolution problems due to `walk_path_segment`
1303 // being called, which processes the path segments generic args, which we have already
1304 // processed using `visit_segment_args`.
1305 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1306 if let Some(hir_id) = segment.hir_id {
1307 let map = scope_for_path.entry(hir_id.owner).or_default();
1308 map.insert(hir_id.local_id, lifetime_scope);
1314 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1315 let scope = self.scope;
1316 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1317 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1318 if let Some(hir_id) = path_segment.hir_id {
1319 let map = scope_for_path.entry(hir_id.owner).or_default();
1320 map.insert(hir_id.local_id, lifetime_scope);
1324 intravisit::walk_path_segment(self, path_span, path_segment);
1327 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1328 let output = match fd.output {
1329 hir::FnRetTy::DefaultReturn(_) => None,
1330 hir::FnRetTy::Return(ref ty) => Some(&**ty),
1332 self.visit_fn_like_elision(&fd.inputs, output);
1335 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1336 if !self.trait_definition_only {
1337 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
1339 let scope = Scope::TraitRefBoundary { s: self.scope };
1340 self.with(scope, |_, this| {
1341 for param in generics.params {
1343 GenericParamKind::Lifetime { .. } => {}
1344 GenericParamKind::Type { ref default, .. } => {
1345 walk_list!(this, visit_param_bound, param.bounds);
1346 if let Some(ref ty) = default {
1350 GenericParamKind::Const { ref ty, .. } => {
1351 let was_in_const_generic = this.is_in_const_generic;
1352 this.is_in_const_generic = true;
1353 walk_list!(this, visit_param_bound, param.bounds);
1355 this.is_in_const_generic = was_in_const_generic;
1359 for predicate in generics.where_clause.predicates {
1361 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1364 ref bound_generic_params,
1367 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1368 bound_generic_params
1371 matches!(param.kind, GenericParamKind::Lifetime { .. })
1374 .map(|(late_bound_idx, param)| {
1376 Region::late(late_bound_idx as u32, &this.tcx.hir(), param);
1377 let r = late_region_as_bound_region(this.tcx, &pair.1);
1381 this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1382 let next_early_index = this.next_early_index();
1383 // Even if there are no lifetimes defined here, we still wrap it in a binder
1384 // scope. If there happens to be a nested poly trait ref (an error), that
1385 // will be `Concatenating` anyways, so we don't have to worry about the depth
1387 let scope = Scope::Binder {
1388 hir_id: bounded_ty.hir_id,
1392 track_lifetime_uses: true,
1393 opaque_type_parent: false,
1394 scope_type: BinderScopeType::Normal,
1396 this.with(scope, |old_scope, this| {
1397 this.check_lifetime_params(old_scope, &bound_generic_params);
1398 this.visit_ty(&bounded_ty);
1399 walk_list!(this, visit_param_bound, bounds);
1402 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1407 this.visit_lifetime(lifetime);
1408 walk_list!(this, visit_param_bound, bounds);
1410 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1415 this.visit_ty(lhs_ty);
1416 this.visit_ty(rhs_ty);
1423 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1425 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1426 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1427 // through the regular poly trait ref code, so we don't get another
1428 // chance to introduce a binder. For now, I'm keeping the existing logic
1429 // of "if there isn't a Binder scope above us, add one", but I
1430 // imagine there's a better way to go about this.
1431 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1433 self.map.late_bound_vars.insert(*hir_id, binders);
1434 let scope = Scope::Binder {
1436 lifetimes: FxIndexMap::default(),
1438 next_early_index: self.next_early_index(),
1439 track_lifetime_uses: true,
1440 opaque_type_parent: false,
1443 self.with(scope, |_, this| {
1444 intravisit::walk_param_bound(this, bound);
1447 _ => intravisit::walk_param_bound(self, bound),
1451 fn visit_poly_trait_ref(
1453 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1454 _modifier: hir::TraitBoundModifier,
1456 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1458 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1460 let next_early_index = self.next_early_index();
1461 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1463 let initial_bound_vars = binders.len() as u32;
1464 let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1465 let binders_iter = trait_ref
1466 .bound_generic_params
1468 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1470 .map(|(late_bound_idx, param)| {
1471 let pair = Region::late(
1472 initial_bound_vars + late_bound_idx as u32,
1476 let r = late_region_as_bound_region(self.tcx, &pair.1);
1477 lifetimes.insert(pair.0, pair.1);
1480 binders.extend(binders_iter);
1483 self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1485 // Always introduce a scope here, even if this is in a where clause and
1486 // we introduced the binders around the bounded Ty. In that case, we
1487 // just reuse the concatenation functionality also present in nested trait
1489 let scope = Scope::Binder {
1490 hir_id: trait_ref.trait_ref.hir_ref_id,
1494 track_lifetime_uses: true,
1495 opaque_type_parent: false,
1498 self.with(scope, |old_scope, this| {
1499 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1500 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1501 this.visit_trait_ref(&trait_ref.trait_ref);
1504 if should_pop_missing_lt {
1505 self.missing_named_lifetime_spots.pop();
1510 #[derive(Copy, Clone, PartialEq)]
1524 fn original_label(span: Span) -> Original {
1525 Original { kind: ShadowKind::Label, span }
1527 fn shadower_label(span: Span) -> Shadower {
1528 Shadower { kind: ShadowKind::Label, span }
1530 fn original_lifetime(span: Span) -> Original {
1531 Original { kind: ShadowKind::Lifetime, span }
1533 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1534 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1538 fn desc(&self) -> &'static str {
1540 ShadowKind::Label => "label",
1541 ShadowKind::Lifetime => "lifetime",
1546 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1547 let lifetime_params: Vec<_> = params
1549 .filter_map(|param| match param.kind {
1550 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1554 let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1555 let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1557 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1562 "cannot mix in-band and explicit lifetime definitions"
1564 .span_label(*in_band_span, "in-band lifetime definition here")
1565 .span_label(*explicit_span, "explicit lifetime definition here")
1570 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1571 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1572 // lifetime/lifetime shadowing is an error
1577 "{} name `{}` shadows a \
1578 {} name that is already in scope",
1579 shadower.kind.desc(),
1584 // shadowing involving a label is only a warning, due to issues with
1585 // labels and lifetimes not being macro-hygienic.
1586 tcx.sess.struct_span_warn(
1589 "{} name `{}` shadows a \
1590 {} name that is already in scope",
1591 shadower.kind.desc(),
1597 err.span_label(orig.span, "first declared here");
1598 err.span_label(shadower.span, format!("{} `{}` already in scope", orig.kind.desc(), name));
1602 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1603 // if one of the label shadows a lifetime or another label.
1604 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1605 struct GatherLabels<'a, 'tcx> {
1607 scope: ScopeRef<'a>,
1608 labels_in_fn: &'a mut Vec<Ident>,
1612 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1613 gather.visit_body(body);
1615 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1616 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1617 if let Some(label) = expression_label(ex) {
1618 for prior_label in &self.labels_in_fn[..] {
1619 // FIXME (#24278): non-hygienic comparison
1620 if label.name == prior_label.name {
1621 signal_shadowing_problem(
1624 original_label(prior_label.span),
1625 shadower_label(label.span),
1630 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1632 self.labels_in_fn.push(label);
1634 intravisit::walk_expr(self, ex)
1638 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1640 hir::ExprKind::Loop(_, Some(label), ..) => Some(label.ident),
1641 hir::ExprKind::Block(_, Some(label)) => Some(label.ident),
1646 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1649 Scope::Body { s, .. }
1650 | Scope::Elision { s, .. }
1651 | Scope::ObjectLifetimeDefault { s, .. }
1652 | Scope::Supertrait { s, .. }
1653 | Scope::TraitRefBoundary { s, .. } => {
1661 Scope::Binder { ref lifetimes, s, .. } => {
1662 // FIXME (#24278): non-hygienic comparison
1664 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1666 signal_shadowing_problem(
1669 original_lifetime(tcx.def_span(def.id().unwrap().expect_local())),
1670 shadower_label(label.span),
1681 fn compute_object_lifetime_defaults(
1683 item: &hir::Item<'_>,
1684 ) -> Option<Vec<ObjectLifetimeDefault>> {
1686 hir::ItemKind::Struct(_, ref generics)
1687 | hir::ItemKind::Union(_, ref generics)
1688 | hir::ItemKind::Enum(_, ref generics)
1689 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1691 origin: hir::OpaqueTyOrigin::TyAlias,
1694 | hir::ItemKind::TyAlias(_, ref generics)
1695 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1696 let result = object_lifetime_defaults_for_item(tcx, generics);
1699 let attrs = tcx.hir().attrs(item.hir_id());
1700 if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1701 let object_lifetime_default_reprs: String = result
1703 .map(|set| match *set {
1704 Set1::Empty => "BaseDefault".into(),
1705 Set1::One(Region::Static) => "'static".into(),
1706 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1709 .find_map(|param| match param.kind {
1710 GenericParamKind::Lifetime { .. } => {
1712 return Some(param.name.ident().to_string().into());
1720 Set1::One(_) => bug!(),
1721 Set1::Many => "Ambiguous".into(),
1723 .collect::<Vec<Cow<'static, str>>>()
1725 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1734 /// Scan the bounds and where-clauses on parameters to extract bounds
1735 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1736 /// for each type parameter.
1737 fn object_lifetime_defaults_for_item(
1739 generics: &hir::Generics<'_>,
1740 ) -> Vec<ObjectLifetimeDefault> {
1741 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1742 for bound in bounds {
1743 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1744 set.insert(lifetime.name.normalize_to_macros_2_0());
1752 .filter_map(|param| match param.kind {
1753 GenericParamKind::Lifetime { .. } => None,
1754 GenericParamKind::Type { .. } => {
1755 let mut set = Set1::Empty;
1757 add_bounds(&mut set, ¶m.bounds);
1759 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1760 for predicate in generics.where_clause.predicates {
1761 // Look for `type: ...` where clauses.
1762 let data = match *predicate {
1763 hir::WherePredicate::BoundPredicate(ref data) => data,
1767 // Ignore `for<'a> type: ...` as they can change what
1768 // lifetimes mean (although we could "just" handle it).
1769 if !data.bound_generic_params.is_empty() {
1773 let res = match data.bounded_ty.kind {
1774 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1778 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1779 add_bounds(&mut set, &data.bounds);
1784 Set1::Empty => Set1::Empty,
1785 Set1::One(name) => {
1786 if name == hir::LifetimeName::Static {
1787 Set1::One(Region::Static)
1792 .filter_map(|param| match param.kind {
1793 GenericParamKind::Lifetime { .. } => Some((
1795 hir::LifetimeName::Param(param.name),
1796 LifetimeDefOrigin::from_param(param),
1801 .find(|&(_, (_, lt_name, _))| lt_name == name)
1802 .map_or(Set1::Many, |(i, (id, _, origin))| {
1803 let def_id = tcx.hir().local_def_id(id);
1804 Set1::One(Region::EarlyBound(
1812 Set1::Many => Set1::Many,
1815 GenericParamKind::Const { .. } => {
1816 // Generic consts don't impose any constraints.
1818 // We still store a dummy value here to allow generic parameters
1819 // in an arbitrary order.
1826 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1827 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1829 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1831 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1832 let labels_in_fn = take(&mut self.labels_in_fn);
1833 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1834 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1835 let mut this = LifetimeContext {
1839 is_in_fn_syntax: self.is_in_fn_syntax,
1840 is_in_const_generic: self.is_in_const_generic,
1841 trait_definition_only: self.trait_definition_only,
1843 xcrate_object_lifetime_defaults,
1845 missing_named_lifetime_spots,
1847 let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1849 let _enter = span.enter();
1850 f(self.scope, &mut this);
1851 if !self.trait_definition_only {
1852 this.check_uses_for_lifetimes_defined_by_scope();
1855 self.labels_in_fn = this.labels_in_fn;
1856 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1857 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1860 /// helper method to determine the span to remove when suggesting the
1861 /// deletion of a lifetime
1862 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1863 generics.params.iter().enumerate().find_map(|(i, param)| {
1864 if param.name.ident() == name {
1865 let in_band = matches!(
1867 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::InBand }
1871 } else if generics.params.len() == 1 {
1872 // if sole lifetime, remove the entire `<>` brackets
1875 // if removing within `<>` brackets, we also want to
1876 // delete a leading or trailing comma as appropriate
1877 if i >= generics.params.len() - 1 {
1878 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1880 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1889 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1890 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1891 fn suggest_eliding_single_use_lifetime(
1893 err: &mut DiagnosticBuilder<'_>,
1895 lifetime: &hir::Lifetime,
1897 let name = lifetime.name.ident();
1898 let remove_decl = self
1901 .and_then(|parent_def_id| parent_def_id.as_local())
1902 .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id))
1903 .and_then(|generics| self.lifetime_deletion_span(name, generics));
1905 let mut remove_use = None;
1906 let mut elide_use = None;
1907 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1908 for input in inputs {
1910 hir::TyKind::Rptr(lt, _) => {
1911 if lt.name.ident() == name {
1912 // include the trailing whitespace between the lifetime and type names
1913 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1918 .span_until_non_whitespace(lt_through_ty_span),
1923 hir::TyKind::Path(QPath::Resolved(_, path)) => {
1924 let last_segment = &path.segments[path.segments.len() - 1];
1925 let generics = last_segment.args();
1926 for arg in generics.args.iter() {
1927 if let GenericArg::Lifetime(lt) = arg {
1928 if lt.name.ident() == name {
1929 elide_use = Some(lt.span);
1940 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1941 if let Some(parent) =
1942 self.tcx.hir().find_by_def_id(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1945 Node::Item(item) => {
1946 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1947 find_arg_use_span(sig.decl.inputs);
1950 Node::ImplItem(impl_item) => {
1951 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1952 find_arg_use_span(sig.decl.inputs);
1960 let msg = "elide the single-use lifetime";
1961 match (remove_decl, remove_use, elide_use) {
1962 (Some(decl_span), Some(use_span), None) => {
1963 // if both declaration and use deletion spans start at the same
1964 // place ("start at" because the latter includes trailing
1965 // whitespace), then this is an in-band lifetime
1966 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1967 err.span_suggestion(
1971 Applicability::MachineApplicable,
1974 err.multipart_suggestion(
1976 vec![(decl_span, String::new()), (use_span, String::new())],
1977 Applicability::MachineApplicable,
1981 (Some(decl_span), None, Some(use_span)) => {
1982 err.multipart_suggestion(
1984 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1985 Applicability::MachineApplicable,
1992 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1993 let defined_by = match self.scope {
1994 Scope::Binder { lifetimes, .. } => lifetimes,
1996 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
2001 let def_ids: Vec<_> = defined_by
2003 .flat_map(|region| match region {
2004 Region::EarlyBound(_, def_id, _)
2005 | Region::LateBound(_, _, def_id, _)
2006 | Region::Free(_, def_id) => Some(*def_id),
2008 Region::LateBoundAnon(..) | Region::Static => None,
2012 'lifetimes: for def_id in def_ids {
2013 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
2015 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
2018 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
2022 match lifetimeuseset {
2023 Some(LifetimeUseSet::One(lifetime)) => {
2025 if let Some((id, span, name)) =
2026 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
2027 Node::Lifetime(hir_lifetime) => Some((
2028 hir_lifetime.hir_id,
2030 hir_lifetime.name.ident(),
2032 Node::GenericParam(param) => {
2033 Some((param.hir_id, param.span, param.name.ident()))
2038 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
2039 if name.name == kw::UnderscoreLifetime {
2043 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2044 if let Some(def_id) = parent_def_id.as_local() {
2045 // lifetimes in `derive` expansions don't count (Issue #53738)
2048 .get_attrs(def_id.to_def_id())
2050 .any(|attr| attr.has_name(sym::automatically_derived))
2055 // opaque types generated when desugaring an async function can have a single
2056 // use lifetime even if it is explicitly denied (Issue #77175)
2057 if let hir::Node::Item(hir::Item {
2058 kind: hir::ItemKind::OpaqueTy(ref opaque),
2060 }) = self.tcx.hir().get_by_def_id(def_id)
2062 if !matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn(..)) {
2063 continue 'lifetimes;
2065 // We want to do this only if the liftime identifier is already defined
2066 // in the async function that generated this. Otherwise it could be
2067 // an opaque type defined by the developer and we still want this
2068 // lint to fail compilation
2069 for p in opaque.generics.params {
2070 if defined_by.contains_key(&p.name) {
2071 continue 'lifetimes;
2078 self.tcx.struct_span_lint_hir(
2079 lint::builtin::SINGLE_USE_LIFETIMES,
2083 let mut err = lint.build(&format!(
2084 "lifetime parameter `{}` only used once",
2087 if span == lifetime.span {
2088 // spans are the same for in-band lifetime declarations
2089 err.span_label(span, "this lifetime is only used here");
2091 err.span_label(span, "this lifetime...");
2092 err.span_label(lifetime.span, "...is used only here");
2094 self.suggest_eliding_single_use_lifetime(
2095 &mut err, def_id, lifetime,
2102 Some(LifetimeUseSet::Many) => {
2103 debug!("not one use lifetime");
2106 if let Some((id, span, name)) =
2107 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
2108 Node::Lifetime(hir_lifetime) => Some((
2109 hir_lifetime.hir_id,
2111 hir_lifetime.name.ident(),
2113 Node::GenericParam(param) => {
2114 Some((param.hir_id, param.span, param.name.ident()))
2119 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
2120 self.tcx.struct_span_lint_hir(
2121 lint::builtin::UNUSED_LIFETIMES,
2126 .build(&format!("lifetime parameter `{}` never used", name));
2127 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2128 if let Some(generics) =
2129 self.tcx.hir().get_generics(parent_def_id.expect_local())
2131 let unused_lt_span =
2132 self.lifetime_deletion_span(name, generics);
2133 if let Some(span) = unused_lt_span {
2134 err.span_suggestion(
2136 "elide the unused lifetime",
2138 Applicability::MachineApplicable,
2152 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
2154 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
2155 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
2156 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
2160 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
2162 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
2163 /// lifetimes may be interspersed together.
2165 /// If early bound lifetimes are present, we separate them into their own list (and likewise
2166 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
2167 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
2168 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
2169 /// ordering is not important there.
2170 fn visit_early_late<F>(
2172 parent_id: Option<LocalDefId>,
2174 decl: &'tcx hir::FnDecl<'tcx>,
2175 generics: &'tcx hir::Generics<'tcx>,
2178 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
2180 insert_late_bound_lifetimes(self.map, decl, generics);
2182 // Find the start of nested early scopes, e.g., in methods.
2183 let mut next_early_index = 0;
2184 if let Some(parent_id) = parent_id {
2185 let parent = self.tcx.hir().expect_item(parent_id);
2186 if sub_items_have_self_param(&parent.kind) {
2187 next_early_index += 1; // Self comes before lifetimes
2190 hir::ItemKind::Trait(_, _, ref generics, ..)
2191 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
2192 next_early_index += generics.params.len() as u32;
2198 let mut non_lifetime_count = 0;
2199 let mut named_late_bound_vars = 0;
2200 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
2203 .filter_map(|param| match param.kind {
2204 GenericParamKind::Lifetime { .. } => {
2205 if self.map.late_bound.contains(¶m.hir_id) {
2206 let late_bound_idx = named_late_bound_vars;
2207 named_late_bound_vars += 1;
2208 Some(Region::late(late_bound_idx, &self.tcx.hir(), param))
2210 Some(Region::early(&self.tcx.hir(), &mut next_early_index, param))
2213 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
2214 non_lifetime_count += 1;
2219 let next_early_index = next_early_index + non_lifetime_count;
2221 let binders: Vec<_> = generics
2225 matches!(param.kind, GenericParamKind::Lifetime { .. })
2226 && self.map.late_bound.contains(¶m.hir_id)
2229 .map(|(late_bound_idx, param)| {
2230 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
2231 late_region_as_bound_region(self.tcx, &pair.1)
2234 self.map.late_bound_vars.insert(hir_id, binders);
2235 let scope = Scope::Binder {
2240 opaque_type_parent: true,
2241 track_lifetime_uses: false,
2242 scope_type: BinderScopeType::Normal,
2244 self.with(scope, move |old_scope, this| {
2245 this.check_lifetime_params(old_scope, &generics.params);
2250 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
2251 let mut scope = self.scope;
2254 Scope::Root => return 0,
2256 Scope::Binder { next_early_index, opaque_type_parent, .. }
2257 if (!only_opaque_type_parent || opaque_type_parent) =>
2259 return next_early_index;
2262 Scope::Binder { s, .. }
2263 | Scope::Body { s, .. }
2264 | Scope::Elision { s, .. }
2265 | Scope::ObjectLifetimeDefault { s, .. }
2266 | Scope::Supertrait { s, .. }
2267 | Scope::TraitRefBoundary { s, .. } => scope = s,
2272 /// Returns the next index one would use for an early-bound-region
2273 /// if extending the current scope.
2274 fn next_early_index(&self) -> u32 {
2275 self.next_early_index_helper(true)
2278 /// Returns the next index one would use for an `impl Trait` that
2279 /// is being converted into an opaque type alias `impl Trait`. This will be the
2280 /// next early index from the enclosing item, for the most
2281 /// part. See the `opaque_type_parent` field for more info.
2282 fn next_early_index_for_opaque_type(&self) -> u32 {
2283 self.next_early_index_helper(false)
2286 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2287 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
2289 // If we've already reported an error, just ignore `lifetime_ref`.
2290 if let LifetimeName::Error = lifetime_ref.name {
2294 // Walk up the scope chain, tracking the number of fn scopes
2295 // that we pass through, until we find a lifetime with the
2296 // given name or we run out of scopes.
2298 let mut late_depth = 0;
2299 let mut scope = self.scope;
2300 let mut outermost_body = None;
2303 Scope::Body { id, s } => {
2304 // Non-static lifetimes are prohibited in anonymous constants without
2305 // `generic_const_exprs`.
2306 self.maybe_emit_forbidden_non_static_lifetime_error(id, lifetime_ref);
2308 outermost_body = Some(id);
2316 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
2317 match lifetime_ref.name {
2318 LifetimeName::Param(param_name) => {
2319 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
2321 break Some(def.shifted(late_depth));
2324 _ => bug!("expected LifetimeName::Param"),
2327 BinderScopeType::Normal => late_depth += 1,
2328 BinderScopeType::Concatenating => {}
2333 Scope::Elision { s, .. }
2334 | Scope::ObjectLifetimeDefault { s, .. }
2335 | Scope::Supertrait { s, .. }
2336 | Scope::TraitRefBoundary { s, .. } => {
2342 if let Some(mut def) = result {
2343 if let Region::EarlyBound(..) = def {
2344 // Do not free early-bound regions, only late-bound ones.
2345 } else if let Some(body_id) = outermost_body {
2346 let fn_id = self.tcx.hir().body_owner(body_id);
2347 match self.tcx.hir().get(fn_id) {
2348 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
2349 | Node::TraitItem(&hir::TraitItem {
2350 kind: hir::TraitItemKind::Fn(..), ..
2352 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
2353 let scope = self.tcx.hir().local_def_id(fn_id);
2354 def = Region::Free(scope.to_def_id(), def.id().unwrap());
2360 // Check for fn-syntax conflicts with in-band lifetime definitions
2361 if !self.trait_definition_only && self.is_in_fn_syntax {
2363 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
2364 | Region::LateBound(_, _, _, LifetimeDefOrigin::InBand) => {
2369 "lifetimes used in `fn` or `Fn` syntax must be \
2370 explicitly declared using `<...>` binders"
2372 .span_label(lifetime_ref.span, "in-band lifetime definition")
2377 | Region::EarlyBound(
2380 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2382 | Region::LateBound(
2386 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2388 | Region::LateBoundAnon(..)
2389 | Region::Free(..) => {}
2393 self.insert_lifetime(lifetime_ref, def);
2395 self.emit_undeclared_lifetime_error(lifetime_ref);
2399 fn visit_segment_args(
2403 generic_args: &'tcx hir::GenericArgs<'tcx>,
2406 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
2407 res, depth, generic_args,
2410 if generic_args.parenthesized {
2411 let was_in_fn_syntax = self.is_in_fn_syntax;
2412 self.is_in_fn_syntax = true;
2413 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
2414 self.is_in_fn_syntax = was_in_fn_syntax;
2418 let mut elide_lifetimes = true;
2419 let lifetimes: Vec<_> = generic_args
2422 .filter_map(|arg| match arg {
2423 hir::GenericArg::Lifetime(lt) => {
2424 if !lt.is_elided() {
2425 elide_lifetimes = false;
2432 // We short-circuit here if all are elided in order to pluralize
2434 if elide_lifetimes {
2435 self.resolve_elided_lifetimes(&lifetimes);
2437 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
2440 // Figure out if this is a type/trait segment,
2441 // which requires object lifetime defaults.
2442 let parent_def_id = |this: &mut Self, def_id: DefId| {
2443 let def_key = this.tcx.def_key(def_id);
2444 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
2446 let type_def_id = match res {
2447 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
2448 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
2456 ) if depth == 0 => Some(def_id),
2460 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
2462 // Compute a vector of defaults, one for each type parameter,
2463 // per the rules given in RFCs 599 and 1156. Example:
2466 // struct Foo<'a, T: 'a, U> { }
2469 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
2470 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
2471 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
2474 // Therefore, we would compute `object_lifetime_defaults` to a
2475 // vector like `['x, 'static]`. Note that the vector only
2476 // includes type parameters.
2477 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
2479 let mut scope = self.scope;
2482 Scope::Root => break false,
2484 Scope::Body { .. } => break true,
2486 Scope::Binder { s, .. }
2487 | Scope::Elision { s, .. }
2488 | Scope::ObjectLifetimeDefault { s, .. }
2489 | Scope::Supertrait { s, .. }
2490 | Scope::TraitRefBoundary { s, .. } => {
2497 let map = &self.map;
2498 let set_to_region = |set: &ObjectLifetimeDefault| match *set {
2503 Some(Region::Static)
2507 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2508 GenericArg::Lifetime(lt) => Some(lt),
2511 r.subst(lifetimes, map)
2515 if let Some(def_id) = def_id.as_local() {
2516 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2517 self.tcx.object_lifetime_defaults(id).unwrap().iter().map(set_to_region).collect()
2520 self.xcrate_object_lifetime_defaults
2522 .or_insert_with(|| {
2523 tcx.generics_of(def_id)
2526 .filter_map(|param| match param.kind {
2527 GenericParamDefKind::Type { object_lifetime_default, .. } => {
2528 Some(object_lifetime_default)
2530 GenericParamDefKind::Const { .. } => Some(Set1::Empty),
2531 GenericParamDefKind::Lifetime => None,
2541 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2544 for arg in generic_args.args {
2546 GenericArg::Lifetime(_) => {}
2547 GenericArg::Type(ty) => {
2548 if let Some(<) = object_lifetime_defaults.get(i) {
2549 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2550 self.with(scope, |_, this| this.visit_ty(ty));
2556 GenericArg::Const(ct) => {
2557 self.visit_anon_const(&ct.value);
2560 GenericArg::Infer(inf) => {
2561 self.visit_id(inf.hir_id);
2567 // Hack: when resolving the type `XX` in binding like `dyn
2568 // Foo<'b, Item = XX>`, the current object-lifetime default
2569 // would be to examine the trait `Foo` to check whether it has
2570 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2571 // declared like so, then the default object lifetime bound in
2572 // `XX` should be `'b`:
2580 // but if we just have `type Item;`, then it would be
2581 // `'static`. However, we don't get all of this logic correct.
2583 // Instead, we do something hacky: if there are no lifetime parameters
2584 // to the trait, then we simply use a default object lifetime
2585 // bound of `'static`, because there is no other possibility. On the other hand,
2586 // if there ARE lifetime parameters, then we require the user to give an
2587 // explicit bound for now.
2589 // This is intended to leave room for us to implement the
2590 // correct behavior in the future.
2591 let has_lifetime_parameter =
2592 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2594 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2595 // in the trait ref `YY<...>` in `Item: YY<...>`.
2596 for binding in generic_args.bindings {
2597 let scope = Scope::ObjectLifetimeDefault {
2598 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2601 if let Some(type_def_id) = type_def_id {
2602 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2607 self.with(scope, |_, this| {
2608 let scope = Scope::Supertrait {
2609 lifetimes: lifetimes.unwrap_or_default(),
2612 this.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2615 self.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2620 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2621 /// associated type name and starting trait.
2622 /// For example, imagine we have
2624 /// trait Foo<'a, 'b> {
2627 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2628 /// trait Bar: for<'b> Bar<'b> {}
2630 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2631 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2632 fn supertrait_hrtb_lifetimes(
2636 ) -> Option<Vec<ty::BoundVariableKind>> {
2637 let trait_defines_associated_type_named = |trait_def_id: DefId| {
2638 tcx.associated_items(trait_def_id)
2639 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2643 use smallvec::{smallvec, SmallVec};
2644 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2645 smallvec![(def_id, smallvec![])];
2646 let mut visited: FxHashSet<DefId> = FxHashSet::default();
2648 let (def_id, bound_vars) = match stack.pop() {
2652 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2653 // there being no supertrait HRTBs.
2654 match tcx.def_kind(def_id) {
2655 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2659 if trait_defines_associated_type_named(def_id) {
2660 break Some(bound_vars.into_iter().collect());
2663 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2664 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2665 let bound_predicate = pred.kind();
2666 match bound_predicate.skip_binder() {
2667 ty::PredicateKind::Trait(data) => {
2668 // The order here needs to match what we would get from `subst_supertrait`
2669 let pred_bound_vars = bound_predicate.bound_vars();
2670 let mut all_bound_vars = bound_vars.clone();
2671 all_bound_vars.extend(pred_bound_vars.iter());
2672 let super_def_id = data.trait_ref.def_id;
2673 Some((super_def_id, all_bound_vars))
2679 let obligations = obligations.filter(|o| visited.insert(o.0));
2680 stack.extend(obligations);
2684 #[tracing::instrument(level = "debug", skip(self))]
2685 fn visit_fn_like_elision(
2687 inputs: &'tcx [hir::Ty<'tcx>],
2688 output: Option<&'tcx hir::Ty<'tcx>>,
2690 debug!("visit_fn_like_elision: enter");
2691 let mut scope = &*self.scope;
2694 Scope::Binder { hir_id, .. } => {
2697 Scope::ObjectLifetimeDefault { ref s, .. }
2698 | Scope::Elision { ref s, .. }
2699 | Scope::Supertrait { ref s, .. }
2700 | Scope::TraitRefBoundary { ref s, .. } => {
2703 Scope::Root | Scope::Body { .. } => {
2704 // See issues #83907 and #83693. Just bail out from looking inside.
2705 self.tcx.sess.delay_span_bug(
2706 rustc_span::DUMMY_SP,
2707 "In fn_like_elision without appropriate scope above",
2713 // While not strictly necessary, we gather anon lifetimes *before* actually
2714 // visiting the argument types.
2715 let mut gather = GatherAnonLifetimes { anon_count: 0 };
2716 for input in inputs {
2717 gather.visit_ty(input);
2719 trace!(?gather.anon_count);
2720 let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2721 let named_late_bound_vars = late_bound_vars.len() as u32;
2722 late_bound_vars.extend(
2723 (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2725 let arg_scope = Scope::Elision {
2726 elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2729 self.with(arg_scope, |_, this| {
2730 for input in inputs {
2731 this.visit_ty(input);
2735 let output = match output {
2740 debug!("determine output");
2742 // Figure out if there's a body we can get argument names from,
2743 // and whether there's a `self` argument (treated specially).
2744 let mut assoc_item_kind = None;
2745 let mut impl_self = None;
2746 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2747 let body = match self.tcx.hir().get(parent) {
2748 // `fn` definitions and methods.
2749 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2751 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2752 if let hir::ItemKind::Trait(.., ref trait_items) =
2753 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2756 trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2759 hir::TraitFn::Required(_) => None,
2760 hir::TraitFn::Provided(body) => Some(body),
2764 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2765 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2766 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2768 impl_self = Some(self_ty);
2770 items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2775 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2776 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2777 // Everything else (only closures?) doesn't
2778 // actually enjoy elision in return types.
2780 self.visit_ty(output);
2785 let has_self = match assoc_item_kind {
2786 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2790 // In accordance with the rules for lifetime elision, we can determine
2791 // what region to use for elision in the output type in two ways.
2792 // First (determined here), if `self` is by-reference, then the
2793 // implied output region is the region of the self parameter.
2795 struct SelfVisitor<'a> {
2796 map: &'a NamedRegionMap,
2797 impl_self: Option<&'a hir::TyKind<'a>>,
2798 lifetime: Set1<Region>,
2801 impl SelfVisitor<'_> {
2802 // Look for `self: &'a Self` - also desugared from `&'a self`,
2803 // and if that matches, use it for elision and return early.
2804 fn is_self_ty(&self, res: Res) -> bool {
2805 if let Res::SelfTy(..) = res {
2809 // Can't always rely on literal (or implied) `Self` due
2810 // to the way elision rules were originally specified.
2811 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2815 // Permit the types that unambiguously always
2816 // result in the same type constructor being used
2817 // (it can't differ between `Self` and `self`).
2818 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2819 | Res::PrimTy(_) => return res == path.res,
2828 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2829 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2830 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2831 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2833 if self.is_self_ty(path.res) {
2834 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2835 self.lifetime.insert(*lifetime);
2840 intravisit::walk_ty(self, ty)
2844 let mut visitor = SelfVisitor {
2846 impl_self: impl_self.map(|ty| &ty.kind),
2847 lifetime: Set1::Empty,
2849 visitor.visit_ty(&inputs[0]);
2850 if let Set1::One(lifetime) = visitor.lifetime {
2851 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2852 self.with(scope, |_, this| this.visit_ty(output));
2857 // Second, if there was exactly one lifetime (either a substitution or a
2858 // reference) in the arguments, then any anonymous regions in the output
2859 // have that lifetime.
2860 let mut possible_implied_output_region = None;
2861 let mut lifetime_count = 0;
2862 let arg_lifetimes = inputs
2865 .skip(has_self as usize)
2867 let mut gather = GatherLifetimes {
2869 outer_index: ty::INNERMOST,
2870 have_bound_regions: false,
2871 lifetimes: Default::default(),
2873 gather.visit_ty(input);
2875 lifetime_count += gather.lifetimes.len();
2877 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2878 // there's a chance that the unique lifetime of this
2879 // iteration will be the appropriate lifetime for output
2880 // parameters, so lets store it.
2881 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2884 ElisionFailureInfo {
2887 lifetime_count: gather.lifetimes.len(),
2888 have_bound_regions: gather.have_bound_regions,
2894 let elide = if lifetime_count == 1 {
2895 Elide::Exact(possible_implied_output_region.unwrap())
2897 Elide::Error(arg_lifetimes)
2902 let scope = Scope::Elision { elide, s: self.scope };
2903 self.with(scope, |_, this| this.visit_ty(output));
2905 struct GatherLifetimes<'a> {
2906 map: &'a NamedRegionMap,
2907 outer_index: ty::DebruijnIndex,
2908 have_bound_regions: bool,
2909 lifetimes: FxHashSet<Region>,
2912 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2913 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2914 if let hir::TyKind::BareFn(_) = ty.kind {
2915 self.outer_index.shift_in(1);
2918 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2919 for bound in bounds {
2920 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2923 // Stay on the safe side and don't include the object
2924 // lifetime default (which may not end up being used).
2925 if !lifetime.is_elided() {
2926 self.visit_lifetime(lifetime);
2930 intravisit::walk_ty(self, ty);
2933 if let hir::TyKind::BareFn(_) = ty.kind {
2934 self.outer_index.shift_out(1);
2938 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2939 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2940 // FIXME(eddyb) Do we want this? It only makes a difference
2941 // if this `for<'a>` lifetime parameter is never used.
2942 self.have_bound_regions = true;
2945 intravisit::walk_generic_param(self, param);
2948 fn visit_poly_trait_ref(
2950 trait_ref: &hir::PolyTraitRef<'_>,
2951 modifier: hir::TraitBoundModifier,
2953 self.outer_index.shift_in(1);
2954 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2955 self.outer_index.shift_out(1);
2958 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2959 if let hir::GenericBound::LangItemTrait { .. } = bound {
2960 self.outer_index.shift_in(1);
2961 intravisit::walk_param_bound(self, bound);
2962 self.outer_index.shift_out(1);
2964 intravisit::walk_param_bound(self, bound);
2968 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2969 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2971 Region::LateBound(debruijn, _, _, _)
2972 | Region::LateBoundAnon(debruijn, _, _)
2973 if debruijn < self.outer_index =>
2975 self.have_bound_regions = true;
2978 // FIXME(jackh726): nested trait refs?
2979 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2986 struct GatherAnonLifetimes {
2989 impl<'v> Visitor<'v> for GatherAnonLifetimes {
2990 #[instrument(skip(self), level = "trace")]
2991 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2992 // If we enter a `BareFn`, then we enter a *new* binding scope
2993 if let hir::TyKind::BareFn(_) = ty.kind {
2996 intravisit::walk_ty(self, ty);
2999 fn visit_generic_args(
3002 generic_args: &'v hir::GenericArgs<'v>,
3004 // parenthesized args enter a new elison scope
3005 if generic_args.parenthesized {
3008 intravisit::walk_generic_args(self, path_span, generic_args)
3011 #[instrument(skip(self), level = "trace")]
3012 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
3013 if lifetime_ref.is_elided() {
3014 self.anon_count += 1;
3020 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
3021 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
3023 if lifetime_refs.is_empty() {
3027 let mut late_depth = 0;
3028 let mut scope = self.scope;
3029 let mut lifetime_names = FxHashSet::default();
3030 let mut lifetime_spans = vec![];
3033 // Do not assign any resolution, it will be inferred.
3034 Scope::Body { .. } => break Ok(()),
3036 Scope::Root => break Err(None),
3038 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
3039 // collect named lifetimes for suggestions
3040 for name in lifetimes.keys() {
3041 if let hir::ParamName::Plain(name) = name {
3042 lifetime_names.insert(name.name);
3043 lifetime_spans.push(name.span);
3047 BinderScopeType::Normal => late_depth += 1,
3048 BinderScopeType::Concatenating => {}
3054 elide: Elide::FreshLateAnon(named_late_bound_vars, ref counter),
3057 for lifetime_ref in lifetime_refs {
3059 Region::late_anon(named_late_bound_vars, counter).shifted(late_depth);
3061 self.insert_lifetime(lifetime_ref, lifetime);
3066 Scope::Elision { elide: Elide::Exact(l), .. } => {
3067 let lifetime = l.shifted(late_depth);
3068 for lifetime_ref in lifetime_refs {
3069 self.insert_lifetime(lifetime_ref, lifetime);
3074 Scope::Elision { elide: Elide::Error(ref e), ref s, .. } => {
3078 Scope::Binder { ref lifetimes, s, .. } => {
3079 // Collect named lifetimes for suggestions.
3080 for name in lifetimes.keys() {
3081 if let hir::ParamName::Plain(name) = name {
3082 lifetime_names.insert(name.name);
3083 lifetime_spans.push(name.span);
3088 Scope::ObjectLifetimeDefault { ref s, .. }
3089 | Scope::Elision { ref s, .. }
3090 | Scope::TraitRefBoundary { ref s, .. } => {
3096 break Err(Some(&e[..]));
3099 Scope::Elision { elide: Elide::Forbid, .. } => break Err(None),
3101 Scope::ObjectLifetimeDefault { s, .. }
3102 | Scope::Supertrait { s, .. }
3103 | Scope::TraitRefBoundary { s, .. } => {
3109 let error = match error {
3111 self.report_elided_lifetime_in_ty(lifetime_refs);
3114 Err(error) => error,
3117 // If we specifically need the `scope_for_path` map, then we're in the
3118 // diagnostic pass and we don't want to emit more errors.
3119 if self.map.scope_for_path.is_some() {
3120 self.tcx.sess.delay_span_bug(
3121 rustc_span::DUMMY_SP,
3122 "Encountered unexpected errors during diagnostics related part",
3127 let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3129 let mut spans_dedup = spans.clone();
3130 spans_dedup.dedup();
3131 let spans_with_counts: Vec<_> = spans_dedup
3133 .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
3136 let mut err = self.report_missing_lifetime_specifiers(spans.clone(), lifetime_refs.len());
3138 if let Some(params) = error {
3139 // If there's no lifetime available, suggest `'static`.
3140 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
3141 lifetime_names.insert(kw::StaticLifetime);
3145 self.add_missing_lifetime_specifiers_label(
3150 error.unwrap_or(&[]),
3155 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
3156 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
3157 let mut late_depth = 0;
3158 let mut scope = self.scope;
3159 let lifetime = loop {
3161 Scope::Binder { s, scope_type, .. } => {
3163 BinderScopeType::Normal => late_depth += 1,
3164 BinderScopeType::Concatenating => {}
3169 Scope::Root | Scope::Elision { .. } => break Region::Static,
3171 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
3173 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
3175 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
3180 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
3183 fn check_lifetime_params(
3185 old_scope: ScopeRef<'_>,
3186 params: &'tcx [hir::GenericParam<'tcx>],
3188 let lifetimes: Vec<_> = params
3190 .filter_map(|param| match param.kind {
3191 GenericParamKind::Lifetime { .. } => {
3192 Some((param, param.name.normalize_to_macros_2_0()))
3197 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
3198 if let hir::ParamName::Plain(_) = lifetime_i_name {
3199 let name = lifetime_i_name.ident().name;
3200 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
3201 let mut err = struct_span_err!(
3205 "invalid lifetime parameter name: `{}`",
3206 lifetime_i.name.ident(),
3210 format!("{} is a reserved lifetime name", name),
3216 // It is a hard error to shadow a lifetime within the same scope.
3217 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
3218 if lifetime_i_name == lifetime_j_name {
3223 "lifetime name `{}` declared twice in the same scope",
3224 lifetime_j.name.ident()
3226 .span_label(lifetime_j.span, "declared twice")
3227 .span_label(lifetime_i.span, "previous declaration here")
3232 // It is a soft error to shadow a lifetime within a parent scope.
3233 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
3235 for bound in lifetime_i.bounds {
3237 hir::GenericBound::Outlives(ref lt) => match lt.name {
3238 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
3240 "use of `'_` in illegal place, but not caught by lowering",
3242 hir::LifetimeName::Static => {
3243 self.insert_lifetime(lt, Region::Static);
3247 lifetime_i.span.to(lt.span),
3249 "unnecessary lifetime parameter `{}`",
3250 lifetime_i.name.ident(),
3254 "you can use the `'static` lifetime directly, in place of `{}`",
3255 lifetime_i.name.ident(),
3259 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit(_) => {
3260 self.resolve_lifetime_ref(lt);
3262 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
3263 self.tcx.sess.delay_span_bug(
3265 "lowering generated `ImplicitObjectLifetimeDefault` \
3266 outside of an object type",
3269 hir::LifetimeName::Error => {
3270 // No need to do anything, error already reported.
3279 fn check_lifetime_param_for_shadowing(
3281 mut old_scope: ScopeRef<'_>,
3282 param: &'tcx hir::GenericParam<'tcx>,
3284 for label in &self.labels_in_fn {
3285 // FIXME (#24278): non-hygienic comparison
3286 if param.name.ident().name == label.name {
3287 signal_shadowing_problem(
3290 original_label(label.span),
3291 shadower_lifetime(¶m),
3299 Scope::Body { s, .. }
3300 | Scope::Elision { s, .. }
3301 | Scope::ObjectLifetimeDefault { s, .. }
3302 | Scope::Supertrait { s, .. }
3303 | Scope::TraitRefBoundary { s, .. } => {
3311 Scope::Binder { ref lifetimes, s, .. } => {
3312 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
3313 signal_shadowing_problem(
3315 param.name.ident().name,
3316 original_lifetime(self.tcx.def_span(def.id().unwrap())),
3317 shadower_lifetime(¶m),
3328 /// Returns `true` if, in the current scope, replacing `'_` would be
3329 /// equivalent to a single-use lifetime.
3330 fn track_lifetime_uses(&self) -> bool {
3331 let mut scope = self.scope;
3334 Scope::Root => break false,
3336 // Inside of items, it depends on the kind of item.
3337 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
3339 // Inside a body, `'_` will use an inference variable,
3341 Scope::Body { .. } => break true,
3343 // A lifetime only used in a fn argument could as well
3344 // be replaced with `'_`, as that would generate a
3346 Scope::Elision { elide: Elide::FreshLateAnon(..), .. } => break true,
3348 // In the return type or other such place, `'_` is not
3349 // going to make a fresh name, so we cannot
3350 // necessarily replace a single-use lifetime with
3353 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
3356 Scope::ObjectLifetimeDefault { s, .. }
3357 | Scope::Supertrait { s, .. }
3358 | Scope::TraitRefBoundary { s, .. } => scope = s,
3363 #[tracing::instrument(level = "debug", skip(self))]
3364 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
3366 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
3367 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
3369 self.map.defs.insert(lifetime_ref.hir_id, def);
3372 Region::LateBoundAnon(..) | Region::Static => {
3373 // These are anonymous lifetimes or lifetimes that are not declared.
3376 Region::Free(_, def_id)
3377 | Region::LateBound(_, _, def_id, _)
3378 | Region::EarlyBound(_, def_id, _) => {
3379 // A lifetime declared by the user.
3380 let track_lifetime_uses = self.track_lifetime_uses();
3381 debug!(?track_lifetime_uses);
3382 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
3383 debug!("first use of {:?}", def_id);
3384 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
3386 debug!("many uses of {:?}", def_id);
3387 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
3393 /// Sometimes we resolve a lifetime, but later find that it is an
3394 /// error (esp. around impl trait). In that case, we remove the
3395 /// entry into `map.defs` so as not to confuse later code.
3396 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
3397 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
3398 assert_eq!(old_value, Some(bad_def));
3402 /// Detects late-bound lifetimes and inserts them into
3403 /// `map.late_bound`.
3405 /// A region declared on a fn is **late-bound** if:
3406 /// - it is constrained by an argument type;
3407 /// - it does not appear in a where-clause.
3409 /// "Constrained" basically means that it appears in any type but
3410 /// not amongst the inputs to a projection. In other words, `<&'a
3411 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
3412 #[tracing::instrument(level = "debug", skip(map))]
3413 fn insert_late_bound_lifetimes(
3414 map: &mut NamedRegionMap,
3415 decl: &hir::FnDecl<'_>,
3416 generics: &hir::Generics<'_>,
3418 let mut constrained_by_input = ConstrainedCollector::default();
3419 for arg_ty in decl.inputs {
3420 constrained_by_input.visit_ty(arg_ty);
3423 let mut appears_in_output = AllCollector::default();
3424 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
3426 debug!(?constrained_by_input.regions);
3428 // Walk the lifetimes that appear in where clauses.
3430 // Subtle point: because we disallow nested bindings, we can just
3431 // ignore binders here and scrape up all names we see.
3432 let mut appears_in_where_clause = AllCollector::default();
3433 appears_in_where_clause.visit_generics(generics);
3435 for param in generics.params {
3436 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
3437 if !param.bounds.is_empty() {
3438 // `'a: 'b` means both `'a` and `'b` are referenced
3439 appears_in_where_clause
3441 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
3446 debug!(?appears_in_where_clause.regions);
3448 // Late bound regions are those that:
3449 // - appear in the inputs
3450 // - do not appear in the where-clauses
3451 // - are not implicitly captured by `impl Trait`
3452 for param in generics.params {
3454 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
3456 // Neither types nor consts are late-bound.
3457 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
3460 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
3461 // appears in the where clauses? early-bound.
3462 if appears_in_where_clause.regions.contains(<_name) {
3466 // does not appear in the inputs, but appears in the return type? early-bound.
3467 if !constrained_by_input.regions.contains(<_name)
3468 && appears_in_output.regions.contains(<_name)
3473 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
3475 let inserted = map.late_bound.insert(param.hir_id);
3476 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
3482 struct ConstrainedCollector {
3483 regions: FxHashSet<hir::LifetimeName>,
3486 impl<'v> Visitor<'v> for ConstrainedCollector {
3487 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3490 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
3492 // ignore lifetimes appearing in associated type
3493 // projections, as they are not *constrained*
3497 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
3498 // consider only the lifetimes on the final
3499 // segment; I am not sure it's even currently
3500 // valid to have them elsewhere, but even if it
3501 // is, those would be potentially inputs to
3503 if let Some(last_segment) = path.segments.last() {
3504 self.visit_path_segment(path.span, last_segment);
3509 intravisit::walk_ty(self, ty);
3514 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3515 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3520 struct AllCollector {
3521 regions: FxHashSet<hir::LifetimeName>,
3524 impl<'v> Visitor<'v> for AllCollector {
3525 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3526 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());