1 //! Name resolution for lifetimes.
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.
9 use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
11 use hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName};
12 use ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
14 use errors::{Applicability, DiagnosticBuilder};
16 use rustc_data_structures::sync::Lrc;
20 use std::mem::replace;
24 use syntax::symbol::keywords;
26 use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet};
28 use hir::intravisit::{self, NestedVisitorMap, Visitor};
29 use hir::{self, GenericParamKind, LifetimeParamKind};
31 /// The origin of a named lifetime definition.
33 /// This is used to prevent the usage of in-band lifetimes in `Fn`/`fn` syntax.
34 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
35 pub enum LifetimeDefOrigin {
36 // Explicit binders like `fn foo<'a>(x: &'a u8)` or elided like `impl Foo<&u32>`
38 // In-band declarations like `fn foo(x: &'a u8)`
40 // Some kind of erroneous origin
44 impl LifetimeDefOrigin {
45 fn from_param(param: &GenericParam) -> Self {
47 GenericParamKind::Lifetime { kind } => match kind {
48 LifetimeParamKind::InBand => LifetimeDefOrigin::InBand,
49 LifetimeParamKind::Explicit => LifetimeDefOrigin::ExplicitOrElided,
50 LifetimeParamKind::Elided => LifetimeDefOrigin::ExplicitOrElided,
51 LifetimeParamKind::Error => LifetimeDefOrigin::Error,
53 _ => bug!("expected a lifetime param"),
58 // This counts the no of times a lifetime is used
59 #[derive(Clone, Copy, Debug)]
60 pub enum LifetimeUseSet<'tcx> {
61 One(&'tcx hir::Lifetime),
65 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
70 /* lifetime decl */ DefId,
75 /* lifetime decl */ DefId,
78 LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
79 Free(DefId, /* lifetime decl */ DefId),
83 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam) -> (ParamName, Region) {
86 let def_id = hir_map.local_def_id(param.id);
87 let origin = LifetimeDefOrigin::from_param(param);
88 debug!("Region::early: index={} def_id={:?}", i, def_id);
89 (param.name.modern(), Region::EarlyBound(i, def_id, origin))
92 fn late(hir_map: &Map<'_>, param: &GenericParam) -> (ParamName, Region) {
93 let depth = ty::INNERMOST;
94 let def_id = hir_map.local_def_id(param.id);
95 let origin = LifetimeDefOrigin::from_param(param);
97 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
98 param, depth, def_id, origin,
102 Region::LateBound(depth, def_id, origin),
106 fn late_anon(index: &Cell<u32>) -> Region {
109 let depth = ty::INNERMOST;
110 Region::LateBoundAnon(depth, i)
113 fn id(&self) -> Option<DefId> {
115 Region::Static | Region::LateBoundAnon(..) => None,
117 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
123 fn shifted(self, amount: u32) -> Region {
125 Region::LateBound(debruijn, id, origin) => {
126 Region::LateBound(debruijn.shifted_in(amount), id, origin)
128 Region::LateBoundAnon(debruijn, index) => {
129 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
135 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
137 Region::LateBound(debruijn, id, origin) => {
138 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
140 Region::LateBoundAnon(debruijn, index) => {
141 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
147 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
149 L: Iterator<Item = &'a hir::Lifetime>,
151 if let Region::EarlyBound(index, _, _) = self {
154 .and_then(|lifetime| map.defs.get(&lifetime.id).cloned())
161 /// A set containing, at most, one known element.
162 /// If two distinct values are inserted into a set, then it
163 /// becomes `Many`, which can be used to detect ambiguities.
164 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
171 impl<T: PartialEq> Set1<T> {
172 pub fn insert(&mut self, value: T) {
173 if let Set1::Empty = *self {
174 *self = Set1::One(value);
177 if let Set1::One(ref old) = *self {
186 pub type ObjectLifetimeDefault = Set1<Region>;
188 /// Maps the id of each lifetime reference to the lifetime decl
189 /// that it corresponds to.
191 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
192 /// actual use. It has the same data, but indexed by `DefIndex`. This
195 struct NamedRegionMap {
196 // maps from every use of a named (not anonymous) lifetime to a
197 // `Region` describing how that region is bound
198 pub defs: NodeMap<Region>,
200 // the set of lifetime def ids that are late-bound; a region can
201 // be late-bound if (a) it does NOT appear in a where-clause and
202 // (b) it DOES appear in the arguments.
203 pub late_bound: NodeSet,
205 // For each type and trait definition, maps type parameters
206 // to the trait object lifetime defaults computed from them.
207 pub object_lifetime_defaults: NodeMap<Vec<ObjectLifetimeDefault>>,
210 /// See `NamedRegionMap`.
212 pub struct ResolveLifetimes {
213 defs: FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Region>>>,
214 late_bound: FxHashMap<LocalDefId, Lrc<FxHashSet<ItemLocalId>>>,
215 object_lifetime_defaults:
216 FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Lrc<Vec<ObjectLifetimeDefault>>>>>,
219 impl_stable_hash_for!(struct ::middle::resolve_lifetime::ResolveLifetimes {
222 object_lifetime_defaults
225 struct LifetimeContext<'a, 'tcx: 'a> {
226 tcx: TyCtxt<'a, 'tcx, 'tcx>,
227 map: &'a mut NamedRegionMap,
230 /// Deep breath. Our representation for poly trait refs contains a single
231 /// binder and thus we only allow a single level of quantification. However,
232 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
233 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
234 /// correct when representing these constraints, we should only introduce one
235 /// scope. However, we want to support both locations for the quantifier and
236 /// during lifetime resolution we want precise information (so we can't
237 /// desugar in an earlier phase).
239 /// SO, if we encounter a quantifier at the outer scope, we set
240 /// trait_ref_hack to true (and introduce a scope), and then if we encounter
241 /// a quantifier at the inner scope, we error. If trait_ref_hack is false,
242 /// then we introduce the scope at the inner quantifier.
245 trait_ref_hack: bool,
247 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
248 is_in_fn_syntax: bool,
250 /// List of labels in the function/method currently under analysis.
251 labels_in_fn: Vec<ast::Ident>,
253 /// Cache for cross-crate per-definition object lifetime defaults.
254 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
256 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
261 /// Declares lifetimes, and each can be early-bound or late-bound.
262 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
263 /// it should be shifted by the number of `Binder`s in between the
264 /// declaration `Binder` and the location it's referenced from.
266 lifetimes: FxHashMap<hir::ParamName, Region>,
268 /// if we extend this scope with another scope, what is the next index
269 /// we should use for an early-bound region?
270 next_early_index: u32,
272 /// Flag is set to true if, in this binder, `'_` would be
273 /// equivalent to a "single-use region". This is true on
274 /// impls, but not other kinds of items.
275 track_lifetime_uses: bool,
277 /// Whether or not this binder would serve as the parent
278 /// binder for abstract types introduced within. For example:
280 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
282 /// Here, the abstract types we create for the `impl Trait`
283 /// and `impl Trait2` references will both have the `foo` item
284 /// as their parent. When we get to `impl Trait2`, we find
285 /// that it is nested within the `for<>` binder -- this flag
286 /// allows us to skip that when looking for the parent binder
287 /// of the resulting abstract type.
288 abstract_type_parent: bool,
293 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
294 /// if this is a fn body, otherwise the original definitions are used.
295 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
296 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
302 /// A scope which either determines unspecified lifetimes or errors
303 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
309 /// Use a specific lifetime (if `Some`) or leave it unset (to be
310 /// inferred in a function body or potentially error outside one),
311 /// for the default choice of lifetime in a trait object type.
312 ObjectLifetimeDefault {
313 lifetime: Option<Region>,
320 #[derive(Clone, Debug)]
322 /// Use a fresh anonymous late-bound lifetime each time, by
323 /// incrementing the counter to generate sequential indices.
324 FreshLateAnon(Cell<u32>),
325 /// Always use this one lifetime.
327 /// Less or more than one lifetime were found, error on unspecified.
328 Error(Vec<ElisionFailureInfo>),
331 #[derive(Clone, Debug)]
332 struct ElisionFailureInfo {
333 /// Where we can find the argument pattern.
334 parent: Option<hir::BodyId>,
335 /// The index of the argument in the original definition.
337 lifetime_count: usize,
338 have_bound_regions: bool,
341 type ScopeRef<'a> = &'a Scope<'a>;
343 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
345 pub fn provide(providers: &mut ty::query::Providers<'_>) {
346 *providers = ty::query::Providers {
349 named_region_map: |tcx, id| {
350 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
351 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id).cloned()
354 is_late_bound_map: |tcx, id| {
355 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
356 tcx.resolve_lifetimes(LOCAL_CRATE)
362 object_lifetime_defaults_map: |tcx, id| {
363 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
364 tcx.resolve_lifetimes(LOCAL_CRATE)
365 .object_lifetime_defaults
373 // (*) FIXME the query should be defined to take a LocalDefId
376 /// Computes the `ResolveLifetimes` map that contains data for the
377 /// entire crate. You should not read the result of this query
378 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
380 fn resolve_lifetimes<'tcx>(
381 tcx: TyCtxt<'_, 'tcx, 'tcx>,
383 ) -> Lrc<ResolveLifetimes> {
384 assert_eq!(for_krate, LOCAL_CRATE);
386 let named_region_map = krate(tcx);
388 let mut rl = ResolveLifetimes::default();
390 for (k, v) in named_region_map.defs {
391 let hir_id = tcx.hir().node_to_hir_id(k);
392 let map = rl.defs.entry(hir_id.owner_local_def_id()).or_default();
393 Lrc::get_mut(map).unwrap().insert(hir_id.local_id, v);
395 for k in named_region_map.late_bound {
396 let hir_id = tcx.hir().node_to_hir_id(k);
397 let map = rl.late_bound
398 .entry(hir_id.owner_local_def_id())
400 Lrc::get_mut(map).unwrap().insert(hir_id.local_id);
402 for (k, v) in named_region_map.object_lifetime_defaults {
403 let hir_id = tcx.hir().node_to_hir_id(k);
404 let map = rl.object_lifetime_defaults
405 .entry(hir_id.owner_local_def_id())
409 .insert(hir_id.local_id, Lrc::new(v));
415 fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> NamedRegionMap {
416 let krate = tcx.hir().krate();
417 let mut map = NamedRegionMap {
418 defs: Default::default(),
419 late_bound: Default::default(),
420 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
423 let mut visitor = LifetimeContext {
427 trait_ref_hack: false,
428 is_in_fn_syntax: false,
429 labels_in_fn: vec![],
430 xcrate_object_lifetime_defaults: Default::default(),
431 lifetime_uses: &mut Default::default(),
433 for (_, item) in &krate.items {
434 visitor.visit_item(item);
440 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
441 /// We have to account for this when computing the index of the other generic parameters.
442 /// This function returns whether there is such an implicit parameter defined on the given item.
443 fn sub_items_have_self_param(node: &hir::ItemKind) -> bool {
445 hir::ItemKind::Trait(..) |
446 hir::ItemKind::TraitAlias(..) => true,
451 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
452 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
453 NestedVisitorMap::All(&self.tcx.hir())
456 // We want to nest trait/impl items in their parent, but nothing else.
457 fn visit_nested_item(&mut self, _: hir::ItemId) {}
459 fn visit_nested_body(&mut self, body: hir::BodyId) {
460 // Each body has their own set of labels, save labels.
461 let saved = replace(&mut self.labels_in_fn, vec![]);
462 let body = self.tcx.hir().body(body);
463 extract_labels(self, body);
470 this.visit_body(body);
473 replace(&mut self.labels_in_fn, saved);
476 fn visit_item(&mut self, item: &'tcx hir::Item) {
478 hir::ItemKind::Fn(ref decl, _, ref generics, _) => {
479 self.visit_early_late(None, decl, generics, |this| {
480 intravisit::walk_item(this, item);
484 hir::ItemKind::ExternCrate(_)
485 | hir::ItemKind::Use(..)
486 | hir::ItemKind::Mod(..)
487 | hir::ItemKind::ForeignMod(..)
488 | hir::ItemKind::GlobalAsm(..) => {
489 // These sorts of items have no lifetime parameters at all.
490 intravisit::walk_item(self, item);
492 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
493 // No lifetime parameters, but implied 'static.
494 let scope = Scope::Elision {
495 elide: Elide::Exact(Region::Static),
498 self.with(scope, |_, this| intravisit::walk_item(this, item));
500 hir::ItemKind::Existential(hir::ExistTy {
501 impl_trait_fn: Some(_),
504 // currently existential type declarations are just generated from impl Trait
505 // items. doing anything on this node is irrelevant, as we currently don't need
508 hir::ItemKind::Ty(_, ref generics)
509 | hir::ItemKind::Existential(hir::ExistTy {
514 | hir::ItemKind::Enum(_, ref generics)
515 | hir::ItemKind::Struct(_, ref generics)
516 | hir::ItemKind::Union(_, ref generics)
517 | hir::ItemKind::Trait(_, _, ref generics, ..)
518 | hir::ItemKind::TraitAlias(ref generics, ..)
519 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
520 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
521 // This is not true for other kinds of items.x
522 let track_lifetime_uses = match item.node {
523 hir::ItemKind::Impl(..) => true,
526 // These kinds of items have only early-bound lifetime parameters.
527 let mut index = if sub_items_have_self_param(&item.node) {
528 1 // Self comes before lifetimes
532 let mut type_count = 0;
533 let lifetimes = generics
536 .filter_map(|param| match param.kind {
537 GenericParamKind::Lifetime { .. } => {
538 Some(Region::early(&self.tcx.hir(), &mut index, param))
540 GenericParamKind::Type { .. } => {
546 let scope = Scope::Binder {
548 next_early_index: index + type_count,
549 abstract_type_parent: true,
553 self.with(scope, |old_scope, this| {
554 this.check_lifetime_params(old_scope, &generics.params);
555 intravisit::walk_item(this, item);
561 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
563 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
564 self.visit_early_late(None, decl, generics, |this| {
565 intravisit::walk_foreign_item(this, item);
568 hir::ForeignItemKind::Static(..) => {
569 intravisit::walk_foreign_item(self, item);
571 hir::ForeignItemKind::Type => {
572 intravisit::walk_foreign_item(self, item);
577 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
578 debug!("visit_ty: id={:?} ty={:?}", ty.id, ty);
580 hir::TyKind::BareFn(ref c) => {
581 let next_early_index = self.next_early_index();
582 let was_in_fn_syntax = self.is_in_fn_syntax;
583 self.is_in_fn_syntax = true;
584 let scope = Scope::Binder {
585 lifetimes: c.generic_params
587 .filter_map(|param| match param.kind {
588 GenericParamKind::Lifetime { .. } => {
589 Some(Region::late(&self.tcx.hir(), param))
596 track_lifetime_uses: true,
597 abstract_type_parent: false,
599 self.with(scope, |old_scope, this| {
600 // a bare fn has no bounds, so everything
601 // contained within is scoped within its binder.
602 this.check_lifetime_params(old_scope, &c.generic_params);
603 intravisit::walk_ty(this, ty);
605 self.is_in_fn_syntax = was_in_fn_syntax;
607 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
608 for bound in bounds {
609 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
611 match lifetime.name {
612 LifetimeName::Implicit => {
613 // If the user does not write *anything*, we
614 // use the object lifetime defaulting
615 // rules. So e.g., `Box<dyn Debug>` becomes
616 // `Box<dyn Debug + 'static>`.
617 self.resolve_object_lifetime_default(lifetime)
619 LifetimeName::Underscore => {
620 // If the user writes `'_`, we use the *ordinary* elision
621 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
622 // resolved the same as the `'_` in `&'_ Foo`.
625 self.resolve_elided_lifetimes(vec![lifetime])
627 LifetimeName::Param(_) | LifetimeName::Static => {
628 // If the user wrote an explicit name, use that.
629 self.visit_lifetime(lifetime);
631 LifetimeName::Error => {}
634 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
635 self.visit_lifetime(lifetime_ref);
636 let scope = Scope::ObjectLifetimeDefault {
637 lifetime: self.map.defs.get(&lifetime_ref.id).cloned(),
640 self.with(scope, |_, this| this.visit_ty(&mt.ty));
642 hir::TyKind::Def(item_id, ref lifetimes) => {
643 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
644 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
645 // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
646 // ^ ^ this gets resolved in the scope of
647 // the exist_ty generics
648 let (generics, bounds) = match self.tcx.hir().expect_item(item_id.id).node {
649 // named existential types are reached via TyKind::Path
650 // this arm is for `impl Trait` in the types of statics, constants and locals
651 hir::ItemKind::Existential(hir::ExistTy {
655 intravisit::walk_ty(self, ty);
658 // RPIT (return position impl trait)
659 hir::ItemKind::Existential(hir::ExistTy {
663 }) => (generics, bounds),
664 ref i => bug!("impl Trait pointed to non-existential type?? {:#?}", i),
667 // Resolve the lifetimes that are applied to the existential type.
668 // These are resolved in the current scope.
669 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
670 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
671 // ^ ^this gets resolved in the current scope
672 for lifetime in lifetimes {
673 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
674 self.visit_lifetime(lifetime);
676 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
677 // and ban them. Type variables instantiated inside binders aren't
678 // well-supported at the moment, so this doesn't work.
679 // In the future, this should be fixed and this error should be removed.
680 let def = self.map.defs.get(&lifetime.id).cloned();
681 if let Some(Region::LateBound(_, def_id, _)) = def {
682 if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
683 // Ensure that the parent of the def is an item, not HRTB
684 let parent_id = self.tcx.hir().get_parent_node(node_id);
685 let parent_impl_id = hir::ImplItemId { node_id: parent_id };
686 let parent_trait_id = hir::TraitItemId { node_id: parent_id };
687 let krate = self.tcx.hir().forest.krate();
688 if !(krate.items.contains_key(&parent_id)
689 || krate.impl_items.contains_key(&parent_impl_id)
690 || krate.trait_items.contains_key(&parent_trait_id))
696 "`impl Trait` can only capture lifetimes \
697 bound at the fn or impl level"
699 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
706 // We want to start our early-bound indices at the end of the parent scope,
707 // not including any parent `impl Trait`s.
708 let mut index = self.next_early_index_for_abstract_type();
709 debug!("visit_ty: index = {}", index);
711 let mut elision = None;
712 let mut lifetimes = FxHashMap::default();
713 let mut type_count = 0;
714 for param in &generics.params {
716 GenericParamKind::Lifetime { .. } => {
717 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
718 if let hir::ParamName::Plain(param_name) = name {
719 if param_name.name == keywords::UnderscoreLifetime.name() {
720 // Pick the elided lifetime "definition" if one exists
721 // and use it to make an elision scope.
724 lifetimes.insert(name, reg);
727 lifetimes.insert(name, reg);
730 GenericParamKind::Type { .. } => {
735 let next_early_index = index + type_count;
737 if let Some(elision_region) = elision {
738 let scope = Scope::Elision {
739 elide: Elide::Exact(elision_region),
742 self.with(scope, |_old_scope, this| {
743 let scope = Scope::Binder {
747 track_lifetime_uses: true,
748 abstract_type_parent: false,
750 this.with(scope, |_old_scope, this| {
751 this.visit_generics(generics);
752 for bound in bounds {
753 this.visit_param_bound(bound);
758 let scope = Scope::Binder {
762 track_lifetime_uses: true,
763 abstract_type_parent: false,
765 self.with(scope, |_old_scope, this| {
766 this.visit_generics(generics);
767 for bound in bounds {
768 this.visit_param_bound(bound);
773 _ => intravisit::walk_ty(self, ty),
777 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
778 use self::hir::TraitItemKind::*;
779 match trait_item.node {
780 Method(ref sig, _) => {
782 self.visit_early_late(
783 Some(tcx.hir().get_parent(trait_item.id)),
785 &trait_item.generics,
786 |this| intravisit::walk_trait_item(this, trait_item),
789 Type(ref bounds, ref ty) => {
790 let generics = &trait_item.generics;
791 let mut index = self.next_early_index();
792 debug!("visit_ty: index = {}", index);
793 let mut type_count = 0;
794 let lifetimes = generics
797 .filter_map(|param| match param.kind {
798 GenericParamKind::Lifetime { .. } => {
799 Some(Region::early(&self.tcx.hir(), &mut index, param))
801 GenericParamKind::Type { .. } => {
807 let scope = Scope::Binder {
809 next_early_index: index + type_count,
811 track_lifetime_uses: true,
812 abstract_type_parent: true,
814 self.with(scope, |_old_scope, this| {
815 this.visit_generics(generics);
816 for bound in bounds {
817 this.visit_param_bound(bound);
819 if let Some(ty) = ty {
825 // Only methods and types support generics.
826 assert!(trait_item.generics.params.is_empty());
827 intravisit::walk_trait_item(self, trait_item);
832 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
833 use self::hir::ImplItemKind::*;
834 match impl_item.node {
835 Method(ref sig, _) => {
837 self.visit_early_late(
838 Some(tcx.hir().get_parent(impl_item.id)),
841 |this| intravisit::walk_impl_item(this, impl_item),
845 let generics = &impl_item.generics;
846 let mut index = self.next_early_index();
847 let mut next_early_index = index;
848 debug!("visit_ty: index = {}", index);
849 let lifetimes = generics
852 .filter_map(|param| match param.kind {
853 GenericParamKind::Lifetime { .. } => {
854 Some(Region::early(&self.tcx.hir(), &mut index, param))
856 GenericParamKind::Type { .. } => {
857 next_early_index += 1;
862 let scope = Scope::Binder {
866 track_lifetime_uses: true,
867 abstract_type_parent: true,
869 self.with(scope, |_old_scope, this| {
870 this.visit_generics(generics);
874 Existential(ref bounds) => {
875 let generics = &impl_item.generics;
876 let mut index = self.next_early_index();
877 let mut next_early_index = index;
878 debug!("visit_ty: index = {}", index);
879 let lifetimes = generics
882 .filter_map(|param| match param.kind {
883 GenericParamKind::Lifetime { .. } => {
884 Some(Region::early(&self.tcx.hir(), &mut index, param))
886 GenericParamKind::Type { .. } => {
887 next_early_index += 1;
893 let scope = Scope::Binder {
897 track_lifetime_uses: true,
898 abstract_type_parent: true,
900 self.with(scope, |_old_scope, this| {
901 this.visit_generics(generics);
902 for bound in bounds {
903 this.visit_param_bound(bound);
908 // Only methods and types support generics.
909 assert!(impl_item.generics.params.is_empty());
910 intravisit::walk_impl_item(self, impl_item);
915 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
916 if lifetime_ref.is_elided() {
917 self.resolve_elided_lifetimes(vec![lifetime_ref]);
920 if lifetime_ref.is_static() {
921 self.insert_lifetime(lifetime_ref, Region::Static);
924 self.resolve_lifetime_ref(lifetime_ref);
927 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
928 for (i, segment) in path.segments.iter().enumerate() {
929 let depth = path.segments.len() - i - 1;
930 if let Some(ref args) = segment.args {
931 self.visit_segment_args(path.def, depth, args);
936 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
937 let output = match fd.output {
938 hir::DefaultReturn(_) => None,
939 hir::Return(ref ty) => Some(ty),
941 self.visit_fn_like_elision(&fd.inputs, output);
944 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
945 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
946 for param in &generics.params {
948 GenericParamKind::Lifetime { .. } => {}
949 GenericParamKind::Type { ref default, .. } => {
950 walk_list!(self, visit_param_bound, ¶m.bounds);
951 if let Some(ref ty) = default {
957 for predicate in &generics.where_clause.predicates {
959 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
962 ref bound_generic_params,
965 let lifetimes: FxHashMap<_, _> = bound_generic_params
967 .filter_map(|param| match param.kind {
968 GenericParamKind::Lifetime { .. } => {
969 Some(Region::late(&self.tcx.hir(), param))
974 if !lifetimes.is_empty() {
975 self.trait_ref_hack = true;
976 let next_early_index = self.next_early_index();
977 let scope = Scope::Binder {
981 track_lifetime_uses: true,
982 abstract_type_parent: false,
984 let result = self.with(scope, |old_scope, this| {
985 this.check_lifetime_params(old_scope, &bound_generic_params);
986 this.visit_ty(&bounded_ty);
987 walk_list!(this, visit_param_bound, bounds);
989 self.trait_ref_hack = false;
992 self.visit_ty(&bounded_ty);
993 walk_list!(self, visit_param_bound, bounds);
996 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1001 self.visit_lifetime(lifetime);
1002 walk_list!(self, visit_param_bound, bounds);
1004 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1009 self.visit_ty(lhs_ty);
1010 self.visit_ty(rhs_ty);
1016 fn visit_poly_trait_ref(
1018 trait_ref: &'tcx hir::PolyTraitRef,
1019 _modifier: hir::TraitBoundModifier,
1021 debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
1023 if !self.trait_ref_hack || trait_ref.bound_generic_params.iter().any(|param| {
1025 GenericParamKind::Lifetime { .. } => true,
1029 if self.trait_ref_hack {
1034 "nested quantification of lifetimes"
1037 let next_early_index = self.next_early_index();
1038 let scope = Scope::Binder {
1039 lifetimes: trait_ref
1040 .bound_generic_params
1042 .filter_map(|param| match param.kind {
1043 GenericParamKind::Lifetime { .. } => {
1044 Some(Region::late(&self.tcx.hir(), param))
1051 track_lifetime_uses: true,
1052 abstract_type_parent: false,
1054 self.with(scope, |old_scope, this| {
1055 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1056 walk_list!(this, visit_generic_param, &trait_ref.bound_generic_params);
1057 this.visit_trait_ref(&trait_ref.trait_ref)
1060 self.visit_trait_ref(&trait_ref.trait_ref)
1065 #[derive(Copy, Clone, PartialEq)]
1079 fn original_label(span: Span) -> Original {
1081 kind: ShadowKind::Label,
1085 fn shadower_label(span: Span) -> Shadower {
1087 kind: ShadowKind::Label,
1091 fn original_lifetime(span: Span) -> Original {
1093 kind: ShadowKind::Lifetime,
1097 fn shadower_lifetime(param: &hir::GenericParam) -> Shadower {
1099 kind: ShadowKind::Lifetime,
1105 fn desc(&self) -> &'static str {
1107 ShadowKind::Label => "label",
1108 ShadowKind::Lifetime => "lifetime",
1113 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_, '_, '_>, params: &P<[hir::GenericParam]>) {
1114 let lifetime_params: Vec<_> = params
1116 .filter_map(|param| match param.kind {
1117 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1121 let explicit = lifetime_params
1123 .find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1124 let in_band = lifetime_params
1126 .find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1128 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1133 "cannot mix in-band and explicit lifetime definitions"
1134 ).span_label(*in_band_span, "in-band lifetime definition here")
1135 .span_label(*explicit_span, "explicit lifetime definition here")
1140 fn signal_shadowing_problem(
1141 tcx: TyCtxt<'_, '_, '_>,
1146 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1147 // lifetime/lifetime shadowing is an error
1152 "{} name `{}` shadows a \
1153 {} name that is already in scope",
1154 shadower.kind.desc(),
1159 // shadowing involving a label is only a warning, due to issues with
1160 // labels and lifetimes not being macro-hygienic.
1161 tcx.sess.struct_span_warn(
1164 "{} name `{}` shadows a \
1165 {} name that is already in scope",
1166 shadower.kind.desc(),
1172 err.span_label(orig.span, "first declared here");
1173 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1177 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1178 // if one of the label shadows a lifetime or another label.
1179 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
1180 struct GatherLabels<'a, 'tcx: 'a> {
1181 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1182 scope: ScopeRef<'a>,
1183 labels_in_fn: &'a mut Vec<ast::Ident>,
1186 let mut gather = GatherLabels {
1189 labels_in_fn: &mut ctxt.labels_in_fn,
1191 gather.visit_body(body);
1193 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1194 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1195 NestedVisitorMap::None
1198 fn visit_expr(&mut self, ex: &hir::Expr) {
1199 if let Some(label) = expression_label(ex) {
1200 for prior_label in &self.labels_in_fn[..] {
1201 // FIXME (#24278): non-hygienic comparison
1202 if label.name == prior_label.name {
1203 signal_shadowing_problem(
1206 original_label(prior_label.span),
1207 shadower_label(label.span),
1212 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1214 self.labels_in_fn.push(label);
1216 intravisit::walk_expr(self, ex)
1220 fn expression_label(ex: &hir::Expr) -> Option<ast::Ident> {
1222 hir::ExprKind::While(.., Some(label)) | hir::ExprKind::Loop(_, Some(label), _) => {
1229 fn check_if_label_shadows_lifetime(
1230 tcx: TyCtxt<'_, '_, '_>,
1231 mut scope: ScopeRef<'_>,
1236 Scope::Body { s, .. }
1237 | Scope::Elision { s, .. }
1238 | Scope::ObjectLifetimeDefault { s, .. } => {
1247 ref lifetimes, s, ..
1249 // FIXME (#24278): non-hygienic comparison
1250 if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1251 let node_id = tcx.hir().as_local_node_id(def.id().unwrap()).unwrap();
1253 signal_shadowing_problem(
1256 original_lifetime(tcx.hir().span(node_id)),
1257 shadower_label(label.span),
1268 fn compute_object_lifetime_defaults(
1269 tcx: TyCtxt<'_, '_, '_>,
1270 ) -> NodeMap<Vec<ObjectLifetimeDefault>> {
1271 let mut map = NodeMap::default();
1272 for item in tcx.hir().krate().items.values() {
1274 hir::ItemKind::Struct(_, ref generics)
1275 | hir::ItemKind::Union(_, ref generics)
1276 | hir::ItemKind::Enum(_, ref generics)
1277 | hir::ItemKind::Existential(hir::ExistTy {
1279 impl_trait_fn: None,
1282 | hir::ItemKind::Ty(_, ref generics)
1283 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1284 let result = object_lifetime_defaults_for_item(tcx, generics);
1287 if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") {
1288 let object_lifetime_default_reprs: String = result
1290 .map(|set| match *set {
1291 Set1::Empty => "BaseDefault".into(),
1292 Set1::One(Region::Static) => "'static".into(),
1293 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1296 .find_map(|param| match param.kind {
1297 GenericParamKind::Lifetime { .. } => {
1299 return Some(param.name.ident().to_string().into());
1307 Set1::One(_) => bug!(),
1308 Set1::Many => "Ambiguous".into(),
1310 .collect::<Vec<Cow<'static, str>>>()
1312 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1315 map.insert(item.id, result);
1323 /// Scan the bounds and where-clauses on parameters to extract bounds
1324 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1325 /// for each type parameter.
1326 fn object_lifetime_defaults_for_item(
1327 tcx: TyCtxt<'_, '_, '_>,
1328 generics: &hir::Generics,
1329 ) -> Vec<ObjectLifetimeDefault> {
1330 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound]) {
1331 for bound in bounds {
1332 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1333 set.insert(lifetime.name.modern());
1341 .filter_map(|param| match param.kind {
1342 GenericParamKind::Lifetime { .. } => None,
1343 GenericParamKind::Type { .. } => {
1344 let mut set = Set1::Empty;
1346 add_bounds(&mut set, ¶m.bounds);
1348 let param_def_id = tcx.hir().local_def_id(param.id);
1349 for predicate in &generics.where_clause.predicates {
1350 // Look for `type: ...` where clauses.
1351 let data = match *predicate {
1352 hir::WherePredicate::BoundPredicate(ref data) => data,
1356 // Ignore `for<'a> type: ...` as they can change what
1357 // lifetimes mean (although we could "just" handle it).
1358 if !data.bound_generic_params.is_empty() {
1362 let def = match data.bounded_ty.node {
1363 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.def,
1367 if def == Def::TyParam(param_def_id) {
1368 add_bounds(&mut set, &data.bounds);
1373 Set1::Empty => Set1::Empty,
1374 Set1::One(name) => {
1375 if name == hir::LifetimeName::Static {
1376 Set1::One(Region::Static)
1381 .filter_map(|param| match param.kind {
1382 GenericParamKind::Lifetime { .. } => Some((
1384 hir::LifetimeName::Param(param.name),
1385 LifetimeDefOrigin::from_param(param),
1390 .find(|&(_, (_, lt_name, _))| lt_name == name)
1391 .map_or(Set1::Many, |(i, (id, _, origin))| {
1392 let def_id = tcx.hir().local_def_id(id);
1393 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1397 Set1::Many => Set1::Many,
1404 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1405 // FIXME(#37666) this works around a limitation in the region inferencer
1406 fn hack<F>(&mut self, f: F)
1408 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1413 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1415 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1417 let LifetimeContext {
1423 let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
1424 let xcrate_object_lifetime_defaults =
1425 replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap::default());
1426 let mut this = LifetimeContext {
1430 trait_ref_hack: self.trait_ref_hack,
1431 is_in_fn_syntax: self.is_in_fn_syntax,
1433 xcrate_object_lifetime_defaults,
1434 lifetime_uses: lifetime_uses,
1436 debug!("entering scope {:?}", this.scope);
1437 f(self.scope, &mut this);
1438 this.check_uses_for_lifetimes_defined_by_scope();
1439 debug!("exiting scope {:?}", this.scope);
1440 self.labels_in_fn = this.labels_in_fn;
1441 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1444 /// helper method to determine the span to remove when suggesting the
1445 /// deletion of a lifetime
1446 fn lifetime_deletion_span(&self, name: ast::Ident, generics: &hir::Generics) -> Option<Span> {
1447 generics.params.iter().enumerate().find_map(|(i, param)| {
1448 if param.name.ident() == name {
1449 let mut in_band = false;
1450 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1451 if let hir::LifetimeParamKind::InBand = kind {
1458 if generics.params.len() == 1 {
1459 // if sole lifetime, remove the entire `<>` brackets
1462 // if removing within `<>` brackets, we also want to
1463 // delete a leading or trailing comma as appropriate
1464 if i >= generics.params.len() - 1 {
1465 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1467 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1477 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1478 fn suggest_eliding_single_use_lifetime(
1479 &self, err: &mut DiagnosticBuilder<'_>, def_id: DefId, lifetime: &hir::Lifetime
1481 // FIXME: future work: also suggest `impl Foo<'_>` for `impl<'a> Foo<'a>`
1482 let name = lifetime.name.ident();
1483 let mut remove_decl = None;
1484 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1485 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1486 remove_decl = self.lifetime_deletion_span(name, generics);
1490 let mut remove_use = None;
1491 let mut find_arg_use_span = |inputs: &hir::HirVec<hir::Ty>| {
1492 for input in inputs {
1493 if let hir::TyKind::Rptr(lt, _) = input.node {
1494 if lt.name.ident() == name {
1495 // include the trailing whitespace between the ampersand and the type name
1496 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1498 self.tcx.sess.source_map()
1499 .span_until_non_whitespace(lt_through_ty_span)
1506 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.id) {
1507 if let Some(parent) = self.tcx.hir().find(self.tcx.hir().get_parent(hir_lifetime.id)) {
1509 Node::Item(item) => {
1510 if let hir::ItemKind::Fn(decl, _, _, _) = &item.node {
1511 find_arg_use_span(&decl.inputs);
1514 Node::ImplItem(impl_item) => {
1515 if let hir::ImplItemKind::Method(sig, _) = &impl_item.node {
1516 find_arg_use_span(&sig.decl.inputs);
1524 if let (Some(decl_span), Some(use_span)) = (remove_decl, remove_use) {
1525 // if both declaration and use deletion spans start at the same
1526 // place ("start at" because the latter includes trailing
1527 // whitespace), then this is an in-band lifetime
1528 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1529 err.span_suggestion_with_applicability(
1531 "elide the single-use lifetime",
1533 Applicability::MachineApplicable,
1536 err.multipart_suggestion_with_applicability(
1537 "elide the single-use lifetime",
1538 vec![(decl_span, String::new()), (use_span, String::new())],
1539 Applicability::MachineApplicable,
1545 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1546 let defined_by = match self.scope {
1547 Scope::Binder { lifetimes, .. } => lifetimes,
1549 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1554 let mut def_ids: Vec<_> = defined_by
1556 .flat_map(|region| match region {
1557 Region::EarlyBound(_, def_id, _)
1558 | Region::LateBound(_, def_id, _)
1559 | Region::Free(_, def_id) => Some(*def_id),
1561 Region::LateBoundAnon(..) | Region::Static => None,
1565 // ensure that we issue lints in a repeatable order
1566 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1568 for def_id in def_ids {
1570 "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
1574 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1577 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1581 match lifetimeuseset {
1582 Some(LifetimeUseSet::One(lifetime)) => {
1583 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
1584 debug!("node id first={:?}", node_id);
1585 if let Some((id, span, name)) = match self.tcx.hir().get(node_id) {
1586 Node::Lifetime(hir_lifetime) => Some((
1589 hir_lifetime.name.ident(),
1591 Node::GenericParam(param) => {
1592 Some((param.id, param.span, param.name.ident()))
1596 debug!("id = {:?} span = {:?} name = {:?}", node_id, span, name);
1598 if name == keywords::UnderscoreLifetime.ident() {
1602 let mut err = self.tcx.struct_span_lint_node(
1603 lint::builtin::SINGLE_USE_LIFETIMES,
1606 &format!("lifetime parameter `{}` only used once", name),
1609 if span == lifetime.span {
1610 // spans are the same for in-band lifetime declarations
1611 err.span_label(span, "this lifetime is only used here");
1613 err.span_label(span, "this lifetime...");
1614 err.span_label(lifetime.span, "...is used only here");
1616 self.suggest_eliding_single_use_lifetime(&mut err, def_id, lifetime);
1620 Some(LifetimeUseSet::Many) => {
1621 debug!("Not one use lifetime");
1624 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
1625 if let Some((id, span, name)) = match self.tcx.hir().get(node_id) {
1626 Node::Lifetime(hir_lifetime) => Some((
1629 hir_lifetime.name.ident(),
1631 Node::GenericParam(param) => {
1632 Some((param.id, param.span, param.name.ident()))
1636 debug!("id ={:?} span = {:?} name = {:?}", node_id, span, name);
1637 let mut err = self.tcx.struct_span_lint_node(
1638 lint::builtin::UNUSED_LIFETIMES,
1641 &format!("lifetime parameter `{}` never used", name),
1643 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1644 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1645 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1646 if let Some(span) = unused_lt_span {
1647 err.span_suggestion_with_applicability(
1649 "elide the unused lifetime",
1651 Applicability::MachineApplicable,
1663 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1665 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1666 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1667 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1671 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1673 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1674 /// lifetimes may be interspersed together.
1676 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1677 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1678 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1679 /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
1680 /// ordering is not important there.
1681 fn visit_early_late<F>(
1683 parent_id: Option<ast::NodeId>,
1684 decl: &'tcx hir::FnDecl,
1685 generics: &'tcx hir::Generics,
1688 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1690 insert_late_bound_lifetimes(self.map, decl, generics);
1692 // Find the start of nested early scopes, e.g., in methods.
1694 if let Some(parent_id) = parent_id {
1695 let parent = self.tcx.hir().expect_item(parent_id);
1696 if sub_items_have_self_param(&parent.node) {
1697 index += 1; // Self comes before lifetimes
1700 hir::ItemKind::Trait(_, _, ref generics, ..)
1701 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
1702 index += generics.params.len() as u32;
1708 let mut type_count = 0;
1709 let lifetimes = generics
1712 .filter_map(|param| match param.kind {
1713 GenericParamKind::Lifetime { .. } => {
1714 if self.map.late_bound.contains(¶m.id) {
1715 Some(Region::late(&self.tcx.hir(), param))
1717 Some(Region::early(&self.tcx.hir(), &mut index, param))
1720 GenericParamKind::Type { .. } => {
1726 let next_early_index = index + type_count;
1728 let scope = Scope::Binder {
1732 abstract_type_parent: true,
1733 track_lifetime_uses: false,
1735 self.with(scope, move |old_scope, this| {
1736 this.check_lifetime_params(old_scope, &generics.params);
1737 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1741 fn next_early_index_helper(&self, only_abstract_type_parent: bool) -> u32 {
1742 let mut scope = self.scope;
1745 Scope::Root => return 0,
1749 abstract_type_parent,
1751 } if (!only_abstract_type_parent || abstract_type_parent) =>
1753 return next_early_index
1756 Scope::Binder { s, .. }
1757 | Scope::Body { s, .. }
1758 | Scope::Elision { s, .. }
1759 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1764 /// Returns the next index one would use for an early-bound-region
1765 /// if extending the current scope.
1766 fn next_early_index(&self) -> u32 {
1767 self.next_early_index_helper(true)
1770 /// Returns the next index one would use for an `impl Trait` that
1771 /// is being converted into an `abstract type`. This will be the
1772 /// next early index from the enclosing item, for the most
1773 /// part. See the `abstract_type_parent` field for more info.
1774 fn next_early_index_for_abstract_type(&self) -> u32 {
1775 self.next_early_index_helper(false)
1778 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1779 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1781 // If we've already reported an error, just ignore `lifetime_ref`.
1782 if let LifetimeName::Error = lifetime_ref.name {
1786 // Walk up the scope chain, tracking the number of fn scopes
1787 // that we pass through, until we find a lifetime with the
1788 // given name or we run out of scopes.
1790 let mut late_depth = 0;
1791 let mut scope = self.scope;
1792 let mut outermost_body = None;
1795 Scope::Body { id, s } => {
1796 outermost_body = Some(id);
1805 ref lifetimes, s, ..
1807 match lifetime_ref.name {
1808 LifetimeName::Param(param_name) => {
1809 if let Some(&def) = lifetimes.get(¶m_name.modern()) {
1810 break Some(def.shifted(late_depth));
1813 _ => bug!("expected LifetimeName::Param"),
1820 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1826 if let Some(mut def) = result {
1827 if let Region::EarlyBound(..) = def {
1828 // Do not free early-bound regions, only late-bound ones.
1829 } else if let Some(body_id) = outermost_body {
1830 let fn_id = self.tcx.hir().body_owner(body_id);
1831 match self.tcx.hir().get(fn_id) {
1832 Node::Item(&hir::Item {
1833 node: hir::ItemKind::Fn(..),
1836 | Node::TraitItem(&hir::TraitItem {
1837 node: hir::TraitItemKind::Method(..),
1840 | Node::ImplItem(&hir::ImplItem {
1841 node: hir::ImplItemKind::Method(..),
1844 let scope = self.tcx.hir().local_def_id(fn_id);
1845 def = Region::Free(scope, def.id().unwrap());
1851 // Check for fn-syntax conflicts with in-band lifetime definitions
1852 if self.is_in_fn_syntax {
1854 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1855 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1860 "lifetimes used in `fn` or `Fn` syntax must be \
1861 explicitly declared using `<...>` binders"
1862 ).span_label(lifetime_ref.span, "in-band lifetime definition")
1867 | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1868 | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1869 | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1870 | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1871 | Region::LateBoundAnon(..)
1872 | Region::Free(..) => {}
1876 self.insert_lifetime(lifetime_ref, def);
1882 "use of undeclared lifetime name `{}`",
1884 ).span_label(lifetime_ref.span, "undeclared lifetime")
1889 fn visit_segment_args(&mut self, def: Def, depth: usize, generic_args: &'tcx hir::GenericArgs) {
1890 if generic_args.parenthesized {
1891 let was_in_fn_syntax = self.is_in_fn_syntax;
1892 self.is_in_fn_syntax = true;
1893 self.visit_fn_like_elision(generic_args.inputs(), Some(&generic_args.bindings[0].ty));
1894 self.is_in_fn_syntax = was_in_fn_syntax;
1898 let mut elide_lifetimes = true;
1899 let lifetimes = generic_args
1902 .filter_map(|arg| match arg {
1903 hir::GenericArg::Lifetime(lt) => {
1904 if !lt.is_elided() {
1905 elide_lifetimes = false;
1912 if elide_lifetimes {
1913 self.resolve_elided_lifetimes(lifetimes);
1915 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1918 // Figure out if this is a type/trait segment,
1919 // which requires object lifetime defaults.
1920 let parent_def_id = |this: &mut Self, def_id: DefId| {
1921 let def_key = this.tcx.def_key(def_id);
1923 krate: def_id.krate,
1924 index: def_key.parent.expect("missing parent"),
1927 let type_def_id = match def {
1928 Def::AssociatedTy(def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1929 Def::Variant(def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1931 | Def::Union(def_id)
1933 | Def::TyAlias(def_id)
1934 | Def::Trait(def_id) if depth == 0 =>
1941 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1943 let mut scope = self.scope;
1946 Scope::Root => break false,
1948 Scope::Body { .. } => break true,
1950 Scope::Binder { s, .. }
1951 | Scope::Elision { s, .. }
1952 | Scope::ObjectLifetimeDefault { s, .. } => {
1959 let map = &self.map;
1960 let unsubst = if let Some(id) = self.tcx.hir().as_local_node_id(def_id) {
1961 &map.object_lifetime_defaults[&id]
1964 self.xcrate_object_lifetime_defaults
1966 .or_insert_with(|| {
1967 tcx.generics_of(def_id)
1970 .filter_map(|param| match param.kind {
1971 GenericParamDefKind::Type {
1972 object_lifetime_default,
1974 } => Some(object_lifetime_default),
1975 GenericParamDefKind::Lifetime => None,
1982 .map(|set| match *set {
1983 Set1::Empty => if in_body {
1986 Some(Region::Static)
1989 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1990 GenericArg::Lifetime(lt) => Some(lt),
1993 r.subst(lifetimes, map)
2001 for arg in &generic_args.args {
2003 GenericArg::Lifetime(_) => {}
2004 GenericArg::Type(ty) => {
2005 if let Some(<) = object_lifetime_defaults.get(i) {
2006 let scope = Scope::ObjectLifetimeDefault {
2010 self.with(scope, |_, this| this.visit_ty(ty));
2019 for b in &generic_args.bindings {
2020 self.visit_assoc_type_binding(b);
2024 fn visit_fn_like_elision(&mut self, inputs: &'tcx [hir::Ty], output: Option<&'tcx P<hir::Ty>>) {
2025 debug!("visit_fn_like_elision: enter");
2026 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2027 let arg_scope = Scope::Elision {
2028 elide: arg_elide.clone(),
2031 self.with(arg_scope, |_, this| {
2032 for input in inputs {
2033 this.visit_ty(input);
2036 Scope::Elision { ref elide, .. } => {
2037 arg_elide = elide.clone();
2043 let output = match output {
2048 debug!("visit_fn_like_elision: determine output");
2050 // Figure out if there's a body we can get argument names from,
2051 // and whether there's a `self` argument (treated specially).
2052 let mut assoc_item_kind = None;
2053 let mut impl_self = None;
2054 let parent = self.tcx.hir().get_parent_node(output.id);
2055 let body = match self.tcx.hir().get(parent) {
2056 // `fn` definitions and methods.
2057 Node::Item(&hir::Item {
2058 node: hir::ItemKind::Fn(.., body),
2062 Node::TraitItem(&hir::TraitItem {
2063 node: hir::TraitItemKind::Method(_, ref m),
2066 if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
2068 .expect_item(self.tcx.hir().get_parent(parent))
2071 assoc_item_kind = trait_items
2073 .find(|ti| ti.id.node_id == parent)
2077 hir::TraitMethod::Required(_) => None,
2078 hir::TraitMethod::Provided(body) => Some(body),
2082 Node::ImplItem(&hir::ImplItem {
2083 node: hir::ImplItemKind::Method(_, body),
2086 if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
2088 .expect_item(self.tcx.hir().get_parent(parent))
2091 impl_self = Some(self_ty);
2092 assoc_item_kind = impl_items
2094 .find(|ii| ii.id.node_id == parent)
2100 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2101 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2102 // Everything else (only closures?) doesn't
2103 // actually enjoy elision in return types.
2105 self.visit_ty(output);
2110 let has_self = match assoc_item_kind {
2111 Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
2115 // In accordance with the rules for lifetime elision, we can determine
2116 // what region to use for elision in the output type in two ways.
2117 // First (determined here), if `self` is by-reference, then the
2118 // implied output region is the region of the self parameter.
2120 // Look for `self: &'a Self` - also desugared from `&'a self`,
2121 // and if that matches, use it for elision and return early.
2122 let is_self_ty = |def: Def| {
2123 if let Def::SelfTy(..) = def {
2127 // Can't always rely on literal (or implied) `Self` due
2128 // to the way elision rules were originally specified.
2129 let impl_self = impl_self.map(|ty| &ty.node);
2130 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) = impl_self {
2132 // Whitelist the types that unambiguously always
2133 // result in the same type constructor being used
2134 // (it can't differ between `Self` and `self`).
2135 Def::Struct(_) | Def::Union(_) | Def::Enum(_) | Def::PrimTy(_) => {
2136 return def == path.def
2145 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = inputs[0].node {
2146 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
2147 if is_self_ty(path.def) {
2148 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
2149 let scope = Scope::Elision {
2150 elide: Elide::Exact(lifetime),
2153 self.with(scope, |_, this| this.visit_ty(output));
2161 // Second, if there was exactly one lifetime (either a substitution or a
2162 // reference) in the arguments, then any anonymous regions in the output
2163 // have that lifetime.
2164 let mut possible_implied_output_region = None;
2165 let mut lifetime_count = 0;
2166 let arg_lifetimes = inputs
2169 .skip(has_self as usize)
2171 let mut gather = GatherLifetimes {
2173 outer_index: ty::INNERMOST,
2174 have_bound_regions: false,
2175 lifetimes: Default::default(),
2177 gather.visit_ty(input);
2179 lifetime_count += gather.lifetimes.len();
2181 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2182 // there's a chance that the unique lifetime of this
2183 // iteration will be the appropriate lifetime for output
2184 // parameters, so lets store it.
2185 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2188 ElisionFailureInfo {
2191 lifetime_count: gather.lifetimes.len(),
2192 have_bound_regions: gather.have_bound_regions,
2197 let elide = if lifetime_count == 1 {
2198 Elide::Exact(possible_implied_output_region.unwrap())
2200 Elide::Error(arg_lifetimes)
2203 debug!("visit_fn_like_elision: elide={:?}", elide);
2205 let scope = Scope::Elision {
2209 self.with(scope, |_, this| this.visit_ty(output));
2210 debug!("visit_fn_like_elision: exit");
2212 struct GatherLifetimes<'a> {
2213 map: &'a NamedRegionMap,
2214 outer_index: ty::DebruijnIndex,
2215 have_bound_regions: bool,
2216 lifetimes: FxHashSet<Region>,
2219 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2220 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2221 NestedVisitorMap::None
2224 fn visit_ty(&mut self, ty: &hir::Ty) {
2225 if let hir::TyKind::BareFn(_) = ty.node {
2226 self.outer_index.shift_in(1);
2228 if let hir::TyKind::TraitObject(ref bounds, ref lifetime) = ty.node {
2229 for bound in bounds {
2230 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2233 // Stay on the safe side and don't include the object
2234 // lifetime default (which may not end up being used).
2235 if !lifetime.is_elided() {
2236 self.visit_lifetime(lifetime);
2239 intravisit::walk_ty(self, ty);
2241 if let hir::TyKind::BareFn(_) = ty.node {
2242 self.outer_index.shift_out(1);
2246 fn visit_generic_param(&mut self, param: &hir::GenericParam) {
2247 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2248 // FIXME(eddyb) Do we want this? It only makes a difference
2249 // if this `for<'a>` lifetime parameter is never used.
2250 self.have_bound_regions = true;
2253 intravisit::walk_generic_param(self, param);
2256 fn visit_poly_trait_ref(
2258 trait_ref: &hir::PolyTraitRef,
2259 modifier: hir::TraitBoundModifier,
2261 self.outer_index.shift_in(1);
2262 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2263 self.outer_index.shift_out(1);
2266 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2267 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
2269 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2270 if debruijn < self.outer_index =>
2272 self.have_bound_regions = true;
2276 .insert(lifetime.shifted_out_to_binder(self.outer_index));
2284 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2285 if lifetime_refs.is_empty() {
2289 let span = lifetime_refs[0].span;
2290 let mut late_depth = 0;
2291 let mut scope = self.scope;
2294 // Do not assign any resolution, it will be inferred.
2295 Scope::Body { .. } => return,
2297 Scope::Root => break None,
2299 Scope::Binder { s, .. } => {
2304 Scope::Elision { ref elide, .. } => {
2305 let lifetime = match *elide {
2306 Elide::FreshLateAnon(ref counter) => {
2307 for lifetime_ref in lifetime_refs {
2308 let lifetime = Region::late_anon(counter).shifted(late_depth);
2309 self.insert_lifetime(lifetime_ref, lifetime);
2313 Elide::Exact(l) => l.shifted(late_depth),
2314 Elide::Error(ref e) => break Some(e),
2316 for lifetime_ref in lifetime_refs {
2317 self.insert_lifetime(lifetime_ref, lifetime);
2322 Scope::ObjectLifetimeDefault { s, .. } => {
2328 let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2329 let mut add_label = true;
2331 if let Some(params) = error {
2332 if lifetime_refs.len() == 1 {
2333 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2337 add_missing_lifetime_specifiers_label(&mut err, span, lifetime_refs.len());
2343 fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2344 match self.tcx.sess.source_map().span_to_snippet(span) {
2345 Ok(ref snippet) => {
2346 let (sugg, applicability) = if snippet == "&" {
2347 ("&'static ".to_owned(), Applicability::MachineApplicable)
2348 } else if snippet == "'_" {
2349 ("'static".to_owned(), Applicability::MachineApplicable)
2351 (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2353 db.span_suggestion_with_applicability(span, msg, sugg, applicability);
2363 fn report_elision_failure(
2365 db: &mut DiagnosticBuilder<'_>,
2366 params: &[ElisionFailureInfo],
2369 let mut m = String::new();
2370 let len = params.len();
2372 let elided_params: Vec<_> = params
2375 .filter(|info| info.lifetime_count > 0)
2378 let elided_len = elided_params.len();
2380 for (i, info) in elided_params.into_iter().enumerate() {
2381 let ElisionFailureInfo {
2388 let help_name = if let Some(body) = parent {
2389 let arg = &self.tcx.hir().body(body).arguments[index];
2390 format!("`{}`", self.tcx.hir().node_to_pretty_string(arg.pat.id))
2392 format!("argument {}", index + 1)
2400 "one of {}'s {} {}lifetimes",
2403 if have_bound_regions { "free " } else { "" }
2408 if elided_len == 2 && i == 0 {
2410 } else if i + 2 == elided_len {
2411 m.push_str(", or ");
2412 } else if i != elided_len - 1 {
2420 "this function's return type contains a borrowed value, but \
2421 there is no value for it to be borrowed from"
2423 self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2424 } else if elided_len == 0 {
2427 "this function's return type contains a borrowed value with \
2428 an elided lifetime, but the lifetime cannot be derived from \
2431 let msg = "consider giving it an explicit bounded or 'static lifetime";
2432 self.suggest_lifetime(db, span, msg)
2433 } else if elided_len == 1 {
2436 "this function's return type contains a borrowed value, but \
2437 the signature does not say which {} it is borrowed from",
2444 "this function's return type contains a borrowed value, but \
2445 the signature does not say whether it is borrowed from {}",
2452 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2453 let mut late_depth = 0;
2454 let mut scope = self.scope;
2455 let lifetime = loop {
2457 Scope::Binder { s, .. } => {
2462 Scope::Root | Scope::Elision { .. } => break Region::Static,
2464 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2466 Scope::ObjectLifetimeDefault {
2467 lifetime: Some(l), ..
2471 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2474 fn check_lifetime_params(
2476 old_scope: ScopeRef<'_>,
2477 params: &'tcx [hir::GenericParam],
2479 let lifetimes: Vec<_> = params
2481 .filter_map(|param| match param.kind {
2482 GenericParamKind::Lifetime { .. } => Some((param, param.name)),
2486 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2487 if let hir::ParamName::Plain(_) = lifetime_i_name {
2488 let name = lifetime_i_name.ident().name;
2489 if name == keywords::UnderscoreLifetime.name()
2490 || name == keywords::StaticLifetime.name()
2492 let mut err = struct_span_err!(
2496 "invalid lifetime parameter name: `{}`",
2497 lifetime_i.name.ident(),
2501 format!("{} is a reserved lifetime name", name),
2507 // It is a hard error to shadow a lifetime within the same scope.
2508 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2509 if lifetime_i_name == lifetime_j_name {
2514 "lifetime name `{}` declared twice in the same scope",
2515 lifetime_j.name.ident()
2516 ).span_label(lifetime_j.span, "declared twice")
2517 .span_label(lifetime_i.span, "previous declaration here")
2522 // It is a soft error to shadow a lifetime within a parent scope.
2523 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2525 for bound in &lifetime_i.bounds {
2527 hir::GenericBound::Outlives(lt) => match lt.name {
2528 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2530 "use of `'_` in illegal place, but not caught by lowering",
2532 hir::LifetimeName::Static => {
2533 self.insert_lifetime(lt, Region::Static);
2537 lifetime_i.span.to(lt.span),
2539 "unnecessary lifetime parameter `{}`",
2540 lifetime_i.name.ident(),
2544 "you can use the `'static` lifetime directly, in place of `{}`",
2545 lifetime_i.name.ident(),
2549 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2550 self.resolve_lifetime_ref(lt);
2552 hir::LifetimeName::Error => {
2553 // No need to do anything, error already reported.
2562 fn check_lifetime_param_for_shadowing(
2564 mut old_scope: ScopeRef<'_>,
2565 param: &'tcx hir::GenericParam,
2567 for label in &self.labels_in_fn {
2568 // FIXME (#24278): non-hygienic comparison
2569 if param.name.ident().name == label.name {
2570 signal_shadowing_problem(
2573 original_label(label.span),
2574 shadower_lifetime(¶m),
2582 Scope::Body { s, .. }
2583 | Scope::Elision { s, .. }
2584 | Scope::ObjectLifetimeDefault { s, .. } => {
2593 ref lifetimes, s, ..
2595 if let Some(&def) = lifetimes.get(¶m.name.modern()) {
2596 let node_id = self.tcx.hir().as_local_node_id(def.id().unwrap()).unwrap();
2598 signal_shadowing_problem(
2600 param.name.ident().name,
2601 original_lifetime(self.tcx.hir().span(node_id)),
2602 shadower_lifetime(¶m),
2613 /// Returns true if, in the current scope, replacing `'_` would be
2614 /// equivalent to a single-use lifetime.
2615 fn track_lifetime_uses(&self) -> bool {
2616 let mut scope = self.scope;
2619 Scope::Root => break false,
2621 // Inside of items, it depends on the kind of item.
2623 track_lifetime_uses,
2625 } => break track_lifetime_uses,
2627 // Inside a body, `'_` will use an inference variable,
2629 Scope::Body { .. } => break true,
2631 // A lifetime only used in a fn argument could as well
2632 // be replaced with `'_`, as that would generate a
2635 elide: Elide::FreshLateAnon(_),
2639 // In the return type or other such place, `'_` is not
2640 // going to make a fresh name, so we cannot
2641 // necessarily replace a single-use lifetime with
2644 elide: Elide::Exact(_),
2648 elide: Elide::Error(_),
2652 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2657 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2658 if lifetime_ref.id == ast::DUMMY_NODE_ID {
2661 "lifetime reference not renumbered, \
2662 probably a bug in syntax::fold"
2667 "insert_lifetime: {} resolved to {:?} span={:?}",
2668 self.tcx.hir().node_to_string(lifetime_ref.id),
2670 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2672 self.map.defs.insert(lifetime_ref.id, def);
2675 Region::LateBoundAnon(..) | Region::Static => {
2676 // These are anonymous lifetimes or lifetimes that are not declared.
2679 Region::Free(_, def_id)
2680 | Region::LateBound(_, def_id, _)
2681 | Region::EarlyBound(_, def_id, _) => {
2682 // A lifetime declared by the user.
2683 let track_lifetime_uses = self.track_lifetime_uses();
2685 "insert_lifetime: track_lifetime_uses={}",
2688 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2689 debug!("insert_lifetime: first use of {:?}", def_id);
2691 .insert(def_id, LifetimeUseSet::One(lifetime_ref));
2693 debug!("insert_lifetime: many uses of {:?}", def_id);
2694 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2700 /// Sometimes we resolve a lifetime, but later find that it is an
2701 /// error (esp. around impl trait). In that case, we remove the
2702 /// entry into `map.defs` so as not to confuse later code.
2703 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2704 let old_value = self.map.defs.remove(&lifetime_ref.id);
2705 assert_eq!(old_value, Some(bad_def));
2709 /// Detects late-bound lifetimes and inserts them into
2710 /// `map.late_bound`.
2712 /// A region declared on a fn is **late-bound** if:
2713 /// - it is constrained by an argument type;
2714 /// - it does not appear in a where-clause.
2716 /// "Constrained" basically means that it appears in any type but
2717 /// not amongst the inputs to a projection. In other words, `<&'a
2718 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2719 fn insert_late_bound_lifetimes(
2720 map: &mut NamedRegionMap,
2722 generics: &hir::Generics,
2725 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2729 let mut constrained_by_input = ConstrainedCollector::default();
2730 for arg_ty in &decl.inputs {
2731 constrained_by_input.visit_ty(arg_ty);
2734 let mut appears_in_output = AllCollector::default();
2735 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2738 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2739 constrained_by_input.regions
2742 // Walk the lifetimes that appear in where clauses.
2744 // Subtle point: because we disallow nested bindings, we can just
2745 // ignore binders here and scrape up all names we see.
2746 let mut appears_in_where_clause = AllCollector::default();
2747 appears_in_where_clause.visit_generics(generics);
2749 for param in &generics.params {
2750 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2751 if !param.bounds.is_empty() {
2752 // `'a: 'b` means both `'a` and `'b` are referenced
2753 appears_in_where_clause
2755 .insert(hir::LifetimeName::Param(param.name.modern()));
2761 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2762 appears_in_where_clause.regions
2765 // Late bound regions are those that:
2766 // - appear in the inputs
2767 // - do not appear in the where-clauses
2768 // - are not implicitly captured by `impl Trait`
2769 for param in &generics.params {
2771 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2773 // Types are not late-bound.
2774 hir::GenericParamKind::Type { .. } => continue,
2777 let lt_name = hir::LifetimeName::Param(param.name.modern());
2778 // appears in the where clauses? early-bound.
2779 if appears_in_where_clause.regions.contains(<_name) {
2783 // does not appear in the inputs, but appears in the return type? early-bound.
2784 if !constrained_by_input.regions.contains(<_name)
2785 && appears_in_output.regions.contains(<_name)
2791 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2796 let inserted = map.late_bound.insert(param.id);
2797 assert!(inserted, "visited lifetime {:?} twice", param.id);
2803 struct ConstrainedCollector {
2804 regions: FxHashSet<hir::LifetimeName>,
2807 impl<'v> Visitor<'v> for ConstrainedCollector {
2808 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2809 NestedVisitorMap::None
2812 fn visit_ty(&mut self, ty: &'v hir::Ty) {
2814 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2815 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2816 // ignore lifetimes appearing in associated type
2817 // projections, as they are not *constrained*
2821 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2822 // consider only the lifetimes on the final
2823 // segment; I am not sure it's even currently
2824 // valid to have them elsewhere, but even if it
2825 // is, those would be potentially inputs to
2827 if let Some(last_segment) = path.segments.last() {
2828 self.visit_path_segment(path.span, last_segment);
2833 intravisit::walk_ty(self, ty);
2838 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2839 self.regions.insert(lifetime_ref.name.modern());
2844 struct AllCollector {
2845 regions: FxHashSet<hir::LifetimeName>,
2848 impl<'v> Visitor<'v> for AllCollector {
2849 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2850 NestedVisitorMap::None
2853 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2854 self.regions.insert(lifetime_ref.name.modern());
2859 fn report_missing_lifetime_specifiers(
2863 ) -> DiagnosticBuilder<'_> {
2868 "missing lifetime specifier{}",
2869 if count > 1 { "s" } else { "" }
2873 fn add_missing_lifetime_specifiers_label(
2874 err: &mut DiagnosticBuilder<'_>,
2879 err.span_label(span, format!("expected {} lifetime parameters", count));
2881 err.span_label(span, "expected lifetime parameter");