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