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 is_in_const_generic: bool,
169 /// Indicates that we only care about the definition of a trait. This should
170 /// be false if the `Item` we are resolving lifetimes for is not a trait or
171 /// we eventually need lifetimes resolve for trait items.
172 trait_definition_only: bool,
174 /// List of labels in the function/method currently under analysis.
175 labels_in_fn: Vec<Ident>,
177 /// Cache for cross-crate per-definition object lifetime defaults.
178 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
180 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
182 /// When encountering an undefined named lifetime, we will suggest introducing it in these
184 crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
189 /// Declares lifetimes, and each can be early-bound or late-bound.
190 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
191 /// it should be shifted by the number of `Binder`s in between the
192 /// declaration `Binder` and the location it's referenced from.
194 /// We use an IndexMap here because we want these lifetimes in order
196 lifetimes: FxIndexMap<hir::ParamName, Region>,
198 /// if we extend this scope with another scope, what is the next index
199 /// we should use for an early-bound region?
200 next_early_index: u32,
202 /// Flag is set to true if, in this binder, `'_` would be
203 /// equivalent to a "single-use region". This is true on
204 /// impls, but not other kinds of items.
205 track_lifetime_uses: bool,
207 /// Whether or not this binder would serve as the parent
208 /// binder for opaque types introduced within. For example:
211 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
214 /// Here, the opaque types we create for the `impl Trait`
215 /// and `impl Trait2` references will both have the `foo` item
216 /// as their parent. When we get to `impl Trait2`, we find
217 /// that it is nested within the `for<>` binder -- this flag
218 /// allows us to skip that when looking for the parent binder
219 /// of the resulting opaque type.
220 opaque_type_parent: bool,
222 scope_type: BinderScopeType,
224 /// The late bound vars for a given item are stored by `HirId` to be
225 /// queried later. However, if we enter an elision scope, we have to
226 /// later append the elided bound vars to the list and need to know what
232 /// In some cases not allowing late bounds allows us to avoid ICEs.
233 /// This is almost ways set to true.
234 allow_late_bound: bool,
237 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
238 /// if this is a fn body, otherwise the original definitions are used.
239 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
240 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
246 /// A scope which either determines unspecified lifetimes or errors
247 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
253 /// Use a specific lifetime (if `Some`) or leave it unset (to be
254 /// inferred in a function body or potentially error outside one),
255 /// for the default choice of lifetime in a trait object type.
256 ObjectLifetimeDefault {
257 lifetime: Option<Region>,
261 /// When we have nested trait refs, we concatenate late bound vars for inner
262 /// trait refs from outer ones. But we also need to include any HRTB
263 /// lifetimes encountered when identifying the trait that an associated type
266 lifetimes: Vec<ty::BoundVariableKind>,
277 #[derive(Copy, Clone, Debug)]
278 enum BinderScopeType {
279 /// Any non-concatenating binder scopes.
281 /// Within a syntactic trait ref, there may be multiple poly trait refs that
282 /// are nested (under the `associated_type_bounds` feature). The binders of
283 /// the inner poly trait refs are extended from the outer poly trait refs
284 /// and don't increase the late bound depth. If you had
285 /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
286 /// would be `Concatenating`. This also used in trait refs in where clauses
287 /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
288 /// out any lifetimes because they aren't needed to show the two scopes).
289 /// The inner `for<>` has a scope of `Concatenating`.
293 // A helper struct for debugging scopes without printing parent scopes
294 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
296 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 .debug_struct("Binder")
310 .field("lifetimes", lifetimes)
311 .field("next_early_index", next_early_index)
312 .field("track_lifetime_uses", track_lifetime_uses)
313 .field("opaque_type_parent", opaque_type_parent)
314 .field("scope_type", scope_type)
315 .field("hir_id", hir_id)
317 .field("allow_late_bound", allow_late_bound)
319 Scope::Body { id, s: _ } => {
320 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
322 Scope::Elision { elide, s: _ } => {
323 f.debug_struct("Elision").field("elide", elide).field("s", &"..").finish()
325 Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
326 .debug_struct("ObjectLifetimeDefault")
327 .field("lifetime", lifetime)
330 Scope::Supertrait { lifetimes, s: _ } => f
331 .debug_struct("Supertrait")
332 .field("lifetimes", lifetimes)
335 Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
336 Scope::Root => f.debug_struct("Root").finish(),
341 #[derive(Clone, Debug)]
343 /// Use a fresh anonymous late-bound lifetime each time, by
344 /// incrementing the counter to generate sequential indices. All
345 /// anonymous lifetimes must start *after* named bound vars.
346 FreshLateAnon(u32, Cell<u32>),
347 /// Always use this one lifetime.
349 /// Less or more than one lifetime were found, error on unspecified.
350 Error(Vec<ElisionFailureInfo>),
351 /// Forbid lifetime elision inside of a larger scope where it would be
352 /// permitted. For example, in let position impl trait.
356 #[derive(Clone, Debug)]
357 crate struct ElisionFailureInfo {
358 /// Where we can find the argument pattern.
359 crate parent: Option<hir::BodyId>,
360 /// The index of the argument in the original definition.
362 crate lifetime_count: usize,
363 crate have_bound_regions: bool,
367 type ScopeRef<'a> = &'a Scope<'a>;
369 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
371 pub fn provide(providers: &mut ty::query::Providers) {
372 *providers = ty::query::Providers {
373 resolve_lifetimes_trait_definition,
376 named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
378 object_lifetime_defaults: |tcx, id| match tcx.hir().find_by_def_id(id) {
379 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
382 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
383 lifetime_scope_map: |tcx, id| {
384 let item_id = item_for(tcx, id);
385 do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
392 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
393 /// Also does not generate any diagnostics.
395 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
396 /// resolves lifetimes only within the trait "header" -- that is, the trait
397 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
398 /// lifetimes within the trait and its items. There is room to refactor this,
399 /// for example to resolve lifetimes for each trait item in separate queries,
400 /// but it's convenient to do the entire trait at once because the lifetimes
401 /// from the trait definition are in scope within the trait items as well.
403 /// The reason for this separate call is to resolve what would otherwise
404 /// be a cycle. Consider this example:
410 /// trait Sub<'b>: for<'a> Base<'a> {
411 /// type SubItem: Sub<BaseItem = &'b u32>;
415 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
416 /// To figure out the index of `'b`, we have to know about the supertraits
417 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
418 /// (This is because we -- currently at least -- flatten all the late-bound
419 /// lifetimes into a single binder.) This requires us to resolve the
420 /// *trait definition* of `Sub`; basically just enough lifetime information
421 /// to look at the supertraits.
422 #[tracing::instrument(level = "debug", skip(tcx))]
423 fn resolve_lifetimes_trait_definition(
425 local_def_id: LocalDefId,
426 ) -> ResolveLifetimes {
427 convert_named_region_map(tcx, do_resolve(tcx, local_def_id, true, false))
430 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
431 /// You should not read the result of this query directly, but rather use
432 /// `named_region_map`, `is_late_bound_map`, etc.
433 #[tracing::instrument(level = "debug", skip(tcx))]
434 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
435 convert_named_region_map(tcx, do_resolve(tcx, local_def_id, false, false))
440 local_def_id: LocalDefId,
441 trait_definition_only: bool,
442 with_scope_for_path: bool,
443 ) -> NamedRegionMap {
444 let item = tcx.hir().expect_item(local_def_id);
445 let mut named_region_map = NamedRegionMap {
446 defs: Default::default(),
447 late_bound: Default::default(),
448 late_bound_vars: Default::default(),
449 scope_for_path: with_scope_for_path.then(|| Default::default()),
451 let mut visitor = LifetimeContext {
453 map: &mut named_region_map,
455 is_in_const_generic: false,
456 trait_definition_only,
457 labels_in_fn: vec![],
458 xcrate_object_lifetime_defaults: Default::default(),
459 lifetime_uses: &mut Default::default(),
460 missing_named_lifetime_spots: vec![],
462 visitor.visit_item(item);
467 fn convert_named_region_map(tcx: TyCtxt<'_>, named_region_map: NamedRegionMap) -> ResolveLifetimes {
468 let mut rl = ResolveLifetimes::default();
470 for (hir_id, v) in named_region_map.defs {
471 let map = rl.defs.entry(hir_id.owner).or_default();
472 map.insert(hir_id.local_id, v);
474 for hir_id in named_region_map.late_bound {
475 let map = rl.late_bound.entry(hir_id.owner).or_default();
476 let def_id = tcx.hir().local_def_id(hir_id);
479 for (hir_id, v) in named_region_map.late_bound_vars {
480 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
481 map.insert(hir_id.local_id, v);
488 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
489 /// There are two important things this does.
490 /// First, we have to resolve lifetimes for
491 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
492 /// where we can have relevant lifetimes.
493 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
494 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
495 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
496 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
497 /// `resolve_lifetimes`.
498 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
499 let item_id = item_for(tcx, def_id);
500 if item_id == def_id {
501 let item = tcx.hir().item(hir::ItemId { def_id: item_id });
503 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
504 _ => tcx.resolve_lifetimes(item_id),
507 tcx.resolve_lifetimes(item_id)
511 /// Finds the `Item` that contains the given `LocalDefId`
512 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
513 match tcx.hir().find_by_def_id(local_def_id) {
514 Some(Node::Item(item)) => {
520 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
521 let mut parent_iter = tcx.hir().parent_iter(hir_id);
523 let node = parent_iter.next().map(|n| n.1);
525 Some(hir::Node::Item(item)) => break item.def_id,
526 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
534 fn is_late_bound_map<'tcx>(
537 ) -> Option<(LocalDefId, &'tcx FxHashSet<LocalDefId>)> {
538 match tcx.def_kind(def_id) {
539 DefKind::AnonConst | DefKind::InlineConst => {
541 .parent(def_id.to_def_id())
542 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
543 // We search for the next outer anon const or fn here
544 // while skipping closures.
546 // Note that for `AnonConst` we still just recurse until we
547 // find a function body, but who cares :shrug:
548 while tcx.is_closure(def_id) {
551 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
554 tcx.is_late_bound_map(def_id.expect_local())
556 _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
560 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
561 /// We have to account for this when computing the index of the other generic parameters.
562 /// This function returns whether there is such an implicit parameter defined on the given item.
563 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
564 matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
567 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
569 Region::LateBound(_, _, def_id) => {
570 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
571 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
573 Region::LateBoundAnon(_, _, anon_idx) => {
574 ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
576 _ => bug!("{:?} is not a late region", region),
580 #[tracing::instrument(level = "debug")]
581 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
582 let mut available_lifetimes = vec![];
585 Scope::Binder { lifetimes, s, .. } => {
586 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
587 hir::ParamName::Plain(ident) => Some(ident.name),
592 Scope::Body { s, .. } => {
595 Scope::Elision { elide, s } => {
596 if let Elide::Exact(_) = elide {
597 return LifetimeScopeForPath::Elided;
602 Scope::ObjectLifetimeDefault { s, .. } => {
606 return LifetimeScopeForPath::NonElided(available_lifetimes);
608 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
615 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
616 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
617 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
618 let mut scope = self.scope;
619 let mut supertrait_lifetimes = vec![];
622 Scope::Body { .. } | Scope::Root => {
623 break (vec![], BinderScopeType::Normal);
626 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
630 Scope::Supertrait { s, lifetimes } => {
631 supertrait_lifetimes = lifetimes.clone();
635 Scope::TraitRefBoundary { .. } => {
636 // We should only see super trait lifetimes if there is a `Binder` above
637 assert!(supertrait_lifetimes.is_empty());
638 break (vec![], BinderScopeType::Normal);
641 Scope::Binder { hir_id, .. } => {
642 // Nested poly trait refs have the binders concatenated
643 let mut full_binders =
644 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
645 full_binders.extend(supertrait_lifetimes.into_iter());
646 break (full_binders, BinderScopeType::Concatenating);
652 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
653 type NestedFilter = nested_filter::All;
655 fn nested_visit_map(&mut self) -> Self::Map {
659 // We want to nest trait/impl items in their parent, but nothing else.
660 fn visit_nested_item(&mut self, _: hir::ItemId) {}
662 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
663 if !self.trait_definition_only {
664 intravisit::walk_trait_item_ref(self, ii)
668 fn visit_nested_body(&mut self, body: hir::BodyId) {
669 // Each body has their own set of labels, save labels.
670 let saved = take(&mut self.labels_in_fn);
671 let body = self.tcx.hir().body(body);
672 extract_labels(self, body);
673 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
674 this.visit_body(body);
676 self.labels_in_fn = saved;
681 fk: intravisit::FnKind<'tcx>,
682 fd: &'tcx hir::FnDecl<'tcx>,
687 let name = match fk {
688 intravisit::FnKind::ItemFn(id, _, _, _) => id.name,
689 intravisit::FnKind::Method(id, _, _) => id.name,
690 intravisit::FnKind::Closure => sym::closure,
692 let name = name.as_str();
693 let span = span!(Level::DEBUG, "visit_fn", name);
694 let _enter = span.enter();
696 // Any `Binders` are handled elsewhere
697 intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
698 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
700 intravisit::FnKind::Closure => {
701 self.map.late_bound_vars.insert(hir_id, vec![]);
702 let scope = Scope::Binder {
704 lifetimes: FxIndexMap::default(),
705 next_early_index: self.next_early_index(),
707 track_lifetime_uses: true,
708 opaque_type_parent: false,
709 scope_type: BinderScopeType::Normal,
710 allow_late_bound: true,
712 self.with(scope, move |_old_scope, this| {
713 intravisit::walk_fn(this, fk, fd, b, s, hir_id)
719 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
721 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
722 if let Some(of_trait) = of_trait {
723 self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
729 hir::ItemKind::Fn(ref sig, ref generics, _) => {
730 self.missing_named_lifetime_spots.push(generics.into());
731 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
732 intravisit::walk_item(this, item);
734 self.missing_named_lifetime_spots.pop();
737 hir::ItemKind::ExternCrate(_)
738 | hir::ItemKind::Use(..)
739 | hir::ItemKind::Macro(..)
740 | hir::ItemKind::Mod(..)
741 | hir::ItemKind::ForeignMod { .. }
742 | hir::ItemKind::GlobalAsm(..) => {
743 // These sorts of items have no lifetime parameters at all.
744 intravisit::walk_item(self, item);
746 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
747 // No lifetime parameters, but implied 'static.
748 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
749 self.with(scope, |_, this| intravisit::walk_item(this, item));
751 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
752 // Opaque types are visited when we visit the
753 // `TyKind::OpaqueDef`, so that they have the lifetimes from
754 // their parent opaque_ty in scope.
756 // The core idea here is that since OpaqueTys are generated with the impl Trait as
757 // their owner, we can keep going until we find the Item that owns that. We then
758 // conservatively add all resolved lifetimes. Otherwise we run into problems in
759 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
760 for (_hir_id, node) in
761 self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
764 hir::Node::Item(parent_item) => {
765 let resolved_lifetimes: &ResolveLifetimes =
766 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
767 // We need to add *all* deps, since opaque tys may want them from *us*
768 for (&owner, defs) in resolved_lifetimes.defs.iter() {
769 defs.iter().for_each(|(&local_id, region)| {
770 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
773 for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
774 late_bound.iter().for_each(|&id| {
775 let hir_id = self.tcx.local_def_id_to_hir_id(id);
776 debug_assert_eq!(owner, hir_id.owner);
777 self.map.late_bound.insert(hir_id);
780 for (&owner, late_bound_vars) in
781 resolved_lifetimes.late_bound_vars.iter()
783 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
784 self.map.late_bound_vars.insert(
785 hir::HirId { owner, local_id },
786 late_bound_vars.clone(),
792 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
797 hir::ItemKind::TyAlias(_, ref generics)
798 | hir::ItemKind::Enum(_, ref generics)
799 | hir::ItemKind::Struct(_, ref generics)
800 | hir::ItemKind::Union(_, ref generics)
801 | hir::ItemKind::Trait(_, _, ref generics, ..)
802 | hir::ItemKind::TraitAlias(ref generics, ..)
803 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
804 self.missing_named_lifetime_spots.push(generics.into());
806 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
807 // This is not true for other kinds of items.
808 let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
809 // These kinds of items have only early-bound lifetime parameters.
810 let mut index = if sub_items_have_self_param(&item.kind) {
811 1 // Self comes before lifetimes
815 let mut non_lifetime_count = 0;
816 let lifetimes = generics
819 .filter_map(|param| match param.kind {
820 GenericParamKind::Lifetime { .. } => {
821 Some(Region::early(self.tcx.hir(), &mut index, param))
823 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
824 non_lifetime_count += 1;
829 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
830 let scope = Scope::Binder {
831 hir_id: item.hir_id(),
833 next_early_index: index + non_lifetime_count,
834 opaque_type_parent: true,
836 scope_type: BinderScopeType::Normal,
838 allow_late_bound: false,
840 self.with(scope, |old_scope, this| {
841 this.check_lifetime_params(old_scope, &generics.params);
842 let scope = Scope::TraitRefBoundary { s: this.scope };
843 this.with(scope, |_, this| {
844 intravisit::walk_item(this, item);
847 self.missing_named_lifetime_spots.pop();
852 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
854 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
855 self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
856 intravisit::walk_foreign_item(this, item);
859 hir::ForeignItemKind::Static(..) => {
860 intravisit::walk_foreign_item(self, item);
862 hir::ForeignItemKind::Type => {
863 intravisit::walk_foreign_item(self, item);
868 #[tracing::instrument(level = "debug", skip(self))]
869 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
871 hir::TyKind::BareFn(ref c) => {
872 let next_early_index = self.next_early_index();
873 let lifetime_span: Option<Span> =
874 c.generic_params.iter().rev().find_map(|param| match param.kind {
875 GenericParamKind::Lifetime { .. } => Some(param.span),
878 let (span, span_type) = if let Some(span) = lifetime_span {
879 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
881 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
883 self.missing_named_lifetime_spots
884 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
885 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
888 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
890 .map(|(late_bound_idx, param)| {
891 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
892 let r = late_region_as_bound_region(self.tcx, &pair.1);
896 self.map.late_bound_vars.insert(ty.hir_id, binders);
897 let scope = Scope::Binder {
902 track_lifetime_uses: true,
903 opaque_type_parent: false,
904 scope_type: BinderScopeType::Normal,
905 allow_late_bound: true,
907 self.with(scope, |old_scope, this| {
908 // a bare fn has no bounds, so everything
909 // contained within is scoped within its binder.
910 this.check_lifetime_params(old_scope, &c.generic_params);
911 intravisit::walk_ty(this, ty);
913 self.missing_named_lifetime_spots.pop();
915 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
916 debug!(?bounds, ?lifetime, "TraitObject");
917 let scope = Scope::TraitRefBoundary { s: self.scope };
918 self.with(scope, |_, this| {
919 for bound in bounds {
920 this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
923 match lifetime.name {
924 LifetimeName::Implicit => {
925 // For types like `dyn Foo`, we should
926 // generate a special form of elided.
927 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
929 LifetimeName::ImplicitObjectLifetimeDefault => {
930 // If the user does not write *anything*, we
931 // use the object lifetime defaulting
932 // rules. So e.g., `Box<dyn Debug>` becomes
933 // `Box<dyn Debug + 'static>`.
934 self.resolve_object_lifetime_default(lifetime)
936 LifetimeName::Underscore => {
937 // If the user writes `'_`, we use the *ordinary* elision
938 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
939 // resolved the same as the `'_` in `&'_ Foo`.
942 self.resolve_elided_lifetimes(&[lifetime])
944 LifetimeName::Param(_) | LifetimeName::Static => {
945 // If the user wrote an explicit name, use that.
946 self.visit_lifetime(lifetime);
948 LifetimeName::Error => {}
951 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
952 self.visit_lifetime(lifetime_ref);
953 let scope = Scope::ObjectLifetimeDefault {
954 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
957 self.with(scope, |_, this| this.visit_ty(&mt.ty));
959 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
960 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
961 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
962 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
963 // ^ ^ this gets resolved in the scope of
964 // the opaque_ty generics
965 let opaque_ty = self.tcx.hir().item(item_id);
966 let (generics, bounds) = match opaque_ty.kind {
967 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
968 // This arm is for `impl Trait` in the types of statics, constants and locals.
969 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
970 origin: hir::OpaqueTyOrigin::TyAlias,
973 intravisit::walk_ty(self, ty);
975 // Elided lifetimes are not allowed in non-return
976 // position impl Trait
977 let scope = Scope::TraitRefBoundary { s: self.scope };
978 self.with(scope, |_, this| {
979 let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
980 this.with(scope, |_, this| {
981 intravisit::walk_item(this, opaque_ty);
987 // RPIT (return position impl trait)
988 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
989 origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
993 }) => (generics, bounds),
994 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
997 // Resolve the lifetimes that are applied to the opaque type.
998 // These are resolved in the current scope.
999 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
1000 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
1001 // ^ ^this gets resolved in the current scope
1002 for lifetime in lifetimes {
1003 let hir::GenericArg::Lifetime(lifetime) = lifetime else {
1006 self.visit_lifetime(lifetime);
1008 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1009 // and ban them. Type variables instantiated inside binders aren't
1010 // well-supported at the moment, so this doesn't work.
1011 // In the future, this should be fixed and this error should be removed.
1012 let def = self.map.defs.get(&lifetime.hir_id).cloned();
1013 let Some(Region::LateBound(_, _, def_id)) = def else {
1016 let Some(def_id) = def_id.as_local() else {
1019 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1020 // Ensure that the parent of the def is an item, not HRTB
1021 let parent_id = self.tcx.hir().get_parent_node(hir_id);
1022 if !parent_id.is_owner() {
1023 if !self.trait_definition_only {
1028 "`impl Trait` can only capture lifetimes \
1029 bound at the fn or impl level"
1033 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1037 // We want to start our early-bound indices at the end of the parent scope,
1038 // not including any parent `impl Trait`s.
1039 let mut index = self.next_early_index_for_opaque_type();
1042 let mut elision = None;
1043 let mut lifetimes = FxIndexMap::default();
1044 let mut non_lifetime_count = 0;
1045 for param in generics.params {
1047 GenericParamKind::Lifetime { .. } => {
1048 let (name, reg) = Region::early(self.tcx.hir(), &mut index, ¶m);
1049 let Region::EarlyBound(_, def_id) = reg else {
1052 // We cannot predict what lifetimes are unused in opaque type.
1053 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
1054 if let hir::ParamName::Plain(Ident {
1055 name: kw::UnderscoreLifetime,
1059 // Pick the elided lifetime "definition" if one exists
1060 // and use it to make an elision scope.
1061 elision = Some(reg);
1063 lifetimes.insert(name, reg);
1066 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1067 non_lifetime_count += 1;
1071 let next_early_index = index + non_lifetime_count;
1072 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1074 if let Some(elision_region) = elision {
1076 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1077 self.with(scope, |_old_scope, this| {
1078 let scope = Scope::Binder {
1083 track_lifetime_uses: true,
1084 opaque_type_parent: false,
1085 scope_type: BinderScopeType::Normal,
1086 allow_late_bound: false,
1088 this.with(scope, |_old_scope, this| {
1089 this.visit_generics(generics);
1090 let scope = Scope::TraitRefBoundary { s: this.scope };
1091 this.with(scope, |_, this| {
1092 for bound in bounds {
1093 this.visit_param_bound(bound);
1099 let scope = Scope::Binder {
1104 track_lifetime_uses: true,
1105 opaque_type_parent: false,
1106 scope_type: BinderScopeType::Normal,
1107 allow_late_bound: false,
1109 self.with(scope, |_old_scope, this| {
1110 let scope = Scope::TraitRefBoundary { s: this.scope };
1111 this.with(scope, |_, this| {
1112 this.visit_generics(generics);
1113 for bound in bounds {
1114 this.visit_param_bound(bound);
1120 _ => intravisit::walk_ty(self, ty),
1124 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1125 use self::hir::TraitItemKind::*;
1126 match trait_item.kind {
1128 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1130 self.visit_early_late(
1131 Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1132 trait_item.hir_id(),
1134 &trait_item.generics,
1135 |this| intravisit::walk_trait_item(this, trait_item),
1137 self.missing_named_lifetime_spots.pop();
1139 Type(bounds, ref ty) => {
1140 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1141 let generics = &trait_item.generics;
1142 let mut index = self.next_early_index();
1143 debug!("visit_ty: index = {}", index);
1144 let mut non_lifetime_count = 0;
1145 let lifetimes = generics
1148 .filter_map(|param| match param.kind {
1149 GenericParamKind::Lifetime { .. } => {
1150 Some(Region::early(self.tcx.hir(), &mut index, param))
1152 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1153 non_lifetime_count += 1;
1158 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1159 let scope = Scope::Binder {
1160 hir_id: trait_item.hir_id(),
1162 next_early_index: index + non_lifetime_count,
1164 track_lifetime_uses: true,
1165 opaque_type_parent: true,
1166 scope_type: BinderScopeType::Normal,
1167 allow_late_bound: false,
1169 self.with(scope, |old_scope, this| {
1170 this.check_lifetime_params(old_scope, &generics.params);
1171 let scope = Scope::TraitRefBoundary { s: this.scope };
1172 this.with(scope, |_, this| {
1173 this.visit_generics(generics);
1174 for bound in bounds {
1175 this.visit_param_bound(bound);
1177 if let Some(ty) = ty {
1182 self.missing_named_lifetime_spots.pop();
1185 // Only methods and types support generics.
1186 assert!(trait_item.generics.params.is_empty());
1187 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1188 intravisit::walk_trait_item(self, trait_item);
1189 self.missing_named_lifetime_spots.pop();
1194 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1195 use self::hir::ImplItemKind::*;
1196 match impl_item.kind {
1198 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1200 self.visit_early_late(
1201 Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1204 &impl_item.generics,
1205 |this| intravisit::walk_impl_item(this, impl_item),
1207 self.missing_named_lifetime_spots.pop();
1209 TyAlias(ref ty) => {
1210 let generics = &impl_item.generics;
1211 self.missing_named_lifetime_spots.push(generics.into());
1212 let mut index = self.next_early_index();
1213 let mut non_lifetime_count = 0;
1214 debug!("visit_ty: index = {}", index);
1215 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1218 .filter_map(|param| match param.kind {
1219 GenericParamKind::Lifetime { .. } => {
1220 Some(Region::early(self.tcx.hir(), &mut index, param))
1222 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1223 non_lifetime_count += 1;
1228 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1229 let scope = Scope::Binder {
1232 next_early_index: index + non_lifetime_count,
1234 track_lifetime_uses: true,
1235 opaque_type_parent: true,
1236 scope_type: BinderScopeType::Normal,
1237 allow_late_bound: true,
1239 self.with(scope, |old_scope, this| {
1240 this.check_lifetime_params(old_scope, &generics.params);
1241 let scope = Scope::TraitRefBoundary { s: this.scope };
1242 this.with(scope, |_, this| {
1243 this.visit_generics(generics);
1247 self.missing_named_lifetime_spots.pop();
1250 // Only methods and types support generics.
1251 assert!(impl_item.generics.params.is_empty());
1252 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1253 intravisit::walk_impl_item(self, impl_item);
1254 self.missing_named_lifetime_spots.pop();
1259 #[tracing::instrument(level = "debug", skip(self))]
1260 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1261 if lifetime_ref.is_elided() {
1262 self.resolve_elided_lifetimes(&[lifetime_ref]);
1265 if lifetime_ref.is_static() {
1266 self.insert_lifetime(lifetime_ref, Region::Static);
1269 if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
1270 self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
1273 self.resolve_lifetime_ref(lifetime_ref);
1276 fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1277 let scope = self.scope;
1278 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1279 // We add lifetime scope information for `Ident`s in associated type bindings and use
1280 // the `HirId` of the type binding as the key in `LifetimeMap`
1281 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1282 let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1283 map.insert(type_binding.hir_id.local_id, lifetime_scope);
1285 hir::intravisit::walk_assoc_type_binding(self, type_binding);
1288 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1289 for (i, segment) in path.segments.iter().enumerate() {
1290 let depth = path.segments.len() - i - 1;
1291 if let Some(ref args) = segment.args {
1292 self.visit_segment_args(path.res, depth, args);
1295 let scope = self.scope;
1296 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1297 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1298 // here because that call would yield to resolution problems due to `walk_path_segment`
1299 // being called, which processes the path segments generic args, which we have already
1300 // processed using `visit_segment_args`.
1301 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1302 if let Some(hir_id) = segment.hir_id {
1303 let map = scope_for_path.entry(hir_id.owner).or_default();
1304 map.insert(hir_id.local_id, lifetime_scope);
1310 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1311 let scope = self.scope;
1312 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1313 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1314 if let Some(hir_id) = path_segment.hir_id {
1315 let map = scope_for_path.entry(hir_id.owner).or_default();
1316 map.insert(hir_id.local_id, lifetime_scope);
1320 intravisit::walk_path_segment(self, path_span, path_segment);
1323 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1324 let output = match fd.output {
1325 hir::FnRetTy::DefaultReturn(_) => None,
1326 hir::FnRetTy::Return(ref ty) => Some(&**ty),
1328 self.visit_fn_like_elision(&fd.inputs, output);
1331 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1332 let scope = Scope::TraitRefBoundary { s: self.scope };
1333 self.with(scope, |_, this| {
1334 for param in generics.params {
1336 GenericParamKind::Lifetime { .. } => {}
1337 GenericParamKind::Type { ref default, .. } => {
1338 walk_list!(this, visit_param_bound, param.bounds);
1339 if let Some(ref ty) = default {
1343 GenericParamKind::Const { ref ty, default } => {
1344 let was_in_const_generic = this.is_in_const_generic;
1345 this.is_in_const_generic = true;
1346 walk_list!(this, visit_param_bound, param.bounds);
1348 if let Some(default) = default {
1349 this.visit_body(this.tcx.hir().body(default.body));
1351 this.is_in_const_generic = was_in_const_generic;
1355 for predicate in generics.where_clause.predicates {
1357 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1360 ref bound_generic_params,
1363 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1364 bound_generic_params
1367 matches!(param.kind, GenericParamKind::Lifetime { .. })
1370 .map(|(late_bound_idx, param)| {
1372 Region::late(late_bound_idx as u32, this.tcx.hir(), param);
1373 let r = late_region_as_bound_region(this.tcx, &pair.1);
1377 this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1378 let next_early_index = this.next_early_index();
1379 // Even if there are no lifetimes defined here, we still wrap it in a binder
1380 // scope. If there happens to be a nested poly trait ref (an error), that
1381 // will be `Concatenating` anyways, so we don't have to worry about the depth
1383 let scope = Scope::Binder {
1384 hir_id: bounded_ty.hir_id,
1388 track_lifetime_uses: true,
1389 opaque_type_parent: false,
1390 scope_type: BinderScopeType::Normal,
1391 allow_late_bound: true,
1393 this.with(scope, |old_scope, this| {
1394 this.check_lifetime_params(old_scope, &bound_generic_params);
1395 this.visit_ty(&bounded_ty);
1396 walk_list!(this, visit_param_bound, bounds);
1399 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1404 this.visit_lifetime(lifetime);
1405 walk_list!(this, visit_param_bound, bounds);
1407 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1412 this.visit_ty(lhs_ty);
1413 this.visit_ty(rhs_ty);
1420 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1422 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1423 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1424 // through the regular poly trait ref code, so we don't get another
1425 // chance to introduce a binder. For now, I'm keeping the existing logic
1426 // of "if there isn't a Binder scope above us, add one", but I
1427 // imagine there's a better way to go about this.
1428 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1430 self.map.late_bound_vars.insert(*hir_id, binders);
1431 let scope = Scope::Binder {
1433 lifetimes: FxIndexMap::default(),
1435 next_early_index: self.next_early_index(),
1436 track_lifetime_uses: true,
1437 opaque_type_parent: false,
1439 allow_late_bound: true,
1441 self.with(scope, |_, this| {
1442 intravisit::walk_param_bound(this, bound);
1445 _ => intravisit::walk_param_bound(self, bound),
1449 fn visit_poly_trait_ref(
1451 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1452 _modifier: hir::TraitBoundModifier,
1454 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1456 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1458 let next_early_index = self.next_early_index();
1459 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1461 let initial_bound_vars = binders.len() as u32;
1462 let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1463 let binders_iter = trait_ref
1464 .bound_generic_params
1466 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1468 .map(|(late_bound_idx, param)| {
1470 Region::late(initial_bound_vars + late_bound_idx as u32, self.tcx.hir(), param);
1471 let r = late_region_as_bound_region(self.tcx, &pair.1);
1472 lifetimes.insert(pair.0, pair.1);
1475 binders.extend(binders_iter);
1478 self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1480 // Always introduce a scope here, even if this is in a where clause and
1481 // we introduced the binders around the bounded Ty. In that case, we
1482 // just reuse the concatenation functionality also present in nested trait
1484 let scope = Scope::Binder {
1485 hir_id: trait_ref.trait_ref.hir_ref_id,
1489 track_lifetime_uses: true,
1490 opaque_type_parent: false,
1492 allow_late_bound: true,
1494 self.with(scope, |old_scope, this| {
1495 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1496 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1497 this.visit_trait_ref(&trait_ref.trait_ref);
1500 if should_pop_missing_lt {
1501 self.missing_named_lifetime_spots.pop();
1506 #[derive(Copy, Clone, PartialEq)]
1520 fn original_label(span: Span) -> Original {
1521 Original { kind: ShadowKind::Label, span }
1523 fn shadower_label(span: Span) -> Shadower {
1524 Shadower { kind: ShadowKind::Label, span }
1526 fn original_lifetime(span: Span) -> Original {
1527 Original { kind: ShadowKind::Lifetime, span }
1529 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1530 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1534 fn desc(&self) -> &'static str {
1536 ShadowKind::Label => "label",
1537 ShadowKind::Lifetime => "lifetime",
1542 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1543 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1544 // lifetime/lifetime shadowing is an error
1549 "{} name `{}` shadows a \
1550 {} name that is already in scope",
1551 shadower.kind.desc(),
1557 // shadowing involving a label is only a warning, due to issues with
1558 // labels and lifetimes not being macro-hygienic.
1559 tcx.sess.struct_span_warn(
1562 "{} name `{}` shadows a \
1563 {} name that is already in scope",
1564 shadower.kind.desc(),
1570 err.span_label(orig.span, "first declared here");
1571 err.span_label(shadower.span, format!("{} `{}` already in scope", orig.kind.desc(), name));
1575 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1576 // if one of the label shadows a lifetime or another label.
1577 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1578 struct GatherLabels<'a, 'tcx> {
1580 scope: ScopeRef<'a>,
1581 labels_in_fn: &'a mut Vec<Ident>,
1585 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1586 gather.visit_body(body);
1588 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1589 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1590 if let Some(label) = expression_label(ex) {
1591 for prior_label in &self.labels_in_fn[..] {
1592 // FIXME (#24278): non-hygienic comparison
1593 if label.name == prior_label.name {
1594 signal_shadowing_problem(
1597 original_label(prior_label.span),
1598 shadower_label(label.span),
1603 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1605 self.labels_in_fn.push(label);
1607 intravisit::walk_expr(self, ex)
1611 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1613 hir::ExprKind::Loop(_, Some(label), ..) => Some(label.ident),
1614 hir::ExprKind::Block(_, Some(label)) => Some(label.ident),
1619 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1622 Scope::Body { s, .. }
1623 | Scope::Elision { s, .. }
1624 | Scope::ObjectLifetimeDefault { s, .. }
1625 | Scope::Supertrait { s, .. }
1626 | Scope::TraitRefBoundary { s, .. } => {
1634 Scope::Binder { ref lifetimes, s, .. } => {
1635 // FIXME (#24278): non-hygienic comparison
1637 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1639 signal_shadowing_problem(
1642 original_lifetime(tcx.def_span(def.id().unwrap().expect_local())),
1643 shadower_label(label.span),
1654 fn compute_object_lifetime_defaults<'tcx>(
1656 item: &hir::Item<'_>,
1657 ) -> Option<&'tcx [ObjectLifetimeDefault]> {
1659 hir::ItemKind::Struct(_, ref generics)
1660 | hir::ItemKind::Union(_, ref generics)
1661 | hir::ItemKind::Enum(_, ref generics)
1662 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1664 origin: hir::OpaqueTyOrigin::TyAlias,
1667 | hir::ItemKind::TyAlias(_, ref generics)
1668 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1669 let result = object_lifetime_defaults_for_item(tcx, generics);
1672 let attrs = tcx.hir().attrs(item.hir_id());
1673 if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1674 let object_lifetime_default_reprs: String = result
1676 .map(|set| match *set {
1677 Set1::Empty => "BaseDefault".into(),
1678 Set1::One(Region::Static) => "'static".into(),
1679 Set1::One(Region::EarlyBound(mut i, _)) => generics
1682 .find_map(|param| match param.kind {
1683 GenericParamKind::Lifetime { .. } => {
1685 return Some(param.name.ident().to_string().into());
1693 Set1::One(_) => bug!(),
1694 Set1::Many => "Ambiguous".into(),
1696 .collect::<Vec<Cow<'static, str>>>()
1698 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1707 /// Scan the bounds and where-clauses on parameters to extract bounds
1708 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1709 /// for each type parameter.
1710 fn object_lifetime_defaults_for_item<'tcx>(
1712 generics: &hir::Generics<'_>,
1713 ) -> &'tcx [ObjectLifetimeDefault] {
1714 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1715 for bound in bounds {
1716 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1717 set.insert(lifetime.name.normalize_to_macros_2_0());
1722 let process_param = |param: &hir::GenericParam<'_>| match param.kind {
1723 GenericParamKind::Lifetime { .. } => None,
1724 GenericParamKind::Type { .. } => {
1725 let mut set = Set1::Empty;
1727 add_bounds(&mut set, ¶m.bounds);
1729 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1730 for predicate in generics.where_clause.predicates {
1731 // Look for `type: ...` where clauses.
1732 let hir::WherePredicate::BoundPredicate(ref data) = *predicate else { continue };
1734 // Ignore `for<'a> type: ...` as they can change what
1735 // lifetimes mean (although we could "just" handle it).
1736 if !data.bound_generic_params.is_empty() {
1740 let res = match data.bounded_ty.kind {
1741 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1745 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1746 add_bounds(&mut set, &data.bounds);
1751 Set1::Empty => Set1::Empty,
1752 Set1::One(name) => {
1753 if name == hir::LifetimeName::Static {
1754 Set1::One(Region::Static)
1759 .filter_map(|param| match param.kind {
1760 GenericParamKind::Lifetime { .. } => {
1761 Some((param.hir_id, hir::LifetimeName::Param(param.name)))
1766 .find(|&(_, (_, lt_name))| lt_name == name)
1767 .map_or(Set1::Many, |(i, (id, _))| {
1768 let def_id = tcx.hir().local_def_id(id);
1769 Set1::One(Region::EarlyBound(i as u32, def_id.to_def_id()))
1773 Set1::Many => Set1::Many,
1776 GenericParamKind::Const { .. } => {
1777 // Generic consts don't impose any constraints.
1779 // We still store a dummy value here to allow generic parameters
1780 // in an arbitrary order.
1785 tcx.arena.alloc_from_iter(generics.params.iter().filter_map(process_param))
1788 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1789 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1791 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1793 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1794 let labels_in_fn = take(&mut self.labels_in_fn);
1795 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1796 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1797 let mut this = LifetimeContext {
1801 is_in_const_generic: self.is_in_const_generic,
1802 trait_definition_only: self.trait_definition_only,
1804 xcrate_object_lifetime_defaults,
1806 missing_named_lifetime_spots,
1808 let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1810 let _enter = span.enter();
1811 f(self.scope, &mut this);
1812 if !self.trait_definition_only {
1813 this.check_uses_for_lifetimes_defined_by_scope();
1816 self.labels_in_fn = this.labels_in_fn;
1817 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1818 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1821 /// helper method to determine the span to remove when suggesting the
1822 /// deletion of a lifetime
1823 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1824 generics.params.iter().enumerate().find_map(|(i, param)| {
1825 if param.name.ident() == name {
1826 if generics.params.len() == 1 {
1827 // if sole lifetime, remove the entire `<>` brackets
1830 // if removing within `<>` brackets, we also want to
1831 // delete a leading or trailing comma as appropriate
1832 if i >= generics.params.len() - 1 {
1833 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1835 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1844 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1845 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1846 fn suggest_eliding_single_use_lifetime(
1848 err: &mut Diagnostic,
1850 lifetime: &hir::Lifetime,
1852 let name = lifetime.name.ident();
1853 let remove_decl = self
1856 .and_then(|parent_def_id| parent_def_id.as_local())
1857 .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id))
1858 .and_then(|generics| self.lifetime_deletion_span(name, generics));
1860 let mut remove_use = None;
1861 let mut elide_use = None;
1862 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1863 for input in inputs {
1865 hir::TyKind::Rptr(lt, _) => {
1866 if lt.name.ident() == name {
1867 // include the trailing whitespace between the lifetime and type names
1868 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1873 .span_until_non_whitespace(lt_through_ty_span),
1878 hir::TyKind::Path(QPath::Resolved(_, path)) => {
1879 let last_segment = &path.segments[path.segments.len() - 1];
1880 let generics = last_segment.args();
1881 for arg in generics.args.iter() {
1882 if let GenericArg::Lifetime(lt) = arg {
1883 if lt.name.ident() == name {
1884 elide_use = Some(lt.span);
1895 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1896 if let Some(parent) =
1897 self.tcx.hir().find_by_def_id(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1900 Node::Item(item) => {
1901 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1902 find_arg_use_span(sig.decl.inputs);
1905 Node::ImplItem(impl_item) => {
1906 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1907 find_arg_use_span(sig.decl.inputs);
1915 let msg = "elide the single-use lifetime";
1916 match (remove_decl, remove_use, elide_use) {
1917 (Some(decl_span), Some(use_span), None) => {
1918 // if both declaration and use deletion spans start at the same
1919 // place ("start at" because the latter includes trailing
1920 // whitespace), then this is an in-band lifetime
1921 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1922 err.span_suggestion(
1926 Applicability::MachineApplicable,
1929 err.multipart_suggestion(
1931 vec![(decl_span, String::new()), (use_span, String::new())],
1932 Applicability::MachineApplicable,
1936 (Some(decl_span), None, Some(use_span)) => {
1937 err.multipart_suggestion(
1939 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1940 Applicability::MachineApplicable,
1947 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1948 let Scope::Binder { lifetimes: defined_by, .. } = self.scope else {
1949 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1953 let def_ids: Vec<_> = defined_by
1955 .flat_map(|region| match region {
1956 Region::EarlyBound(_, def_id)
1957 | Region::LateBound(_, _, def_id)
1958 | Region::Free(_, def_id) => Some(*def_id),
1960 Region::LateBoundAnon(..) | Region::Static => None,
1964 'lifetimes: for def_id in def_ids {
1965 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1967 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1970 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1974 match lifetimeuseset {
1975 Some(LifetimeUseSet::One(lifetime)) => {
1977 if let Some((id, span, name)) =
1978 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
1979 Node::Lifetime(hir_lifetime) => Some((
1980 hir_lifetime.hir_id,
1982 hir_lifetime.name.ident(),
1984 Node::GenericParam(param) => {
1985 Some((param.hir_id, param.span, param.name.ident()))
1990 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1991 if name.name == kw::UnderscoreLifetime {
1995 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1996 if let Some(def_id) = parent_def_id.as_local() {
1997 // lifetimes in `derive` expansions don't count (Issue #53738)
2000 .get_attrs(def_id.to_def_id())
2002 .any(|attr| attr.has_name(sym::automatically_derived))
2007 // opaque types generated when desugaring an async function can have a single
2008 // use lifetime even if it is explicitly denied (Issue #77175)
2009 if let hir::Node::Item(hir::Item {
2010 kind: hir::ItemKind::OpaqueTy(ref opaque),
2012 }) = self.tcx.hir().get_by_def_id(def_id)
2014 if !matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn(..)) {
2015 continue 'lifetimes;
2017 // We want to do this only if the lifetime identifier is already defined
2018 // in the async function that generated this. Otherwise it could be
2019 // an opaque type defined by the developer and we still want this
2020 // lint to fail compilation
2021 for p in opaque.generics.params {
2022 if defined_by.contains_key(&p.name) {
2023 continue 'lifetimes;
2030 self.tcx.struct_span_lint_hir(
2031 lint::builtin::SINGLE_USE_LIFETIMES,
2035 let mut err = lint.build(&format!(
2036 "lifetime parameter `{}` only used once",
2039 if span == lifetime.span {
2040 // spans are the same for in-band lifetime declarations
2041 err.span_label(span, "this lifetime is only used here");
2043 err.span_label(span, "this lifetime...");
2044 err.span_label(lifetime.span, "...is used only here");
2046 self.suggest_eliding_single_use_lifetime(
2047 &mut err, def_id, lifetime,
2054 Some(LifetimeUseSet::Many) => {
2055 debug!("not one use lifetime");
2058 if let Some((id, span, name)) =
2059 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
2060 Node::Lifetime(hir_lifetime) => Some((
2061 hir_lifetime.hir_id,
2063 hir_lifetime.name.ident(),
2065 Node::GenericParam(param) => {
2066 Some((param.hir_id, param.span, param.name.ident()))
2071 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
2072 self.tcx.struct_span_lint_hir(
2073 lint::builtin::UNUSED_LIFETIMES,
2078 .build(&format!("lifetime parameter `{}` never used", name));
2079 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2080 if let Some(generics) =
2081 self.tcx.hir().get_generics(parent_def_id.expect_local())
2083 let unused_lt_span =
2084 self.lifetime_deletion_span(name, generics);
2085 if let Some(span) = unused_lt_span {
2086 err.span_suggestion(
2088 "elide the unused lifetime",
2090 Applicability::MachineApplicable,
2104 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
2106 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
2107 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
2108 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
2112 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
2114 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
2115 /// lifetimes may be interspersed together.
2117 /// If early bound lifetimes are present, we separate them into their own list (and likewise
2118 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
2119 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
2120 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
2121 /// ordering is not important there.
2122 fn visit_early_late<F>(
2124 parent_id: Option<LocalDefId>,
2126 decl: &'tcx hir::FnDecl<'tcx>,
2127 generics: &'tcx hir::Generics<'tcx>,
2130 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
2132 insert_late_bound_lifetimes(self.map, decl, generics);
2134 // Find the start of nested early scopes, e.g., in methods.
2135 let mut next_early_index = 0;
2136 if let Some(parent_id) = parent_id {
2137 let parent = self.tcx.hir().expect_item(parent_id);
2138 if sub_items_have_self_param(&parent.kind) {
2139 next_early_index += 1; // Self comes before lifetimes
2142 hir::ItemKind::Trait(_, _, ref generics, ..)
2143 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
2144 next_early_index += generics.params.len() as u32;
2150 let mut non_lifetime_count = 0;
2151 let mut named_late_bound_vars = 0;
2152 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
2155 .filter_map(|param| match param.kind {
2156 GenericParamKind::Lifetime { .. } => {
2157 if self.map.late_bound.contains(¶m.hir_id) {
2158 let late_bound_idx = named_late_bound_vars;
2159 named_late_bound_vars += 1;
2160 Some(Region::late(late_bound_idx, self.tcx.hir(), param))
2162 Some(Region::early(self.tcx.hir(), &mut next_early_index, param))
2165 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
2166 non_lifetime_count += 1;
2171 let next_early_index = next_early_index + non_lifetime_count;
2173 let binders: Vec<_> = generics
2177 matches!(param.kind, GenericParamKind::Lifetime { .. })
2178 && self.map.late_bound.contains(¶m.hir_id)
2181 .map(|(late_bound_idx, param)| {
2182 let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
2183 late_region_as_bound_region(self.tcx, &pair.1)
2186 self.map.late_bound_vars.insert(hir_id, binders);
2187 let scope = Scope::Binder {
2192 opaque_type_parent: true,
2193 track_lifetime_uses: false,
2194 scope_type: BinderScopeType::Normal,
2195 allow_late_bound: true,
2197 self.with(scope, move |old_scope, this| {
2198 this.check_lifetime_params(old_scope, &generics.params);
2203 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
2204 let mut scope = self.scope;
2207 Scope::Root => return 0,
2209 Scope::Binder { next_early_index, opaque_type_parent, .. }
2210 if (!only_opaque_type_parent || opaque_type_parent) =>
2212 return next_early_index;
2215 Scope::Binder { s, .. }
2216 | Scope::Body { s, .. }
2217 | Scope::Elision { s, .. }
2218 | Scope::ObjectLifetimeDefault { s, .. }
2219 | Scope::Supertrait { s, .. }
2220 | Scope::TraitRefBoundary { s, .. } => scope = s,
2225 /// Returns the next index one would use for an early-bound-region
2226 /// if extending the current scope.
2227 fn next_early_index(&self) -> u32 {
2228 self.next_early_index_helper(true)
2231 /// Returns the next index one would use for an `impl Trait` that
2232 /// is being converted into an opaque type alias `impl Trait`. This will be the
2233 /// next early index from the enclosing item, for the most
2234 /// part. See the `opaque_type_parent` field for more info.
2235 fn next_early_index_for_opaque_type(&self) -> u32 {
2236 self.next_early_index_helper(false)
2239 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2240 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
2242 // If we've already reported an error, just ignore `lifetime_ref`.
2243 if let LifetimeName::Error = lifetime_ref.name {
2247 // Walk up the scope chain, tracking the number of fn scopes
2248 // that we pass through, until we find a lifetime with the
2249 // given name or we run out of scopes.
2251 let mut late_depth = 0;
2252 let mut scope = self.scope;
2253 let mut outermost_body = None;
2256 Scope::Body { id, s } => {
2257 // Non-static lifetimes are prohibited in anonymous constants without
2258 // `generic_const_exprs`.
2259 self.maybe_emit_forbidden_non_static_lifetime_error(id, lifetime_ref);
2261 outermost_body = Some(id);
2269 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
2270 match lifetime_ref.name {
2271 LifetimeName::Param(param_name) => {
2272 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
2274 break Some(def.shifted(late_depth));
2277 _ => bug!("expected LifetimeName::Param"),
2280 BinderScopeType::Normal => late_depth += 1,
2281 BinderScopeType::Concatenating => {}
2286 Scope::Elision { s, .. }
2287 | Scope::ObjectLifetimeDefault { s, .. }
2288 | Scope::Supertrait { s, .. }
2289 | Scope::TraitRefBoundary { s, .. } => {
2295 if let Some(mut def) = result {
2296 if let Region::EarlyBound(..) = def {
2297 // Do not free early-bound regions, only late-bound ones.
2298 } else if let Some(body_id) = outermost_body {
2299 let fn_id = self.tcx.hir().body_owner(body_id);
2300 match self.tcx.hir().get(fn_id) {
2301 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
2302 | Node::TraitItem(&hir::TraitItem {
2303 kind: hir::TraitItemKind::Fn(..), ..
2305 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
2306 let scope = self.tcx.hir().local_def_id(fn_id);
2307 def = Region::Free(scope.to_def_id(), def.id().unwrap());
2313 self.insert_lifetime(lifetime_ref, def);
2315 self.tcx.sess.delay_span_bug(
2317 &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
2322 fn visit_segment_args(
2326 generic_args: &'tcx hir::GenericArgs<'tcx>,
2329 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
2330 res, depth, generic_args,
2333 if generic_args.parenthesized {
2334 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
2338 let mut elide_lifetimes = true;
2339 let lifetimes: Vec<_> = generic_args
2342 .filter_map(|arg| match arg {
2343 hir::GenericArg::Lifetime(lt) => {
2344 if !lt.is_elided() {
2345 elide_lifetimes = false;
2352 // We short-circuit here if all are elided in order to pluralize
2354 if elide_lifetimes {
2355 self.resolve_elided_lifetimes(&lifetimes);
2357 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
2360 // Figure out if this is a type/trait segment,
2361 // which requires object lifetime defaults.
2362 let parent_def_id = |this: &mut Self, def_id: DefId| {
2363 let def_key = this.tcx.def_key(def_id);
2364 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
2366 let type_def_id = match res {
2367 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
2368 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
2376 ) if depth == 0 => Some(def_id),
2380 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
2382 // Compute a vector of defaults, one for each type parameter,
2383 // per the rules given in RFCs 599 and 1156. Example:
2386 // struct Foo<'a, T: 'a, U> { }
2389 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
2390 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
2391 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
2394 // Therefore, we would compute `object_lifetime_defaults` to a
2395 // vector like `['x, 'static]`. Note that the vector only
2396 // includes type parameters.
2397 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
2399 let mut scope = self.scope;
2402 Scope::Root => break false,
2404 Scope::Body { .. } => break true,
2406 Scope::Binder { s, .. }
2407 | Scope::Elision { s, .. }
2408 | Scope::ObjectLifetimeDefault { s, .. }
2409 | Scope::Supertrait { s, .. }
2410 | Scope::TraitRefBoundary { s, .. } => {
2417 let map = &self.map;
2418 let set_to_region = |set: &ObjectLifetimeDefault| match *set {
2423 Some(Region::Static)
2427 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2428 GenericArg::Lifetime(lt) => Some(lt),
2431 r.subst(lifetimes, map)
2435 if let Some(def_id) = def_id.as_local() {
2436 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2438 .object_lifetime_defaults(id.owner)
2445 self.xcrate_object_lifetime_defaults
2447 .or_insert_with(|| {
2448 tcx.generics_of(def_id)
2451 .filter_map(|param| match param.kind {
2452 GenericParamDefKind::Type { object_lifetime_default, .. } => {
2453 Some(object_lifetime_default)
2455 GenericParamDefKind::Const { .. } => Some(Set1::Empty),
2456 GenericParamDefKind::Lifetime => None,
2466 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2469 for arg in generic_args.args {
2471 GenericArg::Lifetime(_) => {}
2472 GenericArg::Type(ty) => {
2473 if let Some(<) = object_lifetime_defaults.get(i) {
2474 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2475 self.with(scope, |_, this| this.visit_ty(ty));
2481 GenericArg::Const(ct) => {
2482 self.visit_anon_const(&ct.value);
2485 GenericArg::Infer(inf) => {
2486 self.visit_id(inf.hir_id);
2492 // Hack: when resolving the type `XX` in binding like `dyn
2493 // Foo<'b, Item = XX>`, the current object-lifetime default
2494 // would be to examine the trait `Foo` to check whether it has
2495 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2496 // declared like so, then the default object lifetime bound in
2497 // `XX` should be `'b`:
2505 // but if we just have `type Item;`, then it would be
2506 // `'static`. However, we don't get all of this logic correct.
2508 // Instead, we do something hacky: if there are no lifetime parameters
2509 // to the trait, then we simply use a default object lifetime
2510 // bound of `'static`, because there is no other possibility. On the other hand,
2511 // if there ARE lifetime parameters, then we require the user to give an
2512 // explicit bound for now.
2514 // This is intended to leave room for us to implement the
2515 // correct behavior in the future.
2516 let has_lifetime_parameter =
2517 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2519 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2520 // in the trait ref `YY<...>` in `Item: YY<...>`.
2521 for binding in generic_args.bindings {
2522 let scope = Scope::ObjectLifetimeDefault {
2523 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2526 if let Some(type_def_id) = type_def_id {
2527 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2532 self.with(scope, |_, this| {
2533 let scope = Scope::Supertrait {
2534 lifetimes: lifetimes.unwrap_or_default(),
2537 this.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2540 self.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2545 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2546 /// associated type name and starting trait.
2547 /// For example, imagine we have
2549 /// trait Foo<'a, 'b> {
2552 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2553 /// trait Bar: for<'b> Bar<'b> {}
2555 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2556 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2557 fn supertrait_hrtb_lifetimes(
2561 ) -> Option<Vec<ty::BoundVariableKind>> {
2562 let trait_defines_associated_type_named = |trait_def_id: DefId| {
2563 tcx.associated_items(trait_def_id)
2564 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2568 use smallvec::{smallvec, SmallVec};
2569 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2570 smallvec![(def_id, smallvec![])];
2571 let mut visited: FxHashSet<DefId> = FxHashSet::default();
2573 let Some((def_id, bound_vars)) = stack.pop() else {
2576 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2577 // there being no supertrait HRTBs.
2578 match tcx.def_kind(def_id) {
2579 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2583 if trait_defines_associated_type_named(def_id) {
2584 break Some(bound_vars.into_iter().collect());
2587 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2588 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2589 let bound_predicate = pred.kind();
2590 match bound_predicate.skip_binder() {
2591 ty::PredicateKind::Trait(data) => {
2592 // The order here needs to match what we would get from `subst_supertrait`
2593 let pred_bound_vars = bound_predicate.bound_vars();
2594 let mut all_bound_vars = bound_vars.clone();
2595 all_bound_vars.extend(pred_bound_vars.iter());
2596 let super_def_id = data.trait_ref.def_id;
2597 Some((super_def_id, all_bound_vars))
2603 let obligations = obligations.filter(|o| visited.insert(o.0));
2604 stack.extend(obligations);
2608 #[tracing::instrument(level = "debug", skip(self))]
2609 fn visit_fn_like_elision(
2611 inputs: &'tcx [hir::Ty<'tcx>],
2612 output: Option<&'tcx hir::Ty<'tcx>>,
2614 debug!("visit_fn_like_elision: enter");
2615 let mut scope = &*self.scope;
2618 Scope::Binder { hir_id, allow_late_bound: true, .. } => {
2621 Scope::ObjectLifetimeDefault { ref s, .. }
2622 | Scope::Elision { ref s, .. }
2623 | Scope::Supertrait { ref s, .. }
2624 | Scope::TraitRefBoundary { ref s, .. } => {
2628 | Scope::Body { .. }
2629 | Scope::Binder { allow_late_bound: false, .. } => {
2630 // See issues #83907 and #83693. Just bail out from looking inside.
2631 // See the issue #95023 for not allowing late bound
2632 self.tcx.sess.delay_span_bug(
2633 rustc_span::DUMMY_SP,
2634 "In fn_like_elision without appropriate scope above",
2640 // While not strictly necessary, we gather anon lifetimes *before* actually
2641 // visiting the argument types.
2642 let mut gather = GatherAnonLifetimes { anon_count: 0 };
2643 for input in inputs {
2644 gather.visit_ty(input);
2646 trace!(?gather.anon_count);
2647 let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2648 let named_late_bound_vars = late_bound_vars.len() as u32;
2649 late_bound_vars.extend(
2650 (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2652 let arg_scope = Scope::Elision {
2653 elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2656 self.with(arg_scope, |_, this| {
2657 for input in inputs {
2658 this.visit_ty(input);
2662 let Some(output) = output else { return };
2664 debug!("determine output");
2666 // Figure out if there's a body we can get argument names from,
2667 // and whether there's a `self` argument (treated specially).
2668 let mut assoc_item_kind = None;
2669 let mut impl_self = None;
2670 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2671 let body = match self.tcx.hir().get(parent) {
2672 // `fn` definitions and methods.
2673 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2675 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2676 if let hir::ItemKind::Trait(.., ref trait_items) =
2677 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2680 trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2683 hir::TraitFn::Required(_) => None,
2684 hir::TraitFn::Provided(body) => Some(body),
2688 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2689 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2690 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2692 impl_self = Some(self_ty);
2694 items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2699 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2700 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2701 // Everything else (only closures?) doesn't
2702 // actually enjoy elision in return types.
2704 self.visit_ty(output);
2709 let has_self = match assoc_item_kind {
2710 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2714 // In accordance with the rules for lifetime elision, we can determine
2715 // what region to use for elision in the output type in two ways.
2716 // First (determined here), if `self` is by-reference, then the
2717 // implied output region is the region of the self parameter.
2719 struct SelfVisitor<'a> {
2720 map: &'a NamedRegionMap,
2721 impl_self: Option<&'a hir::TyKind<'a>>,
2722 lifetime: Set1<Region>,
2725 impl SelfVisitor<'_> {
2726 // Look for `self: &'a Self` - also desugared from `&'a self`,
2727 // and if that matches, use it for elision and return early.
2728 fn is_self_ty(&self, res: Res) -> bool {
2729 if let Res::SelfTy { .. } = res {
2733 // Can't always rely on literal (or implied) `Self` due
2734 // to the way elision rules were originally specified.
2735 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2739 // Permit the types that unambiguously always
2740 // result in the same type constructor being used
2741 // (it can't differ between `Self` and `self`).
2742 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2743 | Res::PrimTy(_) => return res == path.res,
2752 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2753 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2754 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2755 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2757 if self.is_self_ty(path.res) {
2758 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2759 self.lifetime.insert(*lifetime);
2764 intravisit::walk_ty(self, ty)
2768 let mut visitor = SelfVisitor {
2770 impl_self: impl_self.map(|ty| &ty.kind),
2771 lifetime: Set1::Empty,
2773 visitor.visit_ty(&inputs[0]);
2774 if let Set1::One(lifetime) = visitor.lifetime {
2775 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2776 self.with(scope, |_, this| this.visit_ty(output));
2781 // Second, if there was exactly one lifetime (either a substitution or a
2782 // reference) in the arguments, then any anonymous regions in the output
2783 // have that lifetime.
2784 let mut possible_implied_output_region = None;
2785 let mut lifetime_count = 0;
2786 let arg_lifetimes = inputs
2789 .skip(has_self as usize)
2791 let mut gather = GatherLifetimes {
2793 outer_index: ty::INNERMOST,
2794 have_bound_regions: false,
2795 lifetimes: Default::default(),
2797 gather.visit_ty(input);
2799 lifetime_count += gather.lifetimes.len();
2801 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2802 // there's a chance that the unique lifetime of this
2803 // iteration will be the appropriate lifetime for output
2804 // parameters, so lets store it.
2805 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2808 ElisionFailureInfo {
2811 lifetime_count: gather.lifetimes.len(),
2812 have_bound_regions: gather.have_bound_regions,
2818 let elide = if lifetime_count == 1 {
2819 Elide::Exact(possible_implied_output_region.unwrap())
2821 Elide::Error(arg_lifetimes)
2826 let scope = Scope::Elision { elide, s: self.scope };
2827 self.with(scope, |_, this| this.visit_ty(output));
2829 struct GatherLifetimes<'a> {
2830 map: &'a NamedRegionMap,
2831 outer_index: ty::DebruijnIndex,
2832 have_bound_regions: bool,
2833 lifetimes: FxHashSet<Region>,
2836 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2837 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2838 if let hir::TyKind::BareFn(_) = ty.kind {
2839 self.outer_index.shift_in(1);
2842 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2843 for bound in bounds {
2844 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2847 // Stay on the safe side and don't include the object
2848 // lifetime default (which may not end up being used).
2849 if !lifetime.is_elided() {
2850 self.visit_lifetime(lifetime);
2854 intravisit::walk_ty(self, ty);
2857 if let hir::TyKind::BareFn(_) = ty.kind {
2858 self.outer_index.shift_out(1);
2862 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2863 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2864 // FIXME(eddyb) Do we want this? It only makes a difference
2865 // if this `for<'a>` lifetime parameter is never used.
2866 self.have_bound_regions = true;
2869 intravisit::walk_generic_param(self, param);
2872 fn visit_poly_trait_ref(
2874 trait_ref: &hir::PolyTraitRef<'_>,
2875 modifier: hir::TraitBoundModifier,
2877 self.outer_index.shift_in(1);
2878 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2879 self.outer_index.shift_out(1);
2882 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2883 if let hir::GenericBound::LangItemTrait { .. } = bound {
2884 self.outer_index.shift_in(1);
2885 intravisit::walk_param_bound(self, bound);
2886 self.outer_index.shift_out(1);
2888 intravisit::walk_param_bound(self, bound);
2892 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2893 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2895 Region::LateBound(debruijn, _, _)
2896 | Region::LateBoundAnon(debruijn, _, _)
2897 if debruijn < self.outer_index =>
2899 self.have_bound_regions = true;
2902 // FIXME(jackh726): nested trait refs?
2903 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2910 struct GatherAnonLifetimes {
2913 impl<'v> Visitor<'v> for GatherAnonLifetimes {
2914 #[instrument(skip(self), level = "trace")]
2915 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2916 // If we enter a `BareFn`, then we enter a *new* binding scope
2917 if let hir::TyKind::BareFn(_) = ty.kind {
2920 intravisit::walk_ty(self, ty);
2923 fn visit_generic_args(
2926 generic_args: &'v hir::GenericArgs<'v>,
2928 // parenthesized args enter a new elision scope
2929 if generic_args.parenthesized {
2932 intravisit::walk_generic_args(self, path_span, generic_args)
2935 #[instrument(skip(self), level = "trace")]
2936 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2937 if lifetime_ref.is_elided() {
2938 self.anon_count += 1;
2944 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
2945 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2947 if lifetime_refs.is_empty() {
2951 let mut late_depth = 0;
2952 let mut scope = self.scope;
2953 let mut lifetime_names = FxHashSet::default();
2954 let mut lifetime_spans = vec![];
2957 // Do not assign any resolution, it will be inferred.
2958 Scope::Body { .. } => return,
2960 Scope::Root => break None,
2962 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
2963 // collect named lifetimes for suggestions
2964 for name in lifetimes.keys() {
2965 if let hir::ParamName::Plain(name) = name {
2966 lifetime_names.insert(name.name);
2967 lifetime_spans.push(name.span);
2971 BinderScopeType::Normal => late_depth += 1,
2972 BinderScopeType::Concatenating => {}
2978 elide: Elide::FreshLateAnon(named_late_bound_vars, ref counter),
2981 for lifetime_ref in lifetime_refs {
2983 Region::late_anon(named_late_bound_vars, counter).shifted(late_depth);
2985 self.insert_lifetime(lifetime_ref, lifetime);
2990 Scope::Elision { elide: Elide::Exact(l), .. } => {
2991 let lifetime = l.shifted(late_depth);
2992 for lifetime_ref in lifetime_refs {
2993 self.insert_lifetime(lifetime_ref, lifetime);
2998 Scope::Elision { elide: Elide::Error(ref e), ref s, .. } => {
3002 Scope::Binder { ref lifetimes, s, .. } => {
3003 // Collect named lifetimes for suggestions.
3004 for name in lifetimes.keys() {
3005 if let hir::ParamName::Plain(name) = name {
3006 lifetime_names.insert(name.name);
3007 lifetime_spans.push(name.span);
3012 Scope::ObjectLifetimeDefault { ref s, .. }
3013 | Scope::Elision { ref s, .. }
3014 | Scope::TraitRefBoundary { ref s, .. } => {
3023 Scope::Elision { elide: Elide::Forbid, .. } => break None,
3025 Scope::ObjectLifetimeDefault { s, .. }
3026 | Scope::Supertrait { s, .. }
3027 | Scope::TraitRefBoundary { s, .. } => {
3033 // If we specifically need the `scope_for_path` map, then we're in the
3034 // diagnostic pass and we don't want to emit more errors.
3035 if self.map.scope_for_path.is_some() {
3036 self.tcx.sess.delay_span_bug(
3037 rustc_span::DUMMY_SP,
3038 "Encountered unexpected errors during diagnostics related part",
3043 let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3045 let mut spans_dedup = spans.clone();
3046 spans_dedup.dedup();
3047 let spans_with_counts: Vec<_> = spans_dedup
3049 .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
3052 let mut err = self.report_missing_lifetime_specifiers(spans.clone(), lifetime_refs.len());
3054 if let Some(params) = error {
3055 // If there's no lifetime available, suggest `'static`.
3056 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
3057 lifetime_names.insert(kw::StaticLifetime);
3061 self.add_missing_lifetime_specifiers_label(
3066 error.unwrap_or(&[]),
3071 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
3072 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
3073 let mut late_depth = 0;
3074 let mut scope = self.scope;
3075 let lifetime = loop {
3077 Scope::Binder { s, scope_type, .. } => {
3079 BinderScopeType::Normal => late_depth += 1,
3080 BinderScopeType::Concatenating => {}
3085 Scope::Root | Scope::Elision { .. } => break Region::Static,
3087 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
3089 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
3091 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
3096 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
3099 fn check_lifetime_params(
3101 old_scope: ScopeRef<'_>,
3102 params: &'tcx [hir::GenericParam<'tcx>],
3104 let lifetimes: Vec<_> = params
3106 .filter_map(|param| match param.kind {
3107 GenericParamKind::Lifetime { .. } => {
3108 Some((param, param.name.normalize_to_macros_2_0()))
3113 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
3114 if let hir::ParamName::Plain(_) = lifetime_i_name {
3115 let name = lifetime_i_name.ident().name;
3116 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
3117 self.tcx.sess.delay_span_bug(
3119 &format!("invalid lifetime parameter name: `{}`", lifetime_i.name.ident()),
3124 // It is a hard error to shadow a lifetime within the same scope.
3125 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
3126 if lifetime_i_name == lifetime_j_name {
3131 "lifetime name `{}` declared twice in the same scope",
3132 lifetime_j.name.ident()
3134 .span_label(lifetime_j.span, "declared twice")
3135 .span_label(lifetime_i.span, "previous declaration here")
3140 // It is a soft error to shadow a lifetime within a parent scope.
3141 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
3143 for bound in lifetime_i.bounds {
3145 hir::GenericBound::Outlives(ref lt) => match lt.name {
3146 hir::LifetimeName::Underscore => {
3147 self.tcx.sess.delay_span_bug(
3149 "use of `'_` in illegal place, but not caught by lowering",
3152 hir::LifetimeName::Static => {
3153 self.insert_lifetime(lt, Region::Static);
3157 lifetime_i.span.to(lt.span),
3159 "unnecessary lifetime parameter `{}`",
3160 lifetime_i.name.ident(),
3164 "you can use the `'static` lifetime directly, in place of `{}`",
3165 lifetime_i.name.ident(),
3169 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
3170 self.resolve_lifetime_ref(lt);
3172 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
3173 self.tcx.sess.delay_span_bug(
3175 "lowering generated `ImplicitObjectLifetimeDefault` \
3176 outside of an object type",
3179 hir::LifetimeName::Error => {
3180 // No need to do anything, error already reported.
3189 fn check_lifetime_param_for_shadowing(
3191 mut old_scope: ScopeRef<'_>,
3192 param: &'tcx hir::GenericParam<'tcx>,
3194 for label in &self.labels_in_fn {
3195 // FIXME (#24278): non-hygienic comparison
3196 if param.name.ident().name == label.name {
3197 signal_shadowing_problem(
3200 original_label(label.span),
3201 shadower_lifetime(¶m),
3209 Scope::Body { s, .. }
3210 | Scope::Elision { s, .. }
3211 | Scope::ObjectLifetimeDefault { s, .. }
3212 | Scope::Supertrait { s, .. }
3213 | Scope::TraitRefBoundary { s, .. } => {
3221 Scope::Binder { ref lifetimes, s, .. } => {
3222 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
3223 signal_shadowing_problem(
3225 param.name.ident().name,
3226 original_lifetime(self.tcx.def_span(def.id().unwrap())),
3227 shadower_lifetime(¶m),
3238 /// Returns `true` if, in the current scope, replacing `'_` would be
3239 /// equivalent to a single-use lifetime.
3240 fn track_lifetime_uses(&self) -> bool {
3241 let mut scope = self.scope;
3244 Scope::Root => break false,
3246 // Inside of items, it depends on the kind of item.
3247 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
3249 // Inside a body, `'_` will use an inference variable,
3251 Scope::Body { .. } => break true,
3253 // A lifetime only used in a fn argument could as well
3254 // be replaced with `'_`, as that would generate a
3256 Scope::Elision { elide: Elide::FreshLateAnon(..), .. } => break true,
3258 // In the return type or other such place, `'_` is not
3259 // going to make a fresh name, so we cannot
3260 // necessarily replace a single-use lifetime with
3263 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
3266 Scope::ObjectLifetimeDefault { s, .. }
3267 | Scope::Supertrait { s, .. }
3268 | Scope::TraitRefBoundary { s, .. } => scope = s,
3273 #[tracing::instrument(level = "debug", skip(self))]
3274 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
3276 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
3277 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
3279 self.map.defs.insert(lifetime_ref.hir_id, def);
3282 Region::LateBoundAnon(..) | Region::Static => {
3283 // These are anonymous lifetimes or lifetimes that are not declared.
3286 Region::Free(_, def_id)
3287 | Region::LateBound(_, _, def_id)
3288 | Region::EarlyBound(_, def_id) => {
3289 // A lifetime declared by the user.
3290 let track_lifetime_uses = self.track_lifetime_uses();
3291 debug!(?track_lifetime_uses);
3292 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
3293 debug!("first use of {:?}", def_id);
3294 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
3296 debug!("many uses of {:?}", def_id);
3297 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
3303 /// Sometimes we resolve a lifetime, but later find that it is an
3304 /// error (esp. around impl trait). In that case, we remove the
3305 /// entry into `map.defs` so as not to confuse later code.
3306 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
3307 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
3308 assert_eq!(old_value, Some(bad_def));
3312 /// Detects late-bound lifetimes and inserts them into
3313 /// `map.late_bound`.
3315 /// A region declared on a fn is **late-bound** if:
3316 /// - it is constrained by an argument type;
3317 /// - it does not appear in a where-clause.
3319 /// "Constrained" basically means that it appears in any type but
3320 /// not amongst the inputs to a projection. In other words, `<&'a
3321 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
3322 #[tracing::instrument(level = "debug", skip(map))]
3323 fn insert_late_bound_lifetimes(
3324 map: &mut NamedRegionMap,
3325 decl: &hir::FnDecl<'_>,
3326 generics: &hir::Generics<'_>,
3328 let mut constrained_by_input = ConstrainedCollector::default();
3329 for arg_ty in decl.inputs {
3330 constrained_by_input.visit_ty(arg_ty);
3333 let mut appears_in_output = AllCollector::default();
3334 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
3336 debug!(?constrained_by_input.regions);
3338 // Walk the lifetimes that appear in where clauses.
3340 // Subtle point: because we disallow nested bindings, we can just
3341 // ignore binders here and scrape up all names we see.
3342 let mut appears_in_where_clause = AllCollector::default();
3343 appears_in_where_clause.visit_generics(generics);
3345 for param in generics.params {
3346 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
3347 if !param.bounds.is_empty() {
3348 // `'a: 'b` means both `'a` and `'b` are referenced
3349 appears_in_where_clause
3351 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
3356 debug!(?appears_in_where_clause.regions);
3358 // Late bound regions are those that:
3359 // - appear in the inputs
3360 // - do not appear in the where-clauses
3361 // - are not implicitly captured by `impl Trait`
3362 for param in generics.params {
3364 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
3366 // Neither types nor consts are late-bound.
3367 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
3370 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
3371 // appears in the where clauses? early-bound.
3372 if appears_in_where_clause.regions.contains(<_name) {
3376 // does not appear in the inputs, but appears in the return type? early-bound.
3377 if !constrained_by_input.regions.contains(<_name)
3378 && appears_in_output.regions.contains(<_name)
3383 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
3385 let inserted = map.late_bound.insert(param.hir_id);
3386 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
3392 struct ConstrainedCollector {
3393 regions: FxHashSet<hir::LifetimeName>,
3396 impl<'v> Visitor<'v> for ConstrainedCollector {
3397 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3400 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
3402 // ignore lifetimes appearing in associated type
3403 // projections, as they are not *constrained*
3407 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
3408 // consider only the lifetimes on the final
3409 // segment; I am not sure it's even currently
3410 // valid to have them elsewhere, but even if it
3411 // is, those would be potentially inputs to
3413 if let Some(last_segment) = path.segments.last() {
3414 self.visit_path_segment(path.span, last_segment);
3419 intravisit::walk_ty(self, ty);
3424 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3425 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3430 struct AllCollector {
3431 regions: FxHashSet<hir::LifetimeName>,
3434 impl<'v> Visitor<'v> for AllCollector {
3435 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3436 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());