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