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