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