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