]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late/lifetimes.rs
Rollup merge of #74555 - GuillaumeGomez:important-traits-popup, r=Manishearth
[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                 None
1302             }
1303         })
1304         .collect()
1305 }
1306
1307 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1308     // FIXME(#37666) this works around a limitation in the region inferencer
1309     fn hack<F>(&mut self, f: F)
1310     where
1311         F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1312     {
1313         f(self)
1314     }
1315
1316     fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1317     where
1318         F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1319     {
1320         let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1321         let labels_in_fn = take(&mut self.labels_in_fn);
1322         let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1323         let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1324         let mut this = LifetimeContext {
1325             tcx: *tcx,
1326             map,
1327             scope: &wrap_scope,
1328             trait_ref_hack: self.trait_ref_hack,
1329             is_in_fn_syntax: self.is_in_fn_syntax,
1330             is_in_const_generic: self.is_in_const_generic,
1331             labels_in_fn,
1332             xcrate_object_lifetime_defaults,
1333             lifetime_uses,
1334             missing_named_lifetime_spots,
1335         };
1336         debug!("entering scope {:?}", this.scope);
1337         f(self.scope, &mut this);
1338         this.check_uses_for_lifetimes_defined_by_scope();
1339         debug!("exiting scope {:?}", this.scope);
1340         self.labels_in_fn = this.labels_in_fn;
1341         self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1342         self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1343     }
1344
1345     /// helper method to determine the span to remove when suggesting the
1346     /// deletion of a lifetime
1347     fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1348         generics.params.iter().enumerate().find_map(|(i, param)| {
1349             if param.name.ident() == name {
1350                 let mut in_band = false;
1351                 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1352                     if let hir::LifetimeParamKind::InBand = kind {
1353                         in_band = true;
1354                     }
1355                 }
1356                 if in_band {
1357                     Some(param.span)
1358                 } else {
1359                     if generics.params.len() == 1 {
1360                         // if sole lifetime, remove the entire `<>` brackets
1361                         Some(generics.span)
1362                     } else {
1363                         // if removing within `<>` brackets, we also want to
1364                         // delete a leading or trailing comma as appropriate
1365                         if i >= generics.params.len() - 1 {
1366                             Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1367                         } else {
1368                             Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1369                         }
1370                     }
1371                 }
1372             } else {
1373                 None
1374             }
1375         })
1376     }
1377
1378     // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1379     // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1380     fn suggest_eliding_single_use_lifetime(
1381         &self,
1382         err: &mut DiagnosticBuilder<'_>,
1383         def_id: DefId,
1384         lifetime: &hir::Lifetime,
1385     ) {
1386         let name = lifetime.name.ident();
1387         let mut remove_decl = None;
1388         if let Some(parent_def_id) = self.tcx.parent(def_id) {
1389             if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1390                 remove_decl = self.lifetime_deletion_span(name, generics);
1391             }
1392         }
1393
1394         let mut remove_use = None;
1395         let mut elide_use = None;
1396         let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1397             for input in inputs {
1398                 match input.kind {
1399                     hir::TyKind::Rptr(lt, _) => {
1400                         if lt.name.ident() == name {
1401                             // include the trailing whitespace between the lifetime and type names
1402                             let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1403                             remove_use = Some(
1404                                 self.tcx
1405                                     .sess
1406                                     .source_map()
1407                                     .span_until_non_whitespace(lt_through_ty_span),
1408                             );
1409                             break;
1410                         }
1411                     }
1412                     hir::TyKind::Path(ref qpath) => {
1413                         if let QPath::Resolved(_, path) = qpath {
1414                             let last_segment = &path.segments[path.segments.len() - 1];
1415                             let generics = last_segment.generic_args();
1416                             for arg in generics.args.iter() {
1417                                 if let GenericArg::Lifetime(lt) = arg {
1418                                     if lt.name.ident() == name {
1419                                         elide_use = Some(lt.span);
1420                                         break;
1421                                     }
1422                                 }
1423                             }
1424                             break;
1425                         }
1426                     }
1427                     _ => {}
1428                 }
1429             }
1430         };
1431         if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1432             if let Some(parent) =
1433                 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1434             {
1435                 match parent {
1436                     Node::Item(item) => {
1437                         if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1438                             find_arg_use_span(sig.decl.inputs);
1439                         }
1440                     }
1441                     Node::ImplItem(impl_item) => {
1442                         if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1443                             find_arg_use_span(sig.decl.inputs);
1444                         }
1445                     }
1446                     _ => {}
1447                 }
1448             }
1449         }
1450
1451         let msg = "elide the single-use lifetime";
1452         match (remove_decl, remove_use, elide_use) {
1453             (Some(decl_span), Some(use_span), None) => {
1454                 // if both declaration and use deletion spans start at the same
1455                 // place ("start at" because the latter includes trailing
1456                 // whitespace), then this is an in-band lifetime
1457                 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1458                     err.span_suggestion(
1459                         use_span,
1460                         msg,
1461                         String::new(),
1462                         Applicability::MachineApplicable,
1463                     );
1464                 } else {
1465                     err.multipart_suggestion(
1466                         msg,
1467                         vec![(decl_span, String::new()), (use_span, String::new())],
1468                         Applicability::MachineApplicable,
1469                     );
1470                 }
1471             }
1472             (Some(decl_span), None, Some(use_span)) => {
1473                 err.multipart_suggestion(
1474                     msg,
1475                     vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1476                     Applicability::MachineApplicable,
1477                 );
1478             }
1479             _ => {}
1480         }
1481     }
1482
1483     fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1484         let defined_by = match self.scope {
1485             Scope::Binder { lifetimes, .. } => lifetimes,
1486             _ => {
1487                 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1488                 return;
1489             }
1490         };
1491
1492         let mut def_ids: Vec<_> = defined_by
1493             .values()
1494             .flat_map(|region| match region {
1495                 Region::EarlyBound(_, def_id, _)
1496                 | Region::LateBound(_, def_id, _)
1497                 | Region::Free(_, def_id) => Some(*def_id),
1498
1499                 Region::LateBoundAnon(..) | Region::Static => None,
1500             })
1501             .collect();
1502
1503         // ensure that we issue lints in a repeatable order
1504         def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1505
1506         for def_id in def_ids {
1507             debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1508
1509             let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1510
1511             debug!(
1512                 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1513                 lifetimeuseset
1514             );
1515
1516             match lifetimeuseset {
1517                 Some(LifetimeUseSet::One(lifetime)) => {
1518                     let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1519                     debug!("hir id first={:?}", hir_id);
1520                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1521                         Node::Lifetime(hir_lifetime) => Some((
1522                             hir_lifetime.hir_id,
1523                             hir_lifetime.span,
1524                             hir_lifetime.name.ident(),
1525                         )),
1526                         Node::GenericParam(param) => {
1527                             Some((param.hir_id, param.span, param.name.ident()))
1528                         }
1529                         _ => None,
1530                     } {
1531                         debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1532                         if name.name == kw::UnderscoreLifetime {
1533                             continue;
1534                         }
1535
1536                         if let Some(parent_def_id) = self.tcx.parent(def_id) {
1537                             if let Some(def_id) = parent_def_id.as_local() {
1538                                 let parent_hir_id = self.tcx.hir().as_local_hir_id(def_id);
1539                                 // lifetimes in `derive` expansions don't count (Issue #53738)
1540                                 if self
1541                                     .tcx
1542                                     .hir()
1543                                     .attrs(parent_hir_id)
1544                                     .iter()
1545                                     .any(|attr| attr.check_name(sym::automatically_derived))
1546                                 {
1547                                     continue;
1548                                 }
1549                             }
1550                         }
1551
1552                         self.tcx.struct_span_lint_hir(
1553                             lint::builtin::SINGLE_USE_LIFETIMES,
1554                             id,
1555                             span,
1556                             |lint| {
1557                                 let mut err = lint.build(&format!(
1558                                     "lifetime parameter `{}` only used once",
1559                                     name
1560                                 ));
1561                                 if span == lifetime.span {
1562                                     // spans are the same for in-band lifetime declarations
1563                                     err.span_label(span, "this lifetime is only used here");
1564                                 } else {
1565                                     err.span_label(span, "this lifetime...");
1566                                     err.span_label(lifetime.span, "...is used only here");
1567                                 }
1568                                 self.suggest_eliding_single_use_lifetime(
1569                                     &mut err, def_id, lifetime,
1570                                 );
1571                                 err.emit();
1572                             },
1573                         );
1574                     }
1575                 }
1576                 Some(LifetimeUseSet::Many) => {
1577                     debug!("not one use lifetime");
1578                 }
1579                 None => {
1580                     let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1581                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1582                         Node::Lifetime(hir_lifetime) => Some((
1583                             hir_lifetime.hir_id,
1584                             hir_lifetime.span,
1585                             hir_lifetime.name.ident(),
1586                         )),
1587                         Node::GenericParam(param) => {
1588                             Some((param.hir_id, param.span, param.name.ident()))
1589                         }
1590                         _ => None,
1591                     } {
1592                         debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1593                         self.tcx.struct_span_lint_hir(
1594                             lint::builtin::UNUSED_LIFETIMES,
1595                             id,
1596                             span,
1597                             |lint| {
1598                                 let mut err = lint
1599                                     .build(&format!("lifetime parameter `{}` never used", name));
1600                                 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1601                                     if let Some(generics) =
1602                                         self.tcx.hir().get_generics(parent_def_id)
1603                                     {
1604                                         let unused_lt_span =
1605                                             self.lifetime_deletion_span(name, generics);
1606                                         if let Some(span) = unused_lt_span {
1607                                             err.span_suggestion(
1608                                                 span,
1609                                                 "elide the unused lifetime",
1610                                                 String::new(),
1611                                                 Applicability::MachineApplicable,
1612                                             );
1613                                         }
1614                                     }
1615                                 }
1616                                 err.emit();
1617                             },
1618                         );
1619                     }
1620                 }
1621             }
1622         }
1623     }
1624
1625     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1626     ///
1627     /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1628     /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1629     /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1630     ///
1631     /// For example:
1632     ///
1633     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
1634     ///
1635     /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1636     /// lifetimes may be interspersed together.
1637     ///
1638     /// If early bound lifetimes are present, we separate them into their own list (and likewise
1639     /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1640     /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1641     /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1642     /// ordering is not important there.
1643     fn visit_early_late<F>(
1644         &mut self,
1645         parent_id: Option<hir::HirId>,
1646         decl: &'tcx hir::FnDecl<'tcx>,
1647         generics: &'tcx hir::Generics<'tcx>,
1648         walk: F,
1649     ) where
1650         F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1651     {
1652         insert_late_bound_lifetimes(self.map, decl, generics);
1653
1654         // Find the start of nested early scopes, e.g., in methods.
1655         let mut index = 0;
1656         if let Some(parent_id) = parent_id {
1657             let parent = self.tcx.hir().expect_item(parent_id);
1658             if sub_items_have_self_param(&parent.kind) {
1659                 index += 1; // Self comes before lifetimes
1660             }
1661             match parent.kind {
1662                 hir::ItemKind::Trait(_, _, ref generics, ..)
1663                 | hir::ItemKind::Impl { ref generics, .. } => {
1664                     index += generics.params.len() as u32;
1665                 }
1666                 _ => {}
1667             }
1668         }
1669
1670         let mut non_lifetime_count = 0;
1671         let lifetimes = generics
1672             .params
1673             .iter()
1674             .filter_map(|param| match param.kind {
1675                 GenericParamKind::Lifetime { .. } => {
1676                     if self.map.late_bound.contains(&param.hir_id) {
1677                         Some(Region::late(&self.tcx.hir(), param))
1678                     } else {
1679                         Some(Region::early(&self.tcx.hir(), &mut index, param))
1680                     }
1681                 }
1682                 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1683                     non_lifetime_count += 1;
1684                     None
1685                 }
1686             })
1687             .collect();
1688         let next_early_index = index + non_lifetime_count;
1689
1690         let scope = Scope::Binder {
1691             lifetimes,
1692             next_early_index,
1693             s: self.scope,
1694             opaque_type_parent: true,
1695             track_lifetime_uses: false,
1696         };
1697         self.with(scope, move |old_scope, this| {
1698             this.check_lifetime_params(old_scope, &generics.params);
1699             this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1700         });
1701     }
1702
1703     fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1704         let mut scope = self.scope;
1705         loop {
1706             match *scope {
1707                 Scope::Root => return 0,
1708
1709                 Scope::Binder { next_early_index, opaque_type_parent, .. }
1710                     if (!only_opaque_type_parent || opaque_type_parent) =>
1711                 {
1712                     return next_early_index;
1713                 }
1714
1715                 Scope::Binder { s, .. }
1716                 | Scope::Body { s, .. }
1717                 | Scope::Elision { s, .. }
1718                 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1719             }
1720         }
1721     }
1722
1723     /// Returns the next index one would use for an early-bound-region
1724     /// if extending the current scope.
1725     fn next_early_index(&self) -> u32 {
1726         self.next_early_index_helper(true)
1727     }
1728
1729     /// Returns the next index one would use for an `impl Trait` that
1730     /// is being converted into an opaque type alias `impl Trait`. This will be the
1731     /// next early index from the enclosing item, for the most
1732     /// part. See the `opaque_type_parent` field for more info.
1733     fn next_early_index_for_opaque_type(&self) -> u32 {
1734         self.next_early_index_helper(false)
1735     }
1736
1737     fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1738         debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1739
1740         // If we've already reported an error, just ignore `lifetime_ref`.
1741         if let LifetimeName::Error = lifetime_ref.name {
1742             return;
1743         }
1744
1745         // Walk up the scope chain, tracking the number of fn scopes
1746         // that we pass through, until we find a lifetime with the
1747         // given name or we run out of scopes.
1748         // search.
1749         let mut late_depth = 0;
1750         let mut scope = self.scope;
1751         let mut outermost_body = None;
1752         let result = loop {
1753             match *scope {
1754                 Scope::Body { id, s } => {
1755                     outermost_body = Some(id);
1756                     scope = s;
1757                 }
1758
1759                 Scope::Root => {
1760                     break None;
1761                 }
1762
1763                 Scope::Binder { ref lifetimes, s, .. } => {
1764                     match lifetime_ref.name {
1765                         LifetimeName::Param(param_name) => {
1766                             if let Some(&def) = lifetimes.get(&param_name.normalize_to_macros_2_0())
1767                             {
1768                                 break Some(def.shifted(late_depth));
1769                             }
1770                         }
1771                         _ => bug!("expected LifetimeName::Param"),
1772                     }
1773
1774                     late_depth += 1;
1775                     scope = s;
1776                 }
1777
1778                 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1779                     scope = s;
1780                 }
1781             }
1782         };
1783
1784         if let Some(mut def) = result {
1785             if let Region::EarlyBound(..) = def {
1786                 // Do not free early-bound regions, only late-bound ones.
1787             } else if let Some(body_id) = outermost_body {
1788                 let fn_id = self.tcx.hir().body_owner(body_id);
1789                 match self.tcx.hir().get(fn_id) {
1790                     Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1791                     | Node::TraitItem(&hir::TraitItem {
1792                         kind: hir::TraitItemKind::Fn(..), ..
1793                     })
1794                     | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
1795                         let scope = self.tcx.hir().local_def_id(fn_id);
1796                         def = Region::Free(scope.to_def_id(), def.id().unwrap());
1797                     }
1798                     _ => {}
1799                 }
1800             }
1801
1802             // Check for fn-syntax conflicts with in-band lifetime definitions
1803             if self.is_in_fn_syntax {
1804                 match def {
1805                     Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1806                     | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1807                         struct_span_err!(
1808                             self.tcx.sess,
1809                             lifetime_ref.span,
1810                             E0687,
1811                             "lifetimes used in `fn` or `Fn` syntax must be \
1812                              explicitly declared using `<...>` binders"
1813                         )
1814                         .span_label(lifetime_ref.span, "in-band lifetime definition")
1815                         .emit();
1816                     }
1817
1818                     Region::Static
1819                     | Region::EarlyBound(
1820                         _,
1821                         _,
1822                         LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1823                     )
1824                     | Region::LateBound(
1825                         _,
1826                         _,
1827                         LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1828                     )
1829                     | Region::LateBoundAnon(..)
1830                     | Region::Free(..) => {}
1831                 }
1832             }
1833
1834             self.insert_lifetime(lifetime_ref, def);
1835         } else {
1836             self.emit_undeclared_lifetime_error(lifetime_ref);
1837         }
1838     }
1839
1840     fn visit_segment_args(
1841         &mut self,
1842         res: Res,
1843         depth: usize,
1844         generic_args: &'tcx hir::GenericArgs<'tcx>,
1845     ) {
1846         debug!(
1847             "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1848             res, depth, generic_args,
1849         );
1850
1851         if generic_args.parenthesized {
1852             let was_in_fn_syntax = self.is_in_fn_syntax;
1853             self.is_in_fn_syntax = true;
1854             self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1855             self.is_in_fn_syntax = was_in_fn_syntax;
1856             return;
1857         }
1858
1859         let mut elide_lifetimes = true;
1860         let lifetimes = generic_args
1861             .args
1862             .iter()
1863             .filter_map(|arg| match arg {
1864                 hir::GenericArg::Lifetime(lt) => {
1865                     if !lt.is_elided() {
1866                         elide_lifetimes = false;
1867                     }
1868                     Some(lt)
1869                 }
1870                 _ => None,
1871             })
1872             .collect();
1873         if elide_lifetimes {
1874             self.resolve_elided_lifetimes(lifetimes);
1875         } else {
1876             lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1877         }
1878
1879         // Figure out if this is a type/trait segment,
1880         // which requires object lifetime defaults.
1881         let parent_def_id = |this: &mut Self, def_id: DefId| {
1882             let def_key = this.tcx.def_key(def_id);
1883             DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1884         };
1885         let type_def_id = match res {
1886             Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1887             Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1888             Res::Def(
1889                 DefKind::Struct
1890                 | DefKind::Union
1891                 | DefKind::Enum
1892                 | DefKind::TyAlias
1893                 | DefKind::Trait,
1894                 def_id,
1895             ) if depth == 0 => Some(def_id),
1896             _ => None,
1897         };
1898
1899         debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1900
1901         // Compute a vector of defaults, one for each type parameter,
1902         // per the rules given in RFCs 599 and 1156. Example:
1903         //
1904         // ```rust
1905         // struct Foo<'a, T: 'a, U> { }
1906         // ```
1907         //
1908         // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1909         // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1910         // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1911         // such bound).
1912         //
1913         // Therefore, we would compute `object_lifetime_defaults` to a
1914         // vector like `['x, 'static]`. Note that the vector only
1915         // includes type parameters.
1916         let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1917             let in_body = {
1918                 let mut scope = self.scope;
1919                 loop {
1920                     match *scope {
1921                         Scope::Root => break false,
1922
1923                         Scope::Body { .. } => break true,
1924
1925                         Scope::Binder { s, .. }
1926                         | Scope::Elision { s, .. }
1927                         | Scope::ObjectLifetimeDefault { s, .. } => {
1928                             scope = s;
1929                         }
1930                     }
1931                 }
1932             };
1933
1934             let map = &self.map;
1935             let unsubst = if let Some(def_id) = def_id.as_local() {
1936                 let id = self.tcx.hir().as_local_hir_id(def_id);
1937                 &map.object_lifetime_defaults[&id]
1938             } else {
1939                 let tcx = self.tcx;
1940                 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
1941                     tcx.generics_of(def_id)
1942                         .params
1943                         .iter()
1944                         .filter_map(|param| match param.kind {
1945                             GenericParamDefKind::Type { object_lifetime_default, .. } => {
1946                                 Some(object_lifetime_default)
1947                             }
1948                             GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1949                         })
1950                         .collect()
1951                 })
1952             };
1953             debug!("visit_segment_args: unsubst={:?}", unsubst);
1954             unsubst
1955                 .iter()
1956                 .map(|set| match *set {
1957                     Set1::Empty => {
1958                         if in_body {
1959                             None
1960                         } else {
1961                             Some(Region::Static)
1962                         }
1963                     }
1964                     Set1::One(r) => {
1965                         let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1966                             GenericArg::Lifetime(lt) => Some(lt),
1967                             _ => None,
1968                         });
1969                         r.subst(lifetimes, map)
1970                     }
1971                     Set1::Many => None,
1972                 })
1973                 .collect()
1974         });
1975
1976         debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
1977
1978         let mut i = 0;
1979         for arg in generic_args.args {
1980             match arg {
1981                 GenericArg::Lifetime(_) => {}
1982                 GenericArg::Type(ty) => {
1983                     if let Some(&lt) = object_lifetime_defaults.get(i) {
1984                         let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1985                         self.with(scope, |_, this| this.visit_ty(ty));
1986                     } else {
1987                         self.visit_ty(ty);
1988                     }
1989                     i += 1;
1990                 }
1991                 GenericArg::Const(ct) => {
1992                     self.visit_anon_const(&ct.value);
1993                 }
1994             }
1995         }
1996
1997         // Hack: when resolving the type `XX` in binding like `dyn
1998         // Foo<'b, Item = XX>`, the current object-lifetime default
1999         // would be to examine the trait `Foo` to check whether it has
2000         // a lifetime bound declared on `Item`. e.g., if `Foo` is
2001         // declared like so, then the default object lifetime bound in
2002         // `XX` should be `'b`:
2003         //
2004         // ```rust
2005         // trait Foo<'a> {
2006         //   type Item: 'a;
2007         // }
2008         // ```
2009         //
2010         // but if we just have `type Item;`, then it would be
2011         // `'static`. However, we don't get all of this logic correct.
2012         //
2013         // Instead, we do something hacky: if there are no lifetime parameters
2014         // to the trait, then we simply use a default object lifetime
2015         // bound of `'static`, because there is no other possibility. On the other hand,
2016         // if there ARE lifetime parameters, then we require the user to give an
2017         // explicit bound for now.
2018         //
2019         // This is intended to leave room for us to implement the
2020         // correct behavior in the future.
2021         let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
2022             GenericArg::Lifetime(_) => true,
2023             _ => false,
2024         });
2025
2026         // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2027         for b in generic_args.bindings {
2028             let scope = Scope::ObjectLifetimeDefault {
2029                 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2030                 s: self.scope,
2031             };
2032             self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2033         }
2034     }
2035
2036     fn visit_fn_like_elision(
2037         &mut self,
2038         inputs: &'tcx [hir::Ty<'tcx>],
2039         output: Option<&'tcx hir::Ty<'tcx>>,
2040     ) {
2041         debug!("visit_fn_like_elision: enter");
2042         let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2043         let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
2044         self.with(arg_scope, |_, this| {
2045             for input in inputs {
2046                 this.visit_ty(input);
2047             }
2048             match *this.scope {
2049                 Scope::Elision { ref elide, .. } => {
2050                     arg_elide = elide.clone();
2051                 }
2052                 _ => bug!(),
2053             }
2054         });
2055
2056         let output = match output {
2057             Some(ty) => ty,
2058             None => return,
2059         };
2060
2061         debug!("visit_fn_like_elision: determine output");
2062
2063         // Figure out if there's a body we can get argument names from,
2064         // and whether there's a `self` argument (treated specially).
2065         let mut assoc_item_kind = None;
2066         let mut impl_self = None;
2067         let parent = self.tcx.hir().get_parent_node(output.hir_id);
2068         let body = match self.tcx.hir().get(parent) {
2069             // `fn` definitions and methods.
2070             Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2071
2072             Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2073                 if let hir::ItemKind::Trait(.., ref trait_items) =
2074                     self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2075                 {
2076                     assoc_item_kind =
2077                         trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
2078                 }
2079                 match *m {
2080                     hir::TraitFn::Required(_) => None,
2081                     hir::TraitFn::Provided(body) => Some(body),
2082                 }
2083             }
2084
2085             Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2086                 if let hir::ItemKind::Impl { ref self_ty, ref items, .. } =
2087                     self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2088                 {
2089                     impl_self = Some(self_ty);
2090                     assoc_item_kind =
2091                         items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
2092                 }
2093                 Some(body)
2094             }
2095
2096             // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2097             Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2098             // Everything else (only closures?) doesn't
2099             // actually enjoy elision in return types.
2100             _ => {
2101                 self.visit_ty(output);
2102                 return;
2103             }
2104         };
2105
2106         let has_self = match assoc_item_kind {
2107             Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2108             _ => false,
2109         };
2110
2111         // In accordance with the rules for lifetime elision, we can determine
2112         // what region to use for elision in the output type in two ways.
2113         // First (determined here), if `self` is by-reference, then the
2114         // implied output region is the region of the self parameter.
2115         if has_self {
2116             struct SelfVisitor<'a> {
2117                 map: &'a NamedRegionMap,
2118                 impl_self: Option<&'a hir::TyKind<'a>>,
2119                 lifetime: Set1<Region>,
2120             }
2121
2122             impl SelfVisitor<'_> {
2123                 // Look for `self: &'a Self` - also desugared from `&'a self`,
2124                 // and if that matches, use it for elision and return early.
2125                 fn is_self_ty(&self, res: Res) -> bool {
2126                     if let Res::SelfTy(..) = res {
2127                         return true;
2128                     }
2129
2130                     // Can't always rely on literal (or implied) `Self` due
2131                     // to the way elision rules were originally specified.
2132                     if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2133                         self.impl_self
2134                     {
2135                         match path.res {
2136                             // Permit the types that unambiguously always
2137                             // result in the same type constructor being used
2138                             // (it can't differ between `Self` and `self`).
2139                             Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2140                             | Res::PrimTy(_) => return res == path.res,
2141                             _ => {}
2142                         }
2143                     }
2144
2145                     false
2146                 }
2147             }
2148
2149             impl<'a> Visitor<'a> for SelfVisitor<'a> {
2150                 type Map = intravisit::ErasedMap<'a>;
2151
2152                 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2153                     NestedVisitorMap::None
2154                 }
2155
2156                 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2157                     if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2158                         if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2159                         {
2160                             if self.is_self_ty(path.res) {
2161                                 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2162                                     self.lifetime.insert(*lifetime);
2163                                 }
2164                             }
2165                         }
2166                     }
2167                     intravisit::walk_ty(self, ty)
2168                 }
2169             }
2170
2171             let mut visitor = SelfVisitor {
2172                 map: self.map,
2173                 impl_self: impl_self.map(|ty| &ty.kind),
2174                 lifetime: Set1::Empty,
2175             };
2176             visitor.visit_ty(&inputs[0]);
2177             if let Set1::One(lifetime) = visitor.lifetime {
2178                 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2179                 self.with(scope, |_, this| this.visit_ty(output));
2180                 return;
2181             }
2182         }
2183
2184         // Second, if there was exactly one lifetime (either a substitution or a
2185         // reference) in the arguments, then any anonymous regions in the output
2186         // have that lifetime.
2187         let mut possible_implied_output_region = None;
2188         let mut lifetime_count = 0;
2189         let arg_lifetimes = inputs
2190             .iter()
2191             .enumerate()
2192             .skip(has_self as usize)
2193             .map(|(i, input)| {
2194                 let mut gather = GatherLifetimes {
2195                     map: self.map,
2196                     outer_index: ty::INNERMOST,
2197                     have_bound_regions: false,
2198                     lifetimes: Default::default(),
2199                 };
2200                 gather.visit_ty(input);
2201
2202                 lifetime_count += gather.lifetimes.len();
2203
2204                 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2205                     // there's a chance that the unique lifetime of this
2206                     // iteration will be the appropriate lifetime for output
2207                     // parameters, so lets store it.
2208                     possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2209                 }
2210
2211                 ElisionFailureInfo {
2212                     parent: body,
2213                     index: i,
2214                     lifetime_count: gather.lifetimes.len(),
2215                     have_bound_regions: gather.have_bound_regions,
2216                     span: input.span,
2217                 }
2218             })
2219             .collect();
2220
2221         let elide = if lifetime_count == 1 {
2222             Elide::Exact(possible_implied_output_region.unwrap())
2223         } else {
2224             Elide::Error(arg_lifetimes)
2225         };
2226
2227         debug!("visit_fn_like_elision: elide={:?}", elide);
2228
2229         let scope = Scope::Elision { elide, s: self.scope };
2230         self.with(scope, |_, this| this.visit_ty(output));
2231         debug!("visit_fn_like_elision: exit");
2232
2233         struct GatherLifetimes<'a> {
2234             map: &'a NamedRegionMap,
2235             outer_index: ty::DebruijnIndex,
2236             have_bound_regions: bool,
2237             lifetimes: FxHashSet<Region>,
2238         }
2239
2240         impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2241             type Map = intravisit::ErasedMap<'v>;
2242
2243             fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2244                 NestedVisitorMap::None
2245             }
2246
2247             fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2248                 if let hir::TyKind::BareFn(_) = ty.kind {
2249                     self.outer_index.shift_in(1);
2250                 }
2251                 match ty.kind {
2252                     hir::TyKind::TraitObject(bounds, ref lifetime) => {
2253                         for bound in bounds {
2254                             self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2255                         }
2256
2257                         // Stay on the safe side and don't include the object
2258                         // lifetime default (which may not end up being used).
2259                         if !lifetime.is_elided() {
2260                             self.visit_lifetime(lifetime);
2261                         }
2262                     }
2263                     _ => {
2264                         intravisit::walk_ty(self, ty);
2265                     }
2266                 }
2267                 if let hir::TyKind::BareFn(_) = ty.kind {
2268                     self.outer_index.shift_out(1);
2269                 }
2270             }
2271
2272             fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2273                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2274                     // FIXME(eddyb) Do we want this? It only makes a difference
2275                     // if this `for<'a>` lifetime parameter is never used.
2276                     self.have_bound_regions = true;
2277                 }
2278
2279                 intravisit::walk_generic_param(self, param);
2280             }
2281
2282             fn visit_poly_trait_ref(
2283                 &mut self,
2284                 trait_ref: &hir::PolyTraitRef<'_>,
2285                 modifier: hir::TraitBoundModifier,
2286             ) {
2287                 self.outer_index.shift_in(1);
2288                 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2289                 self.outer_index.shift_out(1);
2290             }
2291
2292             fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2293                 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2294                     match lifetime {
2295                         Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2296                             if debruijn < self.outer_index =>
2297                         {
2298                             self.have_bound_regions = true;
2299                         }
2300                         _ => {
2301                             self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2302                         }
2303                     }
2304                 }
2305             }
2306         }
2307     }
2308
2309     fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2310         debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2311
2312         if lifetime_refs.is_empty() {
2313             return;
2314         }
2315
2316         let span = lifetime_refs[0].span;
2317         let mut late_depth = 0;
2318         let mut scope = self.scope;
2319         let mut lifetime_names = FxHashSet::default();
2320         let error = loop {
2321             match *scope {
2322                 // Do not assign any resolution, it will be inferred.
2323                 Scope::Body { .. } => return,
2324
2325                 Scope::Root => break None,
2326
2327                 Scope::Binder { s, ref lifetimes, .. } => {
2328                     // collect named lifetimes for suggestions
2329                     for name in lifetimes.keys() {
2330                         if let hir::ParamName::Plain(name) = name {
2331                             lifetime_names.insert(*name);
2332                         }
2333                     }
2334                     late_depth += 1;
2335                     scope = s;
2336                 }
2337
2338                 Scope::Elision { ref elide, ref s, .. } => {
2339                     let lifetime = match *elide {
2340                         Elide::FreshLateAnon(ref counter) => {
2341                             for lifetime_ref in lifetime_refs {
2342                                 let lifetime = Region::late_anon(counter).shifted(late_depth);
2343                                 self.insert_lifetime(lifetime_ref, lifetime);
2344                             }
2345                             return;
2346                         }
2347                         Elide::Exact(l) => l.shifted(late_depth),
2348                         Elide::Error(ref e) => {
2349                             if let Scope::Binder { ref lifetimes, .. } = s {
2350                                 // collect named lifetimes for suggestions
2351                                 for name in lifetimes.keys() {
2352                                     if let hir::ParamName::Plain(name) = name {
2353                                         lifetime_names.insert(*name);
2354                                     }
2355                                 }
2356                             }
2357                             break Some(e);
2358                         }
2359                         Elide::Forbid => break None,
2360                     };
2361                     for lifetime_ref in lifetime_refs {
2362                         self.insert_lifetime(lifetime_ref, lifetime);
2363                     }
2364                     return;
2365                 }
2366
2367                 Scope::ObjectLifetimeDefault { s, .. } => {
2368                     scope = s;
2369                 }
2370             }
2371         };
2372
2373         let mut err = self.report_missing_lifetime_specifiers(span, lifetime_refs.len());
2374
2375         if let Some(params) = error {
2376             // If there's no lifetime available, suggest `'static`.
2377             if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
2378                 lifetime_names.insert(Ident::with_dummy_span(kw::StaticLifetime));
2379             }
2380         }
2381         self.add_missing_lifetime_specifiers_label(
2382             &mut err,
2383             span,
2384             lifetime_refs.len(),
2385             &lifetime_names,
2386             error.map(|p| &p[..]).unwrap_or(&[]),
2387         );
2388         err.emit();
2389     }
2390
2391     fn report_elision_failure(
2392         &mut self,
2393         db: &mut DiagnosticBuilder<'_>,
2394         params: &[ElisionFailureInfo],
2395     ) -> bool /* add `'static` lifetime to lifetime list */ {
2396         let mut m = String::new();
2397         let len = params.len();
2398
2399         let elided_params: Vec<_> =
2400             params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2401
2402         let elided_len = elided_params.len();
2403
2404         for (i, info) in elided_params.into_iter().enumerate() {
2405             let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2406                 info;
2407
2408             db.span_label(span, "");
2409             let help_name = if let Some(ident) =
2410                 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2411             {
2412                 format!("`{}`", ident)
2413             } else {
2414                 format!("argument {}", index + 1)
2415             };
2416
2417             m.push_str(
2418                 &(if n == 1 {
2419                     help_name
2420                 } else {
2421                     format!(
2422                         "one of {}'s {} {}lifetimes",
2423                         help_name,
2424                         n,
2425                         if have_bound_regions { "free " } else { "" }
2426                     )
2427                 })[..],
2428             );
2429
2430             if elided_len == 2 && i == 0 {
2431                 m.push_str(" or ");
2432             } else if i + 2 == elided_len {
2433                 m.push_str(", or ");
2434             } else if i != elided_len - 1 {
2435                 m.push_str(", ");
2436             }
2437         }
2438
2439         if len == 0 {
2440             db.help(
2441                 "this function's return type contains a borrowed value, \
2442                  but there is no value for it to be borrowed from",
2443             );
2444             true
2445         } else if elided_len == 0 {
2446             db.help(
2447                 "this function's return type contains a borrowed value with \
2448                  an elided lifetime, but the lifetime cannot be derived from \
2449                  the arguments",
2450             );
2451             true
2452         } else if elided_len == 1 {
2453             db.help(&format!(
2454                 "this function's return type contains a borrowed value, \
2455                  but the signature does not say which {} it is borrowed from",
2456                 m
2457             ));
2458             false
2459         } else {
2460             db.help(&format!(
2461                 "this function's return type contains a borrowed value, \
2462                  but the signature does not say whether it is borrowed from {}",
2463                 m
2464             ));
2465             false
2466         }
2467     }
2468
2469     fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2470         debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2471         let mut late_depth = 0;
2472         let mut scope = self.scope;
2473         let lifetime = loop {
2474             match *scope {
2475                 Scope::Binder { s, .. } => {
2476                     late_depth += 1;
2477                     scope = s;
2478                 }
2479
2480                 Scope::Root | Scope::Elision { .. } => break Region::Static,
2481
2482                 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2483
2484                 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2485             }
2486         };
2487         self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2488     }
2489
2490     fn check_lifetime_params(
2491         &mut self,
2492         old_scope: ScopeRef<'_>,
2493         params: &'tcx [hir::GenericParam<'tcx>],
2494     ) {
2495         let lifetimes: Vec<_> = params
2496             .iter()
2497             .filter_map(|param| match param.kind {
2498                 GenericParamKind::Lifetime { .. } => {
2499                     Some((param, param.name.normalize_to_macros_2_0()))
2500                 }
2501                 _ => None,
2502             })
2503             .collect();
2504         for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2505             if let hir::ParamName::Plain(_) = lifetime_i_name {
2506                 let name = lifetime_i_name.ident().name;
2507                 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
2508                     let mut err = struct_span_err!(
2509                         self.tcx.sess,
2510                         lifetime_i.span,
2511                         E0262,
2512                         "invalid lifetime parameter name: `{}`",
2513                         lifetime_i.name.ident(),
2514                     );
2515                     err.span_label(
2516                         lifetime_i.span,
2517                         format!("{} is a reserved lifetime name", name),
2518                     );
2519                     err.emit();
2520                 }
2521             }
2522
2523             // It is a hard error to shadow a lifetime within the same scope.
2524             for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2525                 if lifetime_i_name == lifetime_j_name {
2526                     struct_span_err!(
2527                         self.tcx.sess,
2528                         lifetime_j.span,
2529                         E0263,
2530                         "lifetime name `{}` declared twice in the same scope",
2531                         lifetime_j.name.ident()
2532                     )
2533                     .span_label(lifetime_j.span, "declared twice")
2534                     .span_label(lifetime_i.span, "previous declaration here")
2535                     .emit();
2536                 }
2537             }
2538
2539             // It is a soft error to shadow a lifetime within a parent scope.
2540             self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2541
2542             for bound in lifetime_i.bounds {
2543                 match bound {
2544                     hir::GenericBound::Outlives(ref lt) => match lt.name {
2545                         hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2546                             lt.span,
2547                             "use of `'_` in illegal place, but not caught by lowering",
2548                         ),
2549                         hir::LifetimeName::Static => {
2550                             self.insert_lifetime(lt, Region::Static);
2551                             self.tcx
2552                                 .sess
2553                                 .struct_span_warn(
2554                                     lifetime_i.span.to(lt.span),
2555                                     &format!(
2556                                         "unnecessary lifetime parameter `{}`",
2557                                         lifetime_i.name.ident(),
2558                                     ),
2559                                 )
2560                                 .help(&format!(
2561                                     "you can use the `'static` lifetime directly, in place of `{}`",
2562                                     lifetime_i.name.ident(),
2563                                 ))
2564                                 .emit();
2565                         }
2566                         hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2567                             self.resolve_lifetime_ref(lt);
2568                         }
2569                         hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2570                             self.tcx.sess.delay_span_bug(
2571                                 lt.span,
2572                                 "lowering generated `ImplicitObjectLifetimeDefault` \
2573                                  outside of an object type",
2574                             )
2575                         }
2576                         hir::LifetimeName::Error => {
2577                             // No need to do anything, error already reported.
2578                         }
2579                     },
2580                     _ => bug!(),
2581                 }
2582             }
2583         }
2584     }
2585
2586     fn check_lifetime_param_for_shadowing(
2587         &self,
2588         mut old_scope: ScopeRef<'_>,
2589         param: &'tcx hir::GenericParam<'tcx>,
2590     ) {
2591         for label in &self.labels_in_fn {
2592             // FIXME (#24278): non-hygienic comparison
2593             if param.name.ident().name == label.name {
2594                 signal_shadowing_problem(
2595                     self.tcx,
2596                     label.name,
2597                     original_label(label.span),
2598                     shadower_lifetime(&param),
2599                 );
2600                 return;
2601             }
2602         }
2603
2604         loop {
2605             match *old_scope {
2606                 Scope::Body { s, .. }
2607                 | Scope::Elision { s, .. }
2608                 | Scope::ObjectLifetimeDefault { s, .. } => {
2609                     old_scope = s;
2610                 }
2611
2612                 Scope::Root => {
2613                     return;
2614                 }
2615
2616                 Scope::Binder { ref lifetimes, s, .. } => {
2617                     if let Some(&def) = lifetimes.get(&param.name.normalize_to_macros_2_0()) {
2618                         let hir_id =
2619                             self.tcx.hir().as_local_hir_id(def.id().unwrap().expect_local());
2620
2621                         signal_shadowing_problem(
2622                             self.tcx,
2623                             param.name.ident().name,
2624                             original_lifetime(self.tcx.hir().span(hir_id)),
2625                             shadower_lifetime(&param),
2626                         );
2627                         return;
2628                     }
2629
2630                     old_scope = s;
2631                 }
2632             }
2633         }
2634     }
2635
2636     /// Returns `true` if, in the current scope, replacing `'_` would be
2637     /// equivalent to a single-use lifetime.
2638     fn track_lifetime_uses(&self) -> bool {
2639         let mut scope = self.scope;
2640         loop {
2641             match *scope {
2642                 Scope::Root => break false,
2643
2644                 // Inside of items, it depends on the kind of item.
2645                 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
2646
2647                 // Inside a body, `'_` will use an inference variable,
2648                 // should be fine.
2649                 Scope::Body { .. } => break true,
2650
2651                 // A lifetime only used in a fn argument could as well
2652                 // be replaced with `'_`, as that would generate a
2653                 // fresh name, too.
2654                 Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
2655
2656                 // In the return type or other such place, `'_` is not
2657                 // going to make a fresh name, so we cannot
2658                 // necessarily replace a single-use lifetime with
2659                 // `'_`.
2660                 Scope::Elision {
2661                     elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
2662                 } => break false,
2663
2664                 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2665             }
2666         }
2667     }
2668
2669     fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2670         debug!(
2671             "insert_lifetime: {} resolved to {:?} span={:?}",
2672             self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2673             def,
2674             self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2675         );
2676         self.map.defs.insert(lifetime_ref.hir_id, def);
2677
2678         match def {
2679             Region::LateBoundAnon(..) | Region::Static => {
2680                 // These are anonymous lifetimes or lifetimes that are not declared.
2681             }
2682
2683             Region::Free(_, def_id)
2684             | Region::LateBound(_, def_id, _)
2685             | Region::EarlyBound(_, def_id, _) => {
2686                 // A lifetime declared by the user.
2687                 let track_lifetime_uses = self.track_lifetime_uses();
2688                 debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
2689                 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2690                     debug!("insert_lifetime: first use of {:?}", def_id);
2691                     self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
2692                 } else {
2693                     debug!("insert_lifetime: many uses of {:?}", def_id);
2694                     self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2695                 }
2696             }
2697         }
2698     }
2699
2700     /// Sometimes we resolve a lifetime, but later find that it is an
2701     /// error (esp. around impl trait). In that case, we remove the
2702     /// entry into `map.defs` so as not to confuse later code.
2703     fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2704         let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2705         assert_eq!(old_value, Some(bad_def));
2706     }
2707 }
2708
2709 /// Detects late-bound lifetimes and inserts them into
2710 /// `map.late_bound`.
2711 ///
2712 /// A region declared on a fn is **late-bound** if:
2713 /// - it is constrained by an argument type;
2714 /// - it does not appear in a where-clause.
2715 ///
2716 /// "Constrained" basically means that it appears in any type but
2717 /// not amongst the inputs to a projection. In other words, `<&'a
2718 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2719 fn insert_late_bound_lifetimes(
2720     map: &mut NamedRegionMap,
2721     decl: &hir::FnDecl<'_>,
2722     generics: &hir::Generics<'_>,
2723 ) {
2724     debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
2725
2726     let mut constrained_by_input = ConstrainedCollector::default();
2727     for arg_ty in decl.inputs {
2728         constrained_by_input.visit_ty(arg_ty);
2729     }
2730
2731     let mut appears_in_output = AllCollector::default();
2732     intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2733
2734     debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
2735
2736     // Walk the lifetimes that appear in where clauses.
2737     //
2738     // Subtle point: because we disallow nested bindings, we can just
2739     // ignore binders here and scrape up all names we see.
2740     let mut appears_in_where_clause = AllCollector::default();
2741     appears_in_where_clause.visit_generics(generics);
2742
2743     for param in generics.params {
2744         if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2745             if !param.bounds.is_empty() {
2746                 // `'a: 'b` means both `'a` and `'b` are referenced
2747                 appears_in_where_clause
2748                     .regions
2749                     .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
2750             }
2751         }
2752     }
2753
2754     debug!(
2755         "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2756         appears_in_where_clause.regions
2757     );
2758
2759     // Late bound regions are those that:
2760     // - appear in the inputs
2761     // - do not appear in the where-clauses
2762     // - are not implicitly captured by `impl Trait`
2763     for param in generics.params {
2764         match param.kind {
2765             hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2766
2767             // Neither types nor consts are late-bound.
2768             hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2769         }
2770
2771         let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
2772         // appears in the where clauses? early-bound.
2773         if appears_in_where_clause.regions.contains(&lt_name) {
2774             continue;
2775         }
2776
2777         // does not appear in the inputs, but appears in the return type? early-bound.
2778         if !constrained_by_input.regions.contains(&lt_name)
2779             && appears_in_output.regions.contains(&lt_name)
2780         {
2781             continue;
2782         }
2783
2784         debug!(
2785             "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2786             param.name.ident(),
2787             param.hir_id
2788         );
2789
2790         let inserted = map.late_bound.insert(param.hir_id);
2791         assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2792     }
2793
2794     return;
2795
2796     #[derive(Default)]
2797     struct ConstrainedCollector {
2798         regions: FxHashSet<hir::LifetimeName>,
2799     }
2800
2801     impl<'v> Visitor<'v> for ConstrainedCollector {
2802         type Map = intravisit::ErasedMap<'v>;
2803
2804         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2805             NestedVisitorMap::None
2806         }
2807
2808         fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2809             match ty.kind {
2810                 hir::TyKind::Path(
2811                     hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2812                 ) => {
2813                     // ignore lifetimes appearing in associated type
2814                     // projections, as they are not *constrained*
2815                     // (defined above)
2816                 }
2817
2818                 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2819                     // consider only the lifetimes on the final
2820                     // segment; I am not sure it's even currently
2821                     // valid to have them elsewhere, but even if it
2822                     // is, those would be potentially inputs to
2823                     // projections
2824                     if let Some(last_segment) = path.segments.last() {
2825                         self.visit_path_segment(path.span, last_segment);
2826                     }
2827                 }
2828
2829                 _ => {
2830                     intravisit::walk_ty(self, ty);
2831                 }
2832             }
2833         }
2834
2835         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2836             self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
2837         }
2838     }
2839
2840     #[derive(Default)]
2841     struct AllCollector {
2842         regions: FxHashSet<hir::LifetimeName>,
2843     }
2844
2845     impl<'v> Visitor<'v> for AllCollector {
2846         type Map = intravisit::ErasedMap<'v>;
2847
2848         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2849             NestedVisitorMap::None
2850         }
2851
2852         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2853             self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
2854         }
2855     }
2856 }