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