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