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