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