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