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