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