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