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