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