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