1 // ignore-tidy-filelength
2 //! Name resolution for lifetimes.
3 //!
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.
8 
9 use crate::late::diagnostics::{ForLifetimeSpanType, MissingLifetimeSpot};
10 use rustc_ast::walk_list;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
13 use rustc_hir as hir;
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, NestedVisitorMap, Visitor};
18 use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath};
19 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::middle::resolve_lifetime::*;
22 use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
23 use rustc_middle::{bug, span_bug};
24 use rustc_session::lint;
25 use rustc_span::def_id::DefId;
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
27 use rustc_span::Span;
28 use std::borrow::Cow;
29 use std::cell::Cell;
30 use std::fmt;
31 use std::mem::take;
32 
33 use tracing::{debug, span, Level};
34 
35 // This counts the no of times a lifetime is used
36 #[derive(Clone, Copy, Debug)]
37 pub enum LifetimeUseSet<'tcx> {
38     One(&'tcx hir::Lifetime),
39     Many,
40 }
41 
42 trait RegionExt {
early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region)43     fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
44 
late(index: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region)45     fn late(index: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
46 
late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region47     fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region;
48 
id(&self) -> Option<DefId>49     fn id(&self) -> Option<DefId>;
50 
shifted(self, amount: u32) -> Region51     fn shifted(self, amount: u32) -> Region;
52 
shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region53     fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
54 
subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region> where L: Iterator<Item = &'a hir::Lifetime>55     fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
56     where
57         L: Iterator<Item = &'a hir::Lifetime>;
58 }
59 
60 impl RegionExt for Region {
early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region)61     fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
62         let i = *index;
63         *index += 1;
64         let def_id = hir_map.local_def_id(param.hir_id);
65         let origin = LifetimeDefOrigin::from_param(param);
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(), origin))
68     }
69 
late(idx: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region)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);
73         let origin = LifetimeDefOrigin::from_param(param);
74         debug!(
75             "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?} origin={:?}",
76             idx, param, depth, def_id, origin,
77         );
78         (
79             param.name.normalize_to_macros_2_0(),
80             Region::LateBound(depth, idx, def_id.to_def_id(), origin),
81         )
82     }
83 
late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region84     fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region {
85         let i = index.get();
86         index.set(i + 1);
87         let depth = ty::INNERMOST;
88         Region::LateBoundAnon(depth, named_late_bound_vars + i, i)
89     }
90 
id(&self) -> Option<DefId>91     fn id(&self) -> Option<DefId> {
92         match *self {
93             Region::Static | Region::LateBoundAnon(..) => None,
94 
95             Region::EarlyBound(_, id, _) | Region::LateBound(_, _, id, _) | Region::Free(_, id) => {
96                 Some(id)
97             }
98         }
99     }
100 
shifted(self, amount: u32) -> Region101     fn shifted(self, amount: u32) -> Region {
102         match self {
103             Region::LateBound(debruijn, idx, id, origin) => {
104                 Region::LateBound(debruijn.shifted_in(amount), idx, id, origin)
105             }
106             Region::LateBoundAnon(debruijn, index, anon_index) => {
107                 Region::LateBoundAnon(debruijn.shifted_in(amount), index, anon_index)
108             }
109             _ => self,
110         }
111     }
112 
shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region113     fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
114         match self {
115             Region::LateBound(debruijn, index, id, origin) => {
116                 Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id, origin)
117             }
118             Region::LateBoundAnon(debruijn, index, anon_index) => {
119                 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index, anon_index)
120             }
121             _ => self,
122         }
123     }
124 
subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region> where L: Iterator<Item = &'a hir::Lifetime>,125     fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
126     where
127         L: Iterator<Item = &'a hir::Lifetime>,
128     {
129         if let Region::EarlyBound(index, _, _) = self {
130             params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
131         } else {
132             Some(self)
133         }
134     }
135 }
136 
137 /// Maps the id of each lifetime reference to the lifetime decl
138 /// that it corresponds to.
139 ///
140 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
141 /// actual use. It has the same data, but indexed by `LocalDefId`.  This
142 /// is silly.
143 #[derive(Debug, Default)]
144 struct NamedRegionMap {
145     // maps from every use of a named (not anonymous) lifetime to a
146     // `Region` describing how that region is bound
147     defs: HirIdMap<Region>,
148 
149     // the set of lifetime def ids that are late-bound; a region can
150     // be late-bound if (a) it does NOT appear in a where-clause and
151     // (b) it DOES appear in the arguments.
152     late_bound: HirIdSet,
153 
154     // Maps relevant hir items to the bound vars on them. These include:
155     // - function defs
156     // - function pointers
157     // - closures
158     // - trait refs
159     // - bound types (like `T` in `for<'a> T<'a>: Foo`)
160     late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
161 
162     // maps `PathSegment` `HirId`s to lifetime scopes.
163     scope_for_path: Option<FxHashMap<LocalDefId, FxHashMap<ItemLocalId, LifetimeScopeForPath>>>,
164 }
165 
166 crate struct LifetimeContext<'a, 'tcx> {
167     crate tcx: TyCtxt<'tcx>,
168     map: &'a mut NamedRegionMap,
169     scope: ScopeRef<'a>,
170 
171     /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
172     is_in_fn_syntax: bool,
173 
174     is_in_const_generic: bool,
175 
176     /// Indicates that we only care about the definition of a trait. This should
177     /// be false if the `Item` we are resolving lifetimes for is not a trait or
178     /// we eventually need lifetimes resolve for trait items.
179     trait_definition_only: bool,
180 
181     /// List of labels in the function/method currently under analysis.
182     labels_in_fn: Vec<Ident>,
183 
184     /// Cache for cross-crate per-definition object lifetime defaults.
185     xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
186 
187     lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
188 
189     /// When encountering an undefined named lifetime, we will suggest introducing it in these
190     /// places.
191     crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
192 }
193 
194 #[derive(Debug)]
195 enum Scope<'a> {
196     /// Declares lifetimes, and each can be early-bound or late-bound.
197     /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
198     /// it should be shifted by the number of `Binder`s in between the
199     /// declaration `Binder` and the location it's referenced from.
200     Binder {
201         /// We use an IndexMap here because we want these lifetimes in order
202         /// for diagnostics.
203         lifetimes: FxIndexMap<hir::ParamName, Region>,
204 
205         /// if we extend this scope with another scope, what is the next index
206         /// we should use for an early-bound region?
207         next_early_index: u32,
208 
209         /// Flag is set to true if, in this binder, `'_` would be
210         /// equivalent to a "single-use region". This is true on
211         /// impls, but not other kinds of items.
212         track_lifetime_uses: bool,
213 
214         /// Whether or not this binder would serve as the parent
215         /// binder for opaque types introduced within. For example:
216         ///
217         /// ```text
218         ///     fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
219         /// ```
220         ///
221         /// Here, the opaque types we create for the `impl Trait`
222         /// and `impl Trait2` references will both have the `foo` item
223         /// as their parent. When we get to `impl Trait2`, we find
224         /// that it is nested within the `for<>` binder -- this flag
225         /// allows us to skip that when looking for the parent binder
226         /// of the resulting opaque type.
227         opaque_type_parent: bool,
228 
229         scope_type: BinderScopeType,
230 
231         /// The late bound vars for a given item are stored by `HirId` to be
232         /// queried later. However, if we enter an elision scope, we have to
233         /// later append the elided bound vars to the list and need to know what
234         /// to append to.
235         hir_id: hir::HirId,
236 
237         s: ScopeRef<'a>,
238     },
239 
240     /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
241     /// if this is a fn body, otherwise the original definitions are used.
242     /// Unspecified lifetimes are inferred, unless an elision scope is nested,
243     /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
244     Body {
245         id: hir::BodyId,
246         s: ScopeRef<'a>,
247     },
248 
249     /// A scope which either determines unspecified lifetimes or errors
250     /// on them (e.g., due to ambiguity). For more details, see `Elide`.
251     Elision {
252         elide: Elide,
253         s: ScopeRef<'a>,
254     },
255 
256     /// Use a specific lifetime (if `Some`) or leave it unset (to be
257     /// inferred in a function body or potentially error outside one),
258     /// for the default choice of lifetime in a trait object type.
259     ObjectLifetimeDefault {
260         lifetime: Option<Region>,
261         s: ScopeRef<'a>,
262     },
263 
264     /// When we have nested trait refs, we concanetate late bound vars for inner
265     /// trait refs from outer ones. But we also need to include any HRTB
266     /// lifetimes encountered when identifying the trait that an associated type
267     /// is declared on.
268     Supertrait {
269         lifetimes: Vec<ty::BoundVariableKind>,
270         s: ScopeRef<'a>,
271     },
272 
273     TraitRefBoundary {
274         s: ScopeRef<'a>,
275     },
276 
277     Root,
278 }
279 
280 #[derive(Copy, Clone, Debug)]
281 enum BinderScopeType {
282     /// Any non-concatenating binder scopes.
283     Normal,
284     /// Within a syntactic trait ref, there may be multiple poly trait refs that
285     /// are nested (under the `associcated_type_bounds` feature). The binders of
286     /// the innner poly trait refs are extended from the outer poly trait refs
287     /// and don't increase the late bound depth. If you had
288     /// `T: for<'a>  Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
289     /// would be `Concatenating`. This also used in trait refs in where clauses
290     /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
291     /// out any lifetimes because they aren't needed to show the two scopes).
292     /// The inner `for<>` has a scope of `Concatenating`.
293     Concatenating,
294 }
295 
296 // A helper struct for debugging scopes without printing parent scopes
297 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
298 
299 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result300     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301         match self.0 {
302             Scope::Binder {
303                 lifetimes,
304                 next_early_index,
305                 track_lifetime_uses,
306                 opaque_type_parent,
307                 scope_type,
308                 hir_id,
309                 s: _,
310             } => f
311                 .debug_struct("Binder")
312                 .field("lifetimes", lifetimes)
313                 .field("next_early_index", next_early_index)
314                 .field("track_lifetime_uses", track_lifetime_uses)
315                 .field("opaque_type_parent", opaque_type_parent)
316                 .field("scope_type", scope_type)
317                 .field("hir_id", hir_id)
318                 .field("s", &"..")
319                 .finish(),
320             Scope::Body { id, s: _ } => {
321                 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
322             }
323             Scope::Elision { elide, s: _ } => {
324                 f.debug_struct("Elision").field("elide", elide).field("s", &"..").finish()
325             }
326             Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
327                 .debug_struct("ObjectLifetimeDefault")
328                 .field("lifetime", lifetime)
329                 .field("s", &"..")
330                 .finish(),
331             Scope::Supertrait { lifetimes, s: _ } => f
332                 .debug_struct("Supertrait")
333                 .field("lifetimes", lifetimes)
334                 .field("s", &"..")
335                 .finish(),
336             Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
337             Scope::Root => f.debug_struct("Root").finish(),
338         }
339     }
340 }
341 
342 #[derive(Clone, Debug)]
343 enum Elide {
344     /// Use a fresh anonymous late-bound lifetime each time, by
345     /// incrementing the counter to generate sequential indices. All
346     /// anonymous lifetimes must start *after* named bound vars.
347     FreshLateAnon(u32, Cell<u32>),
348     /// Always use this one lifetime.
349     Exact(Region),
350     /// Less or more than one lifetime were found, error on unspecified.
351     Error(Vec<ElisionFailureInfo>),
352     /// Forbid lifetime elision inside of a larger scope where it would be
353     /// permitted. For example, in let position impl trait.
354     Forbid,
355 }
356 
357 #[derive(Clone, Debug)]
358 crate struct ElisionFailureInfo {
359     /// Where we can find the argument pattern.
360     parent: Option<hir::BodyId>,
361     /// The index of the argument in the original definition.
362     index: usize,
363     lifetime_count: usize,
364     have_bound_regions: bool,
365     crate span: Span,
366 }
367 
368 type ScopeRef<'a> = &'a Scope<'a>;
369 
370 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
371 
provide(providers: &mut ty::query::Providers)372 pub fn provide(providers: &mut ty::query::Providers) {
373     *providers = ty::query::Providers {
374         resolve_lifetimes_trait_definition,
375         resolve_lifetimes,
376 
377         named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
378         is_late_bound_map,
379         object_lifetime_defaults_map: |tcx, id| {
380             let hir_id = tcx.hir().local_def_id_to_hir_id(id);
381             match tcx.hir().find(hir_id) {
382                 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
383                 _ => None,
384             }
385         },
386         late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
387         lifetime_scope_map: |tcx, id| {
388             let item_id = item_for(tcx, id);
389             do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
390         },
391 
392         ..*providers
393     };
394 }
395 
396 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
397 /// Also does not generate any diagnostics.
398 ///
399 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
400 /// resolves lifetimes only within the trait "header" -- that is, the trait
401 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
402 /// lifetimes within the trait and its items. There is room to refactor this,
403 /// for example to resolve lifetimes for each trait item in separate queries,
404 /// but it's convenient to do the entire trait at once because the lifetimes
405 /// from the trait definition are in scope within the trait items as well.
406 ///
407 /// The reason for this separate call is to resolve what would otherwise
408 /// be a cycle. Consider this example:
409 ///
410 /// ```rust
411 /// trait Base<'a> {
412 ///     type BaseItem;
413 /// }
414 /// trait Sub<'b>: for<'a> Base<'a> {
415 ///    type SubItem: Sub<BaseItem = &'b u32>;
416 /// }
417 /// ```
418 ///
419 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
420 /// To figure out the index of `'b`, we have to know about the supertraits
421 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
422 /// (This is because we -- currently at least -- flatten all the late-bound
423 /// lifetimes into a single binder.) This requires us to resolve the
424 /// *trait definition* of `Sub`; basically just enough lifetime information
425 /// to look at the supertraits.
426 #[tracing::instrument(level = "debug", skip(tcx))]
resolve_lifetimes_trait_definition( tcx: TyCtxt<'_>, local_def_id: LocalDefId, ) -> ResolveLifetimes427 fn resolve_lifetimes_trait_definition(
428     tcx: TyCtxt<'_>,
429     local_def_id: LocalDefId,
430 ) -> ResolveLifetimes {
431     convert_named_region_map(do_resolve(tcx, local_def_id, true, false))
432 }
433 
434 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
435 /// You should not read the result of this query directly, but rather use
436 /// `named_region_map`, `is_late_bound_map`, etc.
437 #[tracing::instrument(level = "debug", skip(tcx))]
resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes438 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
439     convert_named_region_map(do_resolve(tcx, local_def_id, false, false))
440 }
441 
do_resolve( tcx: TyCtxt<'_>, local_def_id: LocalDefId, trait_definition_only: bool, with_scope_for_path: bool, ) -> NamedRegionMap442 fn do_resolve(
443     tcx: TyCtxt<'_>,
444     local_def_id: LocalDefId,
445     trait_definition_only: bool,
446     with_scope_for_path: bool,
447 ) -> NamedRegionMap {
448     let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(local_def_id));
449     let mut named_region_map = NamedRegionMap {
450         defs: Default::default(),
451         late_bound: Default::default(),
452         late_bound_vars: Default::default(),
453         scope_for_path: with_scope_for_path.then(|| Default::default()),
454     };
455     let mut visitor = LifetimeContext {
456         tcx,
457         map: &mut named_region_map,
458         scope: ROOT_SCOPE,
459         is_in_fn_syntax: false,
460         is_in_const_generic: false,
461         trait_definition_only,
462         labels_in_fn: vec![],
463         xcrate_object_lifetime_defaults: Default::default(),
464         lifetime_uses: &mut Default::default(),
465         missing_named_lifetime_spots: vec![],
466     };
467     visitor.visit_item(item);
468 
469     named_region_map
470 }
471 
convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes472 fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes {
473     let mut rl = ResolveLifetimes::default();
474 
475     for (hir_id, v) in named_region_map.defs {
476         let map = rl.defs.entry(hir_id.owner).or_default();
477         map.insert(hir_id.local_id, v);
478     }
479     for hir_id in named_region_map.late_bound {
480         let map = rl.late_bound.entry(hir_id.owner).or_default();
481         map.insert(hir_id.local_id);
482     }
483     for (hir_id, v) in named_region_map.late_bound_vars {
484         let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
485         map.insert(hir_id.local_id, v);
486     }
487 
488     debug!(?rl.defs);
489     rl
490 }
491 
492 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
493 /// There are two important things this does.
494 /// First, we have to resolve lifetimes for
495 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
496 /// where we can have relevant lifetimes.
497 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
498 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
499 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
500 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
501 /// `resolve_lifetimes`.
resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes502 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
503     let item_id = item_for(tcx, def_id);
504     if item_id == def_id {
505         let item = tcx.hir().item(hir::ItemId { def_id: item_id });
506         match item.kind {
507             hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
508             _ => tcx.resolve_lifetimes(item_id),
509         }
510     } else {
511         tcx.resolve_lifetimes(item_id)
512     }
513 }
514 
515 /// Finds the `Item` that contains the given `LocalDefId`
item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId516 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
517     let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
518     match tcx.hir().find(hir_id) {
519         Some(Node::Item(item)) => {
520             return item.def_id;
521         }
522         _ => {}
523     }
524     let item = {
525         let mut parent_iter = tcx.hir().parent_iter(hir_id);
526         loop {
527             let node = parent_iter.next().map(|n| n.1);
528             match node {
529                 Some(hir::Node::Item(item)) => break item.def_id,
530                 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
531                 _ => {}
532             }
533         }
534     };
535     item
536 }
537 
is_late_bound_map<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, ) -> Option<(LocalDefId, &'tcx FxHashSet<ItemLocalId>)>538 fn is_late_bound_map<'tcx>(
539     tcx: TyCtxt<'tcx>,
540     def_id: LocalDefId,
541 ) -> Option<(LocalDefId, &'tcx FxHashSet<ItemLocalId>)> {
542     match tcx.def_kind(def_id) {
543         DefKind::AnonConst | DefKind::InlineConst => {
544             let mut def_id = tcx
545                 .parent(def_id.to_def_id())
546                 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
547             // We search for the next outer anon const or fn here
548             // while skipping closures.
549             //
550             // Note that for `AnonConst` we still just recurse until we
551             // find a function body, but who cares :shrug:
552             while tcx.is_closure(def_id) {
553                 def_id = tcx
554                     .parent(def_id)
555                     .unwrap_or_else(|| bug!("anon const or closure without a parent"));
556             }
557 
558             tcx.is_late_bound_map(def_id.expect_local())
559         }
560         _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
561     }
562 }
563 
564 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
565 /// We have to account for this when computing the index of the other generic parameters.
566 /// This function returns whether there is such an implicit parameter defined on the given item.
sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool567 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
568     matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
569 }
570 
late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind571 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
572     match region {
573         Region::LateBound(_, _, def_id, _) => {
574             let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
575             ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
576         }
577         Region::LateBoundAnon(_, _, anon_idx) => {
578             ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
579         }
580         _ => bug!("{:?} is not a late region", region),
581     }
582 }
583 
584 #[tracing::instrument(level = "debug")]
get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath585 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
586     let mut available_lifetimes = vec![];
587     loop {
588         match scope {
589             Scope::Binder { lifetimes, s, .. } => {
590                 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
591                     hir::ParamName::Plain(ident) => Some(ident.name.to_string()),
592                     _ => None,
593                 }));
594                 scope = s;
595             }
596             Scope::Body { s, .. } => {
597                 scope = s;
598             }
599             Scope::Elision { elide, s } => {
600                 if let Elide::Exact(_) = elide {
601                     return LifetimeScopeForPath::Elided;
602                 } else {
603                     scope = s;
604                 }
605             }
606             Scope::ObjectLifetimeDefault { s, .. } => {
607                 scope = s;
608             }
609             Scope::Root => {
610                 return LifetimeScopeForPath::NonElided(available_lifetimes);
611             }
612             Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
613                 scope = s;
614             }
615         }
616     }
617 }
618 
619 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
620     /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType)621     fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
622         let mut scope = self.scope;
623         let mut supertrait_lifetimes = vec![];
624         loop {
625             match scope {
626                 Scope::Body { .. } | Scope::Root => {
627                     break (vec![], BinderScopeType::Normal);
628                 }
629 
630                 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
631                     scope = s;
632                 }
633 
634                 Scope::Supertrait { s, lifetimes } => {
635                     supertrait_lifetimes = lifetimes.clone();
636                     scope = s;
637                 }
638 
639                 Scope::TraitRefBoundary { .. } => {
640                     // We should only see super trait lifetimes if there is a `Binder` above
641                     assert!(supertrait_lifetimes.is_empty());
642                     break (vec![], BinderScopeType::Normal);
643                 }
644 
645                 Scope::Binder { hir_id, .. } => {
646                     // Nested poly trait refs have the binders concatenated
647                     let mut full_binders =
648                         self.map.late_bound_vars.entry(*hir_id).or_default().clone();
649                     full_binders.extend(supertrait_lifetimes.into_iter());
650                     break (full_binders, BinderScopeType::Concatenating);
651                 }
652             }
653         }
654     }
655 }
656 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
657     type Map = Map<'tcx>;
658 
nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map>659     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
660         NestedVisitorMap::All(self.tcx.hir())
661     }
662 
663     // We want to nest trait/impl items in their parent, but nothing else.
visit_nested_item(&mut self, _: hir::ItemId)664     fn visit_nested_item(&mut self, _: hir::ItemId) {}
665 
visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef)666     fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
667         if !self.trait_definition_only {
668             intravisit::walk_trait_item_ref(self, ii)
669         }
670     }
671 
visit_nested_body(&mut self, body: hir::BodyId)672     fn visit_nested_body(&mut self, body: hir::BodyId) {
673         // Each body has their own set of labels, save labels.
674         let saved = take(&mut self.labels_in_fn);
675         let body = self.tcx.hir().body(body);
676         extract_labels(self, body);
677         self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
678             this.visit_body(body);
679         });
680         self.labels_in_fn = saved;
681     }
682 
visit_fn( &mut self, fk: intravisit::FnKind<'tcx>, fd: &'tcx hir::FnDecl<'tcx>, b: hir::BodyId, s: rustc_span::Span, hir_id: hir::HirId, )683     fn visit_fn(
684         &mut self,
685         fk: intravisit::FnKind<'tcx>,
686         fd: &'tcx hir::FnDecl<'tcx>,
687         b: hir::BodyId,
688         s: rustc_span::Span,
689         hir_id: hir::HirId,
690     ) {
691         let name = match fk {
692             intravisit::FnKind::ItemFn(id, _, _, _) => id.as_str(),
693             intravisit::FnKind::Method(id, _, _) => id.as_str(),
694             intravisit::FnKind::Closure => Symbol::intern("closure").as_str(),
695         };
696         let name: &str = &name;
697         let span = span!(Level::DEBUG, "visit_fn", name);
698         let _enter = span.enter();
699         match fk {
700             // Any `Binders` are handled elsewhere
701             intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
702                 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
703             }
704             intravisit::FnKind::Closure => {
705                 self.map.late_bound_vars.insert(hir_id, vec![]);
706                 let scope = Scope::Binder {
707                     hir_id,
708                     lifetimes: FxIndexMap::default(),
709                     next_early_index: self.next_early_index(),
710                     s: self.scope,
711                     track_lifetime_uses: true,
712                     opaque_type_parent: false,
713                     scope_type: BinderScopeType::Normal,
714                 };
715                 self.with(scope, move |_old_scope, this| {
716                     intravisit::walk_fn(this, fk, fd, b, s, hir_id)
717                 });
718             }
719         }
720     }
721 
visit_item(&mut self, item: &'tcx hir::Item<'tcx>)722     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
723         match &item.kind {
724             hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
725                 if let Some(of_trait) = of_trait {
726                     self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
727                 }
728             }
729             _ => {}
730         }
731         match item.kind {
732             hir::ItemKind::Fn(ref sig, ref generics, _) => {
733                 self.missing_named_lifetime_spots.push(generics.into());
734                 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
735                     intravisit::walk_item(this, item);
736                 });
737                 self.missing_named_lifetime_spots.pop();
738             }
739 
740             hir::ItemKind::ExternCrate(_)
741             | hir::ItemKind::Use(..)
742             | hir::ItemKind::Macro(..)
743             | hir::ItemKind::Mod(..)
744             | hir::ItemKind::ForeignMod { .. }
745             | hir::ItemKind::GlobalAsm(..) => {
746                 // These sorts of items have no lifetime parameters at all.
747                 intravisit::walk_item(self, item);
748             }
749             hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
750                 // No lifetime parameters, but implied 'static.
751                 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
752                 self.with(scope, |_, this| intravisit::walk_item(this, item));
753             }
754             hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
755                 // Opaque types are visited when we visit the
756                 // `TyKind::OpaqueDef`, so that they have the lifetimes from
757                 // their parent opaque_ty in scope.
758                 //
759                 // The core idea here is that since OpaqueTys are generated with the impl Trait as
760                 // their owner, we can keep going until we find the Item that owns that. We then
761                 // conservatively add all resolved lifetimes. Otherwise we run into problems in
762                 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
763                 for (_hir_id, node) in
764                     self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
765                 {
766                     match node {
767                         hir::Node::Item(parent_item) => {
768                             let resolved_lifetimes: &ResolveLifetimes =
769                                 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
770                             // We need to add *all* deps, since opaque tys may want them from *us*
771                             for (&owner, defs) in resolved_lifetimes.defs.iter() {
772                                 defs.iter().for_each(|(&local_id, region)| {
773                                     self.map.defs.insert(hir::HirId { owner, local_id }, *region);
774                                 });
775                             }
776                             for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
777                                 late_bound.iter().for_each(|&local_id| {
778                                     self.map.late_bound.insert(hir::HirId { owner, local_id });
779                                 });
780                             }
781                             for (&owner, late_bound_vars) in
782                                 resolved_lifetimes.late_bound_vars.iter()
783                             {
784                                 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
785                                     self.map.late_bound_vars.insert(
786                                         hir::HirId { owner, local_id },
787                                         late_bound_vars.clone(),
788                                     );
789                                 });
790                             }
791                             break;
792                         }
793                         hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
794                         _ => {}
795                     }
796                 }
797             }
798             hir::ItemKind::TyAlias(_, ref generics)
799             | hir::ItemKind::Enum(_, ref generics)
800             | hir::ItemKind::Struct(_, ref generics)
801             | hir::ItemKind::Union(_, ref generics)
802             | hir::ItemKind::Trait(_, _, ref generics, ..)
803             | hir::ItemKind::TraitAlias(ref generics, ..)
804             | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
805                 self.missing_named_lifetime_spots.push(generics.into());
806 
807                 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
808                 // This is not true for other kinds of items.
809                 let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
810                 // These kinds of items have only early-bound lifetime parameters.
811                 let mut index = if sub_items_have_self_param(&item.kind) {
812                     1 // Self comes before lifetimes
813                 } else {
814                     0
815                 };
816                 let mut non_lifetime_count = 0;
817                 let lifetimes = generics
818                     .params
819                     .iter()
820                     .filter_map(|param| match param.kind {
821                         GenericParamKind::Lifetime { .. } => {
822                             Some(Region::early(&self.tcx.hir(), &mut index, param))
823                         }
824                         GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
825                             non_lifetime_count += 1;
826                             None
827                         }
828                     })
829                     .collect();
830                 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
831                 let scope = Scope::Binder {
832                     hir_id: item.hir_id(),
833                     lifetimes,
834                     next_early_index: index + non_lifetime_count,
835                     opaque_type_parent: true,
836                     track_lifetime_uses,
837                     scope_type: BinderScopeType::Normal,
838                     s: ROOT_SCOPE,
839                 };
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);
845                     });
846                 });
847                 self.missing_named_lifetime_spots.pop();
848             }
849         }
850     }
851 
visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>)852     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
853         match item.kind {
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);
857                 })
858             }
859             hir::ForeignItemKind::Static(..) => {
860                 intravisit::walk_foreign_item(self, item);
861             }
862             hir::ForeignItemKind::Type => {
863                 intravisit::walk_foreign_item(self, item);
864             }
865         }
866     }
867 
868     #[tracing::instrument(level = "debug", skip(self))]
visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>)869     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
870         match ty.kind {
871             hir::TyKind::BareFn(ref c) => {
872                 let next_early_index = self.next_early_index();
873                 let was_in_fn_syntax = self.is_in_fn_syntax;
874                 self.is_in_fn_syntax = true;
875                 let lifetime_span: Option<Span> =
876                     c.generic_params.iter().rev().find_map(|param| match param.kind {
877                         GenericParamKind::Lifetime { .. } => Some(param.span),
878                         _ => None,
879                     });
880                 let (span, span_type) = if let Some(span) = lifetime_span {
881                     (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
882                 } else {
883                     (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
884                 };
885                 self.missing_named_lifetime_spots
886                     .push(MissingLifetimeSpot::HigherRanked { span, span_type });
887                 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
888                     .generic_params
889                     .iter()
890                     .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
891                     .enumerate()
892                     .map(|(late_bound_idx, param)| {
893                         let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
894                         let r = late_region_as_bound_region(self.tcx, &pair.1);
895                         (pair, r)
896                     })
897                     .unzip();
898                 self.map.late_bound_vars.insert(ty.hir_id, binders);
899                 let scope = Scope::Binder {
900                     hir_id: ty.hir_id,
901                     lifetimes,
902                     s: self.scope,
903                     next_early_index,
904                     track_lifetime_uses: true,
905                     opaque_type_parent: false,
906                     scope_type: BinderScopeType::Normal,
907                 };
908                 self.with(scope, |old_scope, this| {
909                     // a bare fn has no bounds, so everything
910                     // contained within is scoped within its binder.
911                     this.check_lifetime_params(old_scope, &c.generic_params);
912                     intravisit::walk_ty(this, ty);
913                 });
914                 self.missing_named_lifetime_spots.pop();
915                 self.is_in_fn_syntax = was_in_fn_syntax;
916             }
917             hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
918                 debug!(?bounds, ?lifetime, "TraitObject");
919                 let scope = Scope::TraitRefBoundary { s: self.scope };
920                 self.with(scope, |_, this| {
921                     for bound in bounds {
922                         this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
923                     }
924                 });
925                 match lifetime.name {
926                     LifetimeName::Implicit => {
927                         // For types like `dyn Foo`, we should
928                         // generate a special form of elided.
929                         span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
930                     }
931                     LifetimeName::ImplicitObjectLifetimeDefault => {
932                         // If the user does not write *anything*, we
933                         // use the object lifetime defaulting
934                         // rules. So e.g., `Box<dyn Debug>` becomes
935                         // `Box<dyn Debug + 'static>`.
936                         self.resolve_object_lifetime_default(lifetime)
937                     }
938                     LifetimeName::Underscore => {
939                         // If the user writes `'_`, we use the *ordinary* elision
940                         // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
941                         // resolved the same as the `'_` in `&'_ Foo`.
942                         //
943                         // cc #48468
944                         self.resolve_elided_lifetimes(&[lifetime])
945                     }
946                     LifetimeName::Param(_) | LifetimeName::Static => {
947                         // If the user wrote an explicit name, use that.
948                         self.visit_lifetime(lifetime);
949                     }
950                     LifetimeName::Error => {}
951                 }
952             }
953             hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
954                 self.visit_lifetime(lifetime_ref);
955                 let scope = Scope::ObjectLifetimeDefault {
956                     lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
957                     s: self.scope,
958                 };
959                 self.with(scope, |_, this| this.visit_ty(&mt.ty));
960             }
961             hir::TyKind::OpaqueDef(item_id, lifetimes) => {
962                 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
963                 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
964                 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
965                 //                 ^                  ^ this gets resolved in the scope of
966                 //                                      the opaque_ty generics
967                 let opaque_ty = self.tcx.hir().item(item_id);
968                 let (generics, bounds) = match opaque_ty.kind {
969                     // Named opaque `impl Trait` types are reached via `TyKind::Path`.
970                     // This arm is for `impl Trait` in the types of statics, constants and locals.
971                     hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
972                         intravisit::walk_ty(self, ty);
973 
974                         // Elided lifetimes are not allowed in non-return
975                         // position impl Trait
976                         let scope = Scope::TraitRefBoundary { s: self.scope };
977                         self.with(scope, |_, this| {
978                             let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
979                             this.with(scope, |_, this| {
980                                 intravisit::walk_item(this, opaque_ty);
981                             })
982                         });
983 
984                         return;
985                     }
986                     // RPIT (return position impl trait)
987                     hir::ItemKind::OpaqueTy(hir::OpaqueTy {
988                         impl_trait_fn: Some(_),
989                         ref generics,
990                         bounds,
991                         ..
992                     }) => (generics, bounds),
993                     ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
994                 };
995 
996                 // Resolve the lifetimes that are applied to the opaque type.
997                 // These are resolved in the current scope.
998                 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
999                 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
1000                 //          ^                 ^this gets resolved in the current scope
1001                 for lifetime in lifetimes {
1002                     if let hir::GenericArg::Lifetime(lifetime) = lifetime {
1003                         self.visit_lifetime(lifetime);
1004 
1005                         // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1006                         // and ban them. Type variables instantiated inside binders aren't
1007                         // well-supported at the moment, so this doesn't work.
1008                         // In the future, this should be fixed and this error should be removed.
1009                         let def = self.map.defs.get(&lifetime.hir_id).cloned();
1010                         if let Some(Region::LateBound(_, _, def_id, _)) = def {
1011                             if let Some(def_id) = def_id.as_local() {
1012                                 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1013                                 // Ensure that the parent of the def is an item, not HRTB
1014                                 let parent_id = self.tcx.hir().get_parent_node(hir_id);
1015                                 // FIXME(cjgillot) Can this check be replaced by
1016                                 // `let parent_is_item = parent_id.is_owner();`?
1017                                 let parent_is_item =
1018                                     if let Some(parent_def_id) = parent_id.as_owner() {
1019                                         matches!(
1020                                             self.tcx.hir().krate().owners.get(parent_def_id),
1021                                             Some(Some(_)),
1022                                         )
1023                                     } else {
1024                                         false
1025                                     };
1026 
1027                                 if !parent_is_item {
1028                                     if !self.trait_definition_only {
1029                                         struct_span_err!(
1030                                             self.tcx.sess,
1031                                             lifetime.span,
1032                                             E0657,
1033                                             "`impl Trait` can only capture lifetimes \
1034                                                 bound at the fn or impl level"
1035                                         )
1036                                         .emit();
1037                                     }
1038                                     self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1039                                 }
1040                             }
1041                         }
1042                     }
1043                 }
1044 
1045                 // We want to start our early-bound indices at the end of the parent scope,
1046                 // not including any parent `impl Trait`s.
1047                 let mut index = self.next_early_index_for_opaque_type();
1048                 debug!(?index);
1049 
1050                 let mut elision = None;
1051                 let mut lifetimes = FxIndexMap::default();
1052                 let mut non_lifetime_count = 0;
1053                 for param in generics.params {
1054                     match param.kind {
1055                         GenericParamKind::Lifetime { .. } => {
1056                             let (name, reg) = Region::early(&self.tcx.hir(), &mut index, &param);
1057                             let Region::EarlyBound(_, def_id, _) = reg else {
1058                                 bug!();
1059                             };
1060                             // We cannot predict what lifetimes are unused in opaque type.
1061                             self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
1062                             if let hir::ParamName::Plain(Ident {
1063                                 name: kw::UnderscoreLifetime,
1064                                 ..
1065                             }) = name
1066                             {
1067                                 // Pick the elided lifetime "definition" if one exists
1068                                 // and use it to make an elision scope.
1069                                 elision = Some(reg);
1070                             } else {
1071                                 lifetimes.insert(name, reg);
1072                             }
1073                         }
1074                         GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1075                             non_lifetime_count += 1;
1076                         }
1077                     }
1078                 }
1079                 let next_early_index = index + non_lifetime_count;
1080                 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1081 
1082                 if let Some(elision_region) = elision {
1083                     let scope =
1084                         Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1085                     self.with(scope, |_old_scope, this| {
1086                         let scope = Scope::Binder {
1087                             hir_id: ty.hir_id,
1088                             lifetimes,
1089                             next_early_index,
1090                             s: this.scope,
1091                             track_lifetime_uses: true,
1092                             opaque_type_parent: false,
1093                             scope_type: BinderScopeType::Normal,
1094                         };
1095                         this.with(scope, |_old_scope, this| {
1096                             this.visit_generics(generics);
1097                             let scope = Scope::TraitRefBoundary { s: this.scope };
1098                             this.with(scope, |_, this| {
1099                                 for bound in bounds {
1100                                     this.visit_param_bound(bound);
1101                                 }
1102                             })
1103                         });
1104                     });
1105                 } else {
1106                     let scope = Scope::Binder {
1107                         hir_id: ty.hir_id,
1108                         lifetimes,
1109                         next_early_index,
1110                         s: self.scope,
1111                         track_lifetime_uses: true,
1112                         opaque_type_parent: false,
1113                         scope_type: BinderScopeType::Normal,
1114                     };
1115                     self.with(scope, |_old_scope, this| {
1116                         let scope = Scope::TraitRefBoundary { s: this.scope };
1117                         this.with(scope, |_, this| {
1118                             this.visit_generics(generics);
1119                             for bound in bounds {
1120                                 this.visit_param_bound(bound);
1121                             }
1122                         })
1123                     });
1124                 }
1125             }
1126             _ => intravisit::walk_ty(self, ty),
1127         }
1128     }
1129 
visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>)1130     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1131         use self::hir::TraitItemKind::*;
1132         match trait_item.kind {
1133             Fn(ref sig, _) => {
1134                 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1135                 let tcx = self.tcx;
1136                 self.visit_early_late(
1137                     Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1138                     trait_item.hir_id(),
1139                     &sig.decl,
1140                     &trait_item.generics,
1141                     |this| intravisit::walk_trait_item(this, trait_item),
1142                 );
1143                 self.missing_named_lifetime_spots.pop();
1144             }
1145             Type(bounds, ref ty) => {
1146                 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1147                 let generics = &trait_item.generics;
1148                 let mut index = self.next_early_index();
1149                 debug!("visit_ty: index = {}", index);
1150                 let mut non_lifetime_count = 0;
1151                 let lifetimes = generics
1152                     .params
1153                     .iter()
1154                     .filter_map(|param| match param.kind {
1155                         GenericParamKind::Lifetime { .. } => {
1156                             Some(Region::early(&self.tcx.hir(), &mut index, param))
1157                         }
1158                         GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1159                             non_lifetime_count += 1;
1160                             None
1161                         }
1162                     })
1163                     .collect();
1164                 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1165                 let scope = Scope::Binder {
1166                     hir_id: trait_item.hir_id(),
1167                     lifetimes,
1168                     next_early_index: index + non_lifetime_count,
1169                     s: self.scope,
1170                     track_lifetime_uses: true,
1171                     opaque_type_parent: true,
1172                     scope_type: BinderScopeType::Normal,
1173                 };
1174                 self.with(scope, |old_scope, this| {
1175                     this.check_lifetime_params(old_scope, &generics.params);
1176                     let scope = Scope::TraitRefBoundary { s: this.scope };
1177                     this.with(scope, |_, this| {
1178                         this.visit_generics(generics);
1179                         for bound in bounds {
1180                             this.visit_param_bound(bound);
1181                         }
1182                         if let Some(ty) = ty {
1183                             this.visit_ty(ty);
1184                         }
1185                     })
1186                 });
1187                 self.missing_named_lifetime_spots.pop();
1188             }
1189             Const(_, _) => {
1190                 // Only methods and types support generics.
1191                 assert!(trait_item.generics.params.is_empty());
1192                 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1193                 intravisit::walk_trait_item(self, trait_item);
1194                 self.missing_named_lifetime_spots.pop();
1195             }
1196         }
1197     }
1198 
visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>)1199     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1200         use self::hir::ImplItemKind::*;
1201         match impl_item.kind {
1202             Fn(ref sig, _) => {
1203                 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1204                 let tcx = self.tcx;
1205                 self.visit_early_late(
1206                     Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1207                     impl_item.hir_id(),
1208                     &sig.decl,
1209                     &impl_item.generics,
1210                     |this| intravisit::walk_impl_item(this, impl_item),
1211                 );
1212                 self.missing_named_lifetime_spots.pop();
1213             }
1214             TyAlias(ref ty) => {
1215                 let generics = &impl_item.generics;
1216                 self.missing_named_lifetime_spots.push(generics.into());
1217                 let mut index = self.next_early_index();
1218                 let mut non_lifetime_count = 0;
1219                 debug!("visit_ty: index = {}", index);
1220                 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1221                     .params
1222                     .iter()
1223                     .filter_map(|param| match param.kind {
1224                         GenericParamKind::Lifetime { .. } => {
1225                             Some(Region::early(&self.tcx.hir(), &mut index, param))
1226                         }
1227                         GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1228                             non_lifetime_count += 1;
1229                             None
1230                         }
1231                     })
1232                     .collect();
1233                 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1234                 let scope = Scope::Binder {
1235                     hir_id: ty.hir_id,
1236                     lifetimes,
1237                     next_early_index: index + non_lifetime_count,
1238                     s: self.scope,
1239                     track_lifetime_uses: true,
1240                     opaque_type_parent: true,
1241                     scope_type: BinderScopeType::Normal,
1242                 };
1243                 self.with(scope, |old_scope, this| {
1244                     this.check_lifetime_params(old_scope, &generics.params);
1245                     let scope = Scope::TraitRefBoundary { s: this.scope };
1246                     this.with(scope, |_, this| {
1247                         this.visit_generics(generics);
1248                         this.visit_ty(ty);
1249                     })
1250                 });
1251                 self.missing_named_lifetime_spots.pop();
1252             }
1253             Const(_, _) => {
1254                 // Only methods and types support generics.
1255                 assert!(impl_item.generics.params.is_empty());
1256                 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1257                 intravisit::walk_impl_item(self, impl_item);
1258                 self.missing_named_lifetime_spots.pop();
1259             }
1260         }
1261     }
1262 
1263     #[tracing::instrument(level = "debug", skip(self))]
visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime)1264     fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1265         if lifetime_ref.is_elided() {
1266             self.resolve_elided_lifetimes(&[lifetime_ref]);
1267             return;
1268         }
1269         if lifetime_ref.is_static() {
1270             self.insert_lifetime(lifetime_ref, Region::Static);
1271             return;
1272         }
1273         if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
1274             self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
1275             return;
1276         }
1277         self.resolve_lifetime_ref(lifetime_ref);
1278     }
1279 
visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>)1280     fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1281         let scope = self.scope;
1282         if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1283             // We add lifetime scope information for `Ident`s in associated type bindings and use
1284             // the `HirId` of the type binding as the key in `LifetimeMap`
1285             let lifetime_scope = get_lifetime_scopes_for_path(scope);
1286             let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1287             map.insert(type_binding.hir_id.local_id, lifetime_scope);
1288         }
1289         hir::intravisit::walk_assoc_type_binding(self, type_binding);
1290     }
1291 
visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId)1292     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1293         for (i, segment) in path.segments.iter().enumerate() {
1294             let depth = path.segments.len() - i - 1;
1295             if let Some(ref args) = segment.args {
1296                 self.visit_segment_args(path.res, depth, args);
1297             }
1298 
1299             let scope = self.scope;
1300             if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1301                 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1302                 // here because that call would yield to resolution problems due to `walk_path_segment`
1303                 // being called, which processes the path segments generic args, which we have already
1304                 // processed using `visit_segment_args`.
1305                 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1306                 if let Some(hir_id) = segment.hir_id {
1307                     let map = scope_for_path.entry(hir_id.owner).or_default();
1308                     map.insert(hir_id.local_id, lifetime_scope);
1309                 }
1310             }
1311         }
1312     }
1313 
visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>)1314     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1315         let scope = self.scope;
1316         if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1317             let lifetime_scope = get_lifetime_scopes_for_path(scope);
1318             if let Some(hir_id) = path_segment.hir_id {
1319                 let map = scope_for_path.entry(hir_id.owner).or_default();
1320                 map.insert(hir_id.local_id, lifetime_scope);
1321             }
1322         }
1323 
1324         intravisit::walk_path_segment(self, path_span, path_segment);
1325     }
1326 
visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>)1327     fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1328         let output = match fd.output {
1329             hir::FnRetTy::DefaultReturn(_) => None,
1330             hir::FnRetTy::Return(ref ty) => Some(&**ty),
1331         };
1332         self.visit_fn_like_elision(&fd.inputs, output);
1333     }
1334 
visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>)1335     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1336         if !self.trait_definition_only {
1337             check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
1338         }
1339         let scope = Scope::TraitRefBoundary { s: self.scope };
1340         self.with(scope, |_, this| {
1341             for param in generics.params {
1342                 match param.kind {
1343                     GenericParamKind::Lifetime { .. } => {}
1344                     GenericParamKind::Type { ref default, .. } => {
1345                         walk_list!(this, visit_param_bound, param.bounds);
1346                         if let Some(ref ty) = default {
1347                             this.visit_ty(&ty);
1348                         }
1349                     }
1350                     GenericParamKind::Const { ref ty, .. } => {
1351                         let was_in_const_generic = this.is_in_const_generic;
1352                         this.is_in_const_generic = true;
1353                         walk_list!(this, visit_param_bound, param.bounds);
1354                         this.visit_ty(&ty);
1355                         this.is_in_const_generic = was_in_const_generic;
1356                     }
1357                 }
1358             }
1359             for predicate in generics.where_clause.predicates {
1360                 match predicate {
1361                     &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1362                         ref bounded_ty,
1363                         bounds,
1364                         ref bound_generic_params,
1365                         ..
1366                     }) => {
1367                         let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1368                             bound_generic_params
1369                                 .iter()
1370                                 .filter(|param| {
1371                                     matches!(param.kind, GenericParamKind::Lifetime { .. })
1372                                 })
1373                                 .enumerate()
1374                                 .map(|(late_bound_idx, param)| {
1375                                     let pair =
1376                                         Region::late(late_bound_idx as u32, &this.tcx.hir(), param);
1377                                     let r = late_region_as_bound_region(this.tcx, &pair.1);
1378                                     (pair, r)
1379                                 })
1380                                 .unzip();
1381                         this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1382                         let next_early_index = this.next_early_index();
1383                         // Even if there are no lifetimes defined here, we still wrap it in a binder
1384                         // scope. If there happens to be a nested poly trait ref (an error), that
1385                         // will be `Concatenating` anyways, so we don't have to worry about the depth
1386                         // being wrong.
1387                         let scope = Scope::Binder {
1388                             hir_id: bounded_ty.hir_id,
1389                             lifetimes,
1390                             s: this.scope,
1391                             next_early_index,
1392                             track_lifetime_uses: true,
1393                             opaque_type_parent: false,
1394                             scope_type: BinderScopeType::Normal,
1395                         };
1396                         this.with(scope, |old_scope, this| {
1397                             this.check_lifetime_params(old_scope, &bound_generic_params);
1398                             this.visit_ty(&bounded_ty);
1399                             walk_list!(this, visit_param_bound, bounds);
1400                         })
1401                     }
1402                     &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1403                         ref lifetime,
1404                         bounds,
1405                         ..
1406                     }) => {
1407                         this.visit_lifetime(lifetime);
1408                         walk_list!(this, visit_param_bound, bounds);
1409                     }
1410                     &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1411                         ref lhs_ty,
1412                         ref rhs_ty,
1413                         ..
1414                     }) => {
1415                         this.visit_ty(lhs_ty);
1416                         this.visit_ty(rhs_ty);
1417                     }
1418                 }
1419             }
1420         })
1421     }
1422 
visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>)1423     fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1424         match bound {
1425             hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1426                 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1427                 // through the regular poly trait ref code, so we don't get another
1428                 // chance to introduce a binder. For now, I'm keeping the existing logic
1429                 // of "if there isn't a Binder scope above us, add one", but I
1430                 // imagine there's a better way to go about this.
1431                 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1432 
1433                 self.map.late_bound_vars.insert(*hir_id, binders);
1434                 let scope = Scope::Binder {
1435                     hir_id: *hir_id,
1436                     lifetimes: FxIndexMap::default(),
1437                     s: self.scope,
1438                     next_early_index: self.next_early_index(),
1439                     track_lifetime_uses: true,
1440                     opaque_type_parent: false,
1441                     scope_type,
1442                 };
1443                 self.with(scope, |_, this| {
1444                     intravisit::walk_param_bound(this, bound);
1445                 });
1446             }
1447             _ => intravisit::walk_param_bound(self, bound),
1448         }
1449     }
1450 
visit_poly_trait_ref( &mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>, _modifier: hir::TraitBoundModifier, )1451     fn visit_poly_trait_ref(
1452         &mut self,
1453         trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1454         _modifier: hir::TraitBoundModifier,
1455     ) {
1456         debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1457 
1458         let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1459 
1460         let next_early_index = self.next_early_index();
1461         let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1462 
1463         let initial_bound_vars = binders.len() as u32;
1464         let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1465         let binders_iter = trait_ref
1466             .bound_generic_params
1467             .iter()
1468             .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1469             .enumerate()
1470             .map(|(late_bound_idx, param)| {
1471                 let pair = Region::late(
1472                     initial_bound_vars + late_bound_idx as u32,
1473                     &self.tcx.hir(),
1474                     param,
1475                 );
1476                 let r = late_region_as_bound_region(self.tcx, &pair.1);
1477                 lifetimes.insert(pair.0, pair.1);
1478                 r
1479             });
1480         binders.extend(binders_iter);
1481 
1482         debug!(?binders);
1483         self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1484 
1485         // Always introduce a scope here, even if this is in a where clause and
1486         // we introduced the binders around the bounded Ty. In that case, we
1487         // just reuse the concatenation functionality also present in nested trait
1488         // refs.
1489         let scope = Scope::Binder {
1490             hir_id: trait_ref.trait_ref.hir_ref_id,
1491             lifetimes,
1492             s: self.scope,
1493             next_early_index,
1494             track_lifetime_uses: true,
1495             opaque_type_parent: false,
1496             scope_type,
1497         };
1498         self.with(scope, |old_scope, this| {
1499             this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1500             walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1501             this.visit_trait_ref(&trait_ref.trait_ref);
1502         });
1503 
1504         if should_pop_missing_lt {
1505             self.missing_named_lifetime_spots.pop();
1506         }
1507     }
1508 }
1509 
1510 #[derive(Copy, Clone, PartialEq)]
1511 enum ShadowKind {
1512     Label,
1513     Lifetime,
1514 }
1515 struct Original {
1516     kind: ShadowKind,
1517     span: Span,
1518 }
1519 struct Shadower {
1520     kind: ShadowKind,
1521     span: Span,
1522 }
1523 
original_label(span: Span) -> Original1524 fn original_label(span: Span) -> Original {
1525     Original { kind: ShadowKind::Label, span }
1526 }
shadower_label(span: Span) -> Shadower1527 fn shadower_label(span: Span) -> Shadower {
1528     Shadower { kind: ShadowKind::Label, span }
1529 }
original_lifetime(span: Span) -> Original1530 fn original_lifetime(span: Span) -> Original {
1531     Original { kind: ShadowKind::Lifetime, span }
1532 }
shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower1533 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1534     Shadower { kind: ShadowKind::Lifetime, span: param.span }
1535 }
1536 
1537 impl ShadowKind {
desc(&self) -> &'static str1538     fn desc(&self) -> &'static str {
1539         match *self {
1540             ShadowKind::Label => "label",
1541             ShadowKind::Lifetime => "lifetime",
1542         }
1543     }
1544 }
1545 
check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>])1546 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1547     let lifetime_params: Vec<_> = params
1548         .iter()
1549         .filter_map(|param| match param.kind {
1550             GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1551             _ => None,
1552         })
1553         .collect();
1554     let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1555     let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1556 
1557     if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1558         struct_span_err!(
1559             tcx.sess,
1560             *in_band_span,
1561             E0688,
1562             "cannot mix in-band and explicit lifetime definitions"
1563         )
1564         .span_label(*in_band_span, "in-band lifetime definition here")
1565         .span_label(*explicit_span, "explicit lifetime definition here")
1566         .emit();
1567     }
1568 }
1569 
signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower)1570 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1571     let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1572         // lifetime/lifetime shadowing is an error
1573         struct_span_err!(
1574             tcx.sess,
1575             shadower.span,
1576             E0496,
1577             "{} name `{}` shadows a \
1578              {} name that is already in scope",
1579             shadower.kind.desc(),
1580             name,
1581             orig.kind.desc()
1582         )
1583     } else {
1584         // shadowing involving a label is only a warning, due to issues with
1585         // labels and lifetimes not being macro-hygienic.
1586         tcx.sess.struct_span_warn(
1587             shadower.span,
1588             &format!(
1589                 "{} name `{}` shadows a \
1590                  {} name that is already in scope",
1591                 shadower.kind.desc(),
1592                 name,
1593                 orig.kind.desc()
1594             ),
1595         )
1596     };
1597     err.span_label(orig.span, "first declared here");
1598     err.span_label(shadower.span, format!("{} `{}` already in scope", orig.kind.desc(), name));
1599     err.emit();
1600 }
1601 
1602 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1603 // if one of the label shadows a lifetime or another label.
extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>)1604 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1605     struct GatherLabels<'a, 'tcx> {
1606         tcx: TyCtxt<'tcx>,
1607         scope: ScopeRef<'a>,
1608         labels_in_fn: &'a mut Vec<Ident>,
1609     }
1610 
1611     let mut gather =
1612         GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1613     gather.visit_body(body);
1614 
1615     impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1616         type Map = intravisit::ErasedMap<'v>;
1617 
1618         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1619             NestedVisitorMap::None
1620         }
1621 
1622         fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1623             if let Some(label) = expression_label(ex) {
1624                 for prior_label in &self.labels_in_fn[..] {
1625                     // FIXME (#24278): non-hygienic comparison
1626                     if label.name == prior_label.name {
1627                         signal_shadowing_problem(
1628                             self.tcx,
1629                             label.name,
1630                             original_label(prior_label.span),
1631                             shadower_label(label.span),
1632                         );
1633                     }
1634                 }
1635 
1636                 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1637 
1638                 self.labels_in_fn.push(label);
1639             }
1640             intravisit::walk_expr(self, ex)
1641         }
1642     }
1643 
1644     fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1645         match ex.kind {
1646             hir::ExprKind::Loop(_, Some(label), ..) => Some(label.ident),
1647             hir::ExprKind::Block(_, Some(label)) => Some(label.ident),
1648             _ => None,
1649         }
1650     }
1651 
1652     fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1653         loop {
1654             match *scope {
1655                 Scope::Body { s, .. }
1656                 | Scope::Elision { s, .. }
1657                 | Scope::ObjectLifetimeDefault { s, .. }
1658                 | Scope::Supertrait { s, .. }
1659                 | Scope::TraitRefBoundary { s, .. } => {
1660                     scope = s;
1661                 }
1662 
1663                 Scope::Root => {
1664                     return;
1665                 }
1666 
1667                 Scope::Binder { ref lifetimes, s, .. } => {
1668                     // FIXME (#24278): non-hygienic comparison
1669                     if let Some(def) =
1670                         lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1671                     {
1672                         let hir_id =
1673                             tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
1674 
1675                         signal_shadowing_problem(
1676                             tcx,
1677                             label.name,
1678                             original_lifetime(tcx.hir().span(hir_id)),
1679                             shadower_label(label.span),
1680                         );
1681                         return;
1682                     }
1683                     scope = s;
1684                 }
1685             }
1686         }
1687     }
1688 }
1689 
compute_object_lifetime_defaults( tcx: TyCtxt<'_>, item: &hir::Item<'_>, ) -> Option<Vec<ObjectLifetimeDefault>>1690 fn compute_object_lifetime_defaults(
1691     tcx: TyCtxt<'_>,
1692     item: &hir::Item<'_>,
1693 ) -> Option<Vec<ObjectLifetimeDefault>> {
1694     match item.kind {
1695         hir::ItemKind::Struct(_, ref generics)
1696         | hir::ItemKind::Union(_, ref generics)
1697         | hir::ItemKind::Enum(_, ref generics)
1698         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, impl_trait_fn: None, .. })
1699         | hir::ItemKind::TyAlias(_, ref generics)
1700         | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1701             let result = object_lifetime_defaults_for_item(tcx, generics);
1702 
1703             // Debugging aid.
1704             let attrs = tcx.hir().attrs(item.hir_id());
1705             if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1706                 let object_lifetime_default_reprs: String = result
1707                     .iter()
1708                     .map(|set| match *set {
1709                         Set1::Empty => "BaseDefault".into(),
1710                         Set1::One(Region::Static) => "'static".into(),
1711                         Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1712                             .params
1713                             .iter()
1714                             .find_map(|param| match param.kind {
1715                                 GenericParamKind::Lifetime { .. } => {
1716                                     if i == 0 {
1717                                         return Some(param.name.ident().to_string().into());
1718                                     }
1719                                     i -= 1;
1720                                     None
1721                                 }
1722                                 _ => None,
1723                             })
1724                             .unwrap(),
1725                         Set1::One(_) => bug!(),
1726                         Set1::Many => "Ambiguous".into(),
1727                     })
1728                     .collect::<Vec<Cow<'static, str>>>()
1729                     .join(",");
1730                 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1731             }
1732 
1733             Some(result)
1734         }
1735         _ => None,
1736     }
1737 }
1738 
1739 /// Scan the bounds and where-clauses on parameters to extract bounds
1740 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1741 /// for each type parameter.
object_lifetime_defaults_for_item( tcx: TyCtxt<'_>, generics: &hir::Generics<'_>, ) -> Vec<ObjectLifetimeDefault>1742 fn object_lifetime_defaults_for_item(
1743     tcx: TyCtxt<'_>,
1744     generics: &hir::Generics<'_>,
1745 ) -> Vec<ObjectLifetimeDefault> {
1746     fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1747         for bound in bounds {
1748             if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1749                 set.insert(lifetime.name.normalize_to_macros_2_0());
1750             }
1751         }
1752     }
1753 
1754     generics
1755         .params
1756         .iter()
1757         .filter_map(|param| match param.kind {
1758             GenericParamKind::Lifetime { .. } => None,
1759             GenericParamKind::Type { .. } => {
1760                 let mut set = Set1::Empty;
1761 
1762                 add_bounds(&mut set, &param.bounds);
1763 
1764                 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1765                 for predicate in generics.where_clause.predicates {
1766                     // Look for `type: ...` where clauses.
1767                     let data = match *predicate {
1768                         hir::WherePredicate::BoundPredicate(ref data) => data,
1769                         _ => continue,
1770                     };
1771 
1772                     // Ignore `for<'a> type: ...` as they can change what
1773                     // lifetimes mean (although we could "just" handle it).
1774                     if !data.bound_generic_params.is_empty() {
1775                         continue;
1776                     }
1777 
1778                     let res = match data.bounded_ty.kind {
1779                         hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1780                         _ => continue,
1781                     };
1782 
1783                     if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1784                         add_bounds(&mut set, &data.bounds);
1785                     }
1786                 }
1787 
1788                 Some(match set {
1789                     Set1::Empty => Set1::Empty,
1790                     Set1::One(name) => {
1791                         if name == hir::LifetimeName::Static {
1792                             Set1::One(Region::Static)
1793                         } else {
1794                             generics
1795                                 .params
1796                                 .iter()
1797                                 .filter_map(|param| match param.kind {
1798                                     GenericParamKind::Lifetime { .. } => Some((
1799                                         param.hir_id,
1800                                         hir::LifetimeName::Param(param.name),
1801                                         LifetimeDefOrigin::from_param(param),
1802                                     )),
1803                                     _ => None,
1804                                 })
1805                                 .enumerate()
1806                                 .find(|&(_, (_, lt_name, _))| lt_name == name)
1807                                 .map_or(Set1::Many, |(i, (id, _, origin))| {
1808                                     let def_id = tcx.hir().local_def_id(id);
1809                                     Set1::One(Region::EarlyBound(
1810                                         i as u32,
1811                                         def_id.to_def_id(),
1812                                         origin,
1813                                     ))
1814                                 })
1815                         }
1816                     }
1817                     Set1::Many => Set1::Many,
1818                 })
1819             }
1820             GenericParamKind::Const { .. } => {
1821                 // Generic consts don't impose any constraints.
1822                 //
1823                 // We still store a dummy value here to allow generic parameters
1824                 // in an arbitrary order.
1825                 Some(Set1::Empty)
1826             }
1827         })
1828         .collect()
1829 }
1830 
1831 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
with<F>(&mut self, wrap_scope: Scope<'_>, f: F) where F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),1832     fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1833     where
1834         F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1835     {
1836         let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1837         let labels_in_fn = take(&mut self.labels_in_fn);
1838         let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1839         let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1840         let mut this = LifetimeContext {
1841             tcx: *tcx,
1842             map,
1843             scope: &wrap_scope,
1844             is_in_fn_syntax: self.is_in_fn_syntax,
1845             is_in_const_generic: self.is_in_const_generic,
1846             trait_definition_only: self.trait_definition_only,
1847             labels_in_fn,
1848             xcrate_object_lifetime_defaults,
1849             lifetime_uses,
1850             missing_named_lifetime_spots,
1851         };
1852         let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1853         {
1854             let _enter = span.enter();
1855             f(self.scope, &mut this);
1856             if !self.trait_definition_only {
1857                 this.check_uses_for_lifetimes_defined_by_scope();
1858             }
1859         }
1860         self.labels_in_fn = this.labels_in_fn;
1861         self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1862         self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1863     }
1864 
1865     /// helper method to determine the span to remove when suggesting the
1866     /// deletion of a lifetime
lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span>1867     fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1868         generics.params.iter().enumerate().find_map(|(i, param)| {
1869             if param.name.ident() == name {
1870                 let in_band = matches!(
1871                     param.kind,
1872                     hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::InBand }
1873                 );
1874                 if in_band {
1875                     Some(param.span)
1876                 } else if generics.params.len() == 1 {
1877                     // if sole lifetime, remove the entire `<>` brackets
1878                     Some(generics.span)
1879                 } else {
1880                     // if removing within `<>` brackets, we also want to
1881                     // delete a leading or trailing comma as appropriate
1882                     if i >= generics.params.len() - 1 {
1883                         Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1884                     } else {
1885                         Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1886                     }
1887                 }
1888             } else {
1889                 None
1890             }
1891         })
1892     }
1893 
1894     // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1895     // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
suggest_eliding_single_use_lifetime( &self, err: &mut DiagnosticBuilder<'_>, def_id: DefId, lifetime: &hir::Lifetime, )1896     fn suggest_eliding_single_use_lifetime(
1897         &self,
1898         err: &mut DiagnosticBuilder<'_>,
1899         def_id: DefId,
1900         lifetime: &hir::Lifetime,
1901     ) {
1902         let name = lifetime.name.ident();
1903         let remove_decl = self
1904             .tcx
1905             .parent(def_id)
1906             .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id))
1907             .and_then(|generics| self.lifetime_deletion_span(name, generics));
1908 
1909         let mut remove_use = None;
1910         let mut elide_use = None;
1911         let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1912             for input in inputs {
1913                 match input.kind {
1914                     hir::TyKind::Rptr(lt, _) => {
1915                         if lt.name.ident() == name {
1916                             // include the trailing whitespace between the lifetime and type names
1917                             let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1918                             remove_use = Some(
1919                                 self.tcx
1920                                     .sess
1921                                     .source_map()
1922                                     .span_until_non_whitespace(lt_through_ty_span),
1923                             );
1924                             break;
1925                         }
1926                     }
1927                     hir::TyKind::Path(QPath::Resolved(_, path)) => {
1928                         let last_segment = &path.segments[path.segments.len() - 1];
1929                         let generics = last_segment.args();
1930                         for arg in generics.args.iter() {
1931                             if let GenericArg::Lifetime(lt) = arg {
1932                                 if lt.name.ident() == name {
1933                                     elide_use = Some(lt.span);
1934                                     break;
1935                                 }
1936                             }
1937                         }
1938                         break;
1939                     }
1940                     _ => {}
1941                 }
1942             }
1943         };
1944         if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1945             if let Some(parent) =
1946                 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1947             {
1948                 match parent {
1949                     Node::Item(item) => {
1950                         if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1951                             find_arg_use_span(sig.decl.inputs);
1952                         }
1953                     }
1954                     Node::ImplItem(impl_item) => {
1955                         if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1956                             find_arg_use_span(sig.decl.inputs);
1957                         }
1958                     }
1959                     _ => {}
1960                 }
1961             }
1962         }
1963 
1964         let msg = "elide the single-use lifetime";
1965         match (remove_decl, remove_use, elide_use) {
1966             (Some(decl_span), Some(use_span), None) => {
1967                 // if both declaration and use deletion spans start at the same
1968                 // place ("start at" because the latter includes trailing
1969                 // whitespace), then this is an in-band lifetime
1970                 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1971                     err.span_suggestion(
1972                         use_span,
1973                         msg,
1974                         String::new(),
1975                         Applicability::MachineApplicable,
1976                     );
1977                 } else {
1978                     err.multipart_suggestion(
1979                         msg,
1980                         vec![(decl_span, String::new()), (use_span, String::new())],
1981                         Applicability::MachineApplicable,
1982                     );
1983                 }
1984             }
1985             (Some(decl_span), None, Some(use_span)) => {
1986                 err.multipart_suggestion(
1987                     msg,
1988                     vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1989                     Applicability::MachineApplicable,
1990                 );
1991             }
1992             _ => {}
1993         }
1994     }
1995 
check_uses_for_lifetimes_defined_by_scope(&mut self)1996     fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1997         let defined_by = match self.scope {
1998             Scope::Binder { lifetimes, .. } => lifetimes,
1999             _ => {
2000                 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
2001                 return;
2002             }
2003         };
2004 
2005         let mut def_ids: Vec<_> = defined_by
2006             .values()
2007             .flat_map(|region| match region {
2008                 Region::EarlyBound(_, def_id, _)
2009                 | Region::LateBound(_, _, def_id, _)
2010                 | Region::Free(_, def_id) => Some(*def_id),
2011 
2012                 Region::LateBoundAnon(..) | Region::Static => None,
2013             })
2014             .collect();
2015 
2016         // ensure that we issue lints in a repeatable order
2017         def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
2018 
2019         'lifetimes: for def_id in def_ids {
2020             debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
2021 
2022             let lifetimeuseset = self.lifetime_uses.remove(&def_id);
2023 
2024             debug!(
2025                 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
2026                 lifetimeuseset
2027             );
2028 
2029             match lifetimeuseset {
2030                 Some(LifetimeUseSet::One(lifetime)) => {
2031                     let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2032                     debug!("hir id first={:?}", hir_id);
2033                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
2034                         Node::Lifetime(hir_lifetime) => Some((
2035                             hir_lifetime.hir_id,
2036                             hir_lifetime.span,
2037                             hir_lifetime.name.ident(),
2038                         )),
2039                         Node::GenericParam(param) => {
2040                             Some((param.hir_id, param.span, param.name.ident()))
2041                         }
2042                         _ => None,
2043                     } {
2044                         debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
2045                         if name.name == kw::UnderscoreLifetime {
2046                             continue;
2047                         }
2048 
2049                         if let Some(parent_def_id) = self.tcx.parent(def_id) {
2050                             if let Some(def_id) = parent_def_id.as_local() {
2051                                 let parent_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2052                                 // lifetimes in `derive` expansions don't count (Issue #53738)
2053                                 if self
2054                                     .tcx
2055                                     .hir()
2056                                     .attrs(parent_hir_id)
2057                                     .iter()
2058                                     .any(|attr| attr.has_name(sym::automatically_derived))
2059                                 {
2060                                     continue;
2061                                 }
2062 
2063                                 // opaque types generated when desugaring an async function can have a single
2064                                 // use lifetime even if it is explicitly denied (Issue #77175)
2065                                 if let hir::Node::Item(hir::Item {
2066                                     kind: hir::ItemKind::OpaqueTy(ref opaque),
2067                                     ..
2068                                 }) = self.tcx.hir().get(parent_hir_id)
2069                                 {
2070                                     if opaque.origin != hir::OpaqueTyOrigin::AsyncFn {
2071                                         continue 'lifetimes;
2072                                     }
2073                                     // We want to do this only if the liftime identifier is already defined
2074                                     // in the async function that generated this. Otherwise it could be
2075                                     // an opaque type defined by the developer and we still want this
2076                                     // lint to fail compilation
2077                                     for p in opaque.generics.params {
2078                                         if defined_by.contains_key(&p.name) {
2079                                             continue 'lifetimes;
2080                                         }
2081                                     }
2082                                 }
2083                             }
2084                         }
2085 
2086                         self.tcx.struct_span_lint_hir(
2087                             lint::builtin::SINGLE_USE_LIFETIMES,
2088                             id,
2089                             span,
2090                             |lint| {
2091                                 let mut err = lint.build(&format!(
2092                                     "lifetime parameter `{}` only used once",
2093                                     name
2094                                 ));
2095                                 if span == lifetime.span {
2096                                     // spans are the same for in-band lifetime declarations
2097                                     err.span_label(span, "this lifetime is only used here");
2098                                 } else {
2099                                     err.span_label(span, "this lifetime...");
2100                                     err.span_label(lifetime.span, "...is used only here");
2101                                 }
2102                                 self.suggest_eliding_single_use_lifetime(
2103                                     &mut err, def_id, lifetime,
2104                                 );
2105                                 err.emit();
2106                             },
2107                         );
2108                     }
2109                 }
2110                 Some(LifetimeUseSet::Many) => {
2111                     debug!("not one use lifetime");
2112                 }
2113                 None => {
2114                     let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2115                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
2116                         Node::Lifetime(hir_lifetime) => Some((
2117                             hir_lifetime.hir_id,
2118                             hir_lifetime.span,
2119                             hir_lifetime.name.ident(),
2120                         )),
2121                         Node::GenericParam(param) => {
2122                             Some((param.hir_id, param.span, param.name.ident()))
2123                         }
2124                         _ => None,
2125                     } {
2126                         debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
2127                         self.tcx.struct_span_lint_hir(
2128                             lint::builtin::UNUSED_LIFETIMES,
2129                             id,
2130                             span,
2131                             |lint| {
2132                                 let mut err = lint
2133                                     .build(&format!("lifetime parameter `{}` never used", name));
2134                                 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2135                                     if let Some(generics) =
2136                                         self.tcx.hir().get_generics(parent_def_id)
2137                                     {
2138                                         let unused_lt_span =
2139                                             self.lifetime_deletion_span(name, generics);
2140                                         if let Some(span) = unused_lt_span {
2141                                             err.span_suggestion(
2142                                                 span,
2143                                                 "elide the unused lifetime",
2144                                                 String::new(),
2145                                                 Applicability::MachineApplicable,
2146                                             );
2147                                         }
2148                                     }
2149                                 }
2150                                 err.emit();
2151                             },
2152                         );
2153                     }
2154                 }
2155             }
2156         }
2157     }
2158 
2159     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
2160     ///
2161     /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
2162     /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
2163     /// within type bounds; those are early bound lifetimes, and the rest are late bound.
2164     ///
2165     /// For example:
2166     ///
2167     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
2168     ///
2169     /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
2170     /// lifetimes may be interspersed together.
2171     ///
2172     /// If early bound lifetimes are present, we separate them into their own list (and likewise
2173     /// for late bound). They will be numbered sequentially, starting from the lowest index that is
2174     /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
2175     /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
2176     /// ordering is not important there.
visit_early_late<F>( &mut self, parent_id: Option<hir::HirId>, hir_id: hir::HirId, decl: &'tcx hir::FnDecl<'tcx>, generics: &'tcx hir::Generics<'tcx>, walk: F, ) where F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),2177     fn visit_early_late<F>(
2178         &mut self,
2179         parent_id: Option<hir::HirId>,
2180         hir_id: hir::HirId,
2181         decl: &'tcx hir::FnDecl<'tcx>,
2182         generics: &'tcx hir::Generics<'tcx>,
2183         walk: F,
2184     ) where
2185         F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
2186     {
2187         insert_late_bound_lifetimes(self.map, decl, generics);
2188 
2189         // Find the start of nested early scopes, e.g., in methods.
2190         let mut next_early_index = 0;
2191         if let Some(parent_id) = parent_id {
2192             let parent = self.tcx.hir().expect_item(parent_id);
2193             if sub_items_have_self_param(&parent.kind) {
2194                 next_early_index += 1; // Self comes before lifetimes
2195             }
2196             match parent.kind {
2197                 hir::ItemKind::Trait(_, _, ref generics, ..)
2198                 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
2199                     next_early_index += generics.params.len() as u32;
2200                 }
2201                 _ => {}
2202             }
2203         }
2204 
2205         let mut non_lifetime_count = 0;
2206         let mut named_late_bound_vars = 0;
2207         let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
2208             .params
2209             .iter()
2210             .filter_map(|param| match param.kind {
2211                 GenericParamKind::Lifetime { .. } => {
2212                     if self.map.late_bound.contains(&param.hir_id) {
2213                         let late_bound_idx = named_late_bound_vars;
2214                         named_late_bound_vars += 1;
2215                         Some(Region::late(late_bound_idx, &self.tcx.hir(), param))
2216                     } else {
2217                         Some(Region::early(&self.tcx.hir(), &mut next_early_index, param))
2218                     }
2219                 }
2220                 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
2221                     non_lifetime_count += 1;
2222                     None
2223                 }
2224             })
2225             .collect();
2226         let next_early_index = next_early_index + non_lifetime_count;
2227 
2228         let binders: Vec<_> = generics
2229             .params
2230             .iter()
2231             .filter(|param| {
2232                 matches!(param.kind, GenericParamKind::Lifetime { .. })
2233                     && self.map.late_bound.contains(&param.hir_id)
2234             })
2235             .enumerate()
2236             .map(|(late_bound_idx, param)| {
2237                 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
2238                 late_region_as_bound_region(self.tcx, &pair.1)
2239             })
2240             .collect();
2241         self.map.late_bound_vars.insert(hir_id, binders);
2242         let scope = Scope::Binder {
2243             hir_id,
2244             lifetimes,
2245             next_early_index,
2246             s: self.scope,
2247             opaque_type_parent: true,
2248             track_lifetime_uses: false,
2249             scope_type: BinderScopeType::Normal,
2250         };
2251         self.with(scope, move |old_scope, this| {
2252             this.check_lifetime_params(old_scope, &generics.params);
2253             walk(this);
2254         });
2255     }
2256 
next_early_index_helper(&self, only_opaque_type_parent: bool) -> u322257     fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
2258         let mut scope = self.scope;
2259         loop {
2260             match *scope {
2261                 Scope::Root => return 0,
2262 
2263                 Scope::Binder { next_early_index, opaque_type_parent, .. }
2264                     if (!only_opaque_type_parent || opaque_type_parent) =>
2265                 {
2266                     return next_early_index;
2267                 }
2268 
2269                 Scope::Binder { s, .. }
2270                 | Scope::Body { s, .. }
2271                 | Scope::Elision { s, .. }
2272                 | Scope::ObjectLifetimeDefault { s, .. }
2273                 | Scope::Supertrait { s, .. }
2274                 | Scope::TraitRefBoundary { s, .. } => scope = s,
2275             }
2276         }
2277     }
2278 
2279     /// Returns the next index one would use for an early-bound-region
2280     /// if extending the current scope.
next_early_index(&self) -> u322281     fn next_early_index(&self) -> u32 {
2282         self.next_early_index_helper(true)
2283     }
2284 
2285     /// Returns the next index one would use for an `impl Trait` that
2286     /// is being converted into an opaque type alias `impl Trait`. This will be the
2287     /// next early index from the enclosing item, for the most
2288     /// part. See the `opaque_type_parent` field for more info.
next_early_index_for_opaque_type(&self) -> u322289     fn next_early_index_for_opaque_type(&self) -> u32 {
2290         self.next_early_index_helper(false)
2291     }
2292 
resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime)2293     fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2294         debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
2295 
2296         // If we've already reported an error, just ignore `lifetime_ref`.
2297         if let LifetimeName::Error = lifetime_ref.name {
2298             return;
2299         }
2300 
2301         // Walk up the scope chain, tracking the number of fn scopes
2302         // that we pass through, until we find a lifetime with the
2303         // given name or we run out of scopes.
2304         // search.
2305         let mut late_depth = 0;
2306         let mut scope = self.scope;
2307         let mut outermost_body = None;
2308         let result = loop {
2309             match *scope {
2310                 Scope::Body { id, s } => {
2311                     // Non-static lifetimes are prohibited in anonymous constants without
2312                     // `generic_const_exprs`.
2313                     self.maybe_emit_forbidden_non_static_lifetime_error(id, lifetime_ref);
2314 
2315                     outermost_body = Some(id);
2316                     scope = s;
2317                 }
2318 
2319                 Scope::Root => {
2320                     break None;
2321                 }
2322 
2323                 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
2324                     match lifetime_ref.name {
2325                         LifetimeName::Param(param_name) => {
2326                             if let Some(&def) = lifetimes.get(&param_name.normalize_to_macros_2_0())
2327                             {
2328                                 break Some(def.shifted(late_depth));
2329                             }
2330                         }
2331                         _ => bug!("expected LifetimeName::Param"),
2332                     }
2333                     match scope_type {
2334                         BinderScopeType::Normal => late_depth += 1,
2335                         BinderScopeType::Concatenating => {}
2336                     }
2337                     scope = s;
2338                 }
2339 
2340                 Scope::Elision { s, .. }
2341                 | Scope::ObjectLifetimeDefault { s, .. }
2342                 | Scope::Supertrait { s, .. }
2343                 | Scope::TraitRefBoundary { s, .. } => {
2344                     scope = s;
2345                 }
2346             }
2347         };
2348 
2349         if let Some(mut def) = result {
2350             if let Region::EarlyBound(..) = def {
2351                 // Do not free early-bound regions, only late-bound ones.
2352             } else if let Some(body_id) = outermost_body {
2353                 let fn_id = self.tcx.hir().body_owner(body_id);
2354                 match self.tcx.hir().get(fn_id) {
2355                     Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
2356                     | Node::TraitItem(&hir::TraitItem {
2357                         kind: hir::TraitItemKind::Fn(..), ..
2358                     })
2359                     | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
2360                         let scope = self.tcx.hir().local_def_id(fn_id);
2361                         def = Region::Free(scope.to_def_id(), def.id().unwrap());
2362                     }
2363                     _ => {}
2364                 }
2365             }
2366 
2367             // Check for fn-syntax conflicts with in-band lifetime definitions
2368             if !self.trait_definition_only && self.is_in_fn_syntax {
2369                 match def {
2370                     Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
2371                     | Region::LateBound(_, _, _, LifetimeDefOrigin::InBand) => {
2372                         struct_span_err!(
2373                             self.tcx.sess,
2374                             lifetime_ref.span,
2375                             E0687,
2376                             "lifetimes used in `fn` or `Fn` syntax must be \
2377                              explicitly declared using `<...>` binders"
2378                         )
2379                         .span_label(lifetime_ref.span, "in-band lifetime definition")
2380                         .emit();
2381                     }
2382 
2383                     Region::Static
2384                     | Region::EarlyBound(
2385                         _,
2386                         _,
2387                         LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2388                     )
2389                     | Region::LateBound(
2390                         _,
2391                         _,
2392                         _,
2393                         LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2394                     )
2395                     | Region::LateBoundAnon(..)
2396                     | Region::Free(..) => {}
2397                 }
2398             }
2399 
2400             self.insert_lifetime(lifetime_ref, def);
2401         } else {
2402             self.emit_undeclared_lifetime_error(lifetime_ref);
2403         }
2404     }
2405 
visit_segment_args( &mut self, res: Res, depth: usize, generic_args: &'tcx hir::GenericArgs<'tcx>, )2406     fn visit_segment_args(
2407         &mut self,
2408         res: Res,
2409         depth: usize,
2410         generic_args: &'tcx hir::GenericArgs<'tcx>,
2411     ) {
2412         debug!(
2413             "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
2414             res, depth, generic_args,
2415         );
2416 
2417         if generic_args.parenthesized {
2418             let was_in_fn_syntax = self.is_in_fn_syntax;
2419             self.is_in_fn_syntax = true;
2420             self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
2421             self.is_in_fn_syntax = was_in_fn_syntax;
2422             return;
2423         }
2424 
2425         let mut elide_lifetimes = true;
2426         let lifetimes: Vec<_> = generic_args
2427             .args
2428             .iter()
2429             .filter_map(|arg| match arg {
2430                 hir::GenericArg::Lifetime(lt) => {
2431                     if !lt.is_elided() {
2432                         elide_lifetimes = false;
2433                     }
2434                     Some(lt)
2435                 }
2436                 _ => None,
2437             })
2438             .collect();
2439         // We short-circuit here if all are elided in order to pluralize
2440         // possible errors
2441         if elide_lifetimes {
2442             self.resolve_elided_lifetimes(&lifetimes);
2443         } else {
2444             lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
2445         }
2446 
2447         // Figure out if this is a type/trait segment,
2448         // which requires object lifetime defaults.
2449         let parent_def_id = |this: &mut Self, def_id: DefId| {
2450             let def_key = this.tcx.def_key(def_id);
2451             DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
2452         };
2453         let type_def_id = match res {
2454             Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
2455             Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
2456             Res::Def(
2457                 DefKind::Struct
2458                 | DefKind::Union
2459                 | DefKind::Enum
2460                 | DefKind::TyAlias
2461                 | DefKind::Trait,
2462                 def_id,
2463             ) if depth == 0 => Some(def_id),
2464             _ => None,
2465         };
2466 
2467         debug!("visit_segment_args: type_def_id={:?}", type_def_id);
2468 
2469         // Compute a vector of defaults, one for each type parameter,
2470         // per the rules given in RFCs 599 and 1156. Example:
2471         //
2472         // ```rust
2473         // struct Foo<'a, T: 'a, U> { }
2474         // ```
2475         //
2476         // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
2477         // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
2478         // and `dyn Baz` to `dyn Baz + 'static` (because there is no
2479         // such bound).
2480         //
2481         // Therefore, we would compute `object_lifetime_defaults` to a
2482         // vector like `['x, 'static]`. Note that the vector only
2483         // includes type parameters.
2484         let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
2485             let in_body = {
2486                 let mut scope = self.scope;
2487                 loop {
2488                     match *scope {
2489                         Scope::Root => break false,
2490 
2491                         Scope::Body { .. } => break true,
2492 
2493                         Scope::Binder { s, .. }
2494                         | Scope::Elision { s, .. }
2495                         | Scope::ObjectLifetimeDefault { s, .. }
2496                         | Scope::Supertrait { s, .. }
2497                         | Scope::TraitRefBoundary { s, .. } => {
2498                             scope = s;
2499                         }
2500                     }
2501                 }
2502             };
2503 
2504             let map = &self.map;
2505             let set_to_region = |set: &ObjectLifetimeDefault| match *set {
2506                 Set1::Empty => {
2507                     if in_body {
2508                         None
2509                     } else {
2510                         Some(Region::Static)
2511                     }
2512                 }
2513                 Set1::One(r) => {
2514                     let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2515                         GenericArg::Lifetime(lt) => Some(lt),
2516                         _ => None,
2517                     });
2518                     r.subst(lifetimes, map)
2519                 }
2520                 Set1::Many => None,
2521             };
2522             if let Some(def_id) = def_id.as_local() {
2523                 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2524                 self.tcx.object_lifetime_defaults(id).unwrap().iter().map(set_to_region).collect()
2525             } else {
2526                 let tcx = self.tcx;
2527                 self.xcrate_object_lifetime_defaults
2528                     .entry(def_id)
2529                     .or_insert_with(|| {
2530                         tcx.generics_of(def_id)
2531                             .params
2532                             .iter()
2533                             .filter_map(|param| match param.kind {
2534                                 GenericParamDefKind::Type { object_lifetime_default, .. } => {
2535                                     Some(object_lifetime_default)
2536                                 }
2537                                 GenericParamDefKind::Lifetime
2538                                 | GenericParamDefKind::Const { .. } => None,
2539                             })
2540                             .collect()
2541                     })
2542                     .iter()
2543                     .map(set_to_region)
2544                     .collect()
2545             }
2546         });
2547 
2548         debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2549 
2550         let mut i = 0;
2551         for arg in generic_args.args {
2552             match arg {
2553                 GenericArg::Lifetime(_) => {}
2554                 GenericArg::Type(ty) => {
2555                     if let Some(&lt) = object_lifetime_defaults.get(i) {
2556                         let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2557                         self.with(scope, |_, this| this.visit_ty(ty));
2558                     } else {
2559                         self.visit_ty(ty);
2560                     }
2561                     i += 1;
2562                 }
2563                 GenericArg::Const(ct) => {
2564                     self.visit_anon_const(&ct.value);
2565                 }
2566                 GenericArg::Infer(inf) => {
2567                     self.visit_id(inf.hir_id);
2568                     if inf.kind.is_type() {
2569                         i += 1;
2570                     }
2571                 }
2572             }
2573         }
2574 
2575         // Hack: when resolving the type `XX` in binding like `dyn
2576         // Foo<'b, Item = XX>`, the current object-lifetime default
2577         // would be to examine the trait `Foo` to check whether it has
2578         // a lifetime bound declared on `Item`. e.g., if `Foo` is
2579         // declared like so, then the default object lifetime bound in
2580         // `XX` should be `'b`:
2581         //
2582         // ```rust
2583         // trait Foo<'a> {
2584         //   type Item: 'a;
2585         // }
2586         // ```
2587         //
2588         // but if we just have `type Item;`, then it would be
2589         // `'static`. However, we don't get all of this logic correct.
2590         //
2591         // Instead, we do something hacky: if there are no lifetime parameters
2592         // to the trait, then we simply use a default object lifetime
2593         // bound of `'static`, because there is no other possibility. On the other hand,
2594         // if there ARE lifetime parameters, then we require the user to give an
2595         // explicit bound for now.
2596         //
2597         // This is intended to leave room for us to implement the
2598         // correct behavior in the future.
2599         let has_lifetime_parameter =
2600             generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2601 
2602         // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2603         // in the trait ref `YY<...>` in `Item: YY<...>`.
2604         for binding in generic_args.bindings {
2605             let scope = Scope::ObjectLifetimeDefault {
2606                 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2607                 s: self.scope,
2608             };
2609             if let Some(type_def_id) = type_def_id {
2610                 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2611                     self.tcx,
2612                     type_def_id,
2613                     binding.ident,
2614                 );
2615                 self.with(scope, |_, this| {
2616                     let scope = Scope::Supertrait {
2617                         lifetimes: lifetimes.unwrap_or_default(),
2618                         s: this.scope,
2619                     };
2620                     this.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2621                 });
2622             } else {
2623                 self.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2624             }
2625         }
2626     }
2627 
2628     /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2629     /// associated type name and starting trait.
2630     /// For example, imagine we have
2631     /// ```rust
2632     /// trait Foo<'a, 'b> {
2633     ///   type As;
2634     /// }
2635     /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2636     /// trait Bar: for<'b> Bar<'b> {}
2637     /// ```
2638     /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2639     /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
supertrait_hrtb_lifetimes( tcx: TyCtxt<'tcx>, def_id: DefId, assoc_name: Ident, ) -> Option<Vec<ty::BoundVariableKind>>2640     fn supertrait_hrtb_lifetimes(
2641         tcx: TyCtxt<'tcx>,
2642         def_id: DefId,
2643         assoc_name: Ident,
2644     ) -> Option<Vec<ty::BoundVariableKind>> {
2645         let trait_defines_associated_type_named = |trait_def_id: DefId| {
2646             tcx.associated_items(trait_def_id)
2647                 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2648                 .is_some()
2649         };
2650 
2651         use smallvec::{smallvec, SmallVec};
2652         let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2653             smallvec![(def_id, smallvec![])];
2654         let mut visited: FxHashSet<DefId> = FxHashSet::default();
2655         loop {
2656             let (def_id, bound_vars) = match stack.pop() {
2657                 Some(next) => next,
2658                 None => break None,
2659             };
2660             // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2661             // there being no supertrait HRTBs.
2662             match tcx.def_kind(def_id) {
2663                 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2664                 _ => break None,
2665             }
2666 
2667             if trait_defines_associated_type_named(def_id) {
2668                 break Some(bound_vars.into_iter().collect());
2669             }
2670             let predicates =
2671                 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2672             let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2673                 let bound_predicate = pred.kind();
2674                 match bound_predicate.skip_binder() {
2675                     ty::PredicateKind::Trait(data) => {
2676                         // The order here needs to match what we would get from `subst_supertrait`
2677                         let pred_bound_vars = bound_predicate.bound_vars();
2678                         let mut all_bound_vars = bound_vars.clone();
2679                         all_bound_vars.extend(pred_bound_vars.iter());
2680                         let super_def_id = data.trait_ref.def_id;
2681                         Some((super_def_id, all_bound_vars))
2682                     }
2683                     _ => None,
2684                 }
2685             });
2686 
2687             let obligations = obligations.filter(|o| visited.insert(o.0));
2688             stack.extend(obligations);
2689         }
2690     }
2691 
2692     #[tracing::instrument(level = "debug", skip(self))]
visit_fn_like_elision( &mut self, inputs: &'tcx [hir::Ty<'tcx>], output: Option<&'tcx hir::Ty<'tcx>>, )2693     fn visit_fn_like_elision(
2694         &mut self,
2695         inputs: &'tcx [hir::Ty<'tcx>],
2696         output: Option<&'tcx hir::Ty<'tcx>>,
2697     ) {
2698         debug!("visit_fn_like_elision: enter");
2699         let mut scope = &*self.scope;
2700         let hir_id = loop {
2701             match scope {
2702                 Scope::Binder { hir_id, .. } => {
2703                     break *hir_id;
2704                 }
2705                 Scope::ObjectLifetimeDefault { ref s, .. }
2706                 | Scope::Elision { ref s, .. }
2707                 | Scope::Supertrait { ref s, .. }
2708                 | Scope::TraitRefBoundary { ref s, .. } => {
2709                     scope = *s;
2710                 }
2711                 Scope::Root | Scope::Body { .. } => {
2712                     // See issues #83907 and #83693. Just bail out from looking inside.
2713                     self.tcx.sess.delay_span_bug(
2714                         rustc_span::DUMMY_SP,
2715                         "In fn_like_elision without appropriate scope above",
2716                     );
2717                     return;
2718                 }
2719             }
2720         };
2721         // While not strictly necessary, we gather anon lifetimes *before* actually
2722         // visiting the argument types.
2723         let mut gather = GatherAnonLifetimes { anon_count: 0 };
2724         for input in inputs {
2725             gather.visit_ty(input);
2726         }
2727         trace!(?gather.anon_count);
2728         let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2729         let named_late_bound_vars = late_bound_vars.len() as u32;
2730         late_bound_vars.extend(
2731             (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2732         );
2733         let arg_scope = Scope::Elision {
2734             elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2735             s: self.scope,
2736         };
2737         self.with(arg_scope, |_, this| {
2738             for input in inputs {
2739                 this.visit_ty(input);
2740             }
2741         });
2742 
2743         let output = match output {
2744             Some(ty) => ty,
2745             None => return,
2746         };
2747 
2748         debug!("determine output");
2749 
2750         // Figure out if there's a body we can get argument names from,
2751         // and whether there's a `self` argument (treated specially).
2752         let mut assoc_item_kind = None;
2753         let mut impl_self = None;
2754         let parent = self.tcx.hir().get_parent_node(output.hir_id);
2755         let body = match self.tcx.hir().get(parent) {
2756             // `fn` definitions and methods.
2757             Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2758 
2759             Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2760                 if let hir::ItemKind::Trait(.., ref trait_items) =
2761                     self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2762                 {
2763                     assoc_item_kind =
2764                         trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2765                 }
2766                 match *m {
2767                     hir::TraitFn::Required(_) => None,
2768                     hir::TraitFn::Provided(body) => Some(body),
2769                 }
2770             }
2771 
2772             Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2773                 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2774                     self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2775                 {
2776                     impl_self = Some(self_ty);
2777                     assoc_item_kind =
2778                         items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2779                 }
2780                 Some(body)
2781             }
2782 
2783             // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2784             Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2785             // Everything else (only closures?) doesn't
2786             // actually enjoy elision in return types.
2787             _ => {
2788                 self.visit_ty(output);
2789                 return;
2790             }
2791         };
2792 
2793         let has_self = match assoc_item_kind {
2794             Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2795             _ => false,
2796         };
2797 
2798         // In accordance with the rules for lifetime elision, we can determine
2799         // what region to use for elision in the output type in two ways.
2800         // First (determined here), if `self` is by-reference, then the
2801         // implied output region is the region of the self parameter.
2802         if has_self {
2803             struct SelfVisitor<'a> {
2804                 map: &'a NamedRegionMap,
2805                 impl_self: Option<&'a hir::TyKind<'a>>,
2806                 lifetime: Set1<Region>,
2807             }
2808 
2809             impl SelfVisitor<'_> {
2810                 // Look for `self: &'a Self` - also desugared from `&'a self`,
2811                 // and if that matches, use it for elision and return early.
2812                 fn is_self_ty(&self, res: Res) -> bool {
2813                     if let Res::SelfTy(..) = res {
2814                         return true;
2815                     }
2816 
2817                     // Can't always rely on literal (or implied) `Self` due
2818                     // to the way elision rules were originally specified.
2819                     if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2820                         self.impl_self
2821                     {
2822                         match path.res {
2823                             // Permit the types that unambiguously always
2824                             // result in the same type constructor being used
2825                             // (it can't differ between `Self` and `self`).
2826                             Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2827                             | Res::PrimTy(_) => return res == path.res,
2828                             _ => {}
2829                         }
2830                     }
2831 
2832                     false
2833                 }
2834             }
2835 
2836             impl<'a> Visitor<'a> for SelfVisitor<'a> {
2837                 type Map = intravisit::ErasedMap<'a>;
2838 
2839                 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2840                     NestedVisitorMap::None
2841                 }
2842 
2843                 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2844                     if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2845                         if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2846                         {
2847                             if self.is_self_ty(path.res) {
2848                                 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2849                                     self.lifetime.insert(*lifetime);
2850                                 }
2851                             }
2852                         }
2853                     }
2854                     intravisit::walk_ty(self, ty)
2855                 }
2856             }
2857 
2858             let mut visitor = SelfVisitor {
2859                 map: self.map,
2860                 impl_self: impl_self.map(|ty| &ty.kind),
2861                 lifetime: Set1::Empty,
2862             };
2863             visitor.visit_ty(&inputs[0]);
2864             if let Set1::One(lifetime) = visitor.lifetime {
2865                 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2866                 self.with(scope, |_, this| this.visit_ty(output));
2867                 return;
2868             }
2869         }
2870 
2871         // Second, if there was exactly one lifetime (either a substitution or a
2872         // reference) in the arguments, then any anonymous regions in the output
2873         // have that lifetime.
2874         let mut possible_implied_output_region = None;
2875         let mut lifetime_count = 0;
2876         let arg_lifetimes = inputs
2877             .iter()
2878             .enumerate()
2879             .skip(has_self as usize)
2880             .map(|(i, input)| {
2881                 let mut gather = GatherLifetimes {
2882                     map: self.map,
2883                     outer_index: ty::INNERMOST,
2884                     have_bound_regions: false,
2885                     lifetimes: Default::default(),
2886                 };
2887                 gather.visit_ty(input);
2888 
2889                 lifetime_count += gather.lifetimes.len();
2890 
2891                 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2892                     // there's a chance that the unique lifetime of this
2893                     // iteration will be the appropriate lifetime for output
2894                     // parameters, so lets store it.
2895                     possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2896                 }
2897 
2898                 ElisionFailureInfo {
2899                     parent: body,
2900                     index: i,
2901                     lifetime_count: gather.lifetimes.len(),
2902                     have_bound_regions: gather.have_bound_regions,
2903                     span: input.span,
2904                 }
2905             })
2906             .collect();
2907 
2908         let elide = if lifetime_count == 1 {
2909             Elide::Exact(possible_implied_output_region.unwrap())
2910         } else {
2911             Elide::Error(arg_lifetimes)
2912         };
2913 
2914         debug!(?elide);
2915 
2916         let scope = Scope::Elision { elide, s: self.scope };
2917         self.with(scope, |_, this| this.visit_ty(output));
2918 
2919         struct GatherLifetimes<'a> {
2920             map: &'a NamedRegionMap,
2921             outer_index: ty::DebruijnIndex,
2922             have_bound_regions: bool,
2923             lifetimes: FxHashSet<Region>,
2924         }
2925 
2926         impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2927             type Map = intravisit::ErasedMap<'v>;
2928 
2929             fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2930                 NestedVisitorMap::None
2931             }
2932 
2933             fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2934                 if let hir::TyKind::BareFn(_) = ty.kind {
2935                     self.outer_index.shift_in(1);
2936                 }
2937                 match ty.kind {
2938                     hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2939                         for bound in bounds {
2940                             self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2941                         }
2942 
2943                         // Stay on the safe side and don't include the object
2944                         // lifetime default (which may not end up being used).
2945                         if !lifetime.is_elided() {
2946                             self.visit_lifetime(lifetime);
2947                         }
2948                     }
2949                     _ => {
2950                         intravisit::walk_ty(self, ty);
2951                     }
2952                 }
2953                 if let hir::TyKind::BareFn(_) = ty.kind {
2954                     self.outer_index.shift_out(1);
2955                 }
2956             }
2957 
2958             fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2959                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2960                     // FIXME(eddyb) Do we want this? It only makes a difference
2961                     // if this `for<'a>` lifetime parameter is never used.
2962                     self.have_bound_regions = true;
2963                 }
2964 
2965                 intravisit::walk_generic_param(self, param);
2966             }
2967 
2968             fn visit_poly_trait_ref(
2969                 &mut self,
2970                 trait_ref: &hir::PolyTraitRef<'_>,
2971                 modifier: hir::TraitBoundModifier,
2972             ) {
2973                 self.outer_index.shift_in(1);
2974                 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2975                 self.outer_index.shift_out(1);
2976             }
2977 
2978             fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2979                 if let hir::GenericBound::LangItemTrait { .. } = bound {
2980                     self.outer_index.shift_in(1);
2981                     intravisit::walk_param_bound(self, bound);
2982                     self.outer_index.shift_out(1);
2983                 } else {
2984                     intravisit::walk_param_bound(self, bound);
2985                 }
2986             }
2987 
2988             fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2989                 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2990                     match lifetime {
2991                         Region::LateBound(debruijn, _, _, _)
2992                         | Region::LateBoundAnon(debruijn, _, _)
2993                             if debruijn < self.outer_index =>
2994                         {
2995                             self.have_bound_regions = true;
2996                         }
2997                         _ => {
2998                             // FIXME(jackh726): nested trait refs?
2999                             self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
3000                         }
3001                     }
3002                 }
3003             }
3004         }
3005 
3006         struct GatherAnonLifetimes {
3007             anon_count: u32,
3008         }
3009         impl<'v> Visitor<'v> for GatherAnonLifetimes {
3010             type Map = intravisit::ErasedMap<'v>;
3011 
3012             fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3013                 NestedVisitorMap::None
3014             }
3015 
3016             #[instrument(skip(self), level = "trace")]
3017             fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
3018                 // If we enter a `BareFn`, then we enter a *new* binding scope
3019                 if let hir::TyKind::BareFn(_) = ty.kind {
3020                     return;
3021                 }
3022                 intravisit::walk_ty(self, ty);
3023             }
3024 
3025             fn visit_generic_args(
3026                 &mut self,
3027                 path_span: Span,
3028                 generic_args: &'v hir::GenericArgs<'v>,
3029             ) {
3030                 // parenthesized args enter a new elison scope
3031                 if generic_args.parenthesized {
3032                     return;
3033                 }
3034                 intravisit::walk_generic_args(self, path_span, generic_args)
3035             }
3036 
3037             #[instrument(skip(self), level = "trace")]
3038             fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
3039                 if lifetime_ref.is_elided() {
3040                     self.anon_count += 1;
3041                 }
3042             }
3043         }
3044     }
3045 
resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime])3046     fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
3047         debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
3048 
3049         if lifetime_refs.is_empty() {
3050             return;
3051         }
3052 
3053         let mut late_depth = 0;
3054         let mut scope = self.scope;
3055         let mut lifetime_names = FxHashSet::default();
3056         let mut lifetime_spans = vec![];
3057         let error = loop {
3058             match *scope {
3059                 // Do not assign any resolution, it will be inferred.
3060                 Scope::Body { .. } => return,
3061 
3062                 Scope::Root => break None,
3063 
3064                 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
3065                     // collect named lifetimes for suggestions
3066                     for name in lifetimes.keys() {
3067                         if let hir::ParamName::Plain(name) = name {
3068                             lifetime_names.insert(name.name);
3069                             lifetime_spans.push(name.span);
3070                         }
3071                     }
3072                     match scope_type {
3073                         BinderScopeType::Normal => late_depth += 1,
3074                         BinderScopeType::Concatenating => {}
3075                     }
3076                     scope = s;
3077                 }
3078 
3079                 Scope::Elision { ref elide, ref s, .. } => {
3080                     let lifetime = match *elide {
3081                         Elide::FreshLateAnon(named_late_bound_vars, ref counter) => {
3082                             for lifetime_ref in lifetime_refs {
3083                                 let lifetime = Region::late_anon(named_late_bound_vars, counter)
3084                                     .shifted(late_depth);
3085 
3086                                 self.insert_lifetime(lifetime_ref, lifetime);
3087                             }
3088                             return;
3089                         }
3090                         Elide::Exact(l) => l.shifted(late_depth),
3091                         Elide::Error(ref e) => {
3092                             let mut scope = s;
3093                             loop {
3094                                 match scope {
3095                                     Scope::Binder { ref lifetimes, s, .. } => {
3096                                         // Collect named lifetimes for suggestions.
3097                                         for name in lifetimes.keys() {
3098                                             if let hir::ParamName::Plain(name) = name {
3099                                                 lifetime_names.insert(name.name);
3100                                                 lifetime_spans.push(name.span);
3101                                             }
3102                                         }
3103                                         scope = s;
3104                                     }
3105                                     Scope::ObjectLifetimeDefault { ref s, .. }
3106                                     | Scope::Elision { ref s, .. }
3107                                     | Scope::TraitRefBoundary { ref s, .. } => {
3108                                         scope = s;
3109                                     }
3110                                     _ => break,
3111                                 }
3112                             }
3113                             break Some(&e[..]);
3114                         }
3115                         Elide::Forbid => break None,
3116                     };
3117                     for lifetime_ref in lifetime_refs {
3118                         self.insert_lifetime(lifetime_ref, lifetime);
3119                     }
3120                     return;
3121                 }
3122 
3123                 Scope::ObjectLifetimeDefault { s, .. }
3124                 | Scope::Supertrait { s, .. }
3125                 | Scope::TraitRefBoundary { s, .. } => {
3126                     scope = s;
3127                 }
3128             }
3129         };
3130 
3131         // If we specifically need the `scope_for_path` map, then we're in the
3132         // diagnostic pass and we don't want to emit more errors.
3133         if self.map.scope_for_path.is_some() {
3134             self.tcx.sess.delay_span_bug(
3135                 rustc_span::DUMMY_SP,
3136                 "Encountered unexpected errors during diagnostics related part",
3137             );
3138             return;
3139         }
3140 
3141         let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3142         spans.sort();
3143         let mut spans_dedup = spans.clone();
3144         spans_dedup.dedup();
3145         let spans_with_counts: Vec<_> = spans_dedup
3146             .into_iter()
3147             .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
3148             .collect();
3149 
3150         let mut err = self.report_missing_lifetime_specifiers(spans.clone(), lifetime_refs.len());
3151 
3152         if let Some(params) = error {
3153             // If there's no lifetime available, suggest `'static`.
3154             if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
3155                 lifetime_names.insert(kw::StaticLifetime);
3156             }
3157         }
3158 
3159         self.add_missing_lifetime_specifiers_label(
3160             &mut err,
3161             spans_with_counts,
3162             &lifetime_names,
3163             lifetime_spans,
3164             error.unwrap_or(&[]),
3165         );
3166         err.emit();
3167     }
3168 
report_elision_failure( &mut self, db: &mut DiagnosticBuilder<'_>, params: &[ElisionFailureInfo], ) -> bool3169     fn report_elision_failure(
3170         &mut self,
3171         db: &mut DiagnosticBuilder<'_>,
3172         params: &[ElisionFailureInfo],
3173     ) -> bool /* add `'static` lifetime to lifetime list */ {
3174         let mut m = String::new();
3175         let len = params.len();
3176 
3177         let elided_params: Vec<_> =
3178             params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
3179 
3180         let elided_len = elided_params.len();
3181 
3182         for (i, info) in elided_params.into_iter().enumerate() {
3183             let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
3184                 info;
3185 
3186             db.span_label(span, "");
3187             let help_name = if let Some(ident) =
3188                 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
3189             {
3190                 format!("`{}`", ident)
3191             } else {
3192                 format!("argument {}", index + 1)
3193             };
3194 
3195             m.push_str(
3196                 &(if n == 1 {
3197                     help_name
3198                 } else {
3199                     format!(
3200                         "one of {}'s {} {}lifetimes",
3201                         help_name,
3202                         n,
3203                         if have_bound_regions { "free " } else { "" }
3204                     )
3205                 })[..],
3206             );
3207 
3208             if elided_len == 2 && i == 0 {
3209                 m.push_str(" or ");
3210             } else if i + 2 == elided_len {
3211                 m.push_str(", or ");
3212             } else if i != elided_len - 1 {
3213                 m.push_str(", ");
3214             }
3215         }
3216 
3217         if len == 0 {
3218             db.help(
3219                 "this function's return type contains a borrowed value, \
3220                  but there is no value for it to be borrowed from",
3221             );
3222             true
3223         } else if elided_len == 0 {
3224             db.help(
3225                 "this function's return type contains a borrowed value with \
3226                  an elided lifetime, but the lifetime cannot be derived from \
3227                  the arguments",
3228             );
3229             true
3230         } else if elided_len == 1 {
3231             db.help(&format!(
3232                 "this function's return type contains a borrowed value, \
3233                  but the signature does not say which {} it is borrowed from",
3234                 m
3235             ));
3236             false
3237         } else {
3238             db.help(&format!(
3239                 "this function's return type contains a borrowed value, \
3240                  but the signature does not say whether it is borrowed from {}",
3241                 m
3242             ));
3243             false
3244         }
3245     }
3246 
resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime)3247     fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
3248         debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
3249         let mut late_depth = 0;
3250         let mut scope = self.scope;
3251         let lifetime = loop {
3252             match *scope {
3253                 Scope::Binder { s, scope_type, .. } => {
3254                     match scope_type {
3255                         BinderScopeType::Normal => late_depth += 1,
3256                         BinderScopeType::Concatenating => {}
3257                     }
3258                     scope = s;
3259                 }
3260 
3261                 Scope::Root | Scope::Elision { .. } => break Region::Static,
3262 
3263                 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
3264 
3265                 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
3266 
3267                 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
3268                     scope = s;
3269                 }
3270             }
3271         };
3272         self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
3273     }
3274 
check_lifetime_params( &mut self, old_scope: ScopeRef<'_>, params: &'tcx [hir::GenericParam<'tcx>], )3275     fn check_lifetime_params(
3276         &mut self,
3277         old_scope: ScopeRef<'_>,
3278         params: &'tcx [hir::GenericParam<'tcx>],
3279     ) {
3280         let lifetimes: Vec<_> = params
3281             .iter()
3282             .filter_map(|param| match param.kind {
3283                 GenericParamKind::Lifetime { .. } => {
3284                     Some((param, param.name.normalize_to_macros_2_0()))
3285                 }
3286                 _ => None,
3287             })
3288             .collect();
3289         for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
3290             if let hir::ParamName::Plain(_) = lifetime_i_name {
3291                 let name = lifetime_i_name.ident().name;
3292                 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
3293                     let mut err = struct_span_err!(
3294                         self.tcx.sess,
3295                         lifetime_i.span,
3296                         E0262,
3297                         "invalid lifetime parameter name: `{}`",
3298                         lifetime_i.name.ident(),
3299                     );
3300                     err.span_label(
3301                         lifetime_i.span,
3302                         format!("{} is a reserved lifetime name", name),
3303                     );
3304                     err.emit();
3305                 }
3306             }
3307 
3308             // It is a hard error to shadow a lifetime within the same scope.
3309             for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
3310                 if lifetime_i_name == lifetime_j_name {
3311                     struct_span_err!(
3312                         self.tcx.sess,
3313                         lifetime_j.span,
3314                         E0263,
3315                         "lifetime name `{}` declared twice in the same scope",
3316                         lifetime_j.name.ident()
3317                     )
3318                     .span_label(lifetime_j.span, "declared twice")
3319                     .span_label(lifetime_i.span, "previous declaration here")
3320                     .emit();
3321                 }
3322             }
3323 
3324             // It is a soft error to shadow a lifetime within a parent scope.
3325             self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
3326 
3327             for bound in lifetime_i.bounds {
3328                 match bound {
3329                     hir::GenericBound::Outlives(ref lt) => match lt.name {
3330                         hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
3331                             lt.span,
3332                             "use of `'_` in illegal place, but not caught by lowering",
3333                         ),
3334                         hir::LifetimeName::Static => {
3335                             self.insert_lifetime(lt, Region::Static);
3336                             self.tcx
3337                                 .sess
3338                                 .struct_span_warn(
3339                                     lifetime_i.span.to(lt.span),
3340                                     &format!(
3341                                         "unnecessary lifetime parameter `{}`",
3342                                         lifetime_i.name.ident(),
3343                                     ),
3344                                 )
3345                                 .help(&format!(
3346                                     "you can use the `'static` lifetime directly, in place of `{}`",
3347                                     lifetime_i.name.ident(),
3348                                 ))
3349                                 .emit();
3350                         }
3351                         hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
3352                             self.resolve_lifetime_ref(lt);
3353                         }
3354                         hir::LifetimeName::ImplicitObjectLifetimeDefault => {
3355                             self.tcx.sess.delay_span_bug(
3356                                 lt.span,
3357                                 "lowering generated `ImplicitObjectLifetimeDefault` \
3358                                  outside of an object type",
3359                             )
3360                         }
3361                         hir::LifetimeName::Error => {
3362                             // No need to do anything, error already reported.
3363                         }
3364                     },
3365                     _ => bug!(),
3366                 }
3367             }
3368         }
3369     }
3370 
check_lifetime_param_for_shadowing( &self, mut old_scope: ScopeRef<'_>, param: &'tcx hir::GenericParam<'tcx>, )3371     fn check_lifetime_param_for_shadowing(
3372         &self,
3373         mut old_scope: ScopeRef<'_>,
3374         param: &'tcx hir::GenericParam<'tcx>,
3375     ) {
3376         for label in &self.labels_in_fn {
3377             // FIXME (#24278): non-hygienic comparison
3378             if param.name.ident().name == label.name {
3379                 signal_shadowing_problem(
3380                     self.tcx,
3381                     label.name,
3382                     original_label(label.span),
3383                     shadower_lifetime(&param),
3384                 );
3385                 return;
3386             }
3387         }
3388 
3389         loop {
3390             match *old_scope {
3391                 Scope::Body { s, .. }
3392                 | Scope::Elision { s, .. }
3393                 | Scope::ObjectLifetimeDefault { s, .. }
3394                 | Scope::Supertrait { s, .. }
3395                 | Scope::TraitRefBoundary { s, .. } => {
3396                     old_scope = s;
3397                 }
3398 
3399                 Scope::Root => {
3400                     return;
3401                 }
3402 
3403                 Scope::Binder { ref lifetimes, s, .. } => {
3404                     if let Some(&def) = lifetimes.get(&param.name.normalize_to_macros_2_0()) {
3405                         let hir_id =
3406                             self.tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
3407 
3408                         signal_shadowing_problem(
3409                             self.tcx,
3410                             param.name.ident().name,
3411                             original_lifetime(self.tcx.hir().span(hir_id)),
3412                             shadower_lifetime(&param),
3413                         );
3414                         return;
3415                     }
3416 
3417                     old_scope = s;
3418                 }
3419             }
3420         }
3421     }
3422 
3423     /// Returns `true` if, in the current scope, replacing `'_` would be
3424     /// equivalent to a single-use lifetime.
track_lifetime_uses(&self) -> bool3425     fn track_lifetime_uses(&self) -> bool {
3426         let mut scope = self.scope;
3427         loop {
3428             match *scope {
3429                 Scope::Root => break false,
3430 
3431                 // Inside of items, it depends on the kind of item.
3432                 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
3433 
3434                 // Inside a body, `'_` will use an inference variable,
3435                 // should be fine.
3436                 Scope::Body { .. } => break true,
3437 
3438                 // A lifetime only used in a fn argument could as well
3439                 // be replaced with `'_`, as that would generate a
3440                 // fresh name, too.
3441                 Scope::Elision { elide: Elide::FreshLateAnon(..), .. } => break true,
3442 
3443                 // In the return type or other such place, `'_` is not
3444                 // going to make a fresh name, so we cannot
3445                 // necessarily replace a single-use lifetime with
3446                 // `'_`.
3447                 Scope::Elision {
3448                     elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
3449                 } => break false,
3450 
3451                 Scope::ObjectLifetimeDefault { s, .. }
3452                 | Scope::Supertrait { s, .. }
3453                 | Scope::TraitRefBoundary { s, .. } => scope = s,
3454             }
3455         }
3456     }
3457 
3458     #[tracing::instrument(level = "debug", skip(self))]
insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region)3459     fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
3460         debug!(
3461             node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
3462             span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
3463         );
3464         self.map.defs.insert(lifetime_ref.hir_id, def);
3465 
3466         match def {
3467             Region::LateBoundAnon(..) | Region::Static => {
3468                 // These are anonymous lifetimes or lifetimes that are not declared.
3469             }
3470 
3471             Region::Free(_, def_id)
3472             | Region::LateBound(_, _, def_id, _)
3473             | Region::EarlyBound(_, def_id, _) => {
3474                 // A lifetime declared by the user.
3475                 let track_lifetime_uses = self.track_lifetime_uses();
3476                 debug!(?track_lifetime_uses);
3477                 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
3478                     debug!("first use of {:?}", def_id);
3479                     self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
3480                 } else {
3481                     debug!("many uses of {:?}", def_id);
3482                     self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
3483                 }
3484             }
3485         }
3486     }
3487 
3488     /// Sometimes we resolve a lifetime, but later find that it is an
3489     /// error (esp. around impl trait). In that case, we remove the
3490     /// entry into `map.defs` so as not to confuse later code.
uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region)3491     fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
3492         let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
3493         assert_eq!(old_value, Some(bad_def));
3494     }
3495 }
3496 
3497 /// Detects late-bound lifetimes and inserts them into
3498 /// `map.late_bound`.
3499 ///
3500 /// A region declared on a fn is **late-bound** if:
3501 /// - it is constrained by an argument type;
3502 /// - it does not appear in a where-clause.
3503 ///
3504 /// "Constrained" basically means that it appears in any type but
3505 /// not amongst the inputs to a projection. In other words, `<&'a
3506 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
3507 #[tracing::instrument(level = "debug", skip(map))]
insert_late_bound_lifetimes( map: &mut NamedRegionMap, decl: &hir::FnDecl<'_>, generics: &hir::Generics<'_>, )3508 fn insert_late_bound_lifetimes(
3509     map: &mut NamedRegionMap,
3510     decl: &hir::FnDecl<'_>,
3511     generics: &hir::Generics<'_>,
3512 ) {
3513     let mut constrained_by_input = ConstrainedCollector::default();
3514     for arg_ty in decl.inputs {
3515         constrained_by_input.visit_ty(arg_ty);
3516     }
3517 
3518     let mut appears_in_output = AllCollector::default();
3519     intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
3520 
3521     debug!(?constrained_by_input.regions);
3522 
3523     // Walk the lifetimes that appear in where clauses.
3524     //
3525     // Subtle point: because we disallow nested bindings, we can just
3526     // ignore binders here and scrape up all names we see.
3527     let mut appears_in_where_clause = AllCollector::default();
3528     appears_in_where_clause.visit_generics(generics);
3529 
3530     for param in generics.params {
3531         if let hir::GenericParamKind::Lifetime { .. } = param.kind {
3532             if !param.bounds.is_empty() {
3533                 // `'a: 'b` means both `'a` and `'b` are referenced
3534                 appears_in_where_clause
3535                     .regions
3536                     .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
3537             }
3538         }
3539     }
3540 
3541     debug!(?appears_in_where_clause.regions);
3542 
3543     // Late bound regions are those that:
3544     // - appear in the inputs
3545     // - do not appear in the where-clauses
3546     // - are not implicitly captured by `impl Trait`
3547     for param in generics.params {
3548         match param.kind {
3549             hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
3550 
3551             // Neither types nor consts are late-bound.
3552             hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
3553         }
3554 
3555         let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
3556         // appears in the where clauses? early-bound.
3557         if appears_in_where_clause.regions.contains(&lt_name) {
3558             continue;
3559         }
3560 
3561         // does not appear in the inputs, but appears in the return type? early-bound.
3562         if !constrained_by_input.regions.contains(&lt_name)
3563             && appears_in_output.regions.contains(&lt_name)
3564         {
3565             continue;
3566         }
3567 
3568         debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
3569 
3570         let inserted = map.late_bound.insert(param.hir_id);
3571         assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
3572     }
3573 
3574     return;
3575 
3576     #[derive(Default)]
3577     struct ConstrainedCollector {
3578         regions: FxHashSet<hir::LifetimeName>,
3579     }
3580 
3581     impl<'v> Visitor<'v> for ConstrainedCollector {
3582         type Map = intravisit::ErasedMap<'v>;
3583 
3584         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3585             NestedVisitorMap::None
3586         }
3587 
3588         fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3589             match ty.kind {
3590                 hir::TyKind::Path(
3591                     hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
3592                 ) => {
3593                     // ignore lifetimes appearing in associated type
3594                     // projections, as they are not *constrained*
3595                     // (defined above)
3596                 }
3597 
3598                 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
3599                     // consider only the lifetimes on the final
3600                     // segment; I am not sure it's even currently
3601                     // valid to have them elsewhere, but even if it
3602                     // is, those would be potentially inputs to
3603                     // projections
3604                     if let Some(last_segment) = path.segments.last() {
3605                         self.visit_path_segment(path.span, last_segment);
3606                     }
3607                 }
3608 
3609                 _ => {
3610                     intravisit::walk_ty(self, ty);
3611                 }
3612             }
3613         }
3614 
3615         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3616             self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3617         }
3618     }
3619 
3620     #[derive(Default)]
3621     struct AllCollector {
3622         regions: FxHashSet<hir::LifetimeName>,
3623     }
3624 
3625     impl<'v> Visitor<'v> for AllCollector {
3626         type Map = intravisit::ErasedMap<'v>;
3627 
3628         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3629             NestedVisitorMap::None
3630         }
3631 
3632         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3633             self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3634         }
3635     }
3636 }
3637