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