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, Diagnostic};
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};
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 debug!("Region::early: index={} def_id={:?}", i, def_id);
67 (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id()))
70 fn late(idx: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
71 let depth = ty::INNERMOST;
72 let def_id = hir_map.local_def_id(param.hir_id);
74 "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}",
75 idx, param, depth, def_id,
77 (param.name.normalize_to_macros_2_0(), Region::LateBound(depth, idx, def_id.to_def_id()))
80 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region {
83 let depth = ty::INNERMOST;
84 Region::LateBoundAnon(depth, named_late_bound_vars + i, i)
87 fn id(&self) -> Option<DefId> {
89 Region::Static | Region::LateBoundAnon(..) => None,
91 Region::EarlyBound(_, id) | Region::LateBound(_, _, id) | Region::Free(_, id) => {
97 fn shifted(self, amount: u32) -> Region {
99 Region::LateBound(debruijn, idx, id) => {
100 Region::LateBound(debruijn.shifted_in(amount), idx, id)
102 Region::LateBoundAnon(debruijn, index, anon_index) => {
103 Region::LateBoundAnon(debruijn.shifted_in(amount), index, anon_index)
109 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
111 Region::LateBound(debruijn, index, id) => {
112 Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id)
114 Region::LateBoundAnon(debruijn, index, anon_index) => {
115 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index, anon_index)
121 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
123 L: Iterator<Item = &'a hir::Lifetime>,
125 if let Region::EarlyBound(index, _) = self {
126 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
133 /// Maps the id of each lifetime reference to the lifetime decl
134 /// that it corresponds to.
136 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
137 /// actual use. It has the same data, but indexed by `LocalDefId`. This
139 #[derive(Debug, Default)]
140 struct NamedRegionMap {
141 // maps from every use of a named (not anonymous) lifetime to a
142 // `Region` describing how that region is bound
143 defs: HirIdMap<Region>,
145 // the set of lifetime def ids that are late-bound; a region can
146 // be late-bound if (a) it does NOT appear in a where-clause and
147 // (b) it DOES appear in the arguments.
148 late_bound: HirIdSet,
150 // Maps relevant hir items to the bound vars on them. These include:
152 // - function pointers
155 // - bound types (like `T` in `for<'a> T<'a>: Foo`)
156 late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
158 // maps `PathSegment` `HirId`s to lifetime scopes.
159 scope_for_path: Option<FxHashMap<LocalDefId, FxHashMap<ItemLocalId, LifetimeScopeForPath>>>,
162 crate struct LifetimeContext<'a, 'tcx> {
163 crate tcx: TyCtxt<'tcx>,
164 map: &'a mut NamedRegionMap,
167 /// Indicates that we only care about the definition of a trait. This should
168 /// be false if the `Item` we are resolving lifetimes for is not a trait or
169 /// we eventually need lifetimes resolve for trait items.
170 trait_definition_only: bool,
172 /// List of labels in the function/method currently under analysis.
173 labels_in_fn: Vec<Ident>,
175 /// Cache for cross-crate per-definition object lifetime defaults.
176 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
178 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
180 /// When encountering an undefined named lifetime, we will suggest introducing it in these
182 crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
187 /// Declares lifetimes, and each can be early-bound or late-bound.
188 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
189 /// it should be shifted by the number of `Binder`s in between the
190 /// declaration `Binder` and the location it's referenced from.
192 /// We use an IndexMap here because we want these lifetimes in order
194 lifetimes: FxIndexMap<hir::ParamName, Region>,
196 /// if we extend this scope with another scope, what is the next index
197 /// we should use for an early-bound region?
198 next_early_index: u32,
200 /// Flag is set to true if, in this binder, `'_` would be
201 /// equivalent to a "single-use region". This is true on
202 /// impls, but not other kinds of items.
203 track_lifetime_uses: bool,
205 /// Whether or not this binder would serve as the parent
206 /// binder for opaque types introduced within. For example:
209 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
212 /// Here, the opaque types we create for the `impl Trait`
213 /// and `impl Trait2` references will both have the `foo` item
214 /// as their parent. When we get to `impl Trait2`, we find
215 /// that it is nested within the `for<>` binder -- this flag
216 /// allows us to skip that when looking for the parent binder
217 /// of the resulting opaque type.
218 opaque_type_parent: bool,
220 scope_type: BinderScopeType,
222 /// The late bound vars for a given item are stored by `HirId` to be
223 /// queried later. However, if we enter an elision scope, we have to
224 /// later append the elided bound vars to the list and need to know what
230 /// In some cases not allowing late bounds allows us to avoid ICEs.
231 /// This is almost ways set to true.
232 allow_late_bound: bool,
235 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
236 /// if this is a fn body, otherwise the original definitions are used.
237 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
238 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
244 /// A scope which either determines unspecified lifetimes or errors
245 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
251 /// Use a specific lifetime (if `Some`) or leave it unset (to be
252 /// inferred in a function body or potentially error outside one),
253 /// for the default choice of lifetime in a trait object type.
254 ObjectLifetimeDefault {
255 lifetime: Option<Region>,
259 /// When we have nested trait refs, we concatenate late bound vars for inner
260 /// trait refs from outer ones. But we also need to include any HRTB
261 /// lifetimes encountered when identifying the trait that an associated type
264 lifetimes: Vec<ty::BoundVariableKind>,
275 #[derive(Copy, Clone, Debug)]
276 enum BinderScopeType {
277 /// Any non-concatenating binder scopes.
279 /// Within a syntactic trait ref, there may be multiple poly trait refs that
280 /// are nested (under the `associated_type_bounds` feature). The binders of
281 /// the inner poly trait refs are extended from the outer poly trait refs
282 /// and don't increase the late bound depth. If you had
283 /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
284 /// would be `Concatenating`. This also used in trait refs in where clauses
285 /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
286 /// out any lifetimes because they aren't needed to show the two scopes).
287 /// The inner `for<>` has a scope of `Concatenating`.
291 // A helper struct for debugging scopes without printing parent scopes
292 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
294 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 .debug_struct("Binder")
308 .field("lifetimes", lifetimes)
309 .field("next_early_index", next_early_index)
310 .field("track_lifetime_uses", track_lifetime_uses)
311 .field("opaque_type_parent", opaque_type_parent)
312 .field("scope_type", scope_type)
313 .field("hir_id", hir_id)
315 .field("allow_late_bound", allow_late_bound)
317 Scope::Body { id, s: _ } => {
318 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
320 Scope::Elision { elide, s: _ } => {
321 f.debug_struct("Elision").field("elide", elide).field("s", &"..").finish()
323 Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
324 .debug_struct("ObjectLifetimeDefault")
325 .field("lifetime", lifetime)
328 Scope::Supertrait { lifetimes, s: _ } => f
329 .debug_struct("Supertrait")
330 .field("lifetimes", lifetimes)
333 Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
334 Scope::Root => f.debug_struct("Root").finish(),
339 #[derive(Clone, Debug)]
341 /// Use a fresh anonymous late-bound lifetime each time, by
342 /// incrementing the counter to generate sequential indices. All
343 /// anonymous lifetimes must start *after* named bound vars.
344 FreshLateAnon(u32, Cell<u32>),
345 /// Always use this one lifetime.
347 /// Less or more than one lifetime were found, error on unspecified.
348 Error(Vec<ElisionFailureInfo>),
349 /// Forbid lifetime elision inside of a larger scope where it would be
350 /// permitted. For example, in let position impl trait.
354 #[derive(Clone, Debug)]
355 crate struct ElisionFailureInfo {
356 /// Where we can find the argument pattern.
357 crate parent: Option<hir::BodyId>,
358 /// The index of the argument in the original definition.
360 crate lifetime_count: usize,
361 crate have_bound_regions: bool,
365 type ScopeRef<'a> = &'a Scope<'a>;
367 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
369 pub fn provide(providers: &mut ty::query::Providers) {
370 *providers = ty::query::Providers {
371 resolve_lifetimes_trait_definition,
374 named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
376 object_lifetime_defaults: |tcx, id| match tcx.hir().find_by_def_id(id) {
377 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
380 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
381 lifetime_scope_map: |tcx, id| {
382 let item_id = item_for(tcx, id);
383 do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
390 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
391 /// Also does not generate any diagnostics.
393 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
394 /// resolves lifetimes only within the trait "header" -- that is, the trait
395 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
396 /// lifetimes within the trait and its items. There is room to refactor this,
397 /// for example to resolve lifetimes for each trait item in separate queries,
398 /// but it's convenient to do the entire trait at once because the lifetimes
399 /// from the trait definition are in scope within the trait items as well.
401 /// The reason for this separate call is to resolve what would otherwise
402 /// be a cycle. Consider this example:
404 /// ```ignore UNSOLVED (maybe @jackh726 knows what lifetime parameter to give Sub)
408 /// trait Sub<'b>: for<'a> Base<'a> {
409 /// type SubItem: Sub<BaseItem = &'b u32>;
413 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
414 /// To figure out the index of `'b`, we have to know about the supertraits
415 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
416 /// (This is because we -- currently at least -- flatten all the late-bound
417 /// lifetimes into a single binder.) This requires us to resolve the
418 /// *trait definition* of `Sub`; basically just enough lifetime information
419 /// to look at the supertraits.
420 #[tracing::instrument(level = "debug", skip(tcx))]
421 fn resolve_lifetimes_trait_definition(
423 local_def_id: LocalDefId,
424 ) -> ResolveLifetimes {
425 convert_named_region_map(tcx, do_resolve(tcx, local_def_id, true, false))
428 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
429 /// You should not read the result of this query directly, but rather use
430 /// `named_region_map`, `is_late_bound_map`, etc.
431 #[tracing::instrument(level = "debug", skip(tcx))]
432 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
433 convert_named_region_map(tcx, do_resolve(tcx, local_def_id, false, false))
438 local_def_id: LocalDefId,
439 trait_definition_only: bool,
440 with_scope_for_path: bool,
441 ) -> NamedRegionMap {
442 let item = tcx.hir().expect_item(local_def_id);
443 let mut named_region_map = NamedRegionMap {
444 defs: Default::default(),
445 late_bound: Default::default(),
446 late_bound_vars: Default::default(),
447 scope_for_path: with_scope_for_path.then(|| Default::default()),
449 let mut visitor = LifetimeContext {
451 map: &mut named_region_map,
453 trait_definition_only,
454 labels_in_fn: vec![],
455 xcrate_object_lifetime_defaults: Default::default(),
456 lifetime_uses: &mut Default::default(),
457 missing_named_lifetime_spots: vec![],
459 visitor.visit_item(item);
464 fn convert_named_region_map(tcx: TyCtxt<'_>, named_region_map: NamedRegionMap) -> ResolveLifetimes {
465 let mut rl = ResolveLifetimes::default();
467 for (hir_id, v) in named_region_map.defs {
468 let map = rl.defs.entry(hir_id.owner).or_default();
469 map.insert(hir_id.local_id, v);
471 for hir_id in named_region_map.late_bound {
472 let map = rl.late_bound.entry(hir_id.owner).or_default();
473 let def_id = tcx.hir().local_def_id(hir_id);
476 for (hir_id, v) in named_region_map.late_bound_vars {
477 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
478 map.insert(hir_id.local_id, v);
485 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
486 /// There are two important things this does.
487 /// First, we have to resolve lifetimes for
488 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
489 /// where we can have relevant lifetimes.
490 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
491 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
492 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
493 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
494 /// `resolve_lifetimes`.
495 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
496 let item_id = item_for(tcx, def_id);
497 if item_id == def_id {
498 let item = tcx.hir().item(hir::ItemId { def_id: item_id });
500 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
501 _ => tcx.resolve_lifetimes(item_id),
504 tcx.resolve_lifetimes(item_id)
508 /// Finds the `Item` that contains the given `LocalDefId`
509 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
510 match tcx.hir().find_by_def_id(local_def_id) {
511 Some(Node::Item(item)) => {
517 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
518 let mut parent_iter = tcx.hir().parent_iter(hir_id);
520 let node = parent_iter.next().map(|n| n.1);
522 Some(hir::Node::Item(item)) => break item.def_id,
523 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
531 fn is_late_bound_map<'tcx>(
534 ) -> Option<(LocalDefId, &'tcx FxHashSet<LocalDefId>)> {
535 match tcx.def_kind(def_id) {
536 DefKind::AnonConst | DefKind::InlineConst => {
538 .parent(def_id.to_def_id())
539 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
540 // We search for the next outer anon const or fn here
541 // while skipping closures.
543 // Note that for `AnonConst` we still just recurse until we
544 // find a function body, but who cares :shrug:
545 while tcx.is_closure(def_id) {
548 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
551 tcx.is_late_bound_map(def_id.expect_local())
553 _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
557 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
558 /// We have to account for this when computing the index of the other generic parameters.
559 /// This function returns whether there is such an implicit parameter defined on the given item.
560 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
561 matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
564 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
566 Region::LateBound(_, _, def_id) => {
567 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
568 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
570 Region::LateBoundAnon(_, _, anon_idx) => {
571 ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
573 _ => bug!("{:?} is not a late region", region),
577 #[tracing::instrument(level = "debug")]
578 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
579 let mut available_lifetimes = vec![];
582 Scope::Binder { lifetimes, s, .. } => {
583 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
584 hir::ParamName::Plain(ident) => Some(ident.name),
589 Scope::Body { s, .. } => {
592 Scope::Elision { elide, s } => {
593 if let Elide::Exact(_) = elide {
594 return LifetimeScopeForPath::Elided;
599 Scope::ObjectLifetimeDefault { s, .. } => {
603 return LifetimeScopeForPath::NonElided(available_lifetimes);
605 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
612 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
613 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
614 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
615 let mut scope = self.scope;
616 let mut supertrait_lifetimes = vec![];
619 Scope::Body { .. } | Scope::Root => {
620 break (vec![], BinderScopeType::Normal);
623 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
627 Scope::Supertrait { s, lifetimes } => {
628 supertrait_lifetimes = lifetimes.clone();
632 Scope::TraitRefBoundary { .. } => {
633 // We should only see super trait lifetimes if there is a `Binder` above
634 assert!(supertrait_lifetimes.is_empty());
635 break (vec![], BinderScopeType::Normal);
638 Scope::Binder { hir_id, .. } => {
639 // Nested poly trait refs have the binders concatenated
640 let mut full_binders =
641 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
642 full_binders.extend(supertrait_lifetimes.into_iter());
643 break (full_binders, BinderScopeType::Concatenating);
649 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
650 type NestedFilter = nested_filter::All;
652 fn nested_visit_map(&mut self) -> Self::Map {
656 // We want to nest trait/impl items in their parent, but nothing else.
657 fn visit_nested_item(&mut self, _: hir::ItemId) {}
659 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
660 if !self.trait_definition_only {
661 intravisit::walk_trait_item_ref(self, ii)
665 fn visit_nested_body(&mut self, body: hir::BodyId) {
666 // Each body has their own set of labels, save labels.
667 let saved = take(&mut self.labels_in_fn);
668 let body = self.tcx.hir().body(body);
669 extract_labels(self, body);
670 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
671 this.visit_body(body);
673 self.labels_in_fn = saved;
678 fk: intravisit::FnKind<'tcx>,
679 fd: &'tcx hir::FnDecl<'tcx>,
684 let name = match fk {
685 intravisit::FnKind::ItemFn(id, _, _) => id.name,
686 intravisit::FnKind::Method(id, _) => id.name,
687 intravisit::FnKind::Closure => sym::closure,
689 let name = name.as_str();
690 let span = span!(Level::DEBUG, "visit_fn", name);
691 let _enter = span.enter();
693 // Any `Binders` are handled elsewhere
694 intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
695 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
697 intravisit::FnKind::Closure => {
698 self.map.late_bound_vars.insert(hir_id, vec![]);
699 let scope = Scope::Binder {
701 lifetimes: FxIndexMap::default(),
702 next_early_index: self.next_early_index(),
704 track_lifetime_uses: true,
705 opaque_type_parent: false,
706 scope_type: BinderScopeType::Normal,
707 allow_late_bound: true,
709 self.with(scope, move |_old_scope, this| {
710 intravisit::walk_fn(this, fk, fd, b, s, hir_id)
716 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
718 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
719 if let Some(of_trait) = of_trait {
720 self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
726 hir::ItemKind::Fn(ref sig, ref generics, _) => {
727 self.missing_named_lifetime_spots.push(generics.into());
728 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
729 intravisit::walk_item(this, item);
731 self.missing_named_lifetime_spots.pop();
734 hir::ItemKind::ExternCrate(_)
735 | hir::ItemKind::Use(..)
736 | hir::ItemKind::Macro(..)
737 | hir::ItemKind::Mod(..)
738 | hir::ItemKind::ForeignMod { .. }
739 | hir::ItemKind::GlobalAsm(..) => {
740 // These sorts of items have no lifetime parameters at all.
741 intravisit::walk_item(self, item);
743 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
744 // No lifetime parameters, but implied 'static.
745 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
746 self.with(scope, |_, this| intravisit::walk_item(this, item));
748 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
749 // Opaque types are visited when we visit the
750 // `TyKind::OpaqueDef`, so that they have the lifetimes from
751 // their parent opaque_ty in scope.
753 // The core idea here is that since OpaqueTys are generated with the impl Trait as
754 // their owner, we can keep going until we find the Item that owns that. We then
755 // conservatively add all resolved lifetimes. Otherwise we run into problems in
756 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
757 for (_hir_id, node) in
758 self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
761 hir::Node::Item(parent_item) => {
762 let resolved_lifetimes: &ResolveLifetimes =
763 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
764 // We need to add *all* deps, since opaque tys may want them from *us*
765 for (&owner, defs) in resolved_lifetimes.defs.iter() {
766 defs.iter().for_each(|(&local_id, region)| {
767 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
770 for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
771 late_bound.iter().for_each(|&id| {
772 let hir_id = self.tcx.local_def_id_to_hir_id(id);
773 debug_assert_eq!(owner, hir_id.owner);
774 self.map.late_bound.insert(hir_id);
777 for (&owner, late_bound_vars) in
778 resolved_lifetimes.late_bound_vars.iter()
780 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
781 self.map.late_bound_vars.insert(
782 hir::HirId { owner, local_id },
783 late_bound_vars.clone(),
789 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
794 hir::ItemKind::TyAlias(_, ref generics)
795 | hir::ItemKind::Enum(_, ref generics)
796 | hir::ItemKind::Struct(_, ref generics)
797 | hir::ItemKind::Union(_, ref generics)
798 | hir::ItemKind::Trait(_, _, ref generics, ..)
799 | hir::ItemKind::TraitAlias(ref generics, ..)
800 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
801 self.missing_named_lifetime_spots.push(generics.into());
803 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
804 // This is not true for other kinds of items.
805 let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
806 // These kinds of items have only early-bound lifetime parameters.
807 let mut index = if sub_items_have_self_param(&item.kind) {
808 1 // Self comes before lifetimes
812 let mut non_lifetime_count = 0;
813 let lifetimes = generics
816 .filter_map(|param| match param.kind {
817 GenericParamKind::Lifetime { .. } => {
818 Some(Region::early(self.tcx.hir(), &mut index, param))
820 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
821 non_lifetime_count += 1;
826 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
827 let scope = Scope::Binder {
828 hir_id: item.hir_id(),
830 next_early_index: index + non_lifetime_count,
831 opaque_type_parent: true,
833 scope_type: BinderScopeType::Normal,
835 allow_late_bound: false,
837 self.with(scope, |old_scope, this| {
838 this.check_lifetime_params(old_scope, &generics.params);
839 let scope = Scope::TraitRefBoundary { s: this.scope };
840 this.with(scope, |_, this| {
841 intravisit::walk_item(this, item);
844 self.missing_named_lifetime_spots.pop();
849 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
851 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
852 self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
853 intravisit::walk_foreign_item(this, item);
856 hir::ForeignItemKind::Static(..) => {
857 intravisit::walk_foreign_item(self, item);
859 hir::ForeignItemKind::Type => {
860 intravisit::walk_foreign_item(self, item);
865 #[tracing::instrument(level = "debug", skip(self))]
866 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
868 hir::TyKind::BareFn(ref c) => {
869 let next_early_index = self.next_early_index();
870 let lifetime_span: Option<Span> =
871 c.generic_params.iter().rev().find_map(|param| match param.kind {
872 GenericParamKind::Lifetime { .. } => Some(param.span),
875 let (span, span_type) = if let Some(span) = lifetime_span {
876 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
878 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
880 self.missing_named_lifetime_spots
881 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
882 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
885 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
887 .map(|(late_bound_idx, param)| {
888 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
889 let r = late_region_as_bound_region(self.tcx, &pair.1);
893 self.map.late_bound_vars.insert(ty.hir_id, binders);
894 let scope = Scope::Binder {
899 track_lifetime_uses: true,
900 opaque_type_parent: false,
901 scope_type: BinderScopeType::Normal,
902 allow_late_bound: true,
904 self.with(scope, |old_scope, this| {
905 // a bare fn has no bounds, so everything
906 // contained within is scoped within its binder.
907 this.check_lifetime_params(old_scope, &c.generic_params);
908 intravisit::walk_ty(this, ty);
910 self.missing_named_lifetime_spots.pop();
912 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
913 debug!(?bounds, ?lifetime, "TraitObject");
914 let scope = Scope::TraitRefBoundary { s: self.scope };
915 self.with(scope, |_, this| {
916 for bound in bounds {
917 this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
920 match lifetime.name {
921 LifetimeName::Implicit => {
922 // For types like `dyn Foo`, we should
923 // generate a special form of elided.
924 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
926 LifetimeName::ImplicitObjectLifetimeDefault => {
927 // If the user does not write *anything*, we
928 // use the object lifetime defaulting
929 // rules. So e.g., `Box<dyn Debug>` becomes
930 // `Box<dyn Debug + 'static>`.
931 self.resolve_object_lifetime_default(lifetime)
933 LifetimeName::Underscore => {
934 // If the user writes `'_`, we use the *ordinary* elision
935 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
936 // resolved the same as the `'_` in `&'_ Foo`.
939 self.resolve_elided_lifetimes(&[lifetime])
941 LifetimeName::Param(_) | LifetimeName::Static => {
942 // If the user wrote an explicit name, use that.
943 self.visit_lifetime(lifetime);
945 LifetimeName::Error => {}
948 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
949 self.visit_lifetime(lifetime_ref);
950 let scope = Scope::ObjectLifetimeDefault {
951 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
954 self.with(scope, |_, this| this.visit_ty(&mt.ty));
956 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
957 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
958 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
959 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
960 // ^ ^ this gets resolved in the scope of
961 // the opaque_ty generics
962 let opaque_ty = self.tcx.hir().item(item_id);
963 let (generics, bounds) = match opaque_ty.kind {
964 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
965 // This arm is for `impl Trait` in the types of statics, constants and locals.
966 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
967 origin: hir::OpaqueTyOrigin::TyAlias,
970 intravisit::walk_ty(self, ty);
972 // Elided lifetimes are not allowed in non-return
973 // position impl Trait
974 let scope = Scope::TraitRefBoundary { s: self.scope };
975 self.with(scope, |_, this| {
976 let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
977 this.with(scope, |_, this| {
978 intravisit::walk_item(this, opaque_ty);
984 // RPIT (return position impl trait)
985 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
986 origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
990 }) => (generics, bounds),
991 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
994 // Resolve the lifetimes that are applied to the opaque type.
995 // These are resolved in the current scope.
996 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
997 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
998 // ^ ^this gets resolved in the current scope
999 for lifetime in lifetimes {
1000 let hir::GenericArg::Lifetime(lifetime) = lifetime else {
1003 self.visit_lifetime(lifetime);
1005 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1006 // and ban them. Type variables instantiated inside binders aren't
1007 // well-supported at the moment, so this doesn't work.
1008 // In the future, this should be fixed and this error should be removed.
1009 let def = self.map.defs.get(&lifetime.hir_id).cloned();
1010 let Some(Region::LateBound(_, _, def_id)) = def else {
1013 let Some(def_id) = def_id.as_local() else {
1016 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1017 // Ensure that the parent of the def is an item, not HRTB
1018 let parent_id = self.tcx.hir().get_parent_node(hir_id);
1019 if !parent_id.is_owner() {
1020 if !self.trait_definition_only {
1025 "`impl Trait` can only capture lifetimes \
1026 bound at the fn or impl level"
1030 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1034 // We want to start our early-bound indices at the end of the parent scope,
1035 // not including any parent `impl Trait`s.
1036 let mut index = self.next_early_index_for_opaque_type();
1039 let mut elision = None;
1040 let mut lifetimes = FxIndexMap::default();
1041 let mut non_lifetime_count = 0;
1042 for param in generics.params {
1044 GenericParamKind::Lifetime { .. } => {
1045 let (name, reg) = Region::early(self.tcx.hir(), &mut index, ¶m);
1046 let Region::EarlyBound(_, def_id) = reg else {
1049 // We cannot predict what lifetimes are unused in opaque type.
1050 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
1051 if let hir::ParamName::Plain(Ident {
1052 name: kw::UnderscoreLifetime,
1056 // Pick the elided lifetime "definition" if one exists
1057 // and use it to make an elision scope.
1058 elision = Some(reg);
1060 lifetimes.insert(name, reg);
1063 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1064 non_lifetime_count += 1;
1068 let next_early_index = index + non_lifetime_count;
1069 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1071 if let Some(elision_region) = elision {
1073 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1074 self.with(scope, |_old_scope, this| {
1075 let scope = Scope::Binder {
1080 track_lifetime_uses: true,
1081 opaque_type_parent: false,
1082 scope_type: BinderScopeType::Normal,
1083 allow_late_bound: false,
1085 this.with(scope, |_old_scope, this| {
1086 this.visit_generics(generics);
1087 let scope = Scope::TraitRefBoundary { s: this.scope };
1088 this.with(scope, |_, this| {
1089 for bound in bounds {
1090 this.visit_param_bound(bound);
1096 let scope = Scope::Binder {
1101 track_lifetime_uses: true,
1102 opaque_type_parent: false,
1103 scope_type: BinderScopeType::Normal,
1104 allow_late_bound: false,
1106 self.with(scope, |_old_scope, this| {
1107 let scope = Scope::TraitRefBoundary { s: this.scope };
1108 this.with(scope, |_, this| {
1109 this.visit_generics(generics);
1110 for bound in bounds {
1111 this.visit_param_bound(bound);
1117 _ => intravisit::walk_ty(self, ty),
1121 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1122 use self::hir::TraitItemKind::*;
1123 match trait_item.kind {
1125 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1127 self.visit_early_late(
1128 Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1129 trait_item.hir_id(),
1131 &trait_item.generics,
1132 |this| intravisit::walk_trait_item(this, trait_item),
1134 self.missing_named_lifetime_spots.pop();
1136 Type(bounds, ref ty) => {
1137 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1138 let generics = &trait_item.generics;
1139 let mut index = self.next_early_index();
1140 debug!("visit_ty: index = {}", index);
1141 let mut non_lifetime_count = 0;
1142 let lifetimes = generics
1145 .filter_map(|param| match param.kind {
1146 GenericParamKind::Lifetime { .. } => {
1147 Some(Region::early(self.tcx.hir(), &mut index, param))
1149 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1150 non_lifetime_count += 1;
1155 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1156 let scope = Scope::Binder {
1157 hir_id: trait_item.hir_id(),
1159 next_early_index: index + non_lifetime_count,
1161 track_lifetime_uses: true,
1162 opaque_type_parent: true,
1163 scope_type: BinderScopeType::Normal,
1164 allow_late_bound: false,
1166 self.with(scope, |old_scope, this| {
1167 this.check_lifetime_params(old_scope, &generics.params);
1168 let scope = Scope::TraitRefBoundary { s: this.scope };
1169 this.with(scope, |_, this| {
1170 this.visit_generics(generics);
1171 for bound in bounds {
1172 this.visit_param_bound(bound);
1174 if let Some(ty) = ty {
1179 self.missing_named_lifetime_spots.pop();
1182 // Only methods and types support generics.
1183 assert!(trait_item.generics.params.is_empty());
1184 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1185 intravisit::walk_trait_item(self, trait_item);
1186 self.missing_named_lifetime_spots.pop();
1191 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1192 use self::hir::ImplItemKind::*;
1193 match impl_item.kind {
1195 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1197 self.visit_early_late(
1198 Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1201 &impl_item.generics,
1202 |this| intravisit::walk_impl_item(this, impl_item),
1204 self.missing_named_lifetime_spots.pop();
1206 TyAlias(ref ty) => {
1207 let generics = &impl_item.generics;
1208 self.missing_named_lifetime_spots.push(generics.into());
1209 let mut index = self.next_early_index();
1210 let mut non_lifetime_count = 0;
1211 debug!("visit_ty: index = {}", index);
1212 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1215 .filter_map(|param| match param.kind {
1216 GenericParamKind::Lifetime { .. } => {
1217 Some(Region::early(self.tcx.hir(), &mut index, param))
1219 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1220 non_lifetime_count += 1;
1225 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1226 let scope = Scope::Binder {
1229 next_early_index: index + non_lifetime_count,
1231 track_lifetime_uses: true,
1232 opaque_type_parent: true,
1233 scope_type: BinderScopeType::Normal,
1234 allow_late_bound: true,
1236 self.with(scope, |old_scope, this| {
1237 this.check_lifetime_params(old_scope, &generics.params);
1238 let scope = Scope::TraitRefBoundary { s: this.scope };
1239 this.with(scope, |_, this| {
1240 this.visit_generics(generics);
1244 self.missing_named_lifetime_spots.pop();
1247 // Only methods and types support generics.
1248 assert!(impl_item.generics.params.is_empty());
1249 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1250 intravisit::walk_impl_item(self, impl_item);
1251 self.missing_named_lifetime_spots.pop();
1256 #[tracing::instrument(level = "debug", skip(self))]
1257 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1258 if lifetime_ref.is_elided() {
1259 self.resolve_elided_lifetimes(&[lifetime_ref]);
1262 if lifetime_ref.is_static() {
1263 self.insert_lifetime(lifetime_ref, Region::Static);
1266 self.resolve_lifetime_ref(lifetime_ref);
1269 fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1270 let scope = self.scope;
1271 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1272 // We add lifetime scope information for `Ident`s in associated type bindings and use
1273 // the `HirId` of the type binding as the key in `LifetimeMap`
1274 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1275 let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1276 map.insert(type_binding.hir_id.local_id, lifetime_scope);
1278 hir::intravisit::walk_assoc_type_binding(self, type_binding);
1281 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1282 for (i, segment) in path.segments.iter().enumerate() {
1283 let depth = path.segments.len() - i - 1;
1284 if let Some(ref args) = segment.args {
1285 self.visit_segment_args(path.res, depth, args);
1288 let scope = self.scope;
1289 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1290 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1291 // here because that call would yield to resolution problems due to `walk_path_segment`
1292 // being called, which processes the path segments generic args, which we have already
1293 // processed using `visit_segment_args`.
1294 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1295 if let Some(hir_id) = segment.hir_id {
1296 let map = scope_for_path.entry(hir_id.owner).or_default();
1297 map.insert(hir_id.local_id, lifetime_scope);
1303 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1304 let scope = self.scope;
1305 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1306 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1307 if let Some(hir_id) = path_segment.hir_id {
1308 let map = scope_for_path.entry(hir_id.owner).or_default();
1309 map.insert(hir_id.local_id, lifetime_scope);
1313 intravisit::walk_path_segment(self, path_span, path_segment);
1316 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1317 let output = match fd.output {
1318 hir::FnRetTy::DefaultReturn(_) => None,
1319 hir::FnRetTy::Return(ref ty) => Some(&**ty),
1321 self.visit_fn_like_elision(&fd.inputs, output);
1324 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1325 let scope = Scope::TraitRefBoundary { s: self.scope };
1326 self.with(scope, |_, this| {
1327 for param in generics.params {
1329 GenericParamKind::Lifetime { .. } => {}
1330 GenericParamKind::Type { ref default, .. } => {
1331 if let Some(ref ty) = default {
1335 GenericParamKind::Const { ref ty, default } => {
1337 if let Some(default) = default {
1338 this.visit_body(this.tcx.hir().body(default.body));
1343 for predicate in generics.predicates {
1345 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1348 ref bound_generic_params,
1351 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1352 bound_generic_params
1355 matches!(param.kind, GenericParamKind::Lifetime { .. })
1358 .map(|(late_bound_idx, param)| {
1360 Region::late(late_bound_idx as u32, this.tcx.hir(), param);
1361 let r = late_region_as_bound_region(this.tcx, &pair.1);
1365 this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1366 let next_early_index = this.next_early_index();
1367 // Even if there are no lifetimes defined here, we still wrap it in a binder
1368 // scope. If there happens to be a nested poly trait ref (an error), that
1369 // will be `Concatenating` anyways, so we don't have to worry about the depth
1371 let scope = Scope::Binder {
1372 hir_id: bounded_ty.hir_id,
1376 track_lifetime_uses: true,
1377 opaque_type_parent: false,
1378 scope_type: BinderScopeType::Normal,
1379 allow_late_bound: true,
1381 this.with(scope, |old_scope, this| {
1382 this.check_lifetime_params(old_scope, &bound_generic_params);
1383 this.visit_ty(&bounded_ty);
1384 walk_list!(this, visit_param_bound, bounds);
1387 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1392 this.visit_lifetime(lifetime);
1393 walk_list!(this, visit_param_bound, bounds);
1395 if lifetime.name != hir::LifetimeName::Static {
1396 for bound in bounds {
1397 let hir::GenericBound::Outlives(ref lt) = bound else {
1400 if lt.name != hir::LifetimeName::Static {
1403 this.insert_lifetime(lt, Region::Static);
1409 "unnecessary lifetime parameter `{}`",
1410 lifetime.name.ident(),
1414 "you can use the `'static` lifetime directly, in place of `{}`",
1415 lifetime.name.ident(),
1421 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1426 this.visit_ty(lhs_ty);
1427 this.visit_ty(rhs_ty);
1434 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1436 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1437 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1438 // through the regular poly trait ref code, so we don't get another
1439 // chance to introduce a binder. For now, I'm keeping the existing logic
1440 // of "if there isn't a Binder scope above us, add one", but I
1441 // imagine there's a better way to go about this.
1442 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1444 self.map.late_bound_vars.insert(*hir_id, binders);
1445 let scope = Scope::Binder {
1447 lifetimes: FxIndexMap::default(),
1449 next_early_index: self.next_early_index(),
1450 track_lifetime_uses: true,
1451 opaque_type_parent: false,
1453 allow_late_bound: true,
1455 self.with(scope, |_, this| {
1456 intravisit::walk_param_bound(this, bound);
1459 _ => intravisit::walk_param_bound(self, bound),
1463 fn visit_poly_trait_ref(
1465 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1466 _modifier: hir::TraitBoundModifier,
1468 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1470 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1472 let next_early_index = self.next_early_index();
1473 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1475 let initial_bound_vars = binders.len() as u32;
1476 let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1477 let binders_iter = trait_ref
1478 .bound_generic_params
1480 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1482 .map(|(late_bound_idx, param)| {
1484 Region::late(initial_bound_vars + late_bound_idx as u32, self.tcx.hir(), param);
1485 let r = late_region_as_bound_region(self.tcx, &pair.1);
1486 lifetimes.insert(pair.0, pair.1);
1489 binders.extend(binders_iter);
1492 self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1494 // Always introduce a scope here, even if this is in a where clause and
1495 // we introduced the binders around the bounded Ty. In that case, we
1496 // just reuse the concatenation functionality also present in nested trait
1498 let scope = Scope::Binder {
1499 hir_id: trait_ref.trait_ref.hir_ref_id,
1503 track_lifetime_uses: true,
1504 opaque_type_parent: false,
1506 allow_late_bound: true,
1508 self.with(scope, |old_scope, this| {
1509 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1510 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1511 this.visit_trait_ref(&trait_ref.trait_ref);
1514 if should_pop_missing_lt {
1515 self.missing_named_lifetime_spots.pop();
1520 #[derive(Copy, Clone, PartialEq)]
1534 fn original_label(span: Span) -> Original {
1535 Original { kind: ShadowKind::Label, span }
1537 fn shadower_label(span: Span) -> Shadower {
1538 Shadower { kind: ShadowKind::Label, span }
1540 fn original_lifetime(span: Span) -> Original {
1541 Original { kind: ShadowKind::Lifetime, span }
1543 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1544 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1548 fn desc(&self) -> &'static str {
1550 ShadowKind::Label => "label",
1551 ShadowKind::Lifetime => "lifetime",
1556 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1557 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1558 // lifetime/lifetime shadowing is an error
1563 "{} name `{}` shadows a \
1564 {} name that is already in scope",
1565 shadower.kind.desc(),
1571 // shadowing involving a label is only a warning, due to issues with
1572 // labels and lifetimes not being macro-hygienic.
1573 tcx.sess.struct_span_warn(
1576 "{} name `{}` shadows a \
1577 {} name that is already in scope",
1578 shadower.kind.desc(),
1584 err.span_label(orig.span, "first declared here");
1585 err.span_label(shadower.span, format!("{} `{}` already in scope", orig.kind.desc(), name));
1589 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1590 // if one of the label shadows a lifetime or another label.
1591 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1592 struct GatherLabels<'a, 'tcx> {
1594 scope: ScopeRef<'a>,
1595 labels_in_fn: &'a mut Vec<Ident>,
1599 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1600 gather.visit_body(body);
1602 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1603 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1604 if let Some(label) = expression_label(ex) {
1605 for prior_label in &self.labels_in_fn[..] {
1606 // FIXME (#24278): non-hygienic comparison
1607 if label.name == prior_label.name {
1608 signal_shadowing_problem(
1611 original_label(prior_label.span),
1612 shadower_label(label.span),
1617 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1619 self.labels_in_fn.push(label);
1621 intravisit::walk_expr(self, ex)
1625 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1627 hir::ExprKind::Loop(_, Some(label), ..) => Some(label.ident),
1628 hir::ExprKind::Block(_, Some(label)) => Some(label.ident),
1633 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1636 Scope::Body { s, .. }
1637 | Scope::Elision { s, .. }
1638 | Scope::ObjectLifetimeDefault { s, .. }
1639 | Scope::Supertrait { s, .. }
1640 | Scope::TraitRefBoundary { s, .. } => {
1648 Scope::Binder { ref lifetimes, s, .. } => {
1649 // FIXME (#24278): non-hygienic comparison
1651 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1653 signal_shadowing_problem(
1656 original_lifetime(tcx.def_span(def.id().unwrap().expect_local())),
1657 shadower_label(label.span),
1668 fn compute_object_lifetime_defaults<'tcx>(
1670 item: &hir::Item<'_>,
1671 ) -> Option<&'tcx [ObjectLifetimeDefault]> {
1673 hir::ItemKind::Struct(_, ref generics)
1674 | hir::ItemKind::Union(_, ref generics)
1675 | hir::ItemKind::Enum(_, ref generics)
1676 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1678 origin: hir::OpaqueTyOrigin::TyAlias,
1681 | hir::ItemKind::TyAlias(_, ref generics)
1682 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1683 let result = object_lifetime_defaults_for_item(tcx, generics);
1686 let attrs = tcx.hir().attrs(item.hir_id());
1687 if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1688 let object_lifetime_default_reprs: String = result
1690 .map(|set| match *set {
1691 Set1::Empty => "BaseDefault".into(),
1692 Set1::One(Region::Static) => "'static".into(),
1693 Set1::One(Region::EarlyBound(mut i, _)) => generics
1696 .find_map(|param| match param.kind {
1697 GenericParamKind::Lifetime { .. } => {
1699 return Some(param.name.ident().to_string().into());
1707 Set1::One(_) => bug!(),
1708 Set1::Many => "Ambiguous".into(),
1710 .collect::<Vec<Cow<'static, str>>>()
1712 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1721 /// Scan the bounds and where-clauses on parameters to extract bounds
1722 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1723 /// for each type parameter.
1724 fn object_lifetime_defaults_for_item<'tcx>(
1726 generics: &hir::Generics<'_>,
1727 ) -> &'tcx [ObjectLifetimeDefault] {
1728 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1729 for bound in bounds {
1730 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1731 set.insert(lifetime.name.normalize_to_macros_2_0());
1736 let process_param = |param: &hir::GenericParam<'_>| match param.kind {
1737 GenericParamKind::Lifetime { .. } => None,
1738 GenericParamKind::Type { .. } => {
1739 let mut set = Set1::Empty;
1741 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1742 for predicate in generics.predicates {
1743 // Look for `type: ...` where clauses.
1744 let hir::WherePredicate::BoundPredicate(ref data) = *predicate else { continue };
1746 // Ignore `for<'a> type: ...` as they can change what
1747 // lifetimes mean (although we could "just" handle it).
1748 if !data.bound_generic_params.is_empty() {
1752 let res = match data.bounded_ty.kind {
1753 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1757 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1758 add_bounds(&mut set, &data.bounds);
1763 Set1::Empty => Set1::Empty,
1764 Set1::One(name) => {
1765 if name == hir::LifetimeName::Static {
1766 Set1::One(Region::Static)
1771 .filter_map(|param| match param.kind {
1772 GenericParamKind::Lifetime { .. } => {
1773 Some((param.hir_id, hir::LifetimeName::Param(param.name)))
1778 .find(|&(_, (_, lt_name))| lt_name == name)
1779 .map_or(Set1::Many, |(i, (id, _))| {
1780 let def_id = tcx.hir().local_def_id(id);
1781 Set1::One(Region::EarlyBound(i as u32, def_id.to_def_id()))
1785 Set1::Many => Set1::Many,
1788 GenericParamKind::Const { .. } => {
1789 // Generic consts don't impose any constraints.
1791 // We still store a dummy value here to allow generic parameters
1792 // in an arbitrary order.
1797 tcx.arena.alloc_from_iter(generics.params.iter().filter_map(process_param))
1800 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1801 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1803 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1805 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1806 let labels_in_fn = take(&mut self.labels_in_fn);
1807 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1808 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1809 let mut this = LifetimeContext {
1813 trait_definition_only: self.trait_definition_only,
1815 xcrate_object_lifetime_defaults,
1817 missing_named_lifetime_spots,
1819 let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1821 let _enter = span.enter();
1822 f(self.scope, &mut this);
1823 if !self.trait_definition_only {
1824 this.check_uses_for_lifetimes_defined_by_scope();
1827 self.labels_in_fn = this.labels_in_fn;
1828 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1829 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1832 /// helper method to determine the span to remove when suggesting the
1833 /// deletion of a lifetime
1834 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1835 generics.params.iter().enumerate().find_map(|(i, param)| {
1836 if param.name.ident() == name {
1837 if generics.params.len() == 1 {
1838 // if sole lifetime, remove the entire `<>` brackets
1841 // if removing within `<>` brackets, we also want to
1842 // delete a leading or trailing comma as appropriate
1843 if i >= generics.params.len() - 1 {
1844 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1846 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1855 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1856 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1857 fn suggest_eliding_single_use_lifetime(
1859 err: &mut Diagnostic,
1861 lifetime: &hir::Lifetime,
1863 let name = lifetime.name.ident();
1864 let remove_decl = self
1867 .and_then(|parent_def_id| parent_def_id.as_local())
1868 .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id))
1869 .and_then(|generics| self.lifetime_deletion_span(name, generics));
1871 let mut remove_use = None;
1872 let mut elide_use = None;
1873 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1874 for input in inputs {
1876 hir::TyKind::Rptr(lt, _) => {
1877 if lt.name.ident() == name {
1878 // include the trailing whitespace between the lifetime and type names
1879 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1884 .span_until_non_whitespace(lt_through_ty_span),
1889 hir::TyKind::Path(QPath::Resolved(_, path)) => {
1890 let last_segment = &path.segments[path.segments.len() - 1];
1891 let generics = last_segment.args();
1892 for arg in generics.args.iter() {
1893 if let GenericArg::Lifetime(lt) = arg {
1894 if lt.name.ident() == name {
1895 elide_use = Some(lt.span);
1906 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1907 if let Some(parent) =
1908 self.tcx.hir().find_by_def_id(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1911 Node::Item(item) => {
1912 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1913 find_arg_use_span(sig.decl.inputs);
1916 Node::ImplItem(impl_item) => {
1917 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1918 find_arg_use_span(sig.decl.inputs);
1926 let msg = "elide the single-use lifetime";
1927 match (remove_decl, remove_use, elide_use) {
1928 (Some(decl_span), Some(use_span), None) => {
1929 // if both declaration and use deletion spans start at the same
1930 // place ("start at" because the latter includes trailing
1931 // whitespace), then this is an in-band lifetime
1932 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1933 err.span_suggestion(
1937 Applicability::MachineApplicable,
1940 err.multipart_suggestion(
1942 vec![(decl_span, String::new()), (use_span, String::new())],
1943 Applicability::MachineApplicable,
1947 (Some(decl_span), None, Some(use_span)) => {
1948 err.multipart_suggestion(
1950 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1951 Applicability::MachineApplicable,
1958 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1959 let Scope::Binder { lifetimes: defined_by, .. } = self.scope else {
1960 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1964 let def_ids: Vec<_> = defined_by
1966 .flat_map(|region| match region {
1967 Region::EarlyBound(_, def_id)
1968 | Region::LateBound(_, _, def_id)
1969 | Region::Free(_, def_id) => Some(*def_id),
1971 Region::LateBoundAnon(..) | Region::Static => None,
1975 'lifetimes: for def_id in def_ids {
1976 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1978 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1981 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1985 match lifetimeuseset {
1986 Some(LifetimeUseSet::One(lifetime)) => {
1988 if let Some((id, span, name)) =
1989 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
1990 Node::Lifetime(hir_lifetime) => Some((
1991 hir_lifetime.hir_id,
1993 hir_lifetime.name.ident(),
1995 Node::GenericParam(param) => {
1996 Some((param.hir_id, param.span, param.name.ident()))
2001 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
2002 if name.name == kw::UnderscoreLifetime {
2006 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2007 if let Some(def_id) = parent_def_id.as_local() {
2008 // lifetimes in `derive` expansions don't count (Issue #53738)
2011 .get_attrs(def_id.to_def_id())
2013 .any(|attr| attr.has_name(sym::automatically_derived))
2018 // opaque types generated when desugaring an async function can have a single
2019 // use lifetime even if it is explicitly denied (Issue #77175)
2020 if let hir::Node::Item(hir::Item {
2021 kind: hir::ItemKind::OpaqueTy(ref opaque),
2023 }) = self.tcx.hir().get_by_def_id(def_id)
2025 if !matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn(..)) {
2026 continue 'lifetimes;
2028 // We want to do this only if the lifetime identifier is already defined
2029 // in the async function that generated this. Otherwise it could be
2030 // an opaque type defined by the developer and we still want this
2031 // lint to fail compilation
2032 for p in opaque.generics.params {
2033 if defined_by.contains_key(&p.name) {
2034 continue 'lifetimes;
2041 self.tcx.struct_span_lint_hir(
2042 lint::builtin::SINGLE_USE_LIFETIMES,
2046 let mut err = lint.build(&format!(
2047 "lifetime parameter `{}` only used once",
2050 if span == lifetime.span {
2051 // spans are the same for in-band lifetime declarations
2052 err.span_label(span, "this lifetime is only used here");
2054 err.span_label(span, "this lifetime...");
2055 err.span_label(lifetime.span, "...is used only here");
2057 self.suggest_eliding_single_use_lifetime(
2058 &mut err, def_id, lifetime,
2065 Some(LifetimeUseSet::Many) => {
2066 debug!("not one use lifetime");
2069 if let Some((id, span, name)) =
2070 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
2071 Node::Lifetime(hir_lifetime) => Some((
2072 hir_lifetime.hir_id,
2074 hir_lifetime.name.ident(),
2076 Node::GenericParam(param) => {
2077 Some((param.hir_id, param.span, param.name.ident()))
2082 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
2083 self.tcx.struct_span_lint_hir(
2084 lint::builtin::UNUSED_LIFETIMES,
2089 .build(&format!("lifetime parameter `{}` never used", name));
2090 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2091 if let Some(generics) =
2092 self.tcx.hir().get_generics(parent_def_id.expect_local())
2094 let unused_lt_span =
2095 self.lifetime_deletion_span(name, generics);
2096 if let Some(span) = unused_lt_span {
2097 err.span_suggestion(
2099 "elide the unused lifetime",
2101 Applicability::MachineApplicable,
2115 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
2117 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
2118 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
2119 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
2123 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
2125 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
2126 /// lifetimes may be interspersed together.
2128 /// If early bound lifetimes are present, we separate them into their own list (and likewise
2129 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
2130 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
2131 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
2132 /// ordering is not important there.
2133 fn visit_early_late<F>(
2135 parent_id: Option<LocalDefId>,
2137 decl: &'tcx hir::FnDecl<'tcx>,
2138 generics: &'tcx hir::Generics<'tcx>,
2141 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
2143 insert_late_bound_lifetimes(self.map, decl, generics);
2145 // Find the start of nested early scopes, e.g., in methods.
2146 let mut next_early_index = 0;
2147 if let Some(parent_id) = parent_id {
2148 let parent = self.tcx.hir().expect_item(parent_id);
2149 if sub_items_have_self_param(&parent.kind) {
2150 next_early_index += 1; // Self comes before lifetimes
2153 hir::ItemKind::Trait(_, _, ref generics, ..)
2154 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
2155 next_early_index += generics.params.len() as u32;
2161 let mut non_lifetime_count = 0;
2162 let mut named_late_bound_vars = 0;
2163 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
2166 .filter_map(|param| match param.kind {
2167 GenericParamKind::Lifetime { .. } => {
2168 if self.map.late_bound.contains(¶m.hir_id) {
2169 let late_bound_idx = named_late_bound_vars;
2170 named_late_bound_vars += 1;
2171 Some(Region::late(late_bound_idx, self.tcx.hir(), param))
2173 Some(Region::early(self.tcx.hir(), &mut next_early_index, param))
2176 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
2177 non_lifetime_count += 1;
2182 let next_early_index = next_early_index + non_lifetime_count;
2184 let binders: Vec<_> = generics
2188 matches!(param.kind, GenericParamKind::Lifetime { .. })
2189 && self.map.late_bound.contains(¶m.hir_id)
2192 .map(|(late_bound_idx, param)| {
2193 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
2194 late_region_as_bound_region(self.tcx, &pair.1)
2197 self.map.late_bound_vars.insert(hir_id, binders);
2198 let scope = Scope::Binder {
2203 opaque_type_parent: true,
2204 track_lifetime_uses: false,
2205 scope_type: BinderScopeType::Normal,
2206 allow_late_bound: true,
2208 self.with(scope, move |old_scope, this| {
2209 this.check_lifetime_params(old_scope, &generics.params);
2214 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
2215 let mut scope = self.scope;
2218 Scope::Root => return 0,
2220 Scope::Binder { next_early_index, opaque_type_parent, .. }
2221 if (!only_opaque_type_parent || opaque_type_parent) =>
2223 return next_early_index;
2226 Scope::Binder { s, .. }
2227 | Scope::Body { s, .. }
2228 | Scope::Elision { s, .. }
2229 | Scope::ObjectLifetimeDefault { s, .. }
2230 | Scope::Supertrait { s, .. }
2231 | Scope::TraitRefBoundary { s, .. } => scope = s,
2236 /// Returns the next index one would use for an early-bound-region
2237 /// if extending the current scope.
2238 fn next_early_index(&self) -> u32 {
2239 self.next_early_index_helper(true)
2242 /// Returns the next index one would use for an `impl Trait` that
2243 /// is being converted into an opaque type alias `impl Trait`. This will be the
2244 /// next early index from the enclosing item, for the most
2245 /// part. See the `opaque_type_parent` field for more info.
2246 fn next_early_index_for_opaque_type(&self) -> u32 {
2247 self.next_early_index_helper(false)
2250 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2251 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
2253 // If we've already reported an error, just ignore `lifetime_ref`.
2254 if let LifetimeName::Error = lifetime_ref.name {
2258 // Walk up the scope chain, tracking the number of fn scopes
2259 // that we pass through, until we find a lifetime with the
2260 // given name or we run out of scopes.
2262 let mut late_depth = 0;
2263 let mut scope = self.scope;
2264 let mut outermost_body = None;
2267 Scope::Body { id, s } => {
2268 outermost_body = Some(id);
2276 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
2277 match lifetime_ref.name {
2278 LifetimeName::Param(param_name) => {
2279 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
2281 break Some(def.shifted(late_depth));
2284 _ => bug!("expected LifetimeName::Param"),
2287 BinderScopeType::Normal => late_depth += 1,
2288 BinderScopeType::Concatenating => {}
2293 Scope::Elision { s, .. }
2294 | Scope::ObjectLifetimeDefault { s, .. }
2295 | Scope::Supertrait { s, .. }
2296 | Scope::TraitRefBoundary { s, .. } => {
2302 if let Some(mut def) = result {
2303 if let Region::EarlyBound(..) = def {
2304 // Do not free early-bound regions, only late-bound ones.
2305 } else if let Some(body_id) = outermost_body {
2306 let fn_id = self.tcx.hir().body_owner(body_id);
2307 match self.tcx.hir().get(fn_id) {
2308 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
2309 | Node::TraitItem(&hir::TraitItem {
2310 kind: hir::TraitItemKind::Fn(..), ..
2312 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
2313 let scope = self.tcx.hir().local_def_id(fn_id);
2314 def = Region::Free(scope.to_def_id(), def.id().unwrap());
2320 self.insert_lifetime(lifetime_ref, def);
2322 self.tcx.sess.delay_span_bug(
2324 &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
2329 fn visit_segment_args(
2333 generic_args: &'tcx hir::GenericArgs<'tcx>,
2336 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
2337 res, depth, generic_args,
2340 if generic_args.parenthesized {
2341 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
2345 let mut elide_lifetimes = true;
2346 let lifetimes: Vec<_> = generic_args
2349 .filter_map(|arg| match arg {
2350 hir::GenericArg::Lifetime(lt) => {
2351 if !lt.is_elided() {
2352 elide_lifetimes = false;
2359 // We short-circuit here if all are elided in order to pluralize
2361 if elide_lifetimes {
2362 self.resolve_elided_lifetimes(&lifetimes);
2364 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
2367 // Figure out if this is a type/trait segment,
2368 // which requires object lifetime defaults.
2369 let parent_def_id = |this: &mut Self, def_id: DefId| {
2370 let def_key = this.tcx.def_key(def_id);
2371 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
2373 let type_def_id = match res {
2374 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
2375 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
2383 ) if depth == 0 => Some(def_id),
2387 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
2389 // Compute a vector of defaults, one for each type parameter,
2390 // per the rules given in RFCs 599 and 1156. Example:
2393 // struct Foo<'a, T: 'a, U> { }
2396 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
2397 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
2398 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
2401 // Therefore, we would compute `object_lifetime_defaults` to a
2402 // vector like `['x, 'static]`. Note that the vector only
2403 // includes type parameters.
2404 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
2406 let mut scope = self.scope;
2409 Scope::Root => break false,
2411 Scope::Body { .. } => break true,
2413 Scope::Binder { s, .. }
2414 | Scope::Elision { s, .. }
2415 | Scope::ObjectLifetimeDefault { s, .. }
2416 | Scope::Supertrait { s, .. }
2417 | Scope::TraitRefBoundary { s, .. } => {
2424 let map = &self.map;
2425 let set_to_region = |set: &ObjectLifetimeDefault| match *set {
2430 Some(Region::Static)
2434 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2435 GenericArg::Lifetime(lt) => Some(lt),
2438 r.subst(lifetimes, map)
2442 if let Some(def_id) = def_id.as_local() {
2443 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2445 .object_lifetime_defaults(id.owner)
2452 self.xcrate_object_lifetime_defaults
2454 .or_insert_with(|| {
2455 tcx.generics_of(def_id)
2458 .filter_map(|param| match param.kind {
2459 GenericParamDefKind::Type { object_lifetime_default, .. } => {
2460 Some(object_lifetime_default)
2462 GenericParamDefKind::Const { .. } => Some(Set1::Empty),
2463 GenericParamDefKind::Lifetime => None,
2473 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2476 for arg in generic_args.args {
2478 GenericArg::Lifetime(_) => {}
2479 GenericArg::Type(ty) => {
2480 if let Some(<) = object_lifetime_defaults.get(i) {
2481 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2482 self.with(scope, |_, this| this.visit_ty(ty));
2488 GenericArg::Const(ct) => {
2489 self.visit_anon_const(&ct.value);
2492 GenericArg::Infer(inf) => {
2493 self.visit_id(inf.hir_id);
2499 // Hack: when resolving the type `XX` in binding like `dyn
2500 // Foo<'b, Item = XX>`, the current object-lifetime default
2501 // would be to examine the trait `Foo` to check whether it has
2502 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2503 // declared like so, then the default object lifetime bound in
2504 // `XX` should be `'b`:
2512 // but if we just have `type Item;`, then it would be
2513 // `'static`. However, we don't get all of this logic correct.
2515 // Instead, we do something hacky: if there are no lifetime parameters
2516 // to the trait, then we simply use a default object lifetime
2517 // bound of `'static`, because there is no other possibility. On the other hand,
2518 // if there ARE lifetime parameters, then we require the user to give an
2519 // explicit bound for now.
2521 // This is intended to leave room for us to implement the
2522 // correct behavior in the future.
2523 let has_lifetime_parameter =
2524 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2526 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2527 // in the trait ref `YY<...>` in `Item: YY<...>`.
2528 for binding in generic_args.bindings {
2529 let scope = Scope::ObjectLifetimeDefault {
2530 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2533 if let Some(type_def_id) = type_def_id {
2534 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2539 self.with(scope, |_, this| {
2540 let scope = Scope::Supertrait {
2541 lifetimes: lifetimes.unwrap_or_default(),
2544 this.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2547 self.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2552 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2553 /// associated type name and starting trait.
2554 /// For example, imagine we have
2555 /// ```ignore (illustrative)
2556 /// trait Foo<'a, 'b> {
2559 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2560 /// trait Bar: for<'b> Bar<'b> {}
2562 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2563 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2564 fn supertrait_hrtb_lifetimes(
2568 ) -> Option<Vec<ty::BoundVariableKind>> {
2569 let trait_defines_associated_type_named = |trait_def_id: DefId| {
2570 tcx.associated_items(trait_def_id)
2571 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2575 use smallvec::{smallvec, SmallVec};
2576 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2577 smallvec![(def_id, smallvec![])];
2578 let mut visited: FxHashSet<DefId> = FxHashSet::default();
2580 let Some((def_id, bound_vars)) = stack.pop() else {
2583 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2584 // there being no supertrait HRTBs.
2585 match tcx.def_kind(def_id) {
2586 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2590 if trait_defines_associated_type_named(def_id) {
2591 break Some(bound_vars.into_iter().collect());
2594 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2595 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2596 let bound_predicate = pred.kind();
2597 match bound_predicate.skip_binder() {
2598 ty::PredicateKind::Trait(data) => {
2599 // The order here needs to match what we would get from `subst_supertrait`
2600 let pred_bound_vars = bound_predicate.bound_vars();
2601 let mut all_bound_vars = bound_vars.clone();
2602 all_bound_vars.extend(pred_bound_vars.iter());
2603 let super_def_id = data.trait_ref.def_id;
2604 Some((super_def_id, all_bound_vars))
2610 let obligations = obligations.filter(|o| visited.insert(o.0));
2611 stack.extend(obligations);
2615 #[tracing::instrument(level = "debug", skip(self))]
2616 fn visit_fn_like_elision(
2618 inputs: &'tcx [hir::Ty<'tcx>],
2619 output: Option<&'tcx hir::Ty<'tcx>>,
2621 debug!("visit_fn_like_elision: enter");
2622 let mut scope = &*self.scope;
2625 Scope::Binder { hir_id, allow_late_bound: true, .. } => {
2628 Scope::ObjectLifetimeDefault { ref s, .. }
2629 | Scope::Elision { ref s, .. }
2630 | Scope::Supertrait { ref s, .. }
2631 | Scope::TraitRefBoundary { ref s, .. } => {
2635 | Scope::Body { .. }
2636 | Scope::Binder { allow_late_bound: false, .. } => {
2637 // See issues #83907 and #83693. Just bail out from looking inside.
2638 // See the issue #95023 for not allowing late bound
2639 self.tcx.sess.delay_span_bug(
2640 rustc_span::DUMMY_SP,
2641 "In fn_like_elision without appropriate scope above",
2647 // While not strictly necessary, we gather anon lifetimes *before* actually
2648 // visiting the argument types.
2649 let mut gather = GatherAnonLifetimes { anon_count: 0 };
2650 for input in inputs {
2651 gather.visit_ty(input);
2653 trace!(?gather.anon_count);
2654 let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2655 let named_late_bound_vars = late_bound_vars.len() as u32;
2656 late_bound_vars.extend(
2657 (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2659 let arg_scope = Scope::Elision {
2660 elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2663 self.with(arg_scope, |_, this| {
2664 for input in inputs {
2665 this.visit_ty(input);
2669 let Some(output) = output else { return };
2671 debug!("determine output");
2673 // Figure out if there's a body we can get argument names from,
2674 // and whether there's a `self` argument (treated specially).
2675 let mut assoc_item_kind = None;
2676 let mut impl_self = None;
2677 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2678 let body = match self.tcx.hir().get(parent) {
2679 // `fn` definitions and methods.
2680 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2682 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2683 if let hir::ItemKind::Trait(.., ref trait_items) =
2684 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2687 trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2690 hir::TraitFn::Required(_) => None,
2691 hir::TraitFn::Provided(body) => Some(body),
2695 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2696 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2697 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2699 impl_self = Some(self_ty);
2701 items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2706 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2707 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2708 // Everything else (only closures?) doesn't
2709 // actually enjoy elision in return types.
2711 self.visit_ty(output);
2716 let has_self = match assoc_item_kind {
2717 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2721 // In accordance with the rules for lifetime elision, we can determine
2722 // what region to use for elision in the output type in two ways.
2723 // First (determined here), if `self` is by-reference, then the
2724 // implied output region is the region of the self parameter.
2726 struct SelfVisitor<'a> {
2727 map: &'a NamedRegionMap,
2728 impl_self: Option<&'a hir::TyKind<'a>>,
2729 lifetime: Set1<Region>,
2732 impl SelfVisitor<'_> {
2733 // Look for `self: &'a Self` - also desugared from `&'a self`,
2734 // and if that matches, use it for elision and return early.
2735 fn is_self_ty(&self, res: Res) -> bool {
2736 if let Res::SelfTy { .. } = res {
2740 // Can't always rely on literal (or implied) `Self` due
2741 // to the way elision rules were originally specified.
2742 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2746 // Permit the types that unambiguously always
2747 // result in the same type constructor being used
2748 // (it can't differ between `Self` and `self`).
2749 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2750 | Res::PrimTy(_) => return res == path.res,
2759 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2760 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2761 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2762 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2764 if self.is_self_ty(path.res) {
2765 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2766 self.lifetime.insert(*lifetime);
2771 intravisit::walk_ty(self, ty)
2775 let mut visitor = SelfVisitor {
2777 impl_self: impl_self.map(|ty| &ty.kind),
2778 lifetime: Set1::Empty,
2780 visitor.visit_ty(&inputs[0]);
2781 if let Set1::One(lifetime) = visitor.lifetime {
2782 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2783 self.with(scope, |_, this| this.visit_ty(output));
2788 // Second, if there was exactly one lifetime (either a substitution or a
2789 // reference) in the arguments, then any anonymous regions in the output
2790 // have that lifetime.
2791 let mut possible_implied_output_region = None;
2792 let mut lifetime_count = 0;
2793 let arg_lifetimes = inputs
2796 .skip(has_self as usize)
2798 let mut gather = GatherLifetimes {
2800 outer_index: ty::INNERMOST,
2801 have_bound_regions: false,
2802 lifetimes: Default::default(),
2804 gather.visit_ty(input);
2806 lifetime_count += gather.lifetimes.len();
2808 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2809 // there's a chance that the unique lifetime of this
2810 // iteration will be the appropriate lifetime for output
2811 // parameters, so lets store it.
2812 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2815 ElisionFailureInfo {
2818 lifetime_count: gather.lifetimes.len(),
2819 have_bound_regions: gather.have_bound_regions,
2825 let elide = if lifetime_count == 1 {
2826 Elide::Exact(possible_implied_output_region.unwrap())
2828 Elide::Error(arg_lifetimes)
2833 let scope = Scope::Elision { elide, s: self.scope };
2834 self.with(scope, |_, this| this.visit_ty(output));
2836 struct GatherLifetimes<'a> {
2837 map: &'a NamedRegionMap,
2838 outer_index: ty::DebruijnIndex,
2839 have_bound_regions: bool,
2840 lifetimes: FxHashSet<Region>,
2843 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2844 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2845 if let hir::TyKind::BareFn(_) = ty.kind {
2846 self.outer_index.shift_in(1);
2849 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2850 for bound in bounds {
2851 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2854 // Stay on the safe side and don't include the object
2855 // lifetime default (which may not end up being used).
2856 if !lifetime.is_elided() {
2857 self.visit_lifetime(lifetime);
2861 intravisit::walk_ty(self, ty);
2864 if let hir::TyKind::BareFn(_) = ty.kind {
2865 self.outer_index.shift_out(1);
2869 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2870 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2871 // FIXME(eddyb) Do we want this? It only makes a difference
2872 // if this `for<'a>` lifetime parameter is never used.
2873 self.have_bound_regions = true;
2876 intravisit::walk_generic_param(self, param);
2879 fn visit_poly_trait_ref(
2881 trait_ref: &hir::PolyTraitRef<'_>,
2882 modifier: hir::TraitBoundModifier,
2884 self.outer_index.shift_in(1);
2885 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2886 self.outer_index.shift_out(1);
2889 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2890 if let hir::GenericBound::LangItemTrait { .. } = bound {
2891 self.outer_index.shift_in(1);
2892 intravisit::walk_param_bound(self, bound);
2893 self.outer_index.shift_out(1);
2895 intravisit::walk_param_bound(self, bound);
2899 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2900 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2902 Region::LateBound(debruijn, _, _)
2903 | Region::LateBoundAnon(debruijn, _, _)
2904 if debruijn < self.outer_index =>
2906 self.have_bound_regions = true;
2909 // FIXME(jackh726): nested trait refs?
2910 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2917 struct GatherAnonLifetimes {
2920 impl<'v> Visitor<'v> for GatherAnonLifetimes {
2921 #[instrument(skip(self), level = "trace")]
2922 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2923 // If we enter a `BareFn`, then we enter a *new* binding scope
2924 if let hir::TyKind::BareFn(_) = ty.kind {
2927 intravisit::walk_ty(self, ty);
2930 fn visit_generic_args(
2933 generic_args: &'v hir::GenericArgs<'v>,
2935 // parenthesized args enter a new elision scope
2936 if generic_args.parenthesized {
2939 intravisit::walk_generic_args(self, path_span, generic_args)
2942 #[instrument(skip(self), level = "trace")]
2943 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2944 if lifetime_ref.is_elided() {
2945 self.anon_count += 1;
2951 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
2952 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2954 if lifetime_refs.is_empty() {
2958 let mut late_depth = 0;
2959 let mut scope = self.scope;
2960 let mut lifetime_names = FxHashSet::default();
2961 let mut lifetime_spans = vec![];
2964 // Do not assign any resolution, it will be inferred.
2965 Scope::Body { .. } => return,
2967 Scope::Root => break None,
2969 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
2970 // collect named lifetimes for suggestions
2971 for name in lifetimes.keys() {
2972 if let hir::ParamName::Plain(name) = name {
2973 lifetime_names.insert(name.name);
2974 lifetime_spans.push(name.span);
2978 BinderScopeType::Normal => late_depth += 1,
2979 BinderScopeType::Concatenating => {}
2985 elide: Elide::FreshLateAnon(named_late_bound_vars, ref counter),
2988 for lifetime_ref in lifetime_refs {
2990 Region::late_anon(named_late_bound_vars, counter).shifted(late_depth);
2992 self.insert_lifetime(lifetime_ref, lifetime);
2997 Scope::Elision { elide: Elide::Exact(l), .. } => {
2998 let lifetime = l.shifted(late_depth);
2999 for lifetime_ref in lifetime_refs {
3000 self.insert_lifetime(lifetime_ref, lifetime);
3005 Scope::Elision { elide: Elide::Error(ref e), ref s, .. } => {
3009 Scope::Binder { ref lifetimes, s, .. } => {
3010 // Collect named lifetimes for suggestions.
3011 for name in lifetimes.keys() {
3012 if let hir::ParamName::Plain(name) = name {
3013 lifetime_names.insert(name.name);
3014 lifetime_spans.push(name.span);
3019 Scope::ObjectLifetimeDefault { ref s, .. }
3020 | Scope::Elision { ref s, .. }
3021 | Scope::TraitRefBoundary { ref s, .. } => {
3030 Scope::Elision { elide: Elide::Forbid, .. } => break None,
3032 Scope::ObjectLifetimeDefault { s, .. }
3033 | Scope::Supertrait { s, .. }
3034 | Scope::TraitRefBoundary { s, .. } => {
3040 // If we specifically need the `scope_for_path` map, then we're in the
3041 // diagnostic pass and we don't want to emit more errors.
3042 if self.map.scope_for_path.is_some() {
3043 self.tcx.sess.delay_span_bug(
3044 rustc_span::DUMMY_SP,
3045 "Encountered unexpected errors during diagnostics related part",
3050 let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3052 let mut spans_dedup = spans.clone();
3053 spans_dedup.dedup();
3054 let spans_with_counts: Vec<_> = spans_dedup
3056 .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
3059 let mut err = self.report_missing_lifetime_specifiers(spans.clone(), lifetime_refs.len());
3061 if let Some(params) = error {
3062 // If there's no lifetime available, suggest `'static`.
3063 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
3064 lifetime_names.insert(kw::StaticLifetime);
3068 self.add_missing_lifetime_specifiers_label(
3073 error.unwrap_or(&[]),
3078 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
3079 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
3080 let mut late_depth = 0;
3081 let mut scope = self.scope;
3082 let lifetime = loop {
3084 Scope::Binder { s, scope_type, .. } => {
3086 BinderScopeType::Normal => late_depth += 1,
3087 BinderScopeType::Concatenating => {}
3092 Scope::Root | Scope::Elision { .. } => break Region::Static,
3094 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
3096 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
3098 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
3103 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
3106 fn check_lifetime_params(
3108 old_scope: ScopeRef<'_>,
3109 params: &'tcx [hir::GenericParam<'tcx>],
3111 let lifetimes: Vec<_> = params
3113 .filter_map(|param| match param.kind {
3114 GenericParamKind::Lifetime { .. } => {
3115 Some((param, param.name.normalize_to_macros_2_0()))
3120 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
3121 if let hir::ParamName::Plain(_) = lifetime_i_name {
3122 let name = lifetime_i_name.ident().name;
3123 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
3124 self.tcx.sess.delay_span_bug(
3126 &format!("invalid lifetime parameter name: `{}`", lifetime_i.name.ident()),
3131 // It is a hard error to shadow a lifetime within the same scope.
3132 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
3133 if lifetime_i_name == lifetime_j_name {
3138 "lifetime name `{}` declared twice in the same scope",
3139 lifetime_j.name.ident()
3141 .span_label(lifetime_j.span, "declared twice")
3142 .span_label(lifetime_i.span, "previous declaration here")
3147 // It is a soft error to shadow a lifetime within a parent scope.
3148 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
3152 fn check_lifetime_param_for_shadowing(
3154 mut old_scope: ScopeRef<'_>,
3155 param: &'tcx hir::GenericParam<'tcx>,
3157 for label in &self.labels_in_fn {
3158 // FIXME (#24278): non-hygienic comparison
3159 if param.name.ident().name == label.name {
3160 signal_shadowing_problem(
3163 original_label(label.span),
3164 shadower_lifetime(¶m),
3172 Scope::Body { s, .. }
3173 | Scope::Elision { s, .. }
3174 | Scope::ObjectLifetimeDefault { s, .. }
3175 | Scope::Supertrait { s, .. }
3176 | Scope::TraitRefBoundary { s, .. } => {
3184 Scope::Binder { ref lifetimes, s, .. } => {
3185 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
3186 signal_shadowing_problem(
3188 param.name.ident().name,
3189 original_lifetime(self.tcx.def_span(def.id().unwrap())),
3190 shadower_lifetime(¶m),
3201 /// Returns `true` if, in the current scope, replacing `'_` would be
3202 /// equivalent to a single-use lifetime.
3203 fn track_lifetime_uses(&self) -> bool {
3204 let mut scope = self.scope;
3207 Scope::Root => break false,
3209 // Inside of items, it depends on the kind of item.
3210 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
3212 // Inside a body, `'_` will use an inference variable,
3214 Scope::Body { .. } => break true,
3216 // A lifetime only used in a fn argument could as well
3217 // be replaced with `'_`, as that would generate a
3219 Scope::Elision { elide: Elide::FreshLateAnon(..), .. } => break true,
3221 // In the return type or other such place, `'_` is not
3222 // going to make a fresh name, so we cannot
3223 // necessarily replace a single-use lifetime with
3226 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
3229 Scope::ObjectLifetimeDefault { s, .. }
3230 | Scope::Supertrait { s, .. }
3231 | Scope::TraitRefBoundary { s, .. } => scope = s,
3236 #[tracing::instrument(level = "debug", skip(self))]
3237 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
3239 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
3240 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
3242 self.map.defs.insert(lifetime_ref.hir_id, def);
3245 Region::LateBoundAnon(..) | Region::Static => {
3246 // These are anonymous lifetimes or lifetimes that are not declared.
3249 Region::Free(_, def_id)
3250 | Region::LateBound(_, _, def_id)
3251 | Region::EarlyBound(_, def_id) => {
3252 // A lifetime declared by the user.
3253 let track_lifetime_uses = self.track_lifetime_uses();
3254 debug!(?track_lifetime_uses);
3255 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
3256 debug!("first use of {:?}", def_id);
3257 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
3259 debug!("many uses of {:?}", def_id);
3260 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
3266 /// Sometimes we resolve a lifetime, but later find that it is an
3267 /// error (esp. around impl trait). In that case, we remove the
3268 /// entry into `map.defs` so as not to confuse later code.
3269 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
3270 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
3271 assert_eq!(old_value, Some(bad_def));
3275 /// Detects late-bound lifetimes and inserts them into
3276 /// `map.late_bound`.
3278 /// A region declared on a fn is **late-bound** if:
3279 /// - it is constrained by an argument type;
3280 /// - it does not appear in a where-clause.
3282 /// "Constrained" basically means that it appears in any type but
3283 /// not amongst the inputs to a projection. In other words, `<&'a
3284 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
3285 #[tracing::instrument(level = "debug", skip(map))]
3286 fn insert_late_bound_lifetimes(
3287 map: &mut NamedRegionMap,
3288 decl: &hir::FnDecl<'_>,
3289 generics: &hir::Generics<'_>,
3291 let mut constrained_by_input = ConstrainedCollector::default();
3292 for arg_ty in decl.inputs {
3293 constrained_by_input.visit_ty(arg_ty);
3296 let mut appears_in_output = AllCollector::default();
3297 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
3299 debug!(?constrained_by_input.regions);
3301 // Walk the lifetimes that appear in where clauses.
3303 // Subtle point: because we disallow nested bindings, we can just
3304 // ignore binders here and scrape up all names we see.
3305 let mut appears_in_where_clause = AllCollector::default();
3306 appears_in_where_clause.visit_generics(generics);
3307 debug!(?appears_in_where_clause.regions);
3309 // Late bound regions are those that:
3310 // - appear in the inputs
3311 // - do not appear in the where-clauses
3312 // - are not implicitly captured by `impl Trait`
3313 for param in generics.params {
3315 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
3317 // Neither types nor consts are late-bound.
3318 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
3321 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
3322 // appears in the where clauses? early-bound.
3323 if appears_in_where_clause.regions.contains(<_name) {
3327 // does not appear in the inputs, but appears in the return type? early-bound.
3328 if !constrained_by_input.regions.contains(<_name)
3329 && appears_in_output.regions.contains(<_name)
3334 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
3336 let inserted = map.late_bound.insert(param.hir_id);
3337 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
3343 struct ConstrainedCollector {
3344 regions: FxHashSet<hir::LifetimeName>,
3347 impl<'v> Visitor<'v> for ConstrainedCollector {
3348 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3351 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
3353 // ignore lifetimes appearing in associated type
3354 // projections, as they are not *constrained*
3358 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
3359 // consider only the lifetimes on the final
3360 // segment; I am not sure it's even currently
3361 // valid to have them elsewhere, but even if it
3362 // is, those would be potentially inputs to
3364 if let Some(last_segment) = path.segments.last() {
3365 self.visit_path_segment(path.span, last_segment);
3370 intravisit::walk_ty(self, ty);
3375 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3376 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3381 struct AllCollector {
3382 regions: FxHashSet<hir::LifetimeName>,
3385 impl<'v> Visitor<'v> for AllCollector {
3386 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3387 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());