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