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