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