]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lifetimes.rs
Rollup merge of #67880 - lbonn:fix/multi-substs, r=petrochenkov
[rust.git] / src / librustc_resolve / lifetimes.rs
1 //! Name resolution for lifetimes.
2 //!
3 //! Name resolution for lifetimes follows *much* simpler rules than the
4 //! full resolve. For example, lifetime names are never exported or
5 //! used between functions, and they operate in a purely top-down
6 //! way. Therefore, we break lifetime name resolution into a separate pass.
7
8 use errors::{pluralize, Applicability, DiagnosticBuilder};
9 use rustc::hir::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::{help, span_err, struct_span_err, 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                                     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                                     self.uninsert_lifetime_on_error(lifetime, def.unwrap());
602                                 }
603                             }
604                         }
605                     }
606                 }
607
608                 // We want to start our early-bound indices at the end of the parent scope,
609                 // not including any parent `impl Trait`s.
610                 let mut index = self.next_early_index_for_opaque_type();
611                 debug!("visit_ty: index = {}", index);
612
613                 let mut elision = None;
614                 let mut lifetimes = FxHashMap::default();
615                 let mut non_lifetime_count = 0;
616                 for param in generics.params {
617                     match param.kind {
618                         GenericParamKind::Lifetime { .. } => {
619                             let (name, reg) = Region::early(&self.tcx.hir(), &mut index, &param);
620                             let def_id = if let Region::EarlyBound(_, def_id, _) = reg {
621                                 def_id
622                             } else {
623                                 bug!();
624                             };
625                             if let hir::ParamName::Plain(param_name) = name {
626                                 if param_name.name == kw::UnderscoreLifetime {
627                                     // Pick the elided lifetime "definition" if one exists
628                                     // and use it to make an elision scope.
629                                     self.lifetime_uses.insert(def_id.clone(), LifetimeUseSet::Many);
630                                     elision = Some(reg);
631                                 } else {
632                                     lifetimes.insert(name, reg);
633                                 }
634                             } else {
635                                 self.lifetime_uses.insert(def_id.clone(), LifetimeUseSet::Many);
636                                 lifetimes.insert(name, reg);
637                             }
638                         }
639                         GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
640                             non_lifetime_count += 1;
641                         }
642                     }
643                 }
644                 let next_early_index = index + non_lifetime_count;
645
646                 if let Some(elision_region) = elision {
647                     let scope =
648                         Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
649                     self.with(scope, |_old_scope, this| {
650                         let scope = Scope::Binder {
651                             lifetimes,
652                             next_early_index,
653                             s: this.scope,
654                             track_lifetime_uses: true,
655                             opaque_type_parent: false,
656                         };
657                         this.with(scope, |_old_scope, this| {
658                             this.visit_generics(generics);
659                             for bound in bounds {
660                                 this.visit_param_bound(bound);
661                             }
662                         });
663                     });
664                 } else {
665                     let scope = Scope::Binder {
666                         lifetimes,
667                         next_early_index,
668                         s: self.scope,
669                         track_lifetime_uses: true,
670                         opaque_type_parent: false,
671                     };
672                     self.with(scope, |_old_scope, this| {
673                         this.visit_generics(generics);
674                         for bound in bounds {
675                             this.visit_param_bound(bound);
676                         }
677                     });
678                 }
679             }
680             _ => intravisit::walk_ty(self, ty),
681         }
682     }
683
684     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
685         use self::hir::TraitItemKind::*;
686         match trait_item.kind {
687             Method(ref sig, _) => {
688                 let tcx = self.tcx;
689                 self.visit_early_late(
690                     Some(tcx.hir().get_parent_item(trait_item.hir_id)),
691                     &sig.decl,
692                     &trait_item.generics,
693                     |this| intravisit::walk_trait_item(this, trait_item),
694                 );
695             }
696             Type(bounds, ref ty) => {
697                 let generics = &trait_item.generics;
698                 let mut index = self.next_early_index();
699                 debug!("visit_ty: index = {}", index);
700                 let mut non_lifetime_count = 0;
701                 let lifetimes = generics
702                     .params
703                     .iter()
704                     .filter_map(|param| match param.kind {
705                         GenericParamKind::Lifetime { .. } => {
706                             Some(Region::early(&self.tcx.hir(), &mut index, param))
707                         }
708                         GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
709                             non_lifetime_count += 1;
710                             None
711                         }
712                     })
713                     .collect();
714                 let scope = Scope::Binder {
715                     lifetimes,
716                     next_early_index: index + non_lifetime_count,
717                     s: self.scope,
718                     track_lifetime_uses: true,
719                     opaque_type_parent: true,
720                 };
721                 self.with(scope, |_old_scope, this| {
722                     this.visit_generics(generics);
723                     for bound in bounds {
724                         this.visit_param_bound(bound);
725                     }
726                     if let Some(ty) = ty {
727                         this.visit_ty(ty);
728                     }
729                 });
730             }
731             Const(_, _) => {
732                 // Only methods and types support generics.
733                 assert!(trait_item.generics.params.is_empty());
734                 intravisit::walk_trait_item(self, trait_item);
735             }
736         }
737     }
738
739     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
740         use self::hir::ImplItemKind::*;
741         match impl_item.kind {
742             Method(ref sig, _) => {
743                 let tcx = self.tcx;
744                 self.visit_early_late(
745                     Some(tcx.hir().get_parent_item(impl_item.hir_id)),
746                     &sig.decl,
747                     &impl_item.generics,
748                     |this| intravisit::walk_impl_item(this, impl_item),
749                 )
750             }
751             TyAlias(ref ty) => {
752                 let generics = &impl_item.generics;
753                 let mut index = self.next_early_index();
754                 let mut non_lifetime_count = 0;
755                 debug!("visit_ty: index = {}", index);
756                 let lifetimes = generics
757                     .params
758                     .iter()
759                     .filter_map(|param| match param.kind {
760                         GenericParamKind::Lifetime { .. } => {
761                             Some(Region::early(&self.tcx.hir(), &mut index, param))
762                         }
763                         GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
764                             non_lifetime_count += 1;
765                             None
766                         }
767                     })
768                     .collect();
769                 let scope = Scope::Binder {
770                     lifetimes,
771                     next_early_index: index + non_lifetime_count,
772                     s: self.scope,
773                     track_lifetime_uses: true,
774                     opaque_type_parent: true,
775                 };
776                 self.with(scope, |_old_scope, this| {
777                     this.visit_generics(generics);
778                     this.visit_ty(ty);
779                 });
780             }
781             OpaqueTy(bounds) => {
782                 let generics = &impl_item.generics;
783                 let mut index = self.next_early_index();
784                 let mut next_early_index = index;
785                 debug!("visit_ty: index = {}", index);
786                 let lifetimes = generics
787                     .params
788                     .iter()
789                     .filter_map(|param| match param.kind {
790                         GenericParamKind::Lifetime { .. } => {
791                             Some(Region::early(&self.tcx.hir(), &mut index, param))
792                         }
793                         GenericParamKind::Type { .. } => {
794                             next_early_index += 1;
795                             None
796                         }
797                         GenericParamKind::Const { .. } => {
798                             next_early_index += 1;
799                             None
800                         }
801                     })
802                     .collect();
803
804                 let scope = Scope::Binder {
805                     lifetimes,
806                     next_early_index,
807                     s: self.scope,
808                     track_lifetime_uses: true,
809                     opaque_type_parent: true,
810                 };
811                 self.with(scope, |_old_scope, this| {
812                     this.visit_generics(generics);
813                     for bound in bounds {
814                         this.visit_param_bound(bound);
815                     }
816                 });
817             }
818             Const(_, _) => {
819                 // Only methods and types support generics.
820                 assert!(impl_item.generics.params.is_empty());
821                 intravisit::walk_impl_item(self, impl_item);
822             }
823         }
824     }
825
826     fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
827         debug!("visit_lifetime(lifetime_ref={:?})", lifetime_ref);
828         if lifetime_ref.is_elided() {
829             self.resolve_elided_lifetimes(vec![lifetime_ref]);
830             return;
831         }
832         if lifetime_ref.is_static() {
833             self.insert_lifetime(lifetime_ref, Region::Static);
834             return;
835         }
836         self.resolve_lifetime_ref(lifetime_ref);
837     }
838
839     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
840         for (i, segment) in path.segments.iter().enumerate() {
841             let depth = path.segments.len() - i - 1;
842             if let Some(ref args) = segment.args {
843                 self.visit_segment_args(path.res, depth, args);
844             }
845         }
846     }
847
848     fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
849         let output = match fd.output {
850             hir::FunctionRetTy::DefaultReturn(_) => None,
851             hir::FunctionRetTy::Return(ref ty) => Some(&**ty),
852         };
853         self.visit_fn_like_elision(&fd.inputs, output);
854     }
855
856     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
857         check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
858         for param in generics.params {
859             match param.kind {
860                 GenericParamKind::Lifetime { .. } => {}
861                 GenericParamKind::Type { ref default, .. } => {
862                     walk_list!(self, visit_param_bound, param.bounds);
863                     if let Some(ref ty) = default {
864                         self.visit_ty(&ty);
865                     }
866                 }
867                 GenericParamKind::Const { ref ty, .. } => {
868                     walk_list!(self, visit_param_bound, param.bounds);
869                     self.visit_ty(&ty);
870                 }
871             }
872         }
873         for predicate in generics.where_clause.predicates {
874             match predicate {
875                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
876                     ref bounded_ty,
877                     bounds,
878                     ref bound_generic_params,
879                     ..
880                 }) => {
881                     let lifetimes: FxHashMap<_, _> = bound_generic_params
882                         .iter()
883                         .filter_map(|param| match param.kind {
884                             GenericParamKind::Lifetime { .. } => {
885                                 Some(Region::late(&self.tcx.hir(), param))
886                             }
887                             _ => None,
888                         })
889                         .collect();
890                     if !lifetimes.is_empty() {
891                         self.trait_ref_hack = true;
892                         let next_early_index = self.next_early_index();
893                         let scope = Scope::Binder {
894                             lifetimes,
895                             s: self.scope,
896                             next_early_index,
897                             track_lifetime_uses: true,
898                             opaque_type_parent: false,
899                         };
900                         let result = self.with(scope, |old_scope, this| {
901                             this.check_lifetime_params(old_scope, &bound_generic_params);
902                             this.visit_ty(&bounded_ty);
903                             walk_list!(this, visit_param_bound, bounds);
904                         });
905                         self.trait_ref_hack = false;
906                         result
907                     } else {
908                         self.visit_ty(&bounded_ty);
909                         walk_list!(self, visit_param_bound, bounds);
910                     }
911                 }
912                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
913                     ref lifetime,
914                     bounds,
915                     ..
916                 }) => {
917                     self.visit_lifetime(lifetime);
918                     walk_list!(self, visit_param_bound, bounds);
919                 }
920                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
921                     ref lhs_ty,
922                     ref rhs_ty,
923                     ..
924                 }) => {
925                     self.visit_ty(lhs_ty);
926                     self.visit_ty(rhs_ty);
927                 }
928             }
929         }
930     }
931
932     fn visit_poly_trait_ref(
933         &mut self,
934         trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
935         _modifier: hir::TraitBoundModifier,
936     ) {
937         debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
938
939         if !self.trait_ref_hack
940             || trait_ref.bound_generic_params.iter().any(|param| match param.kind {
941                 GenericParamKind::Lifetime { .. } => true,
942                 _ => false,
943             })
944         {
945             if self.trait_ref_hack {
946                 span_err!(
947                     self.tcx.sess,
948                     trait_ref.span,
949                     E0316,
950                     "nested quantification of lifetimes"
951                 );
952             }
953             let next_early_index = self.next_early_index();
954             let scope = Scope::Binder {
955                 lifetimes: trait_ref
956                     .bound_generic_params
957                     .iter()
958                     .filter_map(|param| match param.kind {
959                         GenericParamKind::Lifetime { .. } => {
960                             Some(Region::late(&self.tcx.hir(), param))
961                         }
962                         _ => None,
963                     })
964                     .collect(),
965                 s: self.scope,
966                 next_early_index,
967                 track_lifetime_uses: true,
968                 opaque_type_parent: false,
969             };
970             self.with(scope, |old_scope, this| {
971                 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
972                 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
973                 this.visit_trait_ref(&trait_ref.trait_ref)
974             })
975         } else {
976             self.visit_trait_ref(&trait_ref.trait_ref)
977         }
978     }
979 }
980
981 #[derive(Copy, Clone, PartialEq)]
982 enum ShadowKind {
983     Label,
984     Lifetime,
985 }
986 struct Original {
987     kind: ShadowKind,
988     span: Span,
989 }
990 struct Shadower {
991     kind: ShadowKind,
992     span: Span,
993 }
994
995 fn original_label(span: Span) -> Original {
996     Original { kind: ShadowKind::Label, span: span }
997 }
998 fn shadower_label(span: Span) -> Shadower {
999     Shadower { kind: ShadowKind::Label, span: span }
1000 }
1001 fn original_lifetime(span: Span) -> Original {
1002     Original { kind: ShadowKind::Lifetime, span: span }
1003 }
1004 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1005     Shadower { kind: ShadowKind::Lifetime, span: param.span }
1006 }
1007
1008 impl ShadowKind {
1009     fn desc(&self) -> &'static str {
1010         match *self {
1011             ShadowKind::Label => "label",
1012             ShadowKind::Lifetime => "lifetime",
1013         }
1014     }
1015 }
1016
1017 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1018     let lifetime_params: Vec<_> = params
1019         .iter()
1020         .filter_map(|param| match param.kind {
1021             GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1022             _ => None,
1023         })
1024         .collect();
1025     let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1026     let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1027
1028     if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1029         struct_span_err!(
1030             tcx.sess,
1031             *in_band_span,
1032             E0688,
1033             "cannot mix in-band and explicit lifetime definitions"
1034         )
1035         .span_label(*in_band_span, "in-band lifetime definition here")
1036         .span_label(*explicit_span, "explicit lifetime definition here")
1037         .emit();
1038     }
1039 }
1040
1041 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: ast::Name, orig: Original, shadower: Shadower) {
1042     let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1043         // lifetime/lifetime shadowing is an error
1044         struct_span_err!(
1045             tcx.sess,
1046             shadower.span,
1047             E0496,
1048             "{} name `{}` shadows a \
1049              {} name that is already in scope",
1050             shadower.kind.desc(),
1051             name,
1052             orig.kind.desc()
1053         )
1054     } else {
1055         // shadowing involving a label is only a warning, due to issues with
1056         // labels and lifetimes not being macro-hygienic.
1057         tcx.sess.struct_span_warn(
1058             shadower.span,
1059             &format!(
1060                 "{} name `{}` shadows a \
1061                  {} name that is already in scope",
1062                 shadower.kind.desc(),
1063                 name,
1064                 orig.kind.desc()
1065             ),
1066         )
1067     };
1068     err.span_label(orig.span, "first declared here");
1069     err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1070     err.emit();
1071 }
1072
1073 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1074 // if one of the label shadows a lifetime or another label.
1075 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1076     struct GatherLabels<'a, 'tcx> {
1077         tcx: TyCtxt<'tcx>,
1078         scope: ScopeRef<'a>,
1079         labels_in_fn: &'a mut Vec<ast::Ident>,
1080     }
1081
1082     let mut gather =
1083         GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1084     gather.visit_body(body);
1085
1086     impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1087         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1088             NestedVisitorMap::None
1089         }
1090
1091         fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1092             if let Some(label) = expression_label(ex) {
1093                 for prior_label in &self.labels_in_fn[..] {
1094                     // FIXME (#24278): non-hygienic comparison
1095                     if label.name == prior_label.name {
1096                         signal_shadowing_problem(
1097                             self.tcx,
1098                             label.name,
1099                             original_label(prior_label.span),
1100                             shadower_label(label.span),
1101                         );
1102                     }
1103                 }
1104
1105                 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1106
1107                 self.labels_in_fn.push(label);
1108             }
1109             intravisit::walk_expr(self, ex)
1110         }
1111     }
1112
1113     fn expression_label(ex: &hir::Expr<'_>) -> Option<ast::Ident> {
1114         if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { Some(label.ident) } else { None }
1115     }
1116
1117     fn check_if_label_shadows_lifetime(
1118         tcx: TyCtxt<'_>,
1119         mut scope: ScopeRef<'_>,
1120         label: ast::Ident,
1121     ) {
1122         loop {
1123             match *scope {
1124                 Scope::Body { s, .. }
1125                 | Scope::Elision { s, .. }
1126                 | Scope::ObjectLifetimeDefault { s, .. } => {
1127                     scope = s;
1128                 }
1129
1130                 Scope::Root => {
1131                     return;
1132                 }
1133
1134                 Scope::Binder { ref lifetimes, s, .. } => {
1135                     // FIXME (#24278): non-hygienic comparison
1136                     if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1137                         let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
1138
1139                         signal_shadowing_problem(
1140                             tcx,
1141                             label.name,
1142                             original_lifetime(tcx.hir().span(hir_id)),
1143                             shadower_label(label.span),
1144                         );
1145                         return;
1146                     }
1147                     scope = s;
1148                 }
1149             }
1150         }
1151     }
1152 }
1153
1154 fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1155     let mut map = HirIdMap::default();
1156     for item in tcx.hir().krate().items.values() {
1157         match item.kind {
1158             hir::ItemKind::Struct(_, ref generics)
1159             | hir::ItemKind::Union(_, ref generics)
1160             | hir::ItemKind::Enum(_, ref generics)
1161             | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1162                 ref generics, impl_trait_fn: None, ..
1163             })
1164             | hir::ItemKind::TyAlias(_, ref generics)
1165             | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1166                 let result = object_lifetime_defaults_for_item(tcx, generics);
1167
1168                 // Debugging aid.
1169                 if attr::contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1170                     let object_lifetime_default_reprs: String = result
1171                         .iter()
1172                         .map(|set| match *set {
1173                             Set1::Empty => "BaseDefault".into(),
1174                             Set1::One(Region::Static) => "'static".into(),
1175                             Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1176                                 .params
1177                                 .iter()
1178                                 .find_map(|param| match param.kind {
1179                                     GenericParamKind::Lifetime { .. } => {
1180                                         if i == 0 {
1181                                             return Some(param.name.ident().to_string().into());
1182                                         }
1183                                         i -= 1;
1184                                         None
1185                                     }
1186                                     _ => None,
1187                                 })
1188                                 .unwrap(),
1189                             Set1::One(_) => bug!(),
1190                             Set1::Many => "Ambiguous".into(),
1191                         })
1192                         .collect::<Vec<Cow<'static, str>>>()
1193                         .join(",");
1194                     tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1195                 }
1196
1197                 map.insert(item.hir_id, result);
1198             }
1199             _ => {}
1200         }
1201     }
1202     map
1203 }
1204
1205 /// Scan the bounds and where-clauses on parameters to extract bounds
1206 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1207 /// for each type parameter.
1208 fn object_lifetime_defaults_for_item(
1209     tcx: TyCtxt<'_>,
1210     generics: &hir::Generics<'_>,
1211 ) -> Vec<ObjectLifetimeDefault> {
1212     fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1213         for bound in bounds {
1214             if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1215                 set.insert(lifetime.name.modern());
1216             }
1217         }
1218     }
1219
1220     generics
1221         .params
1222         .iter()
1223         .filter_map(|param| match param.kind {
1224             GenericParamKind::Lifetime { .. } => None,
1225             GenericParamKind::Type { .. } => {
1226                 let mut set = Set1::Empty;
1227
1228                 add_bounds(&mut set, &param.bounds);
1229
1230                 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1231                 for predicate in generics.where_clause.predicates {
1232                     // Look for `type: ...` where clauses.
1233                     let data = match *predicate {
1234                         hir::WherePredicate::BoundPredicate(ref data) => data,
1235                         _ => continue,
1236                     };
1237
1238                     // Ignore `for<'a> type: ...` as they can change what
1239                     // lifetimes mean (although we could "just" handle it).
1240                     if !data.bound_generic_params.is_empty() {
1241                         continue;
1242                     }
1243
1244                     let res = match data.bounded_ty.kind {
1245                         hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1246                         _ => continue,
1247                     };
1248
1249                     if res == Res::Def(DefKind::TyParam, param_def_id) {
1250                         add_bounds(&mut set, &data.bounds);
1251                     }
1252                 }
1253
1254                 Some(match set {
1255                     Set1::Empty => Set1::Empty,
1256                     Set1::One(name) => {
1257                         if name == hir::LifetimeName::Static {
1258                             Set1::One(Region::Static)
1259                         } else {
1260                             generics
1261                                 .params
1262                                 .iter()
1263                                 .filter_map(|param| match param.kind {
1264                                     GenericParamKind::Lifetime { .. } => Some((
1265                                         param.hir_id,
1266                                         hir::LifetimeName::Param(param.name),
1267                                         LifetimeDefOrigin::from_param(param),
1268                                     )),
1269                                     _ => None,
1270                                 })
1271                                 .enumerate()
1272                                 .find(|&(_, (_, lt_name, _))| lt_name == name)
1273                                 .map_or(Set1::Many, |(i, (id, _, origin))| {
1274                                     let def_id = tcx.hir().local_def_id(id);
1275                                     Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1276                                 })
1277                         }
1278                     }
1279                     Set1::Many => Set1::Many,
1280                 })
1281             }
1282             GenericParamKind::Const { .. } => {
1283                 // Generic consts don't impose any constraints.
1284                 None
1285             }
1286         })
1287         .collect()
1288 }
1289
1290 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1291     // FIXME(#37666) this works around a limitation in the region inferencer
1292     fn hack<F>(&mut self, f: F)
1293     where
1294         F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1295     {
1296         f(self)
1297     }
1298
1299     fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1300     where
1301         F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1302     {
1303         let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1304         let labels_in_fn = take(&mut self.labels_in_fn);
1305         let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1306         let mut this = LifetimeContext {
1307             tcx: *tcx,
1308             map: map,
1309             scope: &wrap_scope,
1310             trait_ref_hack: self.trait_ref_hack,
1311             is_in_fn_syntax: self.is_in_fn_syntax,
1312             labels_in_fn,
1313             xcrate_object_lifetime_defaults,
1314             lifetime_uses: lifetime_uses,
1315         };
1316         debug!("entering scope {:?}", this.scope);
1317         f(self.scope, &mut this);
1318         this.check_uses_for_lifetimes_defined_by_scope();
1319         debug!("exiting scope {:?}", this.scope);
1320         self.labels_in_fn = this.labels_in_fn;
1321         self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1322     }
1323
1324     /// helper method to determine the span to remove when suggesting the
1325     /// deletion of a lifetime
1326     fn lifetime_deletion_span(
1327         &self,
1328         name: ast::Ident,
1329         generics: &hir::Generics<'_>,
1330     ) -> Option<Span> {
1331         generics.params.iter().enumerate().find_map(|(i, param)| {
1332             if param.name.ident() == name {
1333                 let mut in_band = false;
1334                 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1335                     if let hir::LifetimeParamKind::InBand = kind {
1336                         in_band = true;
1337                     }
1338                 }
1339                 if in_band {
1340                     Some(param.span)
1341                 } else {
1342                     if generics.params.len() == 1 {
1343                         // if sole lifetime, remove the entire `<>` brackets
1344                         Some(generics.span)
1345                     } else {
1346                         // if removing within `<>` brackets, we also want to
1347                         // delete a leading or trailing comma as appropriate
1348                         if i >= generics.params.len() - 1 {
1349                             Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1350                         } else {
1351                             Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1352                         }
1353                     }
1354                 }
1355             } else {
1356                 None
1357             }
1358         })
1359     }
1360
1361     // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1362     // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1363     fn suggest_eliding_single_use_lifetime(
1364         &self,
1365         err: &mut DiagnosticBuilder<'_>,
1366         def_id: DefId,
1367         lifetime: &hir::Lifetime,
1368     ) {
1369         let name = lifetime.name.ident();
1370         let mut remove_decl = None;
1371         if let Some(parent_def_id) = self.tcx.parent(def_id) {
1372             if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1373                 remove_decl = self.lifetime_deletion_span(name, generics);
1374             }
1375         }
1376
1377         let mut remove_use = None;
1378         let mut elide_use = None;
1379         let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1380             for input in inputs {
1381                 match input.kind {
1382                     hir::TyKind::Rptr(lt, _) => {
1383                         if lt.name.ident() == name {
1384                             // include the trailing whitespace between the lifetime and type names
1385                             let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1386                             remove_use = Some(
1387                                 self.tcx
1388                                     .sess
1389                                     .source_map()
1390                                     .span_until_non_whitespace(lt_through_ty_span),
1391                             );
1392                             break;
1393                         }
1394                     }
1395                     hir::TyKind::Path(ref qpath) => {
1396                         if let QPath::Resolved(_, path) = qpath {
1397                             let last_segment = &path.segments[path.segments.len() - 1];
1398                             let generics = last_segment.generic_args();
1399                             for arg in generics.args.iter() {
1400                                 if let GenericArg::Lifetime(lt) = arg {
1401                                     if lt.name.ident() == name {
1402                                         elide_use = Some(lt.span);
1403                                         break;
1404                                     }
1405                                 }
1406                             }
1407                             break;
1408                         }
1409                     }
1410                     _ => {}
1411                 }
1412             }
1413         };
1414         if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1415             if let Some(parent) =
1416                 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1417             {
1418                 match parent {
1419                     Node::Item(item) => {
1420                         if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1421                             find_arg_use_span(sig.decl.inputs);
1422                         }
1423                     }
1424                     Node::ImplItem(impl_item) => {
1425                         if let hir::ImplItemKind::Method(sig, _) = &impl_item.kind {
1426                             find_arg_use_span(sig.decl.inputs);
1427                         }
1428                     }
1429                     _ => {}
1430                 }
1431             }
1432         }
1433
1434         let msg = "elide the single-use lifetime";
1435         match (remove_decl, remove_use, elide_use) {
1436             (Some(decl_span), Some(use_span), None) => {
1437                 // if both declaration and use deletion spans start at the same
1438                 // place ("start at" because the latter includes trailing
1439                 // whitespace), then this is an in-band lifetime
1440                 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1441                     err.span_suggestion(
1442                         use_span,
1443                         msg,
1444                         String::new(),
1445                         Applicability::MachineApplicable,
1446                     );
1447                 } else {
1448                     err.multipart_suggestion(
1449                         msg,
1450                         vec![(decl_span, String::new()), (use_span, String::new())],
1451                         Applicability::MachineApplicable,
1452                     );
1453                 }
1454             }
1455             (Some(decl_span), None, Some(use_span)) => {
1456                 err.multipart_suggestion(
1457                     msg,
1458                     vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1459                     Applicability::MachineApplicable,
1460                 );
1461             }
1462             _ => {}
1463         }
1464     }
1465
1466     fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1467         let defined_by = match self.scope {
1468             Scope::Binder { lifetimes, .. } => lifetimes,
1469             _ => {
1470                 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1471                 return;
1472             }
1473         };
1474
1475         let mut def_ids: Vec<_> = defined_by
1476             .values()
1477             .flat_map(|region| match region {
1478                 Region::EarlyBound(_, def_id, _)
1479                 | Region::LateBound(_, def_id, _)
1480                 | Region::Free(_, def_id) => Some(*def_id),
1481
1482                 Region::LateBoundAnon(..) | Region::Static => None,
1483             })
1484             .collect();
1485
1486         // ensure that we issue lints in a repeatable order
1487         def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1488
1489         for def_id in def_ids {
1490             debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1491
1492             let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1493
1494             debug!(
1495                 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1496                 lifetimeuseset
1497             );
1498
1499             match lifetimeuseset {
1500                 Some(LifetimeUseSet::One(lifetime)) => {
1501                     let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1502                     debug!("hir id first={:?}", hir_id);
1503                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1504                         Node::Lifetime(hir_lifetime) => Some((
1505                             hir_lifetime.hir_id,
1506                             hir_lifetime.span,
1507                             hir_lifetime.name.ident(),
1508                         )),
1509                         Node::GenericParam(param) => {
1510                             Some((param.hir_id, param.span, param.name.ident()))
1511                         }
1512                         _ => None,
1513                     } {
1514                         debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1515                         if name.name == kw::UnderscoreLifetime {
1516                             continue;
1517                         }
1518
1519                         if let Some(parent_def_id) = self.tcx.parent(def_id) {
1520                             if let Some(parent_hir_id) =
1521                                 self.tcx.hir().as_local_hir_id(parent_def_id)
1522                             {
1523                                 // lifetimes in `derive` expansions don't count (Issue #53738)
1524                                 if self
1525                                     .tcx
1526                                     .hir()
1527                                     .attrs(parent_hir_id)
1528                                     .iter()
1529                                     .any(|attr| attr.check_name(sym::automatically_derived))
1530                                 {
1531                                     continue;
1532                                 }
1533                             }
1534                         }
1535
1536                         let mut err = self.tcx.struct_span_lint_hir(
1537                             lint::builtin::SINGLE_USE_LIFETIMES,
1538                             id,
1539                             span,
1540                             &format!("lifetime parameter `{}` only used once", name),
1541                         );
1542
1543                         if span == lifetime.span {
1544                             // spans are the same for in-band lifetime declarations
1545                             err.span_label(span, "this lifetime is only used here");
1546                         } else {
1547                             err.span_label(span, "this lifetime...");
1548                             err.span_label(lifetime.span, "...is used only here");
1549                         }
1550                         self.suggest_eliding_single_use_lifetime(&mut err, def_id, lifetime);
1551                         err.emit();
1552                     }
1553                 }
1554                 Some(LifetimeUseSet::Many) => {
1555                     debug!("not one use lifetime");
1556                 }
1557                 None => {
1558                     let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1559                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1560                         Node::Lifetime(hir_lifetime) => Some((
1561                             hir_lifetime.hir_id,
1562                             hir_lifetime.span,
1563                             hir_lifetime.name.ident(),
1564                         )),
1565                         Node::GenericParam(param) => {
1566                             Some((param.hir_id, param.span, param.name.ident()))
1567                         }
1568                         _ => None,
1569                     } {
1570                         debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1571                         let mut err = self.tcx.struct_span_lint_hir(
1572                             lint::builtin::UNUSED_LIFETIMES,
1573                             id,
1574                             span,
1575                             &format!("lifetime parameter `{}` never used", name),
1576                         );
1577                         if let Some(parent_def_id) = self.tcx.parent(def_id) {
1578                             if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1579                                 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1580                                 if let Some(span) = unused_lt_span {
1581                                     err.span_suggestion(
1582                                         span,
1583                                         "elide the unused lifetime",
1584                                         String::new(),
1585                                         Applicability::MachineApplicable,
1586                                     );
1587                                 }
1588                             }
1589                         }
1590                         err.emit();
1591                     }
1592                 }
1593             }
1594         }
1595     }
1596
1597     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1598     ///
1599     /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1600     /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1601     /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1602     ///
1603     /// For example:
1604     ///
1605     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
1606     ///
1607     /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1608     /// lifetimes may be interspersed together.
1609     ///
1610     /// If early bound lifetimes are present, we separate them into their own list (and likewise
1611     /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1612     /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1613     /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1614     /// ordering is not important there.
1615     fn visit_early_late<F>(
1616         &mut self,
1617         parent_id: Option<hir::HirId>,
1618         decl: &'tcx hir::FnDecl<'tcx>,
1619         generics: &'tcx hir::Generics<'tcx>,
1620         walk: F,
1621     ) where
1622         F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1623     {
1624         insert_late_bound_lifetimes(self.map, decl, generics);
1625
1626         // Find the start of nested early scopes, e.g., in methods.
1627         let mut index = 0;
1628         if let Some(parent_id) = parent_id {
1629             let parent = self.tcx.hir().expect_item(parent_id);
1630             if sub_items_have_self_param(&parent.kind) {
1631                 index += 1; // Self comes before lifetimes
1632             }
1633             match parent.kind {
1634                 hir::ItemKind::Trait(_, _, ref generics, ..)
1635                 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
1636                     index += generics.params.len() as u32;
1637                 }
1638                 _ => {}
1639             }
1640         }
1641
1642         let mut non_lifetime_count = 0;
1643         let lifetimes = generics
1644             .params
1645             .iter()
1646             .filter_map(|param| match param.kind {
1647                 GenericParamKind::Lifetime { .. } => {
1648                     if self.map.late_bound.contains(&param.hir_id) {
1649                         Some(Region::late(&self.tcx.hir(), param))
1650                     } else {
1651                         Some(Region::early(&self.tcx.hir(), &mut index, param))
1652                     }
1653                 }
1654                 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1655                     non_lifetime_count += 1;
1656                     None
1657                 }
1658             })
1659             .collect();
1660         let next_early_index = index + non_lifetime_count;
1661
1662         let scope = Scope::Binder {
1663             lifetimes,
1664             next_early_index,
1665             s: self.scope,
1666             opaque_type_parent: true,
1667             track_lifetime_uses: false,
1668         };
1669         self.with(scope, move |old_scope, this| {
1670             this.check_lifetime_params(old_scope, &generics.params);
1671             this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1672         });
1673     }
1674
1675     fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1676         let mut scope = self.scope;
1677         loop {
1678             match *scope {
1679                 Scope::Root => return 0,
1680
1681                 Scope::Binder { next_early_index, opaque_type_parent, .. }
1682                     if (!only_opaque_type_parent || opaque_type_parent) =>
1683                 {
1684                     return next_early_index;
1685                 }
1686
1687                 Scope::Binder { s, .. }
1688                 | Scope::Body { s, .. }
1689                 | Scope::Elision { s, .. }
1690                 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1691             }
1692         }
1693     }
1694
1695     /// Returns the next index one would use for an early-bound-region
1696     /// if extending the current scope.
1697     fn next_early_index(&self) -> u32 {
1698         self.next_early_index_helper(true)
1699     }
1700
1701     /// Returns the next index one would use for an `impl Trait` that
1702     /// is being converted into an opaque type alias `impl Trait`. This will be the
1703     /// next early index from the enclosing item, for the most
1704     /// part. See the `opaque_type_parent` field for more info.
1705     fn next_early_index_for_opaque_type(&self) -> u32 {
1706         self.next_early_index_helper(false)
1707     }
1708
1709     fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1710         debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1711
1712         // If we've already reported an error, just ignore `lifetime_ref`.
1713         if let LifetimeName::Error = lifetime_ref.name {
1714             return;
1715         }
1716
1717         // Walk up the scope chain, tracking the number of fn scopes
1718         // that we pass through, until we find a lifetime with the
1719         // given name or we run out of scopes.
1720         // search.
1721         let mut late_depth = 0;
1722         let mut scope = self.scope;
1723         let mut outermost_body = None;
1724         let result = loop {
1725             match *scope {
1726                 Scope::Body { id, s } => {
1727                     outermost_body = Some(id);
1728                     scope = s;
1729                 }
1730
1731                 Scope::Root => {
1732                     break None;
1733                 }
1734
1735                 Scope::Binder { ref lifetimes, s, .. } => {
1736                     match lifetime_ref.name {
1737                         LifetimeName::Param(param_name) => {
1738                             if let Some(&def) = lifetimes.get(&param_name.modern()) {
1739                                 break Some(def.shifted(late_depth));
1740                             }
1741                         }
1742                         _ => bug!("expected LifetimeName::Param"),
1743                     }
1744
1745                     late_depth += 1;
1746                     scope = s;
1747                 }
1748
1749                 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1750                     scope = s;
1751                 }
1752             }
1753         };
1754
1755         if let Some(mut def) = result {
1756             if let Region::EarlyBound(..) = def {
1757                 // Do not free early-bound regions, only late-bound ones.
1758             } else if let Some(body_id) = outermost_body {
1759                 let fn_id = self.tcx.hir().body_owner(body_id);
1760                 match self.tcx.hir().get(fn_id) {
1761                     Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1762                     | Node::TraitItem(&hir::TraitItem {
1763                         kind: hir::TraitItemKind::Method(..),
1764                         ..
1765                     })
1766                     | Node::ImplItem(&hir::ImplItem {
1767                         kind: hir::ImplItemKind::Method(..), ..
1768                     }) => {
1769                         let scope = self.tcx.hir().local_def_id(fn_id);
1770                         def = Region::Free(scope, def.id().unwrap());
1771                     }
1772                     _ => {}
1773                 }
1774             }
1775
1776             // Check for fn-syntax conflicts with in-band lifetime definitions
1777             if self.is_in_fn_syntax {
1778                 match def {
1779                     Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1780                     | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1781                         struct_span_err!(
1782                             self.tcx.sess,
1783                             lifetime_ref.span,
1784                             E0687,
1785                             "lifetimes used in `fn` or `Fn` syntax must be \
1786                              explicitly declared using `<...>` binders"
1787                         )
1788                         .span_label(lifetime_ref.span, "in-band lifetime definition")
1789                         .emit();
1790                     }
1791
1792                     Region::Static
1793                     | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1794                     | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1795                     | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1796                     | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1797                     | Region::LateBoundAnon(..)
1798                     | Region::Free(..) => {}
1799                 }
1800             }
1801
1802             self.insert_lifetime(lifetime_ref, def);
1803         } else {
1804             struct_span_err!(
1805                 self.tcx.sess,
1806                 lifetime_ref.span,
1807                 E0261,
1808                 "use of undeclared lifetime name `{}`",
1809                 lifetime_ref
1810             )
1811             .span_label(lifetime_ref.span, "undeclared lifetime")
1812             .emit();
1813         }
1814     }
1815
1816     fn visit_segment_args(
1817         &mut self,
1818         res: Res,
1819         depth: usize,
1820         generic_args: &'tcx hir::GenericArgs<'tcx>,
1821     ) {
1822         debug!(
1823             "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1824             res, depth, generic_args,
1825         );
1826
1827         if generic_args.parenthesized {
1828             let was_in_fn_syntax = self.is_in_fn_syntax;
1829             self.is_in_fn_syntax = true;
1830             self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1831             self.is_in_fn_syntax = was_in_fn_syntax;
1832             return;
1833         }
1834
1835         let mut elide_lifetimes = true;
1836         let lifetimes = generic_args
1837             .args
1838             .iter()
1839             .filter_map(|arg| match arg {
1840                 hir::GenericArg::Lifetime(lt) => {
1841                     if !lt.is_elided() {
1842                         elide_lifetimes = false;
1843                     }
1844                     Some(lt)
1845                 }
1846                 _ => None,
1847             })
1848             .collect();
1849         if elide_lifetimes {
1850             self.resolve_elided_lifetimes(lifetimes);
1851         } else {
1852             lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1853         }
1854
1855         // Figure out if this is a type/trait segment,
1856         // which requires object lifetime defaults.
1857         let parent_def_id = |this: &mut Self, def_id: DefId| {
1858             let def_key = this.tcx.def_key(def_id);
1859             DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1860         };
1861         let type_def_id = match res {
1862             Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1863             Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1864             Res::Def(DefKind::Struct, def_id)
1865             | Res::Def(DefKind::Union, def_id)
1866             | Res::Def(DefKind::Enum, def_id)
1867             | Res::Def(DefKind::TyAlias, def_id)
1868             | Res::Def(DefKind::Trait, def_id)
1869                 if depth == 0 =>
1870             {
1871                 Some(def_id)
1872             }
1873             _ => None,
1874         };
1875
1876         debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1877
1878         // Compute a vector of defaults, one for each type parameter,
1879         // per the rules given in RFCs 599 and 1156. Example:
1880         //
1881         // ```rust
1882         // struct Foo<'a, T: 'a, U> { }
1883         // ```
1884         //
1885         // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1886         // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1887         // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1888         // such bound).
1889         //
1890         // Therefore, we would compute `object_lifetime_defaults` to a
1891         // vector like `['x, 'static]`. Note that the vector only
1892         // includes type parameters.
1893         let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1894             let in_body = {
1895                 let mut scope = self.scope;
1896                 loop {
1897                     match *scope {
1898                         Scope::Root => break false,
1899
1900                         Scope::Body { .. } => break true,
1901
1902                         Scope::Binder { s, .. }
1903                         | Scope::Elision { s, .. }
1904                         | Scope::ObjectLifetimeDefault { s, .. } => {
1905                             scope = s;
1906                         }
1907                     }
1908                 }
1909             };
1910
1911             let map = &self.map;
1912             let unsubst = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
1913                 &map.object_lifetime_defaults[&id]
1914             } else {
1915                 let tcx = self.tcx;
1916                 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
1917                     tcx.generics_of(def_id)
1918                         .params
1919                         .iter()
1920                         .filter_map(|param| match param.kind {
1921                             GenericParamDefKind::Type { object_lifetime_default, .. } => {
1922                                 Some(object_lifetime_default)
1923                             }
1924                             GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1925                         })
1926                         .collect()
1927                 })
1928             };
1929             debug!("visit_segment_args: unsubst={:?}", unsubst);
1930             unsubst
1931                 .iter()
1932                 .map(|set| match *set {
1933                     Set1::Empty => {
1934                         if in_body {
1935                             None
1936                         } else {
1937                             Some(Region::Static)
1938                         }
1939                     }
1940                     Set1::One(r) => {
1941                         let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1942                             GenericArg::Lifetime(lt) => Some(lt),
1943                             _ => None,
1944                         });
1945                         r.subst(lifetimes, map)
1946                     }
1947                     Set1::Many => None,
1948                 })
1949                 .collect()
1950         });
1951
1952         debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
1953
1954         let mut i = 0;
1955         for arg in generic_args.args {
1956             match arg {
1957                 GenericArg::Lifetime(_) => {}
1958                 GenericArg::Type(ty) => {
1959                     if let Some(&lt) = object_lifetime_defaults.get(i) {
1960                         let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1961                         self.with(scope, |_, this| this.visit_ty(ty));
1962                     } else {
1963                         self.visit_ty(ty);
1964                     }
1965                     i += 1;
1966                 }
1967                 GenericArg::Const(ct) => {
1968                     self.visit_anon_const(&ct.value);
1969                 }
1970             }
1971         }
1972
1973         // Hack: when resolving the type `XX` in binding like `dyn
1974         // Foo<'b, Item = XX>`, the current object-lifetime default
1975         // would be to examine the trait `Foo` to check whether it has
1976         // a lifetime bound declared on `Item`. e.g., if `Foo` is
1977         // declared like so, then the default object lifetime bound in
1978         // `XX` should be `'b`:
1979         //
1980         // ```rust
1981         // trait Foo<'a> {
1982         //   type Item: 'a;
1983         // }
1984         // ```
1985         //
1986         // but if we just have `type Item;`, then it would be
1987         // `'static`. However, we don't get all of this logic correct.
1988         //
1989         // Instead, we do something hacky: if there are no lifetime parameters
1990         // to the trait, then we simply use a default object lifetime
1991         // bound of `'static`, because there is no other possibility. On the other hand,
1992         // if there ARE lifetime parameters, then we require the user to give an
1993         // explicit bound for now.
1994         //
1995         // This is intended to leave room for us to implement the
1996         // correct behavior in the future.
1997         let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
1998             GenericArg::Lifetime(_) => true,
1999             _ => false,
2000         });
2001
2002         // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2003         for b in generic_args.bindings {
2004             let scope = Scope::ObjectLifetimeDefault {
2005                 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2006                 s: self.scope,
2007             };
2008             self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2009         }
2010     }
2011
2012     fn visit_fn_like_elision(
2013         &mut self,
2014         inputs: &'tcx [hir::Ty<'tcx>],
2015         output: Option<&'tcx hir::Ty<'tcx>>,
2016     ) {
2017         debug!("visit_fn_like_elision: enter");
2018         let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2019         let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
2020         self.with(arg_scope, |_, this| {
2021             for input in inputs {
2022                 this.visit_ty(input);
2023             }
2024             match *this.scope {
2025                 Scope::Elision { ref elide, .. } => {
2026                     arg_elide = elide.clone();
2027                 }
2028                 _ => bug!(),
2029             }
2030         });
2031
2032         let output = match output {
2033             Some(ty) => ty,
2034             None => return,
2035         };
2036
2037         debug!("visit_fn_like_elision: determine output");
2038
2039         // Figure out if there's a body we can get argument names from,
2040         // and whether there's a `self` argument (treated specially).
2041         let mut assoc_item_kind = None;
2042         let mut impl_self = None;
2043         let parent = self.tcx.hir().get_parent_node(output.hir_id);
2044         let body = match self.tcx.hir().get(parent) {
2045             // `fn` definitions and methods.
2046             Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2047
2048             Node::TraitItem(&hir::TraitItem {
2049                 kind: hir::TraitItemKind::Method(_, ref m), ..
2050             }) => {
2051                 if let hir::ItemKind::Trait(.., ref trait_items) =
2052                     self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2053                 {
2054                     assoc_item_kind =
2055                         trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
2056                 }
2057                 match *m {
2058                     hir::TraitMethod::Required(_) => None,
2059                     hir::TraitMethod::Provided(body) => Some(body),
2060                 }
2061             }
2062
2063             Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(_, body), .. }) => {
2064                 if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) =
2065                     self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2066                 {
2067                     impl_self = Some(self_ty);
2068                     assoc_item_kind =
2069                         impl_items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
2070                 }
2071                 Some(body)
2072             }
2073
2074             // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2075             Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2076             // Everything else (only closures?) doesn't
2077             // actually enjoy elision in return types.
2078             _ => {
2079                 self.visit_ty(output);
2080                 return;
2081             }
2082         };
2083
2084         let has_self = match assoc_item_kind {
2085             Some(hir::AssocItemKind::Method { has_self }) => has_self,
2086             _ => false,
2087         };
2088
2089         // In accordance with the rules for lifetime elision, we can determine
2090         // what region to use for elision in the output type in two ways.
2091         // First (determined here), if `self` is by-reference, then the
2092         // implied output region is the region of the self parameter.
2093         if has_self {
2094             struct SelfVisitor<'a> {
2095                 map: &'a NamedRegionMap,
2096                 impl_self: Option<&'a hir::TyKind<'a>>,
2097                 lifetime: Set1<Region>,
2098             }
2099
2100             impl SelfVisitor<'_> {
2101                 // Look for `self: &'a Self` - also desugared from `&'a self`,
2102                 // and if that matches, use it for elision and return early.
2103                 fn is_self_ty(&self, res: Res) -> bool {
2104                     if let Res::SelfTy(..) = res {
2105                         return true;
2106                     }
2107
2108                     // Can't always rely on literal (or implied) `Self` due
2109                     // to the way elision rules were originally specified.
2110                     if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2111                         self.impl_self
2112                     {
2113                         match path.res {
2114                             // Whitelist the types that unambiguously always
2115                             // result in the same type constructor being used
2116                             // (it can't differ between `Self` and `self`).
2117                             Res::Def(DefKind::Struct, _)
2118                             | Res::Def(DefKind::Union, _)
2119                             | Res::Def(DefKind::Enum, _)
2120                             | Res::PrimTy(_) => return res == path.res,
2121                             _ => {}
2122                         }
2123                     }
2124
2125                     false
2126                 }
2127             }
2128
2129             impl<'a> Visitor<'a> for SelfVisitor<'a> {
2130                 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'a> {
2131                     NestedVisitorMap::None
2132                 }
2133
2134                 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2135                     if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2136                         if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2137                         {
2138                             if self.is_self_ty(path.res) {
2139                                 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2140                                     self.lifetime.insert(*lifetime);
2141                                 }
2142                             }
2143                         }
2144                     }
2145                     intravisit::walk_ty(self, ty)
2146                 }
2147             }
2148
2149             let mut visitor = SelfVisitor {
2150                 map: self.map,
2151                 impl_self: impl_self.map(|ty| &ty.kind),
2152                 lifetime: Set1::Empty,
2153             };
2154             visitor.visit_ty(&inputs[0]);
2155             if let Set1::One(lifetime) = visitor.lifetime {
2156                 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2157                 self.with(scope, |_, this| this.visit_ty(output));
2158                 return;
2159             }
2160         }
2161
2162         // Second, if there was exactly one lifetime (either a substitution or a
2163         // reference) in the arguments, then any anonymous regions in the output
2164         // have that lifetime.
2165         let mut possible_implied_output_region = None;
2166         let mut lifetime_count = 0;
2167         let arg_lifetimes = inputs
2168             .iter()
2169             .enumerate()
2170             .skip(has_self as usize)
2171             .map(|(i, input)| {
2172                 let mut gather = GatherLifetimes {
2173                     map: self.map,
2174                     outer_index: ty::INNERMOST,
2175                     have_bound_regions: false,
2176                     lifetimes: Default::default(),
2177                 };
2178                 gather.visit_ty(input);
2179
2180                 lifetime_count += gather.lifetimes.len();
2181
2182                 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2183                     // there's a chance that the unique lifetime of this
2184                     // iteration will be the appropriate lifetime for output
2185                     // parameters, so lets store it.
2186                     possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2187                 }
2188
2189                 ElisionFailureInfo {
2190                     parent: body,
2191                     index: i,
2192                     lifetime_count: gather.lifetimes.len(),
2193                     have_bound_regions: gather.have_bound_regions,
2194                 }
2195             })
2196             .collect();
2197
2198         let elide = if lifetime_count == 1 {
2199             Elide::Exact(possible_implied_output_region.unwrap())
2200         } else {
2201             Elide::Error(arg_lifetimes)
2202         };
2203
2204         debug!("visit_fn_like_elision: elide={:?}", elide);
2205
2206         let scope = Scope::Elision { elide, s: self.scope };
2207         self.with(scope, |_, this| this.visit_ty(output));
2208         debug!("visit_fn_like_elision: exit");
2209
2210         struct GatherLifetimes<'a> {
2211             map: &'a NamedRegionMap,
2212             outer_index: ty::DebruijnIndex,
2213             have_bound_regions: bool,
2214             lifetimes: FxHashSet<Region>,
2215         }
2216
2217         impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2218             fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2219                 NestedVisitorMap::None
2220             }
2221
2222             fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2223                 if let hir::TyKind::BareFn(_) = ty.kind {
2224                     self.outer_index.shift_in(1);
2225                 }
2226                 match ty.kind {
2227                     hir::TyKind::TraitObject(bounds, ref lifetime) => {
2228                         for bound in bounds {
2229                             self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2230                         }
2231
2232                         // Stay on the safe side and don't include the object
2233                         // lifetime default (which may not end up being used).
2234                         if !lifetime.is_elided() {
2235                             self.visit_lifetime(lifetime);
2236                         }
2237                     }
2238                     _ => {
2239                         intravisit::walk_ty(self, ty);
2240                     }
2241                 }
2242                 if let hir::TyKind::BareFn(_) = ty.kind {
2243                     self.outer_index.shift_out(1);
2244                 }
2245             }
2246
2247             fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2248                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2249                     // FIXME(eddyb) Do we want this? It only makes a difference
2250                     // if this `for<'a>` lifetime parameter is never used.
2251                     self.have_bound_regions = true;
2252                 }
2253
2254                 intravisit::walk_generic_param(self, param);
2255             }
2256
2257             fn visit_poly_trait_ref(
2258                 &mut self,
2259                 trait_ref: &hir::PolyTraitRef<'_>,
2260                 modifier: hir::TraitBoundModifier,
2261             ) {
2262                 self.outer_index.shift_in(1);
2263                 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2264                 self.outer_index.shift_out(1);
2265             }
2266
2267             fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2268                 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2269                     match lifetime {
2270                         Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2271                             if debruijn < self.outer_index =>
2272                         {
2273                             self.have_bound_regions = true;
2274                         }
2275                         _ => {
2276                             self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2277                         }
2278                     }
2279                 }
2280             }
2281         }
2282     }
2283
2284     fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2285         debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2286
2287         if lifetime_refs.is_empty() {
2288             return;
2289         }
2290
2291         let span = lifetime_refs[0].span;
2292         let mut late_depth = 0;
2293         let mut scope = self.scope;
2294         let mut lifetime_names = FxHashSet::default();
2295         let error = loop {
2296             match *scope {
2297                 // Do not assign any resolution, it will be inferred.
2298                 Scope::Body { .. } => return,
2299
2300                 Scope::Root => break None,
2301
2302                 Scope::Binder { s, ref lifetimes, .. } => {
2303                     // collect named lifetimes for suggestions
2304                     for name in lifetimes.keys() {
2305                         if let hir::ParamName::Plain(name) = name {
2306                             lifetime_names.insert(*name);
2307                         }
2308                     }
2309                     late_depth += 1;
2310                     scope = s;
2311                 }
2312
2313                 Scope::Elision { ref elide, ref s, .. } => {
2314                     let lifetime = match *elide {
2315                         Elide::FreshLateAnon(ref counter) => {
2316                             for lifetime_ref in lifetime_refs {
2317                                 let lifetime = Region::late_anon(counter).shifted(late_depth);
2318                                 self.insert_lifetime(lifetime_ref, lifetime);
2319                             }
2320                             return;
2321                         }
2322                         Elide::Exact(l) => l.shifted(late_depth),
2323                         Elide::Error(ref e) => {
2324                             if let Scope::Binder { ref lifetimes, .. } = s {
2325                                 // collect named lifetimes for suggestions
2326                                 for name in lifetimes.keys() {
2327                                     if let hir::ParamName::Plain(name) = name {
2328                                         lifetime_names.insert(*name);
2329                                     }
2330                                 }
2331                             }
2332                             break Some(e);
2333                         }
2334                     };
2335                     for lifetime_ref in lifetime_refs {
2336                         self.insert_lifetime(lifetime_ref, lifetime);
2337                     }
2338                     return;
2339                 }
2340
2341                 Scope::ObjectLifetimeDefault { s, .. } => {
2342                     scope = s;
2343                 }
2344             }
2345         };
2346
2347         let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2348         let mut add_label = true;
2349
2350         if let Some(params) = error {
2351             if lifetime_refs.len() == 1 {
2352                 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2353             }
2354         }
2355         if add_label {
2356             add_missing_lifetime_specifiers_label(
2357                 &mut err,
2358                 span,
2359                 lifetime_refs.len(),
2360                 &lifetime_names,
2361                 self.tcx.sess.source_map().span_to_snippet(span).ok().as_ref().map(|s| s.as_str()),
2362             );
2363         }
2364
2365         err.emit();
2366     }
2367
2368     fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2369         match self.tcx.sess.source_map().span_to_snippet(span) {
2370             Ok(ref snippet) => {
2371                 let (sugg, applicability) = if snippet == "&" {
2372                     ("&'static ".to_owned(), Applicability::MachineApplicable)
2373                 } else if snippet == "'_" {
2374                     ("'static".to_owned(), Applicability::MachineApplicable)
2375                 } else {
2376                     (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2377                 };
2378                 db.span_suggestion(span, msg, sugg, applicability);
2379                 false
2380             }
2381             Err(_) => {
2382                 db.help(msg);
2383                 true
2384             }
2385         }
2386     }
2387
2388     fn report_elision_failure(
2389         &mut self,
2390         db: &mut DiagnosticBuilder<'_>,
2391         params: &[ElisionFailureInfo],
2392         span: Span,
2393     ) -> bool {
2394         let mut m = String::new();
2395         let len = params.len();
2396
2397         let elided_params: Vec<_> =
2398             params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2399
2400         let elided_len = elided_params.len();
2401
2402         for (i, info) in elided_params.into_iter().enumerate() {
2403             let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions } = info;
2404
2405             let help_name = if let Some(ident) =
2406                 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2407             {
2408                 format!("`{}`", ident)
2409             } else {
2410                 format!("argument {}", index + 1)
2411             };
2412
2413             m.push_str(
2414                 &(if n == 1 {
2415                     help_name
2416                 } else {
2417                     format!(
2418                         "one of {}'s {} {}lifetimes",
2419                         help_name,
2420                         n,
2421                         if have_bound_regions { "free " } else { "" }
2422                     )
2423                 })[..],
2424             );
2425
2426             if elided_len == 2 && i == 0 {
2427                 m.push_str(" or ");
2428             } else if i + 2 == elided_len {
2429                 m.push_str(", or ");
2430             } else if i != elided_len - 1 {
2431                 m.push_str(", ");
2432             }
2433         }
2434
2435         if len == 0 {
2436             help!(
2437                 db,
2438                 "this function's return type contains a borrowed value, but \
2439                  there is no value for it to be borrowed from"
2440             );
2441             self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2442         } else if elided_len == 0 {
2443             help!(
2444                 db,
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             help!(
2453                 db,
2454                 "this function's return type contains a borrowed value, but \
2455                  the signature does not say which {} it is borrowed from",
2456                 m
2457             );
2458             true
2459         } else {
2460             help!(
2461                 db,
2462                 "this function's return type contains a borrowed value, but \
2463                  the signature does not say whether it is borrowed from {}",
2464                 m
2465             );
2466             true
2467         }
2468     }
2469
2470     fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2471         debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2472         let mut late_depth = 0;
2473         let mut scope = self.scope;
2474         let lifetime = loop {
2475             match *scope {
2476                 Scope::Binder { s, .. } => {
2477                     late_depth += 1;
2478                     scope = s;
2479                 }
2480
2481                 Scope::Root | Scope::Elision { .. } => break Region::Static,
2482
2483                 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2484
2485                 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2486             }
2487         };
2488         self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2489     }
2490
2491     fn check_lifetime_params(
2492         &mut self,
2493         old_scope: ScopeRef<'_>,
2494         params: &'tcx [hir::GenericParam<'tcx>],
2495     ) {
2496         let lifetimes: Vec<_> = params
2497             .iter()
2498             .filter_map(|param| match param.kind {
2499                 GenericParamKind::Lifetime { .. } => Some((param, param.name.modern())),
2500                 _ => None,
2501             })
2502             .collect();
2503         for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2504             if let hir::ParamName::Plain(_) = lifetime_i_name {
2505                 let name = lifetime_i_name.ident().name;
2506                 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
2507                     let mut err = struct_span_err!(
2508                         self.tcx.sess,
2509                         lifetime_i.span,
2510                         E0262,
2511                         "invalid lifetime parameter name: `{}`",
2512                         lifetime_i.name.ident(),
2513                     );
2514                     err.span_label(
2515                         lifetime_i.span,
2516                         format!("{} is a reserved lifetime name", name),
2517                     );
2518                     err.emit();
2519                 }
2520             }
2521
2522             // It is a hard error to shadow a lifetime within the same scope.
2523             for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2524                 if lifetime_i_name == lifetime_j_name {
2525                     struct_span_err!(
2526                         self.tcx.sess,
2527                         lifetime_j.span,
2528                         E0263,
2529                         "lifetime name `{}` declared twice in the same scope",
2530                         lifetime_j.name.ident()
2531                     )
2532                     .span_label(lifetime_j.span, "declared twice")
2533                     .span_label(lifetime_i.span, "previous declaration here")
2534                     .emit();
2535                 }
2536             }
2537
2538             // It is a soft error to shadow a lifetime within a parent scope.
2539             self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2540
2541             for bound in lifetime_i.bounds {
2542                 match bound {
2543                     hir::GenericBound::Outlives(ref lt) => match lt.name {
2544                         hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2545                             lt.span,
2546                             "use of `'_` in illegal place, but not caught by lowering",
2547                         ),
2548                         hir::LifetimeName::Static => {
2549                             self.insert_lifetime(lt, Region::Static);
2550                             self.tcx
2551                                 .sess
2552                                 .struct_span_warn(
2553                                     lifetime_i.span.to(lt.span),
2554                                     &format!(
2555                                         "unnecessary lifetime parameter `{}`",
2556                                         lifetime_i.name.ident(),
2557                                     ),
2558                                 )
2559                                 .help(&format!(
2560                                     "you can use the `'static` lifetime directly, in place of `{}`",
2561                                     lifetime_i.name.ident(),
2562                                 ))
2563                                 .emit();
2564                         }
2565                         hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2566                             self.resolve_lifetime_ref(lt);
2567                         }
2568                         hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2569                             self.tcx.sess.delay_span_bug(
2570                                 lt.span,
2571                                 "lowering generated `ImplicitObjectLifetimeDefault` \
2572                                  outside of an object type",
2573                             )
2574                         }
2575                         hir::LifetimeName::Error => {
2576                             // No need to do anything, error already reported.
2577                         }
2578                     },
2579                     _ => bug!(),
2580                 }
2581             }
2582         }
2583     }
2584
2585     fn check_lifetime_param_for_shadowing(
2586         &self,
2587         mut old_scope: ScopeRef<'_>,
2588         param: &'tcx hir::GenericParam<'tcx>,
2589     ) {
2590         for label in &self.labels_in_fn {
2591             // FIXME (#24278): non-hygienic comparison
2592             if param.name.ident().name == label.name {
2593                 signal_shadowing_problem(
2594                     self.tcx,
2595                     label.name,
2596                     original_label(label.span),
2597                     shadower_lifetime(&param),
2598                 );
2599                 return;
2600             }
2601         }
2602
2603         loop {
2604             match *old_scope {
2605                 Scope::Body { s, .. }
2606                 | Scope::Elision { s, .. }
2607                 | Scope::ObjectLifetimeDefault { s, .. } => {
2608                     old_scope = s;
2609                 }
2610
2611                 Scope::Root => {
2612                     return;
2613                 }
2614
2615                 Scope::Binder { ref lifetimes, s, .. } => {
2616                     if let Some(&def) = lifetimes.get(&param.name.modern()) {
2617                         let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
2618
2619                         signal_shadowing_problem(
2620                             self.tcx,
2621                             param.name.ident().name,
2622                             original_lifetime(self.tcx.hir().span(hir_id)),
2623                             shadower_lifetime(&param),
2624                         );
2625                         return;
2626                     }
2627
2628                     old_scope = s;
2629                 }
2630             }
2631         }
2632     }
2633
2634     /// Returns `true` if, in the current scope, replacing `'_` would be
2635     /// equivalent to a single-use lifetime.
2636     fn track_lifetime_uses(&self) -> bool {
2637         let mut scope = self.scope;
2638         loop {
2639             match *scope {
2640                 Scope::Root => break false,
2641
2642                 // Inside of items, it depends on the kind of item.
2643                 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
2644
2645                 // Inside a body, `'_` will use an inference variable,
2646                 // should be fine.
2647                 Scope::Body { .. } => break true,
2648
2649                 // A lifetime only used in a fn argument could as well
2650                 // be replaced with `'_`, as that would generate a
2651                 // fresh name, too.
2652                 Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
2653
2654                 // In the return type or other such place, `'_` is not
2655                 // going to make a fresh name, so we cannot
2656                 // necessarily replace a single-use lifetime with
2657                 // `'_`.
2658                 Scope::Elision { elide: Elide::Exact(_), .. } => break false,
2659                 Scope::Elision { elide: Elide::Error(_), .. } => break false,
2660
2661                 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2662             }
2663         }
2664     }
2665
2666     fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2667         if lifetime_ref.hir_id == hir::DUMMY_HIR_ID {
2668             span_bug!(
2669                 lifetime_ref.span,
2670                 "lifetime reference not renumbered, \
2671                  probably a bug in syntax::fold"
2672             );
2673         }
2674
2675         debug!(
2676             "insert_lifetime: {} resolved to {:?} span={:?}",
2677             self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2678             def,
2679             self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2680         );
2681         self.map.defs.insert(lifetime_ref.hir_id, def);
2682
2683         match def {
2684             Region::LateBoundAnon(..) | Region::Static => {
2685                 // These are anonymous lifetimes or lifetimes that are not declared.
2686             }
2687
2688             Region::Free(_, def_id)
2689             | Region::LateBound(_, def_id, _)
2690             | Region::EarlyBound(_, def_id, _) => {
2691                 // A lifetime declared by the user.
2692                 let track_lifetime_uses = self.track_lifetime_uses();
2693                 debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
2694                 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2695                     debug!("insert_lifetime: first use of {:?}", def_id);
2696                     self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
2697                 } else {
2698                     debug!("insert_lifetime: many uses of {:?}", def_id);
2699                     self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2700                 }
2701             }
2702         }
2703     }
2704
2705     /// Sometimes we resolve a lifetime, but later find that it is an
2706     /// error (esp. around impl trait). In that case, we remove the
2707     /// entry into `map.defs` so as not to confuse later code.
2708     fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2709         let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2710         assert_eq!(old_value, Some(bad_def));
2711     }
2712 }
2713
2714 /// Detects late-bound lifetimes and inserts them into
2715 /// `map.late_bound`.
2716 ///
2717 /// A region declared on a fn is **late-bound** if:
2718 /// - it is constrained by an argument type;
2719 /// - it does not appear in a where-clause.
2720 ///
2721 /// "Constrained" basically means that it appears in any type but
2722 /// not amongst the inputs to a projection. In other words, `<&'a
2723 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2724 fn insert_late_bound_lifetimes(
2725     map: &mut NamedRegionMap,
2726     decl: &hir::FnDecl<'_>,
2727     generics: &hir::Generics<'_>,
2728 ) {
2729     debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
2730
2731     let mut constrained_by_input = ConstrainedCollector::default();
2732     for arg_ty in decl.inputs {
2733         constrained_by_input.visit_ty(arg_ty);
2734     }
2735
2736     let mut appears_in_output = AllCollector::default();
2737     intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2738
2739     debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
2740
2741     // Walk the lifetimes that appear in where clauses.
2742     //
2743     // Subtle point: because we disallow nested bindings, we can just
2744     // ignore binders here and scrape up all names we see.
2745     let mut appears_in_where_clause = AllCollector::default();
2746     appears_in_where_clause.visit_generics(generics);
2747
2748     for param in generics.params {
2749         if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2750             if !param.bounds.is_empty() {
2751                 // `'a: 'b` means both `'a` and `'b` are referenced
2752                 appears_in_where_clause
2753                     .regions
2754                     .insert(hir::LifetimeName::Param(param.name.modern()));
2755             }
2756         }
2757     }
2758
2759     debug!(
2760         "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2761         appears_in_where_clause.regions
2762     );
2763
2764     // Late bound regions are those that:
2765     // - appear in the inputs
2766     // - do not appear in the where-clauses
2767     // - are not implicitly captured by `impl Trait`
2768     for param in generics.params {
2769         match param.kind {
2770             hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2771
2772             // Neither types nor consts are late-bound.
2773             hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2774         }
2775
2776         let lt_name = hir::LifetimeName::Param(param.name.modern());
2777         // appears in the where clauses? early-bound.
2778         if appears_in_where_clause.regions.contains(&lt_name) {
2779             continue;
2780         }
2781
2782         // does not appear in the inputs, but appears in the return type? early-bound.
2783         if !constrained_by_input.regions.contains(&lt_name)
2784             && appears_in_output.regions.contains(&lt_name)
2785         {
2786             continue;
2787         }
2788
2789         debug!(
2790             "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2791             param.name.ident(),
2792             param.hir_id
2793         );
2794
2795         let inserted = map.late_bound.insert(param.hir_id);
2796         assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2797     }
2798
2799     return;
2800
2801     #[derive(Default)]
2802     struct ConstrainedCollector {
2803         regions: FxHashSet<hir::LifetimeName>,
2804     }
2805
2806     impl<'v> Visitor<'v> for ConstrainedCollector {
2807         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2808             NestedVisitorMap::None
2809         }
2810
2811         fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2812             match ty.kind {
2813                 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2814                 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2815                     // ignore lifetimes appearing in associated type
2816                     // projections, as they are not *constrained*
2817                     // (defined above)
2818                 }
2819
2820                 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2821                     // consider only the lifetimes on the final
2822                     // segment; I am not sure it's even currently
2823                     // valid to have them elsewhere, but even if it
2824                     // is, those would be potentially inputs to
2825                     // projections
2826                     if let Some(last_segment) = path.segments.last() {
2827                         self.visit_path_segment(path.span, last_segment);
2828                     }
2829                 }
2830
2831                 _ => {
2832                     intravisit::walk_ty(self, ty);
2833                 }
2834             }
2835         }
2836
2837         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2838             self.regions.insert(lifetime_ref.name.modern());
2839         }
2840     }
2841
2842     #[derive(Default)]
2843     struct AllCollector {
2844         regions: FxHashSet<hir::LifetimeName>,
2845     }
2846
2847     impl<'v> Visitor<'v> for AllCollector {
2848         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2849             NestedVisitorMap::None
2850         }
2851
2852         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2853             self.regions.insert(lifetime_ref.name.modern());
2854         }
2855     }
2856 }
2857
2858 fn report_missing_lifetime_specifiers(
2859     sess: &Session,
2860     span: Span,
2861     count: usize,
2862 ) -> DiagnosticBuilder<'_> {
2863     struct_span_err!(sess, span, E0106, "missing lifetime specifier{}", pluralize!(count))
2864 }
2865
2866 fn add_missing_lifetime_specifiers_label(
2867     err: &mut DiagnosticBuilder<'_>,
2868     span: Span,
2869     count: usize,
2870     lifetime_names: &FxHashSet<ast::Ident>,
2871     snippet: Option<&str>,
2872 ) {
2873     if count > 1 {
2874         err.span_label(span, format!("expected {} lifetime parameters", count));
2875     } else if let (1, Some(name), Some("&")) =
2876         (lifetime_names.len(), lifetime_names.iter().next(), snippet)
2877     {
2878         err.span_suggestion(
2879             span,
2880             "consider using the named lifetime",
2881             format!("&{} ", name),
2882             Applicability::MaybeIncorrect,
2883         );
2884     } else {
2885         err.span_label(span, "expected lifetime parameter");
2886     }
2887 }