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