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