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 // ignore-tidy-filelength
10 use crate::hir::def::{Res, DefKind};
11 use crate::hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
12 use crate::hir::map::Map;
13 use crate::hir::ptr::P;
14 use crate::hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName, QPath};
15 use crate::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
17 use crate::rustc::lint;
18 use crate::session::Session;
19 use crate::util::nodemap::{DefIdMap, FxHashMap, FxHashSet, HirIdMap, HirIdSet};
20 use errors::{Applicability, DiagnosticBuilder, pluralize};
21 use rustc_macros::HashStable;
24 use std::mem::{replace, take};
27 use syntax::symbol::{kw, sym};
30 use crate::hir::intravisit::{self, NestedVisitorMap, Visitor};
31 use crate::hir::{self, GenericParamKind, LifetimeParamKind};
33 use rustc_error_codes::*;
35 /// The origin of a named lifetime definition.
37 /// This is used to prevent the usage of in-band lifetimes in `Fn`/`fn` syntax.
38 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, HashStable)]
39 pub enum LifetimeDefOrigin {
40 // Explicit binders like `fn foo<'a>(x: &'a u8)` or elided like `impl Foo<&u32>`
42 // In-band declarations like `fn foo(x: &'a u8)`
44 // Some kind of erroneous origin
48 impl LifetimeDefOrigin {
49 fn from_param(param: &GenericParam) -> Self {
51 GenericParamKind::Lifetime { kind } => match kind {
52 LifetimeParamKind::InBand => LifetimeDefOrigin::InBand,
53 LifetimeParamKind::Explicit => LifetimeDefOrigin::ExplicitOrElided,
54 LifetimeParamKind::Elided => LifetimeDefOrigin::ExplicitOrElided,
55 LifetimeParamKind::Error => LifetimeDefOrigin::Error,
57 _ => bug!("expected a lifetime param"),
62 // This counts the no of times a lifetime is used
63 #[derive(Clone, Copy, Debug)]
64 pub enum LifetimeUseSet<'tcx> {
65 One(&'tcx hir::Lifetime),
69 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, HashStable)]
74 /* lifetime decl */ DefId,
79 /* lifetime decl */ DefId,
82 LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
83 Free(DefId, /* lifetime decl */ DefId),
87 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam) -> (ParamName, Region) {
90 let def_id = hir_map.local_def_id(param.hir_id);
91 let origin = LifetimeDefOrigin::from_param(param);
92 debug!("Region::early: index={} def_id={:?}", i, def_id);
93 (param.name.modern(), Region::EarlyBound(i, def_id, origin))
96 fn late(hir_map: &Map<'_>, param: &GenericParam) -> (ParamName, Region) {
97 let depth = ty::INNERMOST;
98 let def_id = hir_map.local_def_id(param.hir_id);
99 let origin = LifetimeDefOrigin::from_param(param);
101 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
102 param, depth, def_id, origin,
106 Region::LateBound(depth, def_id, origin),
110 fn late_anon(index: &Cell<u32>) -> Region {
113 let depth = ty::INNERMOST;
114 Region::LateBoundAnon(depth, i)
117 fn id(&self) -> Option<DefId> {
119 Region::Static | Region::LateBoundAnon(..) => None,
121 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
127 fn shifted(self, amount: u32) -> Region {
129 Region::LateBound(debruijn, id, origin) => {
130 Region::LateBound(debruijn.shifted_in(amount), id, origin)
132 Region::LateBoundAnon(debruijn, index) => {
133 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
139 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
141 Region::LateBound(debruijn, id, origin) => {
142 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
144 Region::LateBoundAnon(debruijn, index) => {
145 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
151 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
153 L: Iterator<Item = &'a hir::Lifetime>,
155 if let Region::EarlyBound(index, _, _) = self {
158 .and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
165 /// A set containing, at most, one known element.
166 /// If two distinct values are inserted into a set, then it
167 /// becomes `Many`, which can be used to detect ambiguities.
168 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
175 impl<T: PartialEq> Set1<T> {
176 pub fn insert(&mut self, value: T) {
178 Set1::Empty => Set1::One(value),
179 Set1::One(old) if *old == value => return,
185 pub type ObjectLifetimeDefault = Set1<Region>;
187 /// Maps the id of each lifetime reference to the lifetime decl
188 /// that it corresponds to.
190 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
191 /// actual use. It has the same data, but indexed by `DefIndex`. This
194 struct NamedRegionMap {
195 // maps from every use of a named (not anonymous) lifetime to a
196 // `Region` describing how that region is bound
197 pub defs: HirIdMap<Region>,
199 // the set of lifetime def ids that are late-bound; a region can
200 // be late-bound if (a) it does NOT appear in a where-clause and
201 // (b) it DOES appear in the arguments.
202 pub late_bound: HirIdSet,
204 // For each type and trait definition, maps type parameters
205 // to the trait object lifetime defaults computed from them.
206 pub object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
209 /// See [`NamedRegionMap`].
210 #[derive(Default, HashStable)]
211 pub struct ResolveLifetimes {
212 defs: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Region>>,
213 late_bound: FxHashMap<LocalDefId, FxHashSet<ItemLocalId>>,
214 object_lifetime_defaults:
215 FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Vec<ObjectLifetimeDefault>>>,
218 struct LifetimeContext<'a, 'tcx> {
220 map: &'a mut NamedRegionMap,
223 /// This is slightly complicated. Our representation for poly-trait-refs contains a single
224 /// binder and thus we only allow a single level of quantification. However,
225 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
226 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
227 /// correct when representing these constraints, we should only introduce one
228 /// scope. However, we want to support both locations for the quantifier and
229 /// during lifetime resolution we want precise information (so we can't
230 /// desugar in an earlier phase).
232 /// So, if we encounter a quantifier at the outer scope, we set
233 /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
234 /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
235 /// then we introduce the scope at the inner quantifier.
236 trait_ref_hack: bool,
238 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
239 is_in_fn_syntax: bool,
241 /// List of labels in the function/method currently under analysis.
242 labels_in_fn: Vec<ast::Ident>,
244 /// Cache for cross-crate per-definition object lifetime defaults.
245 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
247 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
252 /// Declares lifetimes, and each can be early-bound or late-bound.
253 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
254 /// it should be shifted by the number of `Binder`s in between the
255 /// declaration `Binder` and the location it's referenced from.
257 lifetimes: FxHashMap<hir::ParamName, Region>,
259 /// if we extend this scope with another scope, what is the next index
260 /// we should use for an early-bound region?
261 next_early_index: u32,
263 /// Flag is set to true if, in this binder, `'_` would be
264 /// equivalent to a "single-use region". This is true on
265 /// impls, but not other kinds of items.
266 track_lifetime_uses: bool,
268 /// Whether or not this binder would serve as the parent
269 /// binder for opaque types introduced within. For example:
271 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
273 /// Here, the opaque types we create for the `impl Trait`
274 /// and `impl Trait2` references will both have the `foo` item
275 /// as their parent. When we get to `impl Trait2`, we find
276 /// that it is nested within the `for<>` binder -- this flag
277 /// allows us to skip that when looking for the parent binder
278 /// of the resulting opaque type.
279 opaque_type_parent: bool,
284 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
285 /// if this is a fn body, otherwise the original definitions are used.
286 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
287 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
293 /// A scope which either determines unspecified lifetimes or errors
294 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
300 /// Use a specific lifetime (if `Some`) or leave it unset (to be
301 /// inferred in a function body or potentially error outside one),
302 /// for the default choice of lifetime in a trait object type.
303 ObjectLifetimeDefault {
304 lifetime: Option<Region>,
311 #[derive(Clone, Debug)]
313 /// Use a fresh anonymous late-bound lifetime each time, by
314 /// incrementing the counter to generate sequential indices.
315 FreshLateAnon(Cell<u32>),
316 /// Always use this one lifetime.
318 /// Less or more than one lifetime were found, error on unspecified.
319 Error(Vec<ElisionFailureInfo>),
322 #[derive(Clone, Debug)]
323 struct ElisionFailureInfo {
324 /// Where we can find the argument pattern.
325 parent: Option<hir::BodyId>,
326 /// The index of the argument in the original definition.
328 lifetime_count: usize,
329 have_bound_regions: bool,
332 type ScopeRef<'a> = &'a Scope<'a>;
334 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
336 pub fn provide(providers: &mut ty::query::Providers<'_>) {
337 *providers = ty::query::Providers {
340 named_region_map: |tcx, id| {
341 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
342 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id)
345 is_late_bound_map: |tcx, id| {
346 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
347 tcx.resolve_lifetimes(LOCAL_CRATE)
352 object_lifetime_defaults_map: |tcx, id| {
353 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
354 tcx.resolve_lifetimes(LOCAL_CRATE)
355 .object_lifetime_defaults
362 // (*) FIXME the query should be defined to take a LocalDefId
365 /// Computes the `ResolveLifetimes` map that contains data for the
366 /// entire crate. You should not read the result of this query
367 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
369 fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> &ResolveLifetimes {
370 assert_eq!(for_krate, LOCAL_CRATE);
372 let named_region_map = krate(tcx);
374 let mut rl = ResolveLifetimes::default();
376 for (hir_id, v) in named_region_map.defs {
377 let map = rl.defs.entry(hir_id.owner_local_def_id()).or_default();
378 map.insert(hir_id.local_id, v);
380 for hir_id in named_region_map.late_bound {
381 let map = rl.late_bound
382 .entry(hir_id.owner_local_def_id())
384 map.insert(hir_id.local_id);
386 for (hir_id, v) in named_region_map.object_lifetime_defaults {
387 let map = rl.object_lifetime_defaults
388 .entry(hir_id.owner_local_def_id())
390 map.insert(hir_id.local_id, v);
396 fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap {
397 let krate = tcx.hir().krate();
398 let mut map = NamedRegionMap {
399 defs: Default::default(),
400 late_bound: Default::default(),
401 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
404 let mut visitor = LifetimeContext {
408 trait_ref_hack: false,
409 is_in_fn_syntax: false,
410 labels_in_fn: vec![],
411 xcrate_object_lifetime_defaults: Default::default(),
412 lifetime_uses: &mut Default::default(),
414 for (_, item) in &krate.items {
415 visitor.visit_item(item);
421 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
422 /// We have to account for this when computing the index of the other generic parameters.
423 /// This function returns whether there is such an implicit parameter defined on the given item.
424 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
426 hir::ItemKind::Trait(..) |
427 hir::ItemKind::TraitAlias(..) => true,
432 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
433 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
434 NestedVisitorMap::All(&self.tcx.hir())
437 // We want to nest trait/impl items in their parent, but nothing else.
438 fn visit_nested_item(&mut self, _: hir::ItemId) {}
440 fn visit_nested_body(&mut self, body: hir::BodyId) {
441 // Each body has their own set of labels, save labels.
442 let saved = take(&mut self.labels_in_fn);
443 let body = self.tcx.hir().body(body);
444 extract_labels(self, body);
451 this.visit_body(body);
454 replace(&mut self.labels_in_fn, saved);
457 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
459 hir::ItemKind::Fn(ref sig, ref generics, _) => {
460 self.visit_early_late(None, &sig.decl, generics, |this| {
461 intravisit::walk_item(this, item);
465 hir::ItemKind::ExternCrate(_)
466 | hir::ItemKind::Use(..)
467 | hir::ItemKind::Mod(..)
468 | hir::ItemKind::ForeignMod(..)
469 | hir::ItemKind::GlobalAsm(..) => {
470 // These sorts of items have no lifetime parameters at all.
471 intravisit::walk_item(self, item);
473 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
474 // No lifetime parameters, but implied 'static.
475 let scope = Scope::Elision {
476 elide: Elide::Exact(Region::Static),
479 self.with(scope, |_, this| intravisit::walk_item(this, item));
481 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
482 impl_trait_fn: Some(_),
485 // Currently opaque type declarations are just generated from `impl Trait`
486 // items. Doing anything on this node is irrelevant, as we currently don't need
489 hir::ItemKind::TyAlias(_, ref generics)
490 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
495 | hir::ItemKind::Enum(_, ref generics)
496 | hir::ItemKind::Struct(_, ref generics)
497 | hir::ItemKind::Union(_, ref generics)
498 | hir::ItemKind::Trait(_, _, ref generics, ..)
499 | hir::ItemKind::TraitAlias(ref generics, ..)
500 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
501 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
502 // This is not true for other kinds of items.x
503 let track_lifetime_uses = match item.kind {
504 hir::ItemKind::Impl(..) => true,
507 // These kinds of items have only early-bound lifetime parameters.
508 let mut index = if sub_items_have_self_param(&item.kind) {
509 1 // Self comes before lifetimes
513 let mut non_lifetime_count = 0;
514 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
515 GenericParamKind::Lifetime { .. } => {
516 Some(Region::early(&self.tcx.hir(), &mut index, param))
518 GenericParamKind::Type { .. } |
519 GenericParamKind::Const { .. } => {
520 non_lifetime_count += 1;
524 let scope = Scope::Binder {
526 next_early_index: index + non_lifetime_count,
527 opaque_type_parent: true,
531 self.with(scope, |old_scope, this| {
532 this.check_lifetime_params(old_scope, &generics.params);
533 intravisit::walk_item(this, item);
539 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
541 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
542 self.visit_early_late(None, decl, generics, |this| {
543 intravisit::walk_foreign_item(this, item);
546 hir::ForeignItemKind::Static(..) => {
547 intravisit::walk_foreign_item(self, item);
549 hir::ForeignItemKind::Type => {
550 intravisit::walk_foreign_item(self, item);
555 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
556 debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
557 debug!("visit_ty: ty.kind={:?}", ty.kind);
559 hir::TyKind::BareFn(ref c) => {
560 let next_early_index = self.next_early_index();
561 let was_in_fn_syntax = self.is_in_fn_syntax;
562 self.is_in_fn_syntax = true;
563 let scope = Scope::Binder {
564 lifetimes: c.generic_params
566 .filter_map(|param| match param.kind {
567 GenericParamKind::Lifetime { .. } => {
568 Some(Region::late(&self.tcx.hir(), param))
575 track_lifetime_uses: true,
576 opaque_type_parent: false,
578 self.with(scope, |old_scope, this| {
579 // a bare fn has no bounds, so everything
580 // contained within is scoped within its binder.
581 this.check_lifetime_params(old_scope, &c.generic_params);
582 intravisit::walk_ty(this, ty);
584 self.is_in_fn_syntax = was_in_fn_syntax;
586 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
587 debug!("visit_ty: TraitObject(bounds={:?}, lifetime={:?})", bounds, lifetime);
588 for bound in bounds {
589 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
591 match lifetime.name {
592 LifetimeName::Implicit => {
593 // For types like `dyn Foo`, we should
594 // generate a special form of elided.
597 "object-lifetime-default expected, not implict",
600 LifetimeName::ImplicitObjectLifetimeDefault => {
601 // If the user does not write *anything*, we
602 // use the object lifetime defaulting
603 // rules. So e.g., `Box<dyn Debug>` becomes
604 // `Box<dyn Debug + 'static>`.
605 self.resolve_object_lifetime_default(lifetime)
607 LifetimeName::Underscore => {
608 // If the user writes `'_`, we use the *ordinary* elision
609 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
610 // resolved the same as the `'_` in `&'_ Foo`.
613 self.resolve_elided_lifetimes(vec![lifetime])
615 LifetimeName::Param(_) | LifetimeName::Static => {
616 // If the user wrote an explicit name, use that.
617 self.visit_lifetime(lifetime);
619 LifetimeName::Error => {}
622 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
623 self.visit_lifetime(lifetime_ref);
624 let scope = Scope::ObjectLifetimeDefault {
625 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
628 self.with(scope, |_, this| this.visit_ty(&mt.ty));
630 hir::TyKind::Def(item_id, ref lifetimes) => {
631 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
632 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
633 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
634 // ^ ^ this gets resolved in the scope of
635 // the opaque_ty generics
636 let (generics, bounds) = match self.tcx.hir().expect_item(item_id.id).kind {
637 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
638 // This arm is for `impl Trait` in the types of statics, constants and locals.
639 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
643 intravisit::walk_ty(self, ty);
646 // RPIT (return position impl trait)
647 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
651 }) => (generics, bounds),
652 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
655 // Resolve the lifetimes that are applied to the opaque type.
656 // These are resolved in the current scope.
657 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
658 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
659 // ^ ^this gets resolved in the current scope
660 for lifetime in lifetimes {
661 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
662 self.visit_lifetime(lifetime);
664 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
665 // and ban them. Type variables instantiated inside binders aren't
666 // well-supported at the moment, so this doesn't work.
667 // In the future, this should be fixed and this error should be removed.
668 let def = self.map.defs.get(&lifetime.hir_id).cloned();
669 if let Some(Region::LateBound(_, def_id, _)) = def {
670 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
671 // Ensure that the parent of the def is an item, not HRTB
672 let parent_id = self.tcx.hir().get_parent_node(hir_id);
673 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
674 let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
675 let krate = self.tcx.hir().forest.krate();
677 if !(krate.items.contains_key(&parent_id)
678 || krate.impl_items.contains_key(&parent_impl_id)
679 || krate.trait_items.contains_key(&parent_trait_id))
685 "`impl Trait` can only capture lifetimes \
686 bound at the fn or impl level"
688 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
695 // We want to start our early-bound indices at the end of the parent scope,
696 // not including any parent `impl Trait`s.
697 let mut index = self.next_early_index_for_opaque_type();
698 debug!("visit_ty: index = {}", index);
700 let mut elision = None;
701 let mut lifetimes = FxHashMap::default();
702 let mut non_lifetime_count = 0;
703 for param in &generics.params {
705 GenericParamKind::Lifetime { .. } => {
706 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
707 let def_id = if let Region::EarlyBound(_ ,def_id , _) = reg {
712 if let hir::ParamName::Plain(param_name) = name {
713 if param_name.name == kw::UnderscoreLifetime {
714 // Pick the elided lifetime "definition" if one exists
715 // and use it to make an elision scope.
716 self.lifetime_uses.insert(def_id.clone(), LifetimeUseSet::Many);
719 lifetimes.insert(name, reg);
722 self.lifetime_uses.insert(def_id.clone(), LifetimeUseSet::Many);
723 lifetimes.insert(name, reg);
726 GenericParamKind::Type { .. } |
727 GenericParamKind::Const { .. } => {
728 non_lifetime_count += 1;
732 let next_early_index = index + non_lifetime_count;
734 if let Some(elision_region) = elision {
735 let scope = Scope::Elision {
736 elide: Elide::Exact(elision_region),
739 self.with(scope, |_old_scope, this| {
740 let scope = Scope::Binder {
744 track_lifetime_uses: true,
745 opaque_type_parent: false,
747 this.with(scope, |_old_scope, this| {
748 this.visit_generics(generics);
749 for bound in bounds {
750 this.visit_param_bound(bound);
755 let scope = Scope::Binder {
759 track_lifetime_uses: true,
760 opaque_type_parent: false,
762 self.with(scope, |_old_scope, this| {
763 this.visit_generics(generics);
764 for bound in bounds {
765 this.visit_param_bound(bound);
770 _ => intravisit::walk_ty(self, ty),
774 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
775 use self::hir::TraitItemKind::*;
776 match trait_item.kind {
777 Method(ref sig, _) => {
779 self.visit_early_late(
780 Some(tcx.hir().get_parent_item(trait_item.hir_id)),
782 &trait_item.generics,
783 |this| intravisit::walk_trait_item(this, trait_item),
786 Type(ref bounds, ref ty) => {
787 let generics = &trait_item.generics;
788 let mut index = self.next_early_index();
789 debug!("visit_ty: index = {}", index);
790 let mut non_lifetime_count = 0;
791 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
792 GenericParamKind::Lifetime { .. } => {
793 Some(Region::early(&self.tcx.hir(), &mut index, param))
795 GenericParamKind::Type { .. } |
796 GenericParamKind::Const { .. } => {
797 non_lifetime_count += 1;
801 let scope = Scope::Binder {
803 next_early_index: index + non_lifetime_count,
805 track_lifetime_uses: true,
806 opaque_type_parent: true,
808 self.with(scope, |_old_scope, this| {
809 this.visit_generics(generics);
810 for bound in bounds {
811 this.visit_param_bound(bound);
813 if let Some(ty) = ty {
819 // Only methods and types support generics.
820 assert!(trait_item.generics.params.is_empty());
821 intravisit::walk_trait_item(self, trait_item);
826 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
827 use self::hir::ImplItemKind::*;
828 match impl_item.kind {
829 Method(ref sig, _) => {
831 self.visit_early_late(
832 Some(tcx.hir().get_parent_item(impl_item.hir_id)),
835 |this| intravisit::walk_impl_item(this, impl_item),
839 let generics = &impl_item.generics;
840 let mut index = self.next_early_index();
841 let mut non_lifetime_count = 0;
842 debug!("visit_ty: index = {}", index);
843 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
844 GenericParamKind::Lifetime { .. } => {
845 Some(Region::early(&self.tcx.hir(), &mut index, param))
847 GenericParamKind::Const { .. } |
848 GenericParamKind::Type { .. } => {
849 non_lifetime_count += 1;
853 let scope = Scope::Binder {
855 next_early_index: index + non_lifetime_count,
857 track_lifetime_uses: true,
858 opaque_type_parent: true,
860 self.with(scope, |_old_scope, this| {
861 this.visit_generics(generics);
865 OpaqueTy(ref bounds) => {
866 let generics = &impl_item.generics;
867 let mut index = self.next_early_index();
868 let mut next_early_index = index;
869 debug!("visit_ty: index = {}", index);
870 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
871 GenericParamKind::Lifetime { .. } => {
872 Some(Region::early(&self.tcx.hir(), &mut index, param))
874 GenericParamKind::Type { .. } => {
875 next_early_index += 1;
878 GenericParamKind::Const { .. } => {
879 next_early_index += 1;
884 let scope = Scope::Binder {
888 track_lifetime_uses: true,
889 opaque_type_parent: true,
891 self.with(scope, |_old_scope, this| {
892 this.visit_generics(generics);
893 for bound in bounds {
894 this.visit_param_bound(bound);
899 // Only methods and types support generics.
900 assert!(impl_item.generics.params.is_empty());
901 intravisit::walk_impl_item(self, impl_item);
906 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
907 debug!("visit_lifetime(lifetime_ref={:?})", lifetime_ref);
908 if lifetime_ref.is_elided() {
909 self.resolve_elided_lifetimes(vec![lifetime_ref]);
912 if lifetime_ref.is_static() {
913 self.insert_lifetime(lifetime_ref, Region::Static);
916 self.resolve_lifetime_ref(lifetime_ref);
919 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
920 for (i, segment) in path.segments.iter().enumerate() {
921 let depth = path.segments.len() - i - 1;
922 if let Some(ref args) = segment.args {
923 self.visit_segment_args(path.res, depth, args);
928 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
929 let output = match fd.output {
930 hir::DefaultReturn(_) => None,
931 hir::Return(ref ty) => Some(&**ty),
933 self.visit_fn_like_elision(&fd.inputs, output);
936 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
937 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
938 for param in &generics.params {
940 GenericParamKind::Lifetime { .. } => {}
941 GenericParamKind::Type { ref default, .. } => {
942 walk_list!(self, visit_param_bound, ¶m.bounds);
943 if let Some(ref ty) = default {
947 GenericParamKind::Const { ref ty, .. } => {
948 walk_list!(self, visit_param_bound, ¶m.bounds);
953 for predicate in &generics.where_clause.predicates {
955 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
958 ref bound_generic_params,
961 let lifetimes: FxHashMap<_, _> = bound_generic_params
963 .filter_map(|param| match param.kind {
964 GenericParamKind::Lifetime { .. } => {
965 Some(Region::late(&self.tcx.hir(), param))
970 if !lifetimes.is_empty() {
971 self.trait_ref_hack = true;
972 let next_early_index = self.next_early_index();
973 let scope = Scope::Binder {
977 track_lifetime_uses: true,
978 opaque_type_parent: false,
980 let result = self.with(scope, |old_scope, this| {
981 this.check_lifetime_params(old_scope, &bound_generic_params);
982 this.visit_ty(&bounded_ty);
983 walk_list!(this, visit_param_bound, bounds);
985 self.trait_ref_hack = false;
988 self.visit_ty(&bounded_ty);
989 walk_list!(self, visit_param_bound, bounds);
992 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
997 self.visit_lifetime(lifetime);
998 walk_list!(self, visit_param_bound, bounds);
1000 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1005 self.visit_ty(lhs_ty);
1006 self.visit_ty(rhs_ty);
1012 fn visit_poly_trait_ref(
1014 trait_ref: &'tcx hir::PolyTraitRef,
1015 _modifier: hir::TraitBoundModifier,
1017 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1019 if !self.trait_ref_hack || trait_ref.bound_generic_params.iter().any(|param| {
1021 GenericParamKind::Lifetime { .. } => true,
1025 if self.trait_ref_hack {
1030 "nested quantification of lifetimes"
1033 let next_early_index = self.next_early_index();
1034 let scope = Scope::Binder {
1035 lifetimes: trait_ref
1036 .bound_generic_params
1038 .filter_map(|param| match param.kind {
1039 GenericParamKind::Lifetime { .. } => {
1040 Some(Region::late(&self.tcx.hir(), param))
1047 track_lifetime_uses: true,
1048 opaque_type_parent: false,
1050 self.with(scope, |old_scope, this| {
1051 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1052 walk_list!(this, visit_generic_param, &trait_ref.bound_generic_params);
1053 this.visit_trait_ref(&trait_ref.trait_ref)
1056 self.visit_trait_ref(&trait_ref.trait_ref)
1061 #[derive(Copy, Clone, PartialEq)]
1075 fn original_label(span: Span) -> Original {
1077 kind: ShadowKind::Label,
1081 fn shadower_label(span: Span) -> Shadower {
1083 kind: ShadowKind::Label,
1087 fn original_lifetime(span: Span) -> Original {
1089 kind: ShadowKind::Lifetime,
1093 fn shadower_lifetime(param: &hir::GenericParam) -> Shadower {
1095 kind: ShadowKind::Lifetime,
1101 fn desc(&self) -> &'static str {
1103 ShadowKind::Label => "label",
1104 ShadowKind::Lifetime => "lifetime",
1109 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &P<[hir::GenericParam]>) {
1110 let lifetime_params: Vec<_> = params
1112 .filter_map(|param| match param.kind {
1113 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1117 let explicit = lifetime_params
1119 .find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1120 let in_band = lifetime_params
1122 .find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1124 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1129 "cannot mix in-band and explicit lifetime definitions"
1130 ).span_label(*in_band_span, "in-band lifetime definition here")
1131 .span_label(*explicit_span, "explicit lifetime definition here")
1136 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: ast::Name, orig: Original, shadower: Shadower) {
1137 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1138 // lifetime/lifetime shadowing is an error
1143 "{} name `{}` shadows a \
1144 {} name that is already in scope",
1145 shadower.kind.desc(),
1150 // shadowing involving a label is only a warning, due to issues with
1151 // labels and lifetimes not being macro-hygienic.
1152 tcx.sess.struct_span_warn(
1155 "{} name `{}` shadows a \
1156 {} name that is already in scope",
1157 shadower.kind.desc(),
1163 err.span_label(orig.span, "first declared here");
1164 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1168 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1169 // if one of the label shadows a lifetime or another label.
1170 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
1171 struct GatherLabels<'a, 'tcx> {
1173 scope: ScopeRef<'a>,
1174 labels_in_fn: &'a mut Vec<ast::Ident>,
1177 let mut gather = GatherLabels {
1180 labels_in_fn: &mut ctxt.labels_in_fn,
1182 gather.visit_body(body);
1184 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1185 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1186 NestedVisitorMap::None
1189 fn visit_expr(&mut self, ex: &hir::Expr) {
1190 if let Some(label) = expression_label(ex) {
1191 for prior_label in &self.labels_in_fn[..] {
1192 // FIXME (#24278): non-hygienic comparison
1193 if label.name == prior_label.name {
1194 signal_shadowing_problem(
1197 original_label(prior_label.span),
1198 shadower_label(label.span),
1203 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1205 self.labels_in_fn.push(label);
1207 intravisit::walk_expr(self, ex)
1211 fn expression_label(ex: &hir::Expr) -> Option<ast::Ident> {
1212 if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind {
1219 fn check_if_label_shadows_lifetime(
1221 mut scope: ScopeRef<'_>,
1226 Scope::Body { s, .. }
1227 | Scope::Elision { s, .. }
1228 | Scope::ObjectLifetimeDefault { s, .. } => {
1237 ref lifetimes, s, ..
1239 // FIXME (#24278): non-hygienic comparison
1240 if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1241 let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
1243 signal_shadowing_problem(
1246 original_lifetime(tcx.hir().span(hir_id)),
1247 shadower_label(label.span),
1258 fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1259 let mut map = HirIdMap::default();
1260 for item in tcx.hir().krate().items.values() {
1262 hir::ItemKind::Struct(_, ref generics)
1263 | hir::ItemKind::Union(_, ref generics)
1264 | hir::ItemKind::Enum(_, ref generics)
1265 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1267 impl_trait_fn: None,
1270 | hir::ItemKind::TyAlias(_, ref generics)
1271 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1272 let result = object_lifetime_defaults_for_item(tcx, generics);
1275 if attr::contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1276 let object_lifetime_default_reprs: String = result
1278 .map(|set| match *set {
1279 Set1::Empty => "BaseDefault".into(),
1280 Set1::One(Region::Static) => "'static".into(),
1281 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1284 .find_map(|param| match param.kind {
1285 GenericParamKind::Lifetime { .. } => {
1287 return Some(param.name.ident().to_string().into());
1295 Set1::One(_) => bug!(),
1296 Set1::Many => "Ambiguous".into(),
1298 .collect::<Vec<Cow<'static, str>>>()
1300 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1303 map.insert(item.hir_id, result);
1311 /// Scan the bounds and where-clauses on parameters to extract bounds
1312 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1313 /// for each type parameter.
1314 fn object_lifetime_defaults_for_item(
1316 generics: &hir::Generics,
1317 ) -> Vec<ObjectLifetimeDefault> {
1318 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound]) {
1319 for bound in bounds {
1320 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1321 set.insert(lifetime.name.modern());
1329 .filter_map(|param| match param.kind {
1330 GenericParamKind::Lifetime { .. } => None,
1331 GenericParamKind::Type { .. } => {
1332 let mut set = Set1::Empty;
1334 add_bounds(&mut set, ¶m.bounds);
1336 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1337 for predicate in &generics.where_clause.predicates {
1338 // Look for `type: ...` where clauses.
1339 let data = match *predicate {
1340 hir::WherePredicate::BoundPredicate(ref data) => data,
1344 // Ignore `for<'a> type: ...` as they can change what
1345 // lifetimes mean (although we could "just" handle it).
1346 if !data.bound_generic_params.is_empty() {
1350 let res = match data.bounded_ty.kind {
1351 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1355 if res == Res::Def(DefKind::TyParam, param_def_id) {
1356 add_bounds(&mut set, &data.bounds);
1361 Set1::Empty => Set1::Empty,
1362 Set1::One(name) => {
1363 if name == hir::LifetimeName::Static {
1364 Set1::One(Region::Static)
1369 .filter_map(|param| match param.kind {
1370 GenericParamKind::Lifetime { .. } => Some((
1372 hir::LifetimeName::Param(param.name),
1373 LifetimeDefOrigin::from_param(param),
1378 .find(|&(_, (_, lt_name, _))| lt_name == name)
1379 .map_or(Set1::Many, |(i, (id, _, origin))| {
1380 let def_id = tcx.hir().local_def_id(id);
1381 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1385 Set1::Many => Set1::Many,
1388 GenericParamKind::Const { .. } => {
1389 // Generic consts don't impose any constraints.
1396 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1397 // FIXME(#37666) this works around a limitation in the region inferencer
1398 fn hack<F>(&mut self, f: F)
1400 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1405 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1407 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1409 let LifetimeContext {
1415 let labels_in_fn = take(&mut self.labels_in_fn);
1416 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1417 let mut this = LifetimeContext {
1421 trait_ref_hack: self.trait_ref_hack,
1422 is_in_fn_syntax: self.is_in_fn_syntax,
1424 xcrate_object_lifetime_defaults,
1425 lifetime_uses: lifetime_uses,
1427 debug!("entering scope {:?}", this.scope);
1428 f(self.scope, &mut this);
1429 this.check_uses_for_lifetimes_defined_by_scope();
1430 debug!("exiting scope {:?}", this.scope);
1431 self.labels_in_fn = this.labels_in_fn;
1432 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1435 /// helper method to determine the span to remove when suggesting the
1436 /// deletion of a lifetime
1437 fn lifetime_deletion_span(&self, name: ast::Ident, generics: &hir::Generics) -> Option<Span> {
1438 generics.params.iter().enumerate().find_map(|(i, param)| {
1439 if param.name.ident() == name {
1440 let mut in_band = false;
1441 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1442 if let hir::LifetimeParamKind::InBand = kind {
1449 if generics.params.len() == 1 {
1450 // if sole lifetime, remove the entire `<>` brackets
1453 // if removing within `<>` brackets, we also want to
1454 // delete a leading or trailing comma as appropriate
1455 if i >= generics.params.len() - 1 {
1456 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1458 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1468 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1469 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1470 fn suggest_eliding_single_use_lifetime(
1471 &self, err: &mut DiagnosticBuilder<'_>, def_id: DefId, lifetime: &hir::Lifetime
1473 let name = lifetime.name.ident();
1474 let mut remove_decl = None;
1475 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1476 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1477 remove_decl = self.lifetime_deletion_span(name, generics);
1481 let mut remove_use = None;
1482 let mut elide_use = None;
1483 let mut find_arg_use_span = |inputs: &hir::HirVec<hir::Ty>| {
1484 for input in inputs {
1486 hir::TyKind::Rptr(lt, _) => {
1487 if lt.name.ident() == name {
1488 // include the trailing whitespace between the lifetime and type names
1489 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1491 self.tcx.sess.source_map()
1492 .span_until_non_whitespace(lt_through_ty_span)
1497 hir::TyKind::Path(ref qpath) => {
1498 if let QPath::Resolved(_, path) = qpath {
1500 let last_segment = &path.segments[path.segments.len()-1];
1501 let generics = last_segment.generic_args();
1502 for arg in generics.args.iter() {
1503 if let GenericArg::Lifetime(lt) = arg {
1504 if lt.name.ident() == name {
1505 elide_use = Some(lt.span);
1517 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1518 if let Some(parent) = self.tcx.hir().find(
1519 self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1522 Node::Item(item) => {
1523 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1524 find_arg_use_span(&sig.decl.inputs);
1527 Node::ImplItem(impl_item) => {
1528 if let hir::ImplItemKind::Method(sig, _) = &impl_item.kind {
1529 find_arg_use_span(&sig.decl.inputs);
1537 let msg = "elide the single-use lifetime";
1538 match (remove_decl, remove_use, elide_use) {
1539 (Some(decl_span), Some(use_span), None) => {
1540 // if both declaration and use deletion spans start at the same
1541 // place ("start at" because the latter includes trailing
1542 // whitespace), then this is an in-band lifetime
1543 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1544 err.span_suggestion(
1548 Applicability::MachineApplicable,
1551 err.multipart_suggestion(
1553 vec![(decl_span, String::new()), (use_span, String::new())],
1554 Applicability::MachineApplicable,
1558 (Some(decl_span), None, Some(use_span)) => {
1559 err.multipart_suggestion(
1561 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1562 Applicability::MachineApplicable,
1569 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1570 let defined_by = match self.scope {
1571 Scope::Binder { lifetimes, .. } => lifetimes,
1573 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1578 let mut def_ids: Vec<_> = defined_by
1580 .flat_map(|region| match region {
1581 Region::EarlyBound(_, def_id, _)
1582 | Region::LateBound(_, def_id, _)
1583 | Region::Free(_, def_id) => Some(*def_id),
1585 Region::LateBoundAnon(..) | Region::Static => None,
1589 // ensure that we issue lints in a repeatable order
1590 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1592 for def_id in def_ids {
1594 "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
1598 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1601 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1605 match lifetimeuseset {
1606 Some(LifetimeUseSet::One(lifetime)) => {
1607 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1608 debug!("hir id first={:?}", hir_id);
1609 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1610 Node::Lifetime(hir_lifetime) => Some((
1611 hir_lifetime.hir_id,
1613 hir_lifetime.name.ident(),
1615 Node::GenericParam(param) => {
1616 Some((param.hir_id, param.span, param.name.ident()))
1620 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1621 if name.name == kw::UnderscoreLifetime {
1625 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1626 if let Some(parent_hir_id) = self.tcx.hir()
1627 .as_local_hir_id(parent_def_id) {
1628 // lifetimes in `derive` expansions don't count (Issue #53738)
1629 if self.tcx.hir().attrs(parent_hir_id).iter()
1630 .any(|attr| attr.check_name(sym::automatically_derived)) {
1636 let mut err = self.tcx.struct_span_lint_hir(
1637 lint::builtin::SINGLE_USE_LIFETIMES,
1640 &format!("lifetime parameter `{}` only used once", name),
1643 if span == lifetime.span {
1644 // spans are the same for in-band lifetime declarations
1645 err.span_label(span, "this lifetime is only used here");
1647 err.span_label(span, "this lifetime...");
1648 err.span_label(lifetime.span, "...is used only here");
1650 self.suggest_eliding_single_use_lifetime(&mut err, def_id, lifetime);
1654 Some(LifetimeUseSet::Many) => {
1655 debug!("not one use lifetime");
1658 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1659 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1660 Node::Lifetime(hir_lifetime) => Some((
1661 hir_lifetime.hir_id,
1663 hir_lifetime.name.ident(),
1665 Node::GenericParam(param) => {
1666 Some((param.hir_id, param.span, param.name.ident()))
1670 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1671 let mut err = self.tcx.struct_span_lint_hir(
1672 lint::builtin::UNUSED_LIFETIMES,
1675 &format!("lifetime parameter `{}` never used", name),
1677 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1678 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1679 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1680 if let Some(span) = unused_lt_span {
1681 err.span_suggestion(
1683 "elide the unused lifetime",
1685 Applicability::MachineApplicable,
1697 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1699 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1700 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1701 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1705 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1707 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1708 /// lifetimes may be interspersed together.
1710 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1711 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1712 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1713 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1714 /// ordering is not important there.
1715 fn visit_early_late<F>(
1717 parent_id: Option<hir::HirId>,
1718 decl: &'tcx hir::FnDecl,
1719 generics: &'tcx hir::Generics,
1722 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1724 insert_late_bound_lifetimes(self.map, decl, generics);
1726 // Find the start of nested early scopes, e.g., in methods.
1728 if let Some(parent_id) = parent_id {
1729 let parent = self.tcx.hir().expect_item(parent_id);
1730 if sub_items_have_self_param(&parent.kind) {
1731 index += 1; // Self comes before lifetimes
1734 hir::ItemKind::Trait(_, _, ref generics, ..)
1735 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
1736 index += generics.params.len() as u32;
1742 let mut non_lifetime_count = 0;
1743 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
1744 GenericParamKind::Lifetime { .. } => {
1745 if self.map.late_bound.contains(¶m.hir_id) {
1746 Some(Region::late(&self.tcx.hir(), param))
1748 Some(Region::early(&self.tcx.hir(), &mut index, param))
1751 GenericParamKind::Type { .. } |
1752 GenericParamKind::Const { .. } => {
1753 non_lifetime_count += 1;
1757 let next_early_index = index + non_lifetime_count;
1759 let scope = Scope::Binder {
1763 opaque_type_parent: true,
1764 track_lifetime_uses: false,
1766 self.with(scope, move |old_scope, this| {
1767 this.check_lifetime_params(old_scope, &generics.params);
1768 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1772 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1773 let mut scope = self.scope;
1776 Scope::Root => return 0,
1782 } if (!only_opaque_type_parent || opaque_type_parent) =>
1784 return next_early_index
1787 Scope::Binder { s, .. }
1788 | Scope::Body { s, .. }
1789 | Scope::Elision { s, .. }
1790 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1795 /// Returns the next index one would use for an early-bound-region
1796 /// if extending the current scope.
1797 fn next_early_index(&self) -> u32 {
1798 self.next_early_index_helper(true)
1801 /// Returns the next index one would use for an `impl Trait` that
1802 /// is being converted into an opaque type alias `impl Trait`. This will be the
1803 /// next early index from the enclosing item, for the most
1804 /// part. See the `opaque_type_parent` field for more info.
1805 fn next_early_index_for_opaque_type(&self) -> u32 {
1806 self.next_early_index_helper(false)
1809 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1810 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1812 // If we've already reported an error, just ignore `lifetime_ref`.
1813 if let LifetimeName::Error = lifetime_ref.name {
1817 // Walk up the scope chain, tracking the number of fn scopes
1818 // that we pass through, until we find a lifetime with the
1819 // given name or we run out of scopes.
1821 let mut late_depth = 0;
1822 let mut scope = self.scope;
1823 let mut outermost_body = None;
1826 Scope::Body { id, s } => {
1827 outermost_body = Some(id);
1836 ref lifetimes, s, ..
1838 match lifetime_ref.name {
1839 LifetimeName::Param(param_name) => {
1840 if let Some(&def) = lifetimes.get(¶m_name.modern()) {
1841 break Some(def.shifted(late_depth));
1844 _ => bug!("expected LifetimeName::Param"),
1851 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1857 if let Some(mut def) = result {
1858 if let Region::EarlyBound(..) = def {
1859 // Do not free early-bound regions, only late-bound ones.
1860 } else if let Some(body_id) = outermost_body {
1861 let fn_id = self.tcx.hir().body_owner(body_id);
1862 match self.tcx.hir().get(fn_id) {
1863 Node::Item(&hir::Item {
1864 kind: hir::ItemKind::Fn(..),
1867 | Node::TraitItem(&hir::TraitItem {
1868 kind: hir::TraitItemKind::Method(..),
1871 | Node::ImplItem(&hir::ImplItem {
1872 kind: hir::ImplItemKind::Method(..),
1875 let scope = self.tcx.hir().local_def_id(fn_id);
1876 def = Region::Free(scope, def.id().unwrap());
1882 // Check for fn-syntax conflicts with in-band lifetime definitions
1883 if self.is_in_fn_syntax {
1885 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1886 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1891 "lifetimes used in `fn` or `Fn` syntax must be \
1892 explicitly declared using `<...>` binders"
1893 ).span_label(lifetime_ref.span, "in-band lifetime definition")
1898 | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1899 | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1900 | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1901 | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1902 | Region::LateBoundAnon(..)
1903 | Region::Free(..) => {}
1907 self.insert_lifetime(lifetime_ref, def);
1913 "use of undeclared lifetime name `{}`",
1915 ).span_label(lifetime_ref.span, "undeclared lifetime")
1920 fn visit_segment_args(&mut self, res: Res, depth: usize, generic_args: &'tcx hir::GenericArgs) {
1922 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1928 if generic_args.parenthesized {
1929 let was_in_fn_syntax = self.is_in_fn_syntax;
1930 self.is_in_fn_syntax = true;
1931 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1932 self.is_in_fn_syntax = was_in_fn_syntax;
1936 let mut elide_lifetimes = true;
1937 let lifetimes = generic_args
1940 .filter_map(|arg| match arg {
1941 hir::GenericArg::Lifetime(lt) => {
1942 if !lt.is_elided() {
1943 elide_lifetimes = false;
1950 if elide_lifetimes {
1951 self.resolve_elided_lifetimes(lifetimes);
1953 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1956 // Figure out if this is a type/trait segment,
1957 // which requires object lifetime defaults.
1958 let parent_def_id = |this: &mut Self, def_id: DefId| {
1959 let def_key = this.tcx.def_key(def_id);
1961 krate: def_id.krate,
1962 index: def_key.parent.expect("missing parent"),
1965 let type_def_id = match res {
1966 Res::Def(DefKind::AssocTy, def_id)
1967 if depth == 1 => Some(parent_def_id(self, def_id)),
1968 Res::Def(DefKind::Variant, def_id)
1969 if depth == 0 => Some(parent_def_id(self, def_id)),
1970 Res::Def(DefKind::Struct, def_id)
1971 | Res::Def(DefKind::Union, def_id)
1972 | Res::Def(DefKind::Enum, def_id)
1973 | Res::Def(DefKind::TyAlias, def_id)
1974 | Res::Def(DefKind::Trait, def_id) if depth == 0 =>
1981 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1983 // Compute a vector of defaults, one for each type parameter,
1984 // per the rules given in RFCs 599 and 1156. Example:
1987 // struct Foo<'a, T: 'a, U> { }
1990 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1991 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1992 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1995 // Therefore, we would compute `object_lifetime_defaults` to a
1996 // vector like `['x, 'static]`. Note that the vector only
1997 // includes type parameters.
1998 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
2000 let mut scope = self.scope;
2003 Scope::Root => break false,
2005 Scope::Body { .. } => break true,
2007 Scope::Binder { s, .. }
2008 | Scope::Elision { s, .. }
2009 | Scope::ObjectLifetimeDefault { s, .. } => {
2016 let map = &self.map;
2017 let unsubst = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
2018 &map.object_lifetime_defaults[&id]
2021 self.xcrate_object_lifetime_defaults
2023 .or_insert_with(|| {
2024 tcx.generics_of(def_id)
2027 .filter_map(|param| match param.kind {
2028 GenericParamDefKind::Type {
2029 object_lifetime_default,
2031 } => Some(object_lifetime_default),
2032 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
2037 debug!("visit_segment_args: unsubst={:?}", unsubst);
2040 .map(|set| match *set {
2041 Set1::Empty => if in_body {
2044 Some(Region::Static)
2047 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2048 GenericArg::Lifetime(lt) => Some(lt),
2051 r.subst(lifetimes, map)
2058 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2061 for arg in &generic_args.args {
2063 GenericArg::Lifetime(_) => {}
2064 GenericArg::Type(ty) => {
2065 if let Some(<) = object_lifetime_defaults.get(i) {
2066 let scope = Scope::ObjectLifetimeDefault {
2070 self.with(scope, |_, this| this.visit_ty(ty));
2076 GenericArg::Const(ct) => {
2077 self.visit_anon_const(&ct.value);
2082 // Hack: when resolving the type `XX` in binding like `dyn
2083 // Foo<'b, Item = XX>`, the current object-lifetime default
2084 // would be to examine the trait `Foo` to check whether it has
2085 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2086 // declared like so, then the default object lifetime bound in
2087 // `XX` should be `'b`:
2095 // but if we just have `type Item;`, then it would be
2096 // `'static`. However, we don't get all of this logic correct.
2098 // Instead, we do something hacky: if there are no lifetime parameters
2099 // to the trait, then we simply use a default object lifetime
2100 // bound of `'static`, because there is no other possibility. On the other hand,
2101 // if there ARE lifetime parameters, then we require the user to give an
2102 // explicit bound for now.
2104 // This is intended to leave room for us to implement the
2105 // correct behavior in the future.
2106 let has_lifetime_parameter = generic_args
2109 .any(|arg| match arg {
2110 GenericArg::Lifetime(_) => true,
2114 // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2115 for b in &generic_args.bindings {
2116 let scope = Scope::ObjectLifetimeDefault {
2117 lifetime: if has_lifetime_parameter {
2120 Some(Region::Static)
2124 self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2128 fn visit_fn_like_elision(&mut self, inputs: &'tcx [hir::Ty], output: Option<&'tcx hir::Ty>) {
2129 debug!("visit_fn_like_elision: enter");
2130 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2131 let arg_scope = Scope::Elision {
2132 elide: arg_elide.clone(),
2135 self.with(arg_scope, |_, this| {
2136 for input in inputs {
2137 this.visit_ty(input);
2140 Scope::Elision { ref elide, .. } => {
2141 arg_elide = elide.clone();
2147 let output = match output {
2152 debug!("visit_fn_like_elision: determine output");
2154 // Figure out if there's a body we can get argument names from,
2155 // and whether there's a `self` argument (treated specially).
2156 let mut assoc_item_kind = None;
2157 let mut impl_self = None;
2158 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2159 let body = match self.tcx.hir().get(parent) {
2160 // `fn` definitions and methods.
2161 Node::Item(&hir::Item {
2162 kind: hir::ItemKind::Fn(.., body),
2166 Node::TraitItem(&hir::TraitItem {
2167 kind: hir::TraitItemKind::Method(_, ref m),
2170 if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
2172 .expect_item(self.tcx.hir().get_parent_item(parent))
2175 assoc_item_kind = trait_items
2177 .find(|ti| ti.id.hir_id == parent)
2181 hir::TraitMethod::Required(_) => None,
2182 hir::TraitMethod::Provided(body) => Some(body),
2186 Node::ImplItem(&hir::ImplItem {
2187 kind: hir::ImplItemKind::Method(_, body),
2190 if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
2192 .expect_item(self.tcx.hir().get_parent_item(parent))
2195 impl_self = Some(self_ty);
2196 assoc_item_kind = impl_items
2198 .find(|ii| ii.id.hir_id == parent)
2204 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2205 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2206 // Everything else (only closures?) doesn't
2207 // actually enjoy elision in return types.
2209 self.visit_ty(output);
2214 let has_self = match assoc_item_kind {
2215 Some(hir::AssocItemKind::Method { has_self }) => has_self,
2219 // In accordance with the rules for lifetime elision, we can determine
2220 // what region to use for elision in the output type in two ways.
2221 // First (determined here), if `self` is by-reference, then the
2222 // implied output region is the region of the self parameter.
2224 struct SelfVisitor<'a> {
2225 map: &'a NamedRegionMap,
2226 impl_self: Option<&'a hir::TyKind>,
2227 lifetime: Set1<Region>,
2230 impl SelfVisitor<'_> {
2231 // Look for `self: &'a Self` - also desugared from `&'a self`,
2232 // and if that matches, use it for elision and return early.
2233 fn is_self_ty(&self, res: Res) -> bool {
2234 if let Res::SelfTy(..) = res {
2238 // Can't always rely on literal (or implied) `Self` due
2239 // to the way elision rules were originally specified.
2240 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2244 // Whitelist the types that unambiguously always
2245 // result in the same type constructor being used
2246 // (it can't differ between `Self` and `self`).
2247 Res::Def(DefKind::Struct, _)
2248 | Res::Def(DefKind::Union, _)
2249 | Res::Def(DefKind::Enum, _)
2250 | Res::PrimTy(_) => {
2251 return res == path.res
2261 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2262 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'a> {
2263 NestedVisitorMap::None
2266 fn visit_ty(&mut self, ty: &'a hir::Ty) {
2267 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2268 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2270 if self.is_self_ty(path.res) {
2271 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2272 self.lifetime.insert(*lifetime);
2277 intravisit::walk_ty(self, ty)
2281 let mut visitor = SelfVisitor {
2283 impl_self: impl_self.map(|ty| &ty.kind),
2284 lifetime: Set1::Empty,
2286 visitor.visit_ty(&inputs[0]);
2287 if let Set1::One(lifetime) = visitor.lifetime {
2288 let scope = Scope::Elision {
2289 elide: Elide::Exact(lifetime),
2292 self.with(scope, |_, this| this.visit_ty(output));
2297 // Second, if there was exactly one lifetime (either a substitution or a
2298 // reference) in the arguments, then any anonymous regions in the output
2299 // have that lifetime.
2300 let mut possible_implied_output_region = None;
2301 let mut lifetime_count = 0;
2302 let arg_lifetimes = inputs
2305 .skip(has_self as usize)
2307 let mut gather = GatherLifetimes {
2309 outer_index: ty::INNERMOST,
2310 have_bound_regions: false,
2311 lifetimes: Default::default(),
2313 gather.visit_ty(input);
2315 lifetime_count += gather.lifetimes.len();
2317 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2318 // there's a chance that the unique lifetime of this
2319 // iteration will be the appropriate lifetime for output
2320 // parameters, so lets store it.
2321 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2324 ElisionFailureInfo {
2327 lifetime_count: gather.lifetimes.len(),
2328 have_bound_regions: gather.have_bound_regions,
2333 let elide = if lifetime_count == 1 {
2334 Elide::Exact(possible_implied_output_region.unwrap())
2336 Elide::Error(arg_lifetimes)
2339 debug!("visit_fn_like_elision: elide={:?}", elide);
2341 let scope = Scope::Elision {
2345 self.with(scope, |_, this| this.visit_ty(output));
2346 debug!("visit_fn_like_elision: exit");
2348 struct GatherLifetimes<'a> {
2349 map: &'a NamedRegionMap,
2350 outer_index: ty::DebruijnIndex,
2351 have_bound_regions: bool,
2352 lifetimes: FxHashSet<Region>,
2355 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2356 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2357 NestedVisitorMap::None
2360 fn visit_ty(&mut self, ty: &hir::Ty) {
2361 if let hir::TyKind::BareFn(_) = ty.kind {
2362 self.outer_index.shift_in(1);
2365 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2366 for bound in bounds {
2367 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2370 // Stay on the safe side and don't include the object
2371 // lifetime default (which may not end up being used).
2372 if !lifetime.is_elided() {
2373 self.visit_lifetime(lifetime);
2377 intravisit::walk_ty(self, ty);
2380 if let hir::TyKind::BareFn(_) = ty.kind {
2381 self.outer_index.shift_out(1);
2385 fn visit_generic_param(&mut self, param: &hir::GenericParam) {
2386 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2387 // FIXME(eddyb) Do we want this? It only makes a difference
2388 // if this `for<'a>` lifetime parameter is never used.
2389 self.have_bound_regions = true;
2392 intravisit::walk_generic_param(self, param);
2395 fn visit_poly_trait_ref(
2397 trait_ref: &hir::PolyTraitRef,
2398 modifier: hir::TraitBoundModifier,
2400 self.outer_index.shift_in(1);
2401 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2402 self.outer_index.shift_out(1);
2405 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2406 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2408 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2409 if debruijn < self.outer_index =>
2411 self.have_bound_regions = true;
2415 .insert(lifetime.shifted_out_to_binder(self.outer_index));
2423 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2424 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2426 if lifetime_refs.is_empty() {
2430 let span = lifetime_refs[0].span;
2431 let mut late_depth = 0;
2432 let mut scope = self.scope;
2433 let mut lifetime_names = FxHashSet::default();
2436 // Do not assign any resolution, it will be inferred.
2437 Scope::Body { .. } => return,
2439 Scope::Root => break None,
2441 Scope::Binder { s, ref lifetimes, .. } => {
2442 // collect named lifetimes for suggestions
2443 for name in lifetimes.keys() {
2444 if let hir::ParamName::Plain(name) = name {
2445 lifetime_names.insert(*name);
2452 Scope::Elision { ref elide, ref s, .. } => {
2453 let lifetime = match *elide {
2454 Elide::FreshLateAnon(ref counter) => {
2455 for lifetime_ref in lifetime_refs {
2456 let lifetime = Region::late_anon(counter).shifted(late_depth);
2457 self.insert_lifetime(lifetime_ref, lifetime);
2461 Elide::Exact(l) => l.shifted(late_depth),
2462 Elide::Error(ref e) => {
2463 if let Scope::Binder { ref lifetimes, .. } = s {
2464 // collect named lifetimes for suggestions
2465 for name in lifetimes.keys() {
2466 if let hir::ParamName::Plain(name) = name {
2467 lifetime_names.insert(*name);
2474 for lifetime_ref in lifetime_refs {
2475 self.insert_lifetime(lifetime_ref, lifetime);
2480 Scope::ObjectLifetimeDefault { s, .. } => {
2486 let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2487 let mut add_label = true;
2489 if let Some(params) = error {
2490 if lifetime_refs.len() == 1 {
2491 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2495 add_missing_lifetime_specifiers_label(
2498 lifetime_refs.len(),
2500 self.tcx.sess.source_map().span_to_snippet(span).ok().as_ref().map(|s| s.as_str()),
2507 fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2508 match self.tcx.sess.source_map().span_to_snippet(span) {
2509 Ok(ref snippet) => {
2510 let (sugg, applicability) = if snippet == "&" {
2511 ("&'static ".to_owned(), Applicability::MachineApplicable)
2512 } else if snippet == "'_" {
2513 ("'static".to_owned(), Applicability::MachineApplicable)
2515 (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2517 db.span_suggestion(span, msg, sugg, applicability);
2527 fn report_elision_failure(
2529 db: &mut DiagnosticBuilder<'_>,
2530 params: &[ElisionFailureInfo],
2533 let mut m = String::new();
2534 let len = params.len();
2536 let elided_params: Vec<_> = params
2539 .filter(|info| info.lifetime_count > 0)
2542 let elided_len = elided_params.len();
2544 for (i, info) in elided_params.into_iter().enumerate() {
2545 let ElisionFailureInfo {
2552 let help_name = if let Some(ident) = parent.and_then(|body| {
2553 self.tcx.hir().body(body).params[index].pat.simple_ident()
2555 format!("`{}`", ident)
2557 format!("argument {}", index + 1)
2565 "one of {}'s {} {}lifetimes",
2568 if have_bound_regions { "free " } else { "" }
2573 if elided_len == 2 && i == 0 {
2575 } else if i + 2 == elided_len {
2576 m.push_str(", or ");
2577 } else if i != elided_len - 1 {
2585 "this function's return type contains a borrowed value, but \
2586 there is no value for it to be borrowed from"
2588 self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2589 } else if elided_len == 0 {
2592 "this function's return type contains a borrowed value with \
2593 an elided lifetime, but the lifetime cannot be derived from \
2596 let msg = "consider giving it an explicit bounded or 'static lifetime";
2597 self.suggest_lifetime(db, span, msg)
2598 } else if elided_len == 1 {
2601 "this function's return type contains a borrowed value, but \
2602 the signature does not say which {} it is borrowed from",
2609 "this function's return type contains a borrowed value, but \
2610 the signature does not say whether it is borrowed from {}",
2617 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2618 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2619 let mut late_depth = 0;
2620 let mut scope = self.scope;
2621 let lifetime = loop {
2623 Scope::Binder { s, .. } => {
2628 Scope::Root | Scope::Elision { .. } => break Region::Static,
2630 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2632 Scope::ObjectLifetimeDefault {
2633 lifetime: Some(l), ..
2637 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2640 fn check_lifetime_params(
2642 old_scope: ScopeRef<'_>,
2643 params: &'tcx [hir::GenericParam],
2645 let lifetimes: Vec<_> = params
2647 .filter_map(|param| match param.kind {
2648 GenericParamKind::Lifetime { .. } => Some((param, param.name.modern())),
2652 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2653 if let hir::ParamName::Plain(_) = lifetime_i_name {
2654 let name = lifetime_i_name.ident().name;
2655 if name == kw::UnderscoreLifetime
2656 || name == kw::StaticLifetime
2658 let mut err = struct_span_err!(
2662 "invalid lifetime parameter name: `{}`",
2663 lifetime_i.name.ident(),
2667 format!("{} is a reserved lifetime name", name),
2673 // It is a hard error to shadow a lifetime within the same scope.
2674 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2675 if lifetime_i_name == lifetime_j_name {
2680 "lifetime name `{}` declared twice in the same scope",
2681 lifetime_j.name.ident()
2682 ).span_label(lifetime_j.span, "declared twice")
2683 .span_label(lifetime_i.span, "previous declaration here")
2688 // It is a soft error to shadow a lifetime within a parent scope.
2689 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2691 for bound in &lifetime_i.bounds {
2693 hir::GenericBound::Outlives(lt) => match lt.name {
2694 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2696 "use of `'_` in illegal place, but not caught by lowering",
2698 hir::LifetimeName::Static => {
2699 self.insert_lifetime(lt, Region::Static);
2703 lifetime_i.span.to(lt.span),
2705 "unnecessary lifetime parameter `{}`",
2706 lifetime_i.name.ident(),
2710 "you can use the `'static` lifetime directly, in place of `{}`",
2711 lifetime_i.name.ident(),
2715 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2716 self.resolve_lifetime_ref(lt);
2718 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2719 self.tcx.sess.delay_span_bug(
2721 "lowering generated `ImplicitObjectLifetimeDefault` \
2722 outside of an object type",
2725 hir::LifetimeName::Error => {
2726 // No need to do anything, error already reported.
2735 fn check_lifetime_param_for_shadowing(
2737 mut old_scope: ScopeRef<'_>,
2738 param: &'tcx hir::GenericParam,
2740 for label in &self.labels_in_fn {
2741 // FIXME (#24278): non-hygienic comparison
2742 if param.name.ident().name == label.name {
2743 signal_shadowing_problem(
2746 original_label(label.span),
2747 shadower_lifetime(¶m),
2755 Scope::Body { s, .. }
2756 | Scope::Elision { s, .. }
2757 | Scope::ObjectLifetimeDefault { s, .. } => {
2766 ref lifetimes, s, ..
2768 if let Some(&def) = lifetimes.get(¶m.name.modern()) {
2769 let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
2771 signal_shadowing_problem(
2773 param.name.ident().name,
2774 original_lifetime(self.tcx.hir().span(hir_id)),
2775 shadower_lifetime(¶m),
2786 /// Returns `true` if, in the current scope, replacing `'_` would be
2787 /// equivalent to a single-use lifetime.
2788 fn track_lifetime_uses(&self) -> bool {
2789 let mut scope = self.scope;
2792 Scope::Root => break false,
2794 // Inside of items, it depends on the kind of item.
2796 track_lifetime_uses,
2798 } => break track_lifetime_uses,
2800 // Inside a body, `'_` will use an inference variable,
2802 Scope::Body { .. } => break true,
2804 // A lifetime only used in a fn argument could as well
2805 // be replaced with `'_`, as that would generate a
2808 elide: Elide::FreshLateAnon(_),
2812 // In the return type or other such place, `'_` is not
2813 // going to make a fresh name, so we cannot
2814 // necessarily replace a single-use lifetime with
2817 elide: Elide::Exact(_),
2821 elide: Elide::Error(_),
2825 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2830 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2831 if lifetime_ref.hir_id == hir::DUMMY_HIR_ID {
2834 "lifetime reference not renumbered, \
2835 probably a bug in syntax::fold"
2840 "insert_lifetime: {} resolved to {:?} span={:?}",
2841 self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2843 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2845 self.map.defs.insert(lifetime_ref.hir_id, def);
2848 Region::LateBoundAnon(..) | Region::Static => {
2849 // These are anonymous lifetimes or lifetimes that are not declared.
2852 Region::Free(_, def_id)
2853 | Region::LateBound(_, def_id, _)
2854 | Region::EarlyBound(_, def_id, _) => {
2855 // A lifetime declared by the user.
2856 let track_lifetime_uses = self.track_lifetime_uses();
2858 "insert_lifetime: track_lifetime_uses={}",
2861 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2862 debug!("insert_lifetime: first use of {:?}", def_id);
2864 .insert(def_id, LifetimeUseSet::One(lifetime_ref));
2866 debug!("insert_lifetime: many uses of {:?}", def_id);
2867 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2873 /// Sometimes we resolve a lifetime, but later find that it is an
2874 /// error (esp. around impl trait). In that case, we remove the
2875 /// entry into `map.defs` so as not to confuse later code.
2876 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2877 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2878 assert_eq!(old_value, Some(bad_def));
2882 /// Detects late-bound lifetimes and inserts them into
2883 /// `map.late_bound`.
2885 /// A region declared on a fn is **late-bound** if:
2886 /// - it is constrained by an argument type;
2887 /// - it does not appear in a where-clause.
2889 /// "Constrained" basically means that it appears in any type but
2890 /// not amongst the inputs to a projection. In other words, `<&'a
2891 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2892 fn insert_late_bound_lifetimes(
2893 map: &mut NamedRegionMap,
2895 generics: &hir::Generics,
2898 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2902 let mut constrained_by_input = ConstrainedCollector::default();
2903 for arg_ty in &decl.inputs {
2904 constrained_by_input.visit_ty(arg_ty);
2907 let mut appears_in_output = AllCollector::default();
2908 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2911 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2912 constrained_by_input.regions
2915 // Walk the lifetimes that appear in where clauses.
2917 // Subtle point: because we disallow nested bindings, we can just
2918 // ignore binders here and scrape up all names we see.
2919 let mut appears_in_where_clause = AllCollector::default();
2920 appears_in_where_clause.visit_generics(generics);
2922 for param in &generics.params {
2923 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2924 if !param.bounds.is_empty() {
2925 // `'a: 'b` means both `'a` and `'b` are referenced
2926 appears_in_where_clause
2928 .insert(hir::LifetimeName::Param(param.name.modern()));
2934 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2935 appears_in_where_clause.regions
2938 // Late bound regions are those that:
2939 // - appear in the inputs
2940 // - do not appear in the where-clauses
2941 // - are not implicitly captured by `impl Trait`
2942 for param in &generics.params {
2944 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2946 // Neither types nor consts are late-bound.
2947 hir::GenericParamKind::Type { .. }
2948 | hir::GenericParamKind::Const { .. } => continue,
2951 let lt_name = hir::LifetimeName::Param(param.name.modern());
2952 // appears in the where clauses? early-bound.
2953 if appears_in_where_clause.regions.contains(<_name) {
2957 // does not appear in the inputs, but appears in the return type? early-bound.
2958 if !constrained_by_input.regions.contains(<_name)
2959 && appears_in_output.regions.contains(<_name)
2965 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2970 let inserted = map.late_bound.insert(param.hir_id);
2971 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2977 struct ConstrainedCollector {
2978 regions: FxHashSet<hir::LifetimeName>,
2981 impl<'v> Visitor<'v> for ConstrainedCollector {
2982 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2983 NestedVisitorMap::None
2986 fn visit_ty(&mut self, ty: &'v hir::Ty) {
2988 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2989 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2990 // ignore lifetimes appearing in associated type
2991 // projections, as they are not *constrained*
2995 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2996 // consider only the lifetimes on the final
2997 // segment; I am not sure it's even currently
2998 // valid to have them elsewhere, but even if it
2999 // is, those would be potentially inputs to
3001 if let Some(last_segment) = path.segments.last() {
3002 self.visit_path_segment(path.span, last_segment);
3007 intravisit::walk_ty(self, ty);
3012 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3013 self.regions.insert(lifetime_ref.name.modern());
3018 struct AllCollector {
3019 regions: FxHashSet<hir::LifetimeName>,
3022 impl<'v> Visitor<'v> for AllCollector {
3023 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
3024 NestedVisitorMap::None
3027 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3028 self.regions.insert(lifetime_ref.name.modern());
3033 pub fn report_missing_lifetime_specifiers(
3037 ) -> DiagnosticBuilder<'_> {
3042 "missing lifetime specifier{}",
3047 fn add_missing_lifetime_specifiers_label(
3048 err: &mut DiagnosticBuilder<'_>,
3051 lifetime_names: &FxHashSet<ast::Ident>,
3052 snippet: Option<&str>,
3055 err.span_label(span, format!("expected {} lifetime parameters", count));
3056 } else if let (1, Some(name), Some("&")) = (
3057 lifetime_names.len(),
3058 lifetime_names.iter().next(),
3061 err.span_suggestion(
3063 "consider using the named lifetime",
3064 format!("&{} ", name),
3065 Applicability::MaybeIncorrect,
3068 err.span_label(span, "expected lifetime parameter");