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