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