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