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