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