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.
8 use crate::hir::def::{Res, DefKind};
9 use crate::hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
10 use crate::hir::map::Map;
11 use crate::hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName};
12 use crate::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
14 use crate::rustc::lint;
15 use crate::session::Session;
16 use crate::util::nodemap::{DefIdMap, FxHashMap, FxHashSet, HirIdMap, HirIdSet};
17 use errors::{Applicability, DiagnosticBuilder};
18 use rustc_macros::HashStable;
21 use std::mem::replace;
25 use syntax::symbol::{kw, sym};
28 use crate::hir::intravisit::{self, NestedVisitorMap, Visitor};
29 use crate::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, HashStable)]
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, HashStable)]
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_from_hir_id(param.hir_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_from_hir_id(param.hir_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.hir_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, HashStable)]
171 impl<T: PartialEq> Set1<T> {
172 pub fn insert(&mut self, value: T) {
174 Set1::Empty => Set1::One(value),
175 Set1::One(old) if *old == value => return,
181 pub type ObjectLifetimeDefault = Set1<Region>;
183 /// Maps the id of each lifetime reference to the lifetime decl
184 /// that it corresponds to.
186 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
187 /// actual use. It has the same data, but indexed by `DefIndex`. This
190 struct NamedRegionMap {
191 // maps from every use of a named (not anonymous) lifetime to a
192 // `Region` describing how that region is bound
193 pub defs: HirIdMap<Region>,
195 // the set of lifetime def ids that are late-bound; a region can
196 // be late-bound if (a) it does NOT appear in a where-clause and
197 // (b) it DOES appear in the arguments.
198 pub late_bound: HirIdSet,
200 // For each type and trait definition, maps type parameters
201 // to the trait object lifetime defaults computed from them.
202 pub object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
205 /// See [`NamedRegionMap`].
207 pub struct ResolveLifetimes {
208 defs: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Region>>,
209 late_bound: FxHashMap<LocalDefId, FxHashSet<ItemLocalId>>,
210 object_lifetime_defaults:
211 FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Vec<ObjectLifetimeDefault>>>,
214 impl_stable_hash_for!(struct crate::middle::resolve_lifetime::ResolveLifetimes {
217 object_lifetime_defaults
220 struct LifetimeContext<'a, 'tcx> {
222 map: &'a mut NamedRegionMap,
225 /// This is slightly complicated. Our representation for poly-trait-refs contains a single
226 /// binder and thus we only allow a single level of quantification. However,
227 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
228 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
229 /// correct when representing these constraints, we should only introduce one
230 /// scope. However, we want to support both locations for the quantifier and
231 /// during lifetime resolution we want precise information (so we can't
232 /// desugar in an earlier phase).
234 /// So, if we encounter a quantifier at the outer scope, we set
235 /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
236 /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
237 /// then we introduce the scope at the inner quantifier.
238 trait_ref_hack: bool,
240 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
241 is_in_fn_syntax: bool,
243 /// List of labels in the function/method currently under analysis.
244 labels_in_fn: Vec<ast::Ident>,
246 /// Cache for cross-crate per-definition object lifetime defaults.
247 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
249 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
254 /// Declares lifetimes, and each can be early-bound or late-bound.
255 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
256 /// it should be shifted by the number of `Binder`s in between the
257 /// declaration `Binder` and the location it's referenced from.
259 lifetimes: FxHashMap<hir::ParamName, Region>,
261 /// if we extend this scope with another scope, what is the next index
262 /// we should use for an early-bound region?
263 next_early_index: u32,
265 /// Flag is set to true if, in this binder, `'_` would be
266 /// equivalent to a "single-use region". This is true on
267 /// impls, but not other kinds of items.
268 track_lifetime_uses: bool,
270 /// Whether or not this binder would serve as the parent
271 /// binder for abstract types introduced within. For example:
273 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
275 /// Here, the abstract types we create for the `impl Trait`
276 /// and `impl Trait2` references will both have the `foo` item
277 /// as their parent. When we get to `impl Trait2`, we find
278 /// that it is nested within the `for<>` binder -- this flag
279 /// allows us to skip that when looking for the parent binder
280 /// of the resulting abstract type.
281 abstract_type_parent: bool,
286 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
287 /// if this is a fn body, otherwise the original definitions are used.
288 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
289 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
295 /// A scope which either determines unspecified lifetimes or errors
296 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
302 /// Use a specific lifetime (if `Some`) or leave it unset (to be
303 /// inferred in a function body or potentially error outside one),
304 /// for the default choice of lifetime in a trait object type.
305 ObjectLifetimeDefault {
306 lifetime: Option<Region>,
313 #[derive(Clone, Debug)]
315 /// Use a fresh anonymous late-bound lifetime each time, by
316 /// incrementing the counter to generate sequential indices.
317 FreshLateAnon(Cell<u32>),
318 /// Always use this one lifetime.
320 /// Less or more than one lifetime were found, error on unspecified.
321 Error(Vec<ElisionFailureInfo>),
324 #[derive(Clone, Debug)]
325 struct ElisionFailureInfo {
326 /// Where we can find the argument pattern.
327 parent: Option<hir::BodyId>,
328 /// The index of the argument in the original definition.
330 lifetime_count: usize,
331 have_bound_regions: bool,
334 type ScopeRef<'a> = &'a Scope<'a>;
336 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
338 pub fn provide(providers: &mut ty::query::Providers<'_>) {
339 *providers = ty::query::Providers {
342 named_region_map: |tcx, id| {
343 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
344 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id)
347 is_late_bound_map: |tcx, id| {
348 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
349 tcx.resolve_lifetimes(LOCAL_CRATE)
354 object_lifetime_defaults_map: |tcx, id| {
355 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
356 tcx.resolve_lifetimes(LOCAL_CRATE)
357 .object_lifetime_defaults
364 // (*) FIXME the query should be defined to take a LocalDefId
367 /// Computes the `ResolveLifetimes` map that contains data for the
368 /// entire crate. You should not read the result of this query
369 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
371 fn resolve_lifetimes<'tcx>(tcx: TyCtxt<'tcx>, for_krate: CrateNum) -> &'tcx ResolveLifetimes {
372 assert_eq!(for_krate, LOCAL_CRATE);
374 let named_region_map = krate(tcx);
376 let mut rl = ResolveLifetimes::default();
378 for (hir_id, v) in named_region_map.defs {
379 let map = rl.defs.entry(hir_id.owner_local_def_id()).or_default();
380 map.insert(hir_id.local_id, v);
382 for hir_id in named_region_map.late_bound {
383 let map = rl.late_bound
384 .entry(hir_id.owner_local_def_id())
386 map.insert(hir_id.local_id);
388 for (hir_id, v) in named_region_map.object_lifetime_defaults {
389 let map = rl.object_lifetime_defaults
390 .entry(hir_id.owner_local_def_id())
392 map.insert(hir_id.local_id, v);
398 fn krate<'tcx>(tcx: TyCtxt<'tcx>) -> NamedRegionMap {
399 let krate = tcx.hir().krate();
400 let mut map = NamedRegionMap {
401 defs: Default::default(),
402 late_bound: Default::default(),
403 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
406 let mut visitor = LifetimeContext {
410 trait_ref_hack: false,
411 is_in_fn_syntax: false,
412 labels_in_fn: vec![],
413 xcrate_object_lifetime_defaults: Default::default(),
414 lifetime_uses: &mut Default::default(),
416 for (_, item) in &krate.items {
417 visitor.visit_item(item);
423 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
424 /// We have to account for this when computing the index of the other generic parameters.
425 /// This function returns whether there is such an implicit parameter defined on the given item.
426 fn sub_items_have_self_param(node: &hir::ItemKind) -> bool {
428 hir::ItemKind::Trait(..) |
429 hir::ItemKind::TraitAlias(..) => true,
434 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
435 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
436 NestedVisitorMap::All(&self.tcx.hir())
439 // We want to nest trait/impl items in their parent, but nothing else.
440 fn visit_nested_item(&mut self, _: hir::ItemId) {}
442 fn visit_nested_body(&mut self, body: hir::BodyId) {
443 // Each body has their own set of labels, save labels.
444 let saved = replace(&mut self.labels_in_fn, vec![]);
445 let body = self.tcx.hir().body(body);
446 extract_labels(self, body);
453 this.visit_body(body);
456 replace(&mut self.labels_in_fn, saved);
459 fn visit_item(&mut self, item: &'tcx hir::Item) {
461 hir::ItemKind::Fn(ref decl, _, ref generics, _) => {
462 self.visit_early_late(None, decl, generics, |this| {
463 intravisit::walk_item(this, item);
467 hir::ItemKind::ExternCrate(_)
468 | hir::ItemKind::Use(..)
469 | hir::ItemKind::Mod(..)
470 | hir::ItemKind::ForeignMod(..)
471 | hir::ItemKind::GlobalAsm(..) => {
472 // These sorts of items have no lifetime parameters at all.
473 intravisit::walk_item(self, item);
475 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
476 // No lifetime parameters, but implied 'static.
477 let scope = Scope::Elision {
478 elide: Elide::Exact(Region::Static),
481 self.with(scope, |_, this| intravisit::walk_item(this, item));
483 hir::ItemKind::Existential(hir::ExistTy {
484 impl_trait_fn: Some(_),
487 // currently existential type declarations are just generated from impl Trait
488 // items. doing anything on this node is irrelevant, as we currently don't need
491 hir::ItemKind::Ty(_, ref generics)
492 | hir::ItemKind::Existential(hir::ExistTy {
497 | hir::ItemKind::Enum(_, ref generics)
498 | hir::ItemKind::Struct(_, ref generics)
499 | hir::ItemKind::Union(_, ref generics)
500 | hir::ItemKind::Trait(_, _, ref generics, ..)
501 | hir::ItemKind::TraitAlias(ref generics, ..)
502 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
503 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
504 // This is not true for other kinds of items.x
505 let track_lifetime_uses = match item.node {
506 hir::ItemKind::Impl(..) => true,
509 // These kinds of items have only early-bound lifetime parameters.
510 let mut index = if sub_items_have_self_param(&item.node) {
511 1 // Self comes before lifetimes
515 let mut non_lifetime_count = 0;
516 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
517 GenericParamKind::Lifetime { .. } => {
518 Some(Region::early(&self.tcx.hir(), &mut index, param))
520 GenericParamKind::Type { .. } |
521 GenericParamKind::Const { .. } => {
522 non_lifetime_count += 1;
526 let scope = Scope::Binder {
528 next_early_index: index + non_lifetime_count,
529 abstract_type_parent: true,
533 self.with(scope, |old_scope, this| {
534 this.check_lifetime_params(old_scope, &generics.params);
535 intravisit::walk_item(this, item);
541 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
543 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
544 self.visit_early_late(None, decl, generics, |this| {
545 intravisit::walk_foreign_item(this, item);
548 hir::ForeignItemKind::Static(..) => {
549 intravisit::walk_foreign_item(self, item);
551 hir::ForeignItemKind::Type => {
552 intravisit::walk_foreign_item(self, item);
557 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
558 debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
560 hir::TyKind::BareFn(ref c) => {
561 let next_early_index = self.next_early_index();
562 let was_in_fn_syntax = self.is_in_fn_syntax;
563 self.is_in_fn_syntax = true;
564 let scope = Scope::Binder {
565 lifetimes: c.generic_params
567 .filter_map(|param| match param.kind {
568 GenericParamKind::Lifetime { .. } => {
569 Some(Region::late(&self.tcx.hir(), param))
576 track_lifetime_uses: true,
577 abstract_type_parent: false,
579 self.with(scope, |old_scope, this| {
580 // a bare fn has no bounds, so everything
581 // contained within is scoped within its binder.
582 this.check_lifetime_params(old_scope, &c.generic_params);
583 intravisit::walk_ty(this, ty);
585 self.is_in_fn_syntax = was_in_fn_syntax;
587 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
588 for bound in bounds {
589 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
591 match lifetime.name {
592 LifetimeName::Implicit => {
593 // If the user does not write *anything*, we
594 // use the object lifetime defaulting
595 // rules. So e.g., `Box<dyn Debug>` becomes
596 // `Box<dyn Debug + 'static>`.
597 self.resolve_object_lifetime_default(lifetime)
599 LifetimeName::Underscore => {
600 // If the user writes `'_`, we use the *ordinary* elision
601 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
602 // resolved the same as the `'_` in `&'_ Foo`.
605 self.resolve_elided_lifetimes(vec![lifetime])
607 LifetimeName::Param(_) | LifetimeName::Static => {
608 // If the user wrote an explicit name, use that.
609 self.visit_lifetime(lifetime);
611 LifetimeName::Error => {}
614 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
615 self.visit_lifetime(lifetime_ref);
616 let scope = Scope::ObjectLifetimeDefault {
617 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
620 self.with(scope, |_, this| this.visit_ty(&mt.ty));
622 hir::TyKind::Def(item_id, ref lifetimes) => {
623 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
624 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
625 // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
626 // ^ ^ this gets resolved in the scope of
627 // the exist_ty generics
628 let (generics, bounds) = match self.tcx.hir().expect_item(item_id.id).node
630 // named existential types are reached via TyKind::Path
631 // this arm is for `impl Trait` in the types of statics, constants and locals
632 hir::ItemKind::Existential(hir::ExistTy {
636 intravisit::walk_ty(self, ty);
639 // RPIT (return position impl trait)
640 hir::ItemKind::Existential(hir::ExistTy {
644 }) => (generics, bounds),
645 ref i => bug!("impl Trait pointed to non-existential type?? {:#?}", i),
648 // Resolve the lifetimes that are applied to the existential type.
649 // These are resolved in the current scope.
650 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
651 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
652 // ^ ^this gets resolved in the current scope
653 for lifetime in lifetimes {
654 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
655 self.visit_lifetime(lifetime);
657 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
658 // and ban them. Type variables instantiated inside binders aren't
659 // well-supported at the moment, so this doesn't work.
660 // In the future, this should be fixed and this error should be removed.
661 let def = self.map.defs.get(&lifetime.hir_id).cloned();
662 if let Some(Region::LateBound(_, def_id, _)) = def {
663 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
664 // Ensure that the parent of the def is an item, not HRTB
665 let parent_id = self.tcx.hir().get_parent_node(hir_id);
666 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
667 let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
668 let krate = self.tcx.hir().forest.krate();
670 if !(krate.items.contains_key(&parent_id)
671 || krate.impl_items.contains_key(&parent_impl_id)
672 || krate.trait_items.contains_key(&parent_trait_id))
678 "`impl Trait` can only capture lifetimes \
679 bound at the fn or impl level"
681 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
688 // We want to start our early-bound indices at the end of the parent scope,
689 // not including any parent `impl Trait`s.
690 let mut index = self.next_early_index_for_abstract_type();
691 debug!("visit_ty: index = {}", index);
693 let mut elision = None;
694 let mut lifetimes = FxHashMap::default();
695 let mut non_lifetime_count = 0;
696 for param in &generics.params {
698 GenericParamKind::Lifetime { .. } => {
699 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
700 if let hir::ParamName::Plain(param_name) = name {
701 if param_name.name == kw::UnderscoreLifetime {
702 // Pick the elided lifetime "definition" if one exists
703 // and use it to make an elision scope.
706 lifetimes.insert(name, reg);
709 lifetimes.insert(name, reg);
712 GenericParamKind::Type { .. } |
713 GenericParamKind::Const { .. } => {
714 non_lifetime_count += 1;
718 let next_early_index = index + non_lifetime_count;
720 if let Some(elision_region) = elision {
721 let scope = Scope::Elision {
722 elide: Elide::Exact(elision_region),
725 self.with(scope, |_old_scope, this| {
726 let scope = Scope::Binder {
730 track_lifetime_uses: true,
731 abstract_type_parent: false,
733 this.with(scope, |_old_scope, this| {
734 this.visit_generics(generics);
735 for bound in bounds {
736 this.visit_param_bound(bound);
741 let scope = Scope::Binder {
745 track_lifetime_uses: true,
746 abstract_type_parent: false,
748 self.with(scope, |_old_scope, this| {
749 this.visit_generics(generics);
750 for bound in bounds {
751 this.visit_param_bound(bound);
756 hir::TyKind::CVarArgs(ref lt) => {
757 // Resolve the generated lifetime for the C-variadic arguments.
758 // The lifetime is generated in AST -> HIR lowering.
759 if lt.name.is_elided() {
760 self.resolve_elided_lifetimes(vec![lt])
763 _ => intravisit::walk_ty(self, ty),
767 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
768 use self::hir::TraitItemKind::*;
769 match trait_item.node {
770 Method(ref sig, _) => {
772 self.visit_early_late(
773 Some(tcx.hir().get_parent_item(trait_item.hir_id)),
775 &trait_item.generics,
776 |this| intravisit::walk_trait_item(this, trait_item),
779 Type(ref bounds, ref ty) => {
780 let generics = &trait_item.generics;
781 let mut index = self.next_early_index();
782 debug!("visit_ty: index = {}", index);
783 let mut non_lifetime_count = 0;
784 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
785 GenericParamKind::Lifetime { .. } => {
786 Some(Region::early(&self.tcx.hir(), &mut index, param))
788 GenericParamKind::Type { .. } |
789 GenericParamKind::Const { .. } => {
790 non_lifetime_count += 1;
794 let scope = Scope::Binder {
796 next_early_index: index + non_lifetime_count,
798 track_lifetime_uses: true,
799 abstract_type_parent: true,
801 self.with(scope, |_old_scope, this| {
802 this.visit_generics(generics);
803 for bound in bounds {
804 this.visit_param_bound(bound);
806 if let Some(ty) = ty {
812 // Only methods and types support generics.
813 assert!(trait_item.generics.params.is_empty());
814 intravisit::walk_trait_item(self, trait_item);
819 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
820 use self::hir::ImplItemKind::*;
821 match impl_item.node {
822 Method(ref sig, _) => {
824 self.visit_early_late(
825 Some(tcx.hir().get_parent_item(impl_item.hir_id)),
828 |this| intravisit::walk_impl_item(this, impl_item),
832 let generics = &impl_item.generics;
833 let mut index = self.next_early_index();
834 let mut non_lifetime_count = 0;
835 debug!("visit_ty: index = {}", index);
836 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
837 GenericParamKind::Lifetime { .. } => {
838 Some(Region::early(&self.tcx.hir(), &mut index, param))
840 GenericParamKind::Const { .. } |
841 GenericParamKind::Type { .. } => {
842 non_lifetime_count += 1;
846 let scope = Scope::Binder {
848 next_early_index: index + non_lifetime_count,
850 track_lifetime_uses: true,
851 abstract_type_parent: true,
853 self.with(scope, |_old_scope, this| {
854 this.visit_generics(generics);
858 Existential(ref bounds) => {
859 let generics = &impl_item.generics;
860 let mut index = self.next_early_index();
861 let mut next_early_index = index;
862 debug!("visit_ty: index = {}", index);
863 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
864 GenericParamKind::Lifetime { .. } => {
865 Some(Region::early(&self.tcx.hir(), &mut index, param))
867 GenericParamKind::Type { .. } => {
868 next_early_index += 1;
871 GenericParamKind::Const { .. } => {
872 next_early_index += 1;
877 let scope = Scope::Binder {
881 track_lifetime_uses: true,
882 abstract_type_parent: true,
884 self.with(scope, |_old_scope, this| {
885 this.visit_generics(generics);
886 for bound in bounds {
887 this.visit_param_bound(bound);
892 // Only methods and types support generics.
893 assert!(impl_item.generics.params.is_empty());
894 intravisit::walk_impl_item(self, impl_item);
899 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
900 if lifetime_ref.is_elided() {
901 self.resolve_elided_lifetimes(vec![lifetime_ref]);
904 if lifetime_ref.is_static() {
905 self.insert_lifetime(lifetime_ref, Region::Static);
908 self.resolve_lifetime_ref(lifetime_ref);
911 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
912 for (i, segment) in path.segments.iter().enumerate() {
913 let depth = path.segments.len() - i - 1;
914 if let Some(ref args) = segment.args {
915 self.visit_segment_args(path.res, depth, args);
920 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
921 let output = match fd.output {
922 hir::DefaultReturn(_) => None,
923 hir::Return(ref ty) => Some(&**ty),
925 self.visit_fn_like_elision(&fd.inputs, output);
928 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
929 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
930 for param in &generics.params {
932 GenericParamKind::Lifetime { .. } => {}
933 GenericParamKind::Type { ref default, .. } => {
934 walk_list!(self, visit_param_bound, ¶m.bounds);
935 if let Some(ref ty) = default {
939 GenericParamKind::Const { ref ty, .. } => {
940 walk_list!(self, visit_param_bound, ¶m.bounds);
945 for predicate in &generics.where_clause.predicates {
947 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
950 ref bound_generic_params,
953 let lifetimes: FxHashMap<_, _> = bound_generic_params
955 .filter_map(|param| match param.kind {
956 GenericParamKind::Lifetime { .. } => {
957 Some(Region::late(&self.tcx.hir(), param))
962 if !lifetimes.is_empty() {
963 self.trait_ref_hack = true;
964 let next_early_index = self.next_early_index();
965 let scope = Scope::Binder {
969 track_lifetime_uses: true,
970 abstract_type_parent: false,
972 let result = self.with(scope, |old_scope, this| {
973 this.check_lifetime_params(old_scope, &bound_generic_params);
974 this.visit_ty(&bounded_ty);
975 walk_list!(this, visit_param_bound, bounds);
977 self.trait_ref_hack = false;
980 self.visit_ty(&bounded_ty);
981 walk_list!(self, visit_param_bound, bounds);
984 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
989 self.visit_lifetime(lifetime);
990 walk_list!(self, visit_param_bound, bounds);
992 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
997 self.visit_ty(lhs_ty);
998 self.visit_ty(rhs_ty);
1004 fn visit_poly_trait_ref(
1006 trait_ref: &'tcx hir::PolyTraitRef,
1007 _modifier: hir::TraitBoundModifier,
1009 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1011 if !self.trait_ref_hack || trait_ref.bound_generic_params.iter().any(|param| {
1013 GenericParamKind::Lifetime { .. } => true,
1017 if self.trait_ref_hack {
1022 "nested quantification of lifetimes"
1025 let next_early_index = self.next_early_index();
1026 let scope = Scope::Binder {
1027 lifetimes: trait_ref
1028 .bound_generic_params
1030 .filter_map(|param| match param.kind {
1031 GenericParamKind::Lifetime { .. } => {
1032 Some(Region::late(&self.tcx.hir(), param))
1039 track_lifetime_uses: true,
1040 abstract_type_parent: false,
1042 self.with(scope, |old_scope, this| {
1043 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1044 walk_list!(this, visit_generic_param, &trait_ref.bound_generic_params);
1045 this.visit_trait_ref(&trait_ref.trait_ref)
1048 self.visit_trait_ref(&trait_ref.trait_ref)
1053 #[derive(Copy, Clone, PartialEq)]
1067 fn original_label(span: Span) -> Original {
1069 kind: ShadowKind::Label,
1073 fn shadower_label(span: Span) -> Shadower {
1075 kind: ShadowKind::Label,
1079 fn original_lifetime(span: Span) -> Original {
1081 kind: ShadowKind::Lifetime,
1085 fn shadower_lifetime(param: &hir::GenericParam) -> Shadower {
1087 kind: ShadowKind::Lifetime,
1093 fn desc(&self) -> &'static str {
1095 ShadowKind::Label => "label",
1096 ShadowKind::Lifetime => "lifetime",
1101 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &P<[hir::GenericParam]>) {
1102 let lifetime_params: Vec<_> = params
1104 .filter_map(|param| match param.kind {
1105 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1109 let explicit = lifetime_params
1111 .find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1112 let in_band = lifetime_params
1114 .find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1116 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1121 "cannot mix in-band and explicit lifetime definitions"
1122 ).span_label(*in_band_span, "in-band lifetime definition here")
1123 .span_label(*explicit_span, "explicit lifetime definition here")
1128 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: ast::Name, orig: Original, shadower: Shadower) {
1129 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1130 // lifetime/lifetime shadowing is an error
1135 "{} name `{}` shadows a \
1136 {} name that is already in scope",
1137 shadower.kind.desc(),
1142 // shadowing involving a label is only a warning, due to issues with
1143 // labels and lifetimes not being macro-hygienic.
1144 tcx.sess.struct_span_warn(
1147 "{} name `{}` shadows a \
1148 {} name that is already in scope",
1149 shadower.kind.desc(),
1155 err.span_label(orig.span, "first declared here");
1156 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1160 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1161 // if one of the label shadows a lifetime or another label.
1162 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
1163 struct GatherLabels<'a, 'tcx> {
1165 scope: ScopeRef<'a>,
1166 labels_in_fn: &'a mut Vec<ast::Ident>,
1169 let mut gather = GatherLabels {
1172 labels_in_fn: &mut ctxt.labels_in_fn,
1174 gather.visit_body(body);
1176 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1177 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1178 NestedVisitorMap::None
1181 fn visit_expr(&mut self, ex: &hir::Expr) {
1182 if let Some(label) = expression_label(ex) {
1183 for prior_label in &self.labels_in_fn[..] {
1184 // FIXME (#24278): non-hygienic comparison
1185 if label.name == prior_label.name {
1186 signal_shadowing_problem(
1189 original_label(prior_label.span),
1190 shadower_label(label.span),
1195 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1197 self.labels_in_fn.push(label);
1199 intravisit::walk_expr(self, ex)
1203 fn expression_label(ex: &hir::Expr) -> Option<ast::Ident> {
1205 hir::ExprKind::While(.., Some(label)) | hir::ExprKind::Loop(_, Some(label), _) => {
1212 fn check_if_label_shadows_lifetime(
1214 mut scope: ScopeRef<'_>,
1219 Scope::Body { s, .. }
1220 | Scope::Elision { s, .. }
1221 | Scope::ObjectLifetimeDefault { s, .. } => {
1230 ref lifetimes, s, ..
1232 // FIXME (#24278): non-hygienic comparison
1233 if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1234 let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
1236 signal_shadowing_problem(
1239 original_lifetime(tcx.hir().span(hir_id)),
1240 shadower_label(label.span),
1251 fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1252 let mut map = HirIdMap::default();
1253 for item in tcx.hir().krate().items.values() {
1255 hir::ItemKind::Struct(_, ref generics)
1256 | hir::ItemKind::Union(_, ref generics)
1257 | hir::ItemKind::Enum(_, ref generics)
1258 | hir::ItemKind::Existential(hir::ExistTy {
1260 impl_trait_fn: None,
1263 | hir::ItemKind::Ty(_, ref generics)
1264 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1265 let result = object_lifetime_defaults_for_item(tcx, generics);
1268 if attr::contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1269 let object_lifetime_default_reprs: String = result
1271 .map(|set| match *set {
1272 Set1::Empty => "BaseDefault".into(),
1273 Set1::One(Region::Static) => "'static".into(),
1274 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1277 .find_map(|param| match param.kind {
1278 GenericParamKind::Lifetime { .. } => {
1280 return Some(param.name.ident().to_string().into());
1288 Set1::One(_) => bug!(),
1289 Set1::Many => "Ambiguous".into(),
1291 .collect::<Vec<Cow<'static, str>>>()
1293 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1296 map.insert(item.hir_id, result);
1304 /// Scan the bounds and where-clauses on parameters to extract bounds
1305 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1306 /// for each type parameter.
1307 fn object_lifetime_defaults_for_item(
1309 generics: &hir::Generics,
1310 ) -> Vec<ObjectLifetimeDefault> {
1311 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound]) {
1312 for bound in bounds {
1313 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1314 set.insert(lifetime.name.modern());
1322 .filter_map(|param| match param.kind {
1323 GenericParamKind::Lifetime { .. } => None,
1324 GenericParamKind::Type { .. } => {
1325 let mut set = Set1::Empty;
1327 add_bounds(&mut set, ¶m.bounds);
1329 let param_def_id = tcx.hir().local_def_id_from_hir_id(param.hir_id);
1330 for predicate in &generics.where_clause.predicates {
1331 // Look for `type: ...` where clauses.
1332 let data = match *predicate {
1333 hir::WherePredicate::BoundPredicate(ref data) => data,
1337 // Ignore `for<'a> type: ...` as they can change what
1338 // lifetimes mean (although we could "just" handle it).
1339 if !data.bound_generic_params.is_empty() {
1343 let res = match data.bounded_ty.node {
1344 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1348 if res == Res::Def(DefKind::TyParam, param_def_id) {
1349 add_bounds(&mut set, &data.bounds);
1354 Set1::Empty => Set1::Empty,
1355 Set1::One(name) => {
1356 if name == hir::LifetimeName::Static {
1357 Set1::One(Region::Static)
1362 .filter_map(|param| match param.kind {
1363 GenericParamKind::Lifetime { .. } => Some((
1365 hir::LifetimeName::Param(param.name),
1366 LifetimeDefOrigin::from_param(param),
1371 .find(|&(_, (_, lt_name, _))| lt_name == name)
1372 .map_or(Set1::Many, |(i, (id, _, origin))| {
1373 let def_id = tcx.hir().local_def_id_from_hir_id(id);
1374 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1378 Set1::Many => Set1::Many,
1381 GenericParamKind::Const { .. } => {
1382 // Generic consts don't impose any constraints.
1389 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1390 // FIXME(#37666) this works around a limitation in the region inferencer
1391 fn hack<F>(&mut self, f: F)
1393 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1398 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1400 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1402 let LifetimeContext {
1408 let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
1409 let xcrate_object_lifetime_defaults =
1410 replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap::default());
1411 let mut this = LifetimeContext {
1415 trait_ref_hack: self.trait_ref_hack,
1416 is_in_fn_syntax: self.is_in_fn_syntax,
1418 xcrate_object_lifetime_defaults,
1419 lifetime_uses: lifetime_uses,
1421 debug!("entering scope {:?}", this.scope);
1422 f(self.scope, &mut this);
1423 this.check_uses_for_lifetimes_defined_by_scope();
1424 debug!("exiting scope {:?}", this.scope);
1425 self.labels_in_fn = this.labels_in_fn;
1426 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1429 /// helper method to determine the span to remove when suggesting the
1430 /// deletion of a lifetime
1431 fn lifetime_deletion_span(&self, name: ast::Ident, generics: &hir::Generics) -> Option<Span> {
1432 generics.params.iter().enumerate().find_map(|(i, param)| {
1433 if param.name.ident() == name {
1434 let mut in_band = false;
1435 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1436 if let hir::LifetimeParamKind::InBand = kind {
1443 if generics.params.len() == 1 {
1444 // if sole lifetime, remove the entire `<>` brackets
1447 // if removing within `<>` brackets, we also want to
1448 // delete a leading or trailing comma as appropriate
1449 if i >= generics.params.len() - 1 {
1450 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1452 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1462 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1463 fn suggest_eliding_single_use_lifetime(
1464 &self, err: &mut DiagnosticBuilder<'_>, def_id: DefId, lifetime: &hir::Lifetime
1466 // FIXME: future work: also suggest `impl Foo<'_>` for `impl<'a> Foo<'a>`
1467 let name = lifetime.name.ident();
1468 let mut remove_decl = None;
1469 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1470 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1471 remove_decl = self.lifetime_deletion_span(name, generics);
1475 let mut remove_use = None;
1476 let mut find_arg_use_span = |inputs: &hir::HirVec<hir::Ty>| {
1477 for input in inputs {
1478 if let hir::TyKind::Rptr(lt, _) = input.node {
1479 if lt.name.ident() == name {
1480 // include the trailing whitespace between the ampersand and the type name
1481 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1483 self.tcx.sess.source_map()
1484 .span_until_non_whitespace(lt_through_ty_span)
1491 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1492 if let Some(parent) = self.tcx.hir().find(
1493 self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1496 Node::Item(item) => {
1497 if let hir::ItemKind::Fn(decl, _, _, _) = &item.node {
1498 find_arg_use_span(&decl.inputs);
1501 Node::ImplItem(impl_item) => {
1502 if let hir::ImplItemKind::Method(sig, _) = &impl_item.node {
1503 find_arg_use_span(&sig.decl.inputs);
1511 if let (Some(decl_span), Some(use_span)) = (remove_decl, remove_use) {
1512 // if both declaration and use deletion spans start at the same
1513 // place ("start at" because the latter includes trailing
1514 // whitespace), then this is an in-band lifetime
1515 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1516 err.span_suggestion(
1518 "elide the single-use lifetime",
1520 Applicability::MachineApplicable,
1523 err.multipart_suggestion(
1524 "elide the single-use lifetime",
1525 vec![(decl_span, String::new()), (use_span, String::new())],
1526 Applicability::MachineApplicable,
1532 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1533 let defined_by = match self.scope {
1534 Scope::Binder { lifetimes, .. } => lifetimes,
1536 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1541 let mut def_ids: Vec<_> = defined_by
1543 .flat_map(|region| match region {
1544 Region::EarlyBound(_, def_id, _)
1545 | Region::LateBound(_, def_id, _)
1546 | Region::Free(_, def_id) => Some(*def_id),
1548 Region::LateBoundAnon(..) | Region::Static => None,
1552 // ensure that we issue lints in a repeatable order
1553 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1555 for def_id in def_ids {
1557 "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
1561 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1564 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1568 match lifetimeuseset {
1569 Some(LifetimeUseSet::One(lifetime)) => {
1570 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1571 debug!("hir id first={:?}", hir_id);
1572 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1573 Node::Lifetime(hir_lifetime) => Some((
1574 hir_lifetime.hir_id,
1576 hir_lifetime.name.ident(),
1578 Node::GenericParam(param) => {
1579 Some((param.hir_id, param.span, param.name.ident()))
1583 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1585 if name.name == kw::UnderscoreLifetime {
1589 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1590 if let Some(parent_hir_id) = self.tcx.hir()
1591 .as_local_hir_id(parent_def_id) {
1592 // lifetimes in `derive` expansions don't count (Issue #53738)
1593 if self.tcx.hir().attrs(parent_hir_id).iter()
1594 .any(|attr| attr.check_name(sym::automatically_derived)) {
1600 let mut err = self.tcx.struct_span_lint_hir(
1601 lint::builtin::SINGLE_USE_LIFETIMES,
1604 &format!("lifetime parameter `{}` only used once", name),
1607 if span == lifetime.span {
1608 // spans are the same for in-band lifetime declarations
1609 err.span_label(span, "this lifetime is only used here");
1611 err.span_label(span, "this lifetime...");
1612 err.span_label(lifetime.span, "...is used only here");
1614 self.suggest_eliding_single_use_lifetime(&mut err, def_id, lifetime);
1618 Some(LifetimeUseSet::Many) => {
1619 debug!("Not one use lifetime");
1622 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1623 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1624 Node::Lifetime(hir_lifetime) => Some((
1625 hir_lifetime.hir_id,
1627 hir_lifetime.name.ident(),
1629 Node::GenericParam(param) => {
1630 Some((param.hir_id, param.span, param.name.ident()))
1634 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1635 let mut err = self.tcx.struct_span_lint_hir(
1636 lint::builtin::UNUSED_LIFETIMES,
1639 &format!("lifetime parameter `{}` never used", name),
1641 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1642 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1643 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1644 if let Some(span) = unused_lt_span {
1645 err.span_suggestion(
1647 "elide the unused lifetime",
1649 Applicability::MachineApplicable,
1661 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1663 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1664 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1665 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1669 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1671 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1672 /// lifetimes may be interspersed together.
1674 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1675 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1676 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1677 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1678 /// ordering is not important there.
1679 fn visit_early_late<F>(
1681 parent_id: Option<hir::HirId>,
1682 decl: &'tcx hir::FnDecl,
1683 generics: &'tcx hir::Generics,
1686 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1688 insert_late_bound_lifetimes(self.map, decl, generics);
1690 // Find the start of nested early scopes, e.g., in methods.
1692 if let Some(parent_id) = parent_id {
1693 let parent = self.tcx.hir().expect_item(parent_id);
1694 if sub_items_have_self_param(&parent.node) {
1695 index += 1; // Self comes before lifetimes
1698 hir::ItemKind::Trait(_, _, ref generics, ..)
1699 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
1700 index += generics.params.len() as u32;
1706 let mut non_lifetime_count = 0;
1707 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
1708 GenericParamKind::Lifetime { .. } => {
1709 if self.map.late_bound.contains(¶m.hir_id) {
1710 Some(Region::late(&self.tcx.hir(), param))
1712 Some(Region::early(&self.tcx.hir(), &mut index, param))
1715 GenericParamKind::Type { .. } |
1716 GenericParamKind::Const { .. } => {
1717 non_lifetime_count += 1;
1721 let next_early_index = index + non_lifetime_count;
1723 let scope = Scope::Binder {
1727 abstract_type_parent: true,
1728 track_lifetime_uses: false,
1730 self.with(scope, move |old_scope, this| {
1731 this.check_lifetime_params(old_scope, &generics.params);
1732 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1736 fn next_early_index_helper(&self, only_abstract_type_parent: bool) -> u32 {
1737 let mut scope = self.scope;
1740 Scope::Root => return 0,
1744 abstract_type_parent,
1746 } if (!only_abstract_type_parent || abstract_type_parent) =>
1748 return next_early_index
1751 Scope::Binder { s, .. }
1752 | Scope::Body { s, .. }
1753 | Scope::Elision { s, .. }
1754 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1759 /// Returns the next index one would use for an early-bound-region
1760 /// if extending the current scope.
1761 fn next_early_index(&self) -> u32 {
1762 self.next_early_index_helper(true)
1765 /// Returns the next index one would use for an `impl Trait` that
1766 /// is being converted into an `abstract type`. This will be the
1767 /// next early index from the enclosing item, for the most
1768 /// part. See the `abstract_type_parent` field for more info.
1769 fn next_early_index_for_abstract_type(&self) -> u32 {
1770 self.next_early_index_helper(false)
1773 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1774 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1776 // If we've already reported an error, just ignore `lifetime_ref`.
1777 if let LifetimeName::Error = lifetime_ref.name {
1781 // Walk up the scope chain, tracking the number of fn scopes
1782 // that we pass through, until we find a lifetime with the
1783 // given name or we run out of scopes.
1785 let mut late_depth = 0;
1786 let mut scope = self.scope;
1787 let mut outermost_body = None;
1790 Scope::Body { id, s } => {
1791 outermost_body = Some(id);
1800 ref lifetimes, s, ..
1802 match lifetime_ref.name {
1803 LifetimeName::Param(param_name) => {
1804 if let Some(&def) = lifetimes.get(¶m_name.modern()) {
1805 break Some(def.shifted(late_depth));
1808 _ => bug!("expected LifetimeName::Param"),
1815 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1821 if let Some(mut def) = result {
1822 if let Region::EarlyBound(..) = def {
1823 // Do not free early-bound regions, only late-bound ones.
1824 } else if let Some(body_id) = outermost_body {
1825 let fn_id = self.tcx.hir().body_owner(body_id);
1826 match self.tcx.hir().get(fn_id) {
1827 Node::Item(&hir::Item {
1828 node: hir::ItemKind::Fn(..),
1831 | Node::TraitItem(&hir::TraitItem {
1832 node: hir::TraitItemKind::Method(..),
1835 | Node::ImplItem(&hir::ImplItem {
1836 node: hir::ImplItemKind::Method(..),
1839 let scope = self.tcx.hir().local_def_id_from_hir_id(fn_id);
1840 def = Region::Free(scope, def.id().unwrap());
1846 // Check for fn-syntax conflicts with in-band lifetime definitions
1847 if self.is_in_fn_syntax {
1849 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1850 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1855 "lifetimes used in `fn` or `Fn` syntax must be \
1856 explicitly declared using `<...>` binders"
1857 ).span_label(lifetime_ref.span, "in-band lifetime definition")
1862 | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1863 | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1864 | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1865 | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1866 | Region::LateBoundAnon(..)
1867 | Region::Free(..) => {}
1871 self.insert_lifetime(lifetime_ref, def);
1877 "use of undeclared lifetime name `{}`",
1879 ).span_label(lifetime_ref.span, "undeclared lifetime")
1884 fn visit_segment_args(&mut self, res: Res, depth: usize, generic_args: &'tcx hir::GenericArgs) {
1885 if generic_args.parenthesized {
1886 let was_in_fn_syntax = self.is_in_fn_syntax;
1887 self.is_in_fn_syntax = true;
1888 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1889 self.is_in_fn_syntax = was_in_fn_syntax;
1893 let mut elide_lifetimes = true;
1894 let lifetimes = generic_args
1897 .filter_map(|arg| match arg {
1898 hir::GenericArg::Lifetime(lt) => {
1899 if !lt.is_elided() {
1900 elide_lifetimes = false;
1907 if elide_lifetimes {
1908 self.resolve_elided_lifetimes(lifetimes);
1910 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1913 // Figure out if this is a type/trait segment,
1914 // which requires object lifetime defaults.
1915 let parent_def_id = |this: &mut Self, def_id: DefId| {
1916 let def_key = this.tcx.def_key(def_id);
1918 krate: def_id.krate,
1919 index: def_key.parent.expect("missing parent"),
1922 let type_def_id = match res {
1923 Res::Def(DefKind::AssocTy, def_id)
1924 if depth == 1 => Some(parent_def_id(self, def_id)),
1925 Res::Def(DefKind::Variant, def_id)
1926 if depth == 0 => Some(parent_def_id(self, def_id)),
1927 Res::Def(DefKind::Struct, def_id)
1928 | Res::Def(DefKind::Union, def_id)
1929 | Res::Def(DefKind::Enum, def_id)
1930 | Res::Def(DefKind::TyAlias, def_id)
1931 | Res::Def(DefKind::Trait, def_id) if depth == 0 =>
1938 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1940 let mut scope = self.scope;
1943 Scope::Root => break false,
1945 Scope::Body { .. } => break true,
1947 Scope::Binder { s, .. }
1948 | Scope::Elision { s, .. }
1949 | Scope::ObjectLifetimeDefault { s, .. } => {
1956 let map = &self.map;
1957 let unsubst = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
1958 &map.object_lifetime_defaults[&id]
1961 self.xcrate_object_lifetime_defaults
1963 .or_insert_with(|| {
1964 tcx.generics_of(def_id)
1967 .filter_map(|param| match param.kind {
1968 GenericParamDefKind::Type {
1969 object_lifetime_default,
1971 } => Some(object_lifetime_default),
1972 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1979 .map(|set| match *set {
1980 Set1::Empty => if in_body {
1983 Some(Region::Static)
1986 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1987 GenericArg::Lifetime(lt) => Some(lt),
1990 r.subst(lifetimes, map)
1998 for arg in &generic_args.args {
2000 GenericArg::Lifetime(_) => {}
2001 GenericArg::Type(ty) => {
2002 if let Some(<) = object_lifetime_defaults.get(i) {
2003 let scope = Scope::ObjectLifetimeDefault {
2007 self.with(scope, |_, this| this.visit_ty(ty));
2013 GenericArg::Const(ct) => {
2014 self.visit_anon_const(&ct.value);
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 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.hir_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_item(parent))
2071 assoc_item_kind = trait_items
2073 .find(|ti| ti.id.hir_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_item(parent))
2091 impl_self = Some(self_ty);
2092 assoc_item_kind = impl_items
2094 .find(|ii| ii.id.hir_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::AssocItemKind::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 = |res: Res| {
2123 if let Res::SelfTy(..) = res {
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 Res::Def(DefKind::Struct, _)
2136 | Res::Def(DefKind::Union, _)
2137 | Res::Def(DefKind::Enum, _)
2138 | Res::PrimTy(_) => {
2139 return res == path.res
2148 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = inputs[0].node {
2149 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
2150 if is_self_ty(path.res) {
2151 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2152 let scope = Scope::Elision {
2153 elide: Elide::Exact(lifetime),
2156 self.with(scope, |_, this| this.visit_ty(output));
2164 // Second, if there was exactly one lifetime (either a substitution or a
2165 // reference) in the arguments, then any anonymous regions in the output
2166 // have that lifetime.
2167 let mut possible_implied_output_region = None;
2168 let mut lifetime_count = 0;
2169 let arg_lifetimes = inputs
2172 .skip(has_self as usize)
2174 let mut gather = GatherLifetimes {
2176 outer_index: ty::INNERMOST,
2177 have_bound_regions: false,
2178 lifetimes: Default::default(),
2180 gather.visit_ty(input);
2182 lifetime_count += gather.lifetimes.len();
2184 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2185 // there's a chance that the unique lifetime of this
2186 // iteration will be the appropriate lifetime for output
2187 // parameters, so lets store it.
2188 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2191 ElisionFailureInfo {
2194 lifetime_count: gather.lifetimes.len(),
2195 have_bound_regions: gather.have_bound_regions,
2200 let elide = if lifetime_count == 1 {
2201 Elide::Exact(possible_implied_output_region.unwrap())
2203 Elide::Error(arg_lifetimes)
2206 debug!("visit_fn_like_elision: elide={:?}", elide);
2208 let scope = Scope::Elision {
2212 self.with(scope, |_, this| this.visit_ty(output));
2213 debug!("visit_fn_like_elision: exit");
2215 struct GatherLifetimes<'a> {
2216 map: &'a NamedRegionMap,
2217 outer_index: ty::DebruijnIndex,
2218 have_bound_regions: bool,
2219 lifetimes: FxHashSet<Region>,
2222 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2223 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2224 NestedVisitorMap::None
2227 fn visit_ty(&mut self, ty: &hir::Ty) {
2228 if let hir::TyKind::BareFn(_) = ty.node {
2229 self.outer_index.shift_in(1);
2232 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2233 for bound in bounds {
2234 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2237 // Stay on the safe side and don't include the object
2238 // lifetime default (which may not end up being used).
2239 if !lifetime.is_elided() {
2240 self.visit_lifetime(lifetime);
2243 hir::TyKind::CVarArgs(_) => {}
2245 intravisit::walk_ty(self, ty);
2248 if let hir::TyKind::BareFn(_) = ty.node {
2249 self.outer_index.shift_out(1);
2253 fn visit_generic_param(&mut self, param: &hir::GenericParam) {
2254 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2255 // FIXME(eddyb) Do we want this? It only makes a difference
2256 // if this `for<'a>` lifetime parameter is never used.
2257 self.have_bound_regions = true;
2260 intravisit::walk_generic_param(self, param);
2263 fn visit_poly_trait_ref(
2265 trait_ref: &hir::PolyTraitRef,
2266 modifier: hir::TraitBoundModifier,
2268 self.outer_index.shift_in(1);
2269 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2270 self.outer_index.shift_out(1);
2273 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2274 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2276 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2277 if debruijn < self.outer_index =>
2279 self.have_bound_regions = true;
2283 .insert(lifetime.shifted_out_to_binder(self.outer_index));
2291 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2292 if lifetime_refs.is_empty() {
2296 let span = lifetime_refs[0].span;
2297 let mut late_depth = 0;
2298 let mut scope = self.scope;
2299 let mut lifetime_names = FxHashSet::default();
2302 // Do not assign any resolution, it will be inferred.
2303 Scope::Body { .. } => return,
2305 Scope::Root => break None,
2307 Scope::Binder { s, ref lifetimes, .. } => {
2308 // collect named lifetimes for suggestions
2309 for name in lifetimes.keys() {
2310 if let hir::ParamName::Plain(name) = name {
2311 lifetime_names.insert(*name);
2318 Scope::Elision { ref elide, ref s, .. } => {
2319 let lifetime = match *elide {
2320 Elide::FreshLateAnon(ref counter) => {
2321 for lifetime_ref in lifetime_refs {
2322 let lifetime = Region::late_anon(counter).shifted(late_depth);
2323 self.insert_lifetime(lifetime_ref, lifetime);
2327 Elide::Exact(l) => l.shifted(late_depth),
2328 Elide::Error(ref e) => {
2329 if let Scope::Binder { ref lifetimes, .. } = s {
2330 // collect named lifetimes for suggestions
2331 for name in lifetimes.keys() {
2332 if let hir::ParamName::Plain(name) = name {
2333 lifetime_names.insert(*name);
2340 for lifetime_ref in lifetime_refs {
2341 self.insert_lifetime(lifetime_ref, lifetime);
2346 Scope::ObjectLifetimeDefault { s, .. } => {
2352 let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2353 let mut add_label = true;
2355 if let Some(params) = error {
2356 if lifetime_refs.len() == 1 {
2357 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2361 add_missing_lifetime_specifiers_label(
2364 lifetime_refs.len(),
2366 self.tcx.sess.source_map().span_to_snippet(span).ok().as_ref().map(|s| s.as_str()),
2373 fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2374 match self.tcx.sess.source_map().span_to_snippet(span) {
2375 Ok(ref snippet) => {
2376 let (sugg, applicability) = if snippet == "&" {
2377 ("&'static ".to_owned(), Applicability::MachineApplicable)
2378 } else if snippet == "'_" {
2379 ("'static".to_owned(), Applicability::MachineApplicable)
2381 (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2383 db.span_suggestion(span, msg, sugg, applicability);
2393 fn report_elision_failure(
2395 db: &mut DiagnosticBuilder<'_>,
2396 params: &[ElisionFailureInfo],
2399 let mut m = String::new();
2400 let len = params.len();
2402 let elided_params: Vec<_> = params
2405 .filter(|info| info.lifetime_count > 0)
2408 let elided_len = elided_params.len();
2410 for (i, info) in elided_params.into_iter().enumerate() {
2411 let ElisionFailureInfo {
2418 let help_name = if let Some(ident) = parent.and_then(|body| {
2419 self.tcx.hir().body(body).arguments[index].pat.simple_ident()
2421 format!("`{}`", ident)
2423 format!("argument {}", index + 1)
2431 "one of {}'s {} {}lifetimes",
2434 if have_bound_regions { "free " } else { "" }
2439 if elided_len == 2 && i == 0 {
2441 } else if i + 2 == elided_len {
2442 m.push_str(", or ");
2443 } else if i != elided_len - 1 {
2451 "this function's return type contains a borrowed value, but \
2452 there is no value for it to be borrowed from"
2454 self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2455 } else if elided_len == 0 {
2458 "this function's return type contains a borrowed value with \
2459 an elided lifetime, but the lifetime cannot be derived from \
2462 let msg = "consider giving it an explicit bounded or 'static lifetime";
2463 self.suggest_lifetime(db, span, msg)
2464 } else if elided_len == 1 {
2467 "this function's return type contains a borrowed value, but \
2468 the signature does not say which {} it is borrowed from",
2475 "this function's return type contains a borrowed value, but \
2476 the signature does not say whether it is borrowed from {}",
2483 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2484 let mut late_depth = 0;
2485 let mut scope = self.scope;
2486 let lifetime = loop {
2488 Scope::Binder { s, .. } => {
2493 Scope::Root | Scope::Elision { .. } => break Region::Static,
2495 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2497 Scope::ObjectLifetimeDefault {
2498 lifetime: Some(l), ..
2502 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2505 fn check_lifetime_params(
2507 old_scope: ScopeRef<'_>,
2508 params: &'tcx [hir::GenericParam],
2510 let lifetimes: Vec<_> = params
2512 .filter_map(|param| match param.kind {
2513 GenericParamKind::Lifetime { .. } => Some((param, param.name)),
2517 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2518 if let hir::ParamName::Plain(_) = lifetime_i_name {
2519 let name = lifetime_i_name.ident().name;
2520 if name == kw::UnderscoreLifetime
2521 || name == kw::StaticLifetime
2523 let mut err = struct_span_err!(
2527 "invalid lifetime parameter name: `{}`",
2528 lifetime_i.name.ident(),
2532 format!("{} is a reserved lifetime name", name),
2538 // It is a hard error to shadow a lifetime within the same scope.
2539 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2540 if lifetime_i_name == lifetime_j_name {
2545 "lifetime name `{}` declared twice in the same scope",
2546 lifetime_j.name.ident()
2547 ).span_label(lifetime_j.span, "declared twice")
2548 .span_label(lifetime_i.span, "previous declaration here")
2553 // It is a soft error to shadow a lifetime within a parent scope.
2554 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2556 for bound in &lifetime_i.bounds {
2558 hir::GenericBound::Outlives(lt) => match lt.name {
2559 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2561 "use of `'_` in illegal place, but not caught by lowering",
2563 hir::LifetimeName::Static => {
2564 self.insert_lifetime(lt, Region::Static);
2568 lifetime_i.span.to(lt.span),
2570 "unnecessary lifetime parameter `{}`",
2571 lifetime_i.name.ident(),
2575 "you can use the `'static` lifetime directly, in place of `{}`",
2576 lifetime_i.name.ident(),
2580 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2581 self.resolve_lifetime_ref(lt);
2583 hir::LifetimeName::Error => {
2584 // No need to do anything, error already reported.
2593 fn check_lifetime_param_for_shadowing(
2595 mut old_scope: ScopeRef<'_>,
2596 param: &'tcx hir::GenericParam,
2598 for label in &self.labels_in_fn {
2599 // FIXME (#24278): non-hygienic comparison
2600 if param.name.ident().name == label.name {
2601 signal_shadowing_problem(
2604 original_label(label.span),
2605 shadower_lifetime(¶m),
2613 Scope::Body { s, .. }
2614 | Scope::Elision { s, .. }
2615 | Scope::ObjectLifetimeDefault { s, .. } => {
2624 ref lifetimes, s, ..
2626 if let Some(&def) = lifetimes.get(¶m.name.modern()) {
2627 let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
2629 signal_shadowing_problem(
2631 param.name.ident().name,
2632 original_lifetime(self.tcx.hir().span(hir_id)),
2633 shadower_lifetime(¶m),
2644 /// Returns `true` if, in the current scope, replacing `'_` would be
2645 /// equivalent to a single-use lifetime.
2646 fn track_lifetime_uses(&self) -> bool {
2647 let mut scope = self.scope;
2650 Scope::Root => break false,
2652 // Inside of items, it depends on the kind of item.
2654 track_lifetime_uses,
2656 } => break track_lifetime_uses,
2658 // Inside a body, `'_` will use an inference variable,
2660 Scope::Body { .. } => break true,
2662 // A lifetime only used in a fn argument could as well
2663 // be replaced with `'_`, as that would generate a
2666 elide: Elide::FreshLateAnon(_),
2670 // In the return type or other such place, `'_` is not
2671 // going to make a fresh name, so we cannot
2672 // necessarily replace a single-use lifetime with
2675 elide: Elide::Exact(_),
2679 elide: Elide::Error(_),
2683 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2688 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2689 if lifetime_ref.hir_id == hir::DUMMY_HIR_ID {
2692 "lifetime reference not renumbered, \
2693 probably a bug in syntax::fold"
2698 "insert_lifetime: {} resolved to {:?} span={:?}",
2699 self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2701 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2703 self.map.defs.insert(lifetime_ref.hir_id, def);
2706 Region::LateBoundAnon(..) | Region::Static => {
2707 // These are anonymous lifetimes or lifetimes that are not declared.
2710 Region::Free(_, def_id)
2711 | Region::LateBound(_, def_id, _)
2712 | Region::EarlyBound(_, def_id, _) => {
2713 // A lifetime declared by the user.
2714 let track_lifetime_uses = self.track_lifetime_uses();
2716 "insert_lifetime: track_lifetime_uses={}",
2719 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2720 debug!("insert_lifetime: first use of {:?}", def_id);
2722 .insert(def_id, LifetimeUseSet::One(lifetime_ref));
2724 debug!("insert_lifetime: many uses of {:?}", def_id);
2725 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2731 /// Sometimes we resolve a lifetime, but later find that it is an
2732 /// error (esp. around impl trait). In that case, we remove the
2733 /// entry into `map.defs` so as not to confuse later code.
2734 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2735 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2736 assert_eq!(old_value, Some(bad_def));
2740 /// Detects late-bound lifetimes and inserts them into
2741 /// `map.late_bound`.
2743 /// A region declared on a fn is **late-bound** if:
2744 /// - it is constrained by an argument type;
2745 /// - it does not appear in a where-clause.
2747 /// "Constrained" basically means that it appears in any type but
2748 /// not amongst the inputs to a projection. In other words, `<&'a
2749 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2750 fn insert_late_bound_lifetimes(
2751 map: &mut NamedRegionMap,
2753 generics: &hir::Generics,
2756 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2760 let mut constrained_by_input = ConstrainedCollector::default();
2761 for arg_ty in &decl.inputs {
2762 constrained_by_input.visit_ty(arg_ty);
2765 let mut appears_in_output = AllCollector::default();
2766 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2769 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2770 constrained_by_input.regions
2773 // Walk the lifetimes that appear in where clauses.
2775 // Subtle point: because we disallow nested bindings, we can just
2776 // ignore binders here and scrape up all names we see.
2777 let mut appears_in_where_clause = AllCollector::default();
2778 appears_in_where_clause.visit_generics(generics);
2780 for param in &generics.params {
2781 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2782 if !param.bounds.is_empty() {
2783 // `'a: 'b` means both `'a` and `'b` are referenced
2784 appears_in_where_clause
2786 .insert(hir::LifetimeName::Param(param.name.modern()));
2792 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2793 appears_in_where_clause.regions
2796 // Late bound regions are those that:
2797 // - appear in the inputs
2798 // - do not appear in the where-clauses
2799 // - are not implicitly captured by `impl Trait`
2800 for param in &generics.params {
2802 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2804 // Neither types nor consts are late-bound.
2805 hir::GenericParamKind::Type { .. }
2806 | hir::GenericParamKind::Const { .. } => continue,
2809 let lt_name = hir::LifetimeName::Param(param.name.modern());
2810 // appears in the where clauses? early-bound.
2811 if appears_in_where_clause.regions.contains(<_name) {
2815 // does not appear in the inputs, but appears in the return type? early-bound.
2816 if !constrained_by_input.regions.contains(<_name)
2817 && appears_in_output.regions.contains(<_name)
2823 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2828 let inserted = map.late_bound.insert(param.hir_id);
2829 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2835 struct ConstrainedCollector {
2836 regions: FxHashSet<hir::LifetimeName>,
2839 impl<'v> Visitor<'v> for ConstrainedCollector {
2840 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2841 NestedVisitorMap::None
2844 fn visit_ty(&mut self, ty: &'v hir::Ty) {
2846 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2847 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2848 // ignore lifetimes appearing in associated type
2849 // projections, as they are not *constrained*
2853 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2854 // consider only the lifetimes on the final
2855 // segment; I am not sure it's even currently
2856 // valid to have them elsewhere, but even if it
2857 // is, those would be potentially inputs to
2859 if let Some(last_segment) = path.segments.last() {
2860 self.visit_path_segment(path.span, last_segment);
2865 intravisit::walk_ty(self, ty);
2870 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2871 self.regions.insert(lifetime_ref.name.modern());
2876 struct AllCollector {
2877 regions: FxHashSet<hir::LifetimeName>,
2880 impl<'v> Visitor<'v> for AllCollector {
2881 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2882 NestedVisitorMap::None
2885 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2886 self.regions.insert(lifetime_ref.name.modern());
2891 pub fn report_missing_lifetime_specifiers(
2895 ) -> DiagnosticBuilder<'_> {
2900 "missing lifetime specifier{}",
2901 if count > 1 { "s" } else { "" }
2905 fn add_missing_lifetime_specifiers_label(
2906 err: &mut DiagnosticBuilder<'_>,
2909 lifetime_names: &FxHashSet<ast::Ident>,
2910 snippet: Option<&str>,
2913 err.span_label(span, format!("expected {} lifetime parameters", count));
2914 } else if let (1, Some(name), Some("&")) = (
2915 lifetime_names.len(),
2916 lifetime_names.iter().next(),
2919 err.span_suggestion(
2921 "consider using the named lifetime",
2922 format!("&{} ", name),
2923 Applicability::MaybeIncorrect,
2926 err.span_label(span, "expected lifetime parameter");