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_data_structures::sync::Lrc;
19 use rustc_macros::HashStable;
22 use std::mem::replace;
26 use syntax::symbol::{keywords, sym};
29 use crate::hir::intravisit::{self, NestedVisitorMap, Visitor};
30 use crate::hir::{self, GenericParamKind, LifetimeParamKind};
32 /// The origin of a named lifetime definition.
34 /// This is used to prevent the usage of in-band lifetimes in `Fn`/`fn` syntax.
35 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, HashStable)]
36 pub enum LifetimeDefOrigin {
37 // Explicit binders like `fn foo<'a>(x: &'a u8)` or elided like `impl Foo<&u32>`
39 // In-band declarations like `fn foo(x: &'a u8)`
41 // Some kind of erroneous origin
45 impl LifetimeDefOrigin {
46 fn from_param(param: &GenericParam) -> Self {
48 GenericParamKind::Lifetime { kind } => match kind {
49 LifetimeParamKind::InBand => LifetimeDefOrigin::InBand,
50 LifetimeParamKind::Explicit => LifetimeDefOrigin::ExplicitOrElided,
51 LifetimeParamKind::Elided => LifetimeDefOrigin::ExplicitOrElided,
52 LifetimeParamKind::Error => LifetimeDefOrigin::Error,
54 _ => bug!("expected a lifetime param"),
59 // This counts the no of times a lifetime is used
60 #[derive(Clone, Copy, Debug)]
61 pub enum LifetimeUseSet<'tcx> {
62 One(&'tcx hir::Lifetime),
66 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, HashStable)]
71 /* lifetime decl */ DefId,
76 /* lifetime decl */ DefId,
79 LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
80 Free(DefId, /* lifetime decl */ DefId),
84 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam) -> (ParamName, Region) {
87 let def_id = hir_map.local_def_id_from_hir_id(param.hir_id);
88 let origin = LifetimeDefOrigin::from_param(param);
89 debug!("Region::early: index={} def_id={:?}", i, def_id);
90 (param.name.modern(), Region::EarlyBound(i, def_id, origin))
93 fn late(hir_map: &Map<'_>, param: &GenericParam) -> (ParamName, Region) {
94 let depth = ty::INNERMOST;
95 let def_id = hir_map.local_def_id_from_hir_id(param.hir_id);
96 let origin = LifetimeDefOrigin::from_param(param);
98 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
99 param, depth, def_id, origin,
103 Region::LateBound(depth, def_id, origin),
107 fn late_anon(index: &Cell<u32>) -> Region {
110 let depth = ty::INNERMOST;
111 Region::LateBoundAnon(depth, i)
114 fn id(&self) -> Option<DefId> {
116 Region::Static | Region::LateBoundAnon(..) => None,
118 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
124 fn shifted(self, amount: u32) -> Region {
126 Region::LateBound(debruijn, id, origin) => {
127 Region::LateBound(debruijn.shifted_in(amount), id, origin)
129 Region::LateBoundAnon(debruijn, index) => {
130 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
136 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
138 Region::LateBound(debruijn, id, origin) => {
139 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
141 Region::LateBoundAnon(debruijn, index) => {
142 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
148 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
150 L: Iterator<Item = &'a hir::Lifetime>,
152 if let Region::EarlyBound(index, _, _) = self {
155 .and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
162 /// A set containing, at most, one known element.
163 /// If two distinct values are inserted into a set, then it
164 /// becomes `Many`, which can be used to detect ambiguities.
165 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
172 impl<T: PartialEq> Set1<T> {
173 pub fn insert(&mut self, value: T) {
174 if let Set1::Empty = *self {
175 *self = Set1::One(value);
178 if let Set1::One(ref old) = *self {
187 pub type ObjectLifetimeDefault = Set1<Region>;
189 /// Maps the id of each lifetime reference to the lifetime decl
190 /// that it corresponds to.
192 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
193 /// actual use. It has the same data, but indexed by `DefIndex`. This
196 struct NamedRegionMap {
197 // maps from every use of a named (not anonymous) lifetime to a
198 // `Region` describing how that region is bound
199 pub defs: HirIdMap<Region>,
201 // the set of lifetime def ids that are late-bound; a region can
202 // be late-bound if (a) it does NOT appear in a where-clause and
203 // (b) it DOES appear in the arguments.
204 pub late_bound: HirIdSet,
206 // For each type and trait definition, maps type parameters
207 // to the trait object lifetime defaults computed from them.
208 pub object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
211 /// See [`NamedRegionMap`].
213 pub struct ResolveLifetimes {
214 defs: FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Region>>>,
215 late_bound: FxHashMap<LocalDefId, Lrc<FxHashSet<ItemLocalId>>>,
216 object_lifetime_defaults:
217 FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Lrc<Vec<ObjectLifetimeDefault>>>>>,
220 impl_stable_hash_for!(struct crate::middle::resolve_lifetime::ResolveLifetimes {
223 object_lifetime_defaults
226 struct LifetimeContext<'a, 'tcx: 'a> {
227 tcx: TyCtxt<'a, 'tcx, 'tcx>,
228 map: &'a mut NamedRegionMap,
231 /// This is slightly complicated. Our representation for poly-trait-refs contains a single
232 /// binder and thus we only allow a single level of quantification. However,
233 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
234 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
235 /// correct when representing these constraints, we should only introduce one
236 /// scope. However, we want to support both locations for the quantifier and
237 /// during lifetime resolution we want precise information (so we can't
238 /// desugar in an earlier phase).
240 /// So, if we encounter a quantifier at the outer scope, we set
241 /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
242 /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
243 /// then we introduce the scope at the inner quantifier.
244 trait_ref_hack: bool,
246 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
247 is_in_fn_syntax: bool,
249 /// List of labels in the function/method currently under analysis.
250 labels_in_fn: Vec<ast::Ident>,
252 /// Cache for cross-crate per-definition object lifetime defaults.
253 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
255 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
260 /// Declares lifetimes, and each can be early-bound or late-bound.
261 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
262 /// it should be shifted by the number of `Binder`s in between the
263 /// declaration `Binder` and the location it's referenced from.
265 lifetimes: FxHashMap<hir::ParamName, Region>,
267 /// if we extend this scope with another scope, what is the next index
268 /// we should use for an early-bound region?
269 next_early_index: u32,
271 /// Flag is set to true if, in this binder, `'_` would be
272 /// equivalent to a "single-use region". This is true on
273 /// impls, but not other kinds of items.
274 track_lifetime_uses: bool,
276 /// Whether or not this binder would serve as the parent
277 /// binder for abstract types introduced within. For example:
279 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
281 /// Here, the abstract types we create for the `impl Trait`
282 /// and `impl Trait2` references will both have the `foo` item
283 /// as their parent. When we get to `impl Trait2`, we find
284 /// that it is nested within the `for<>` binder -- this flag
285 /// allows us to skip that when looking for the parent binder
286 /// of the resulting abstract type.
287 abstract_type_parent: bool,
292 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
293 /// if this is a fn body, otherwise the original definitions are used.
294 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
295 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
301 /// A scope which either determines unspecified lifetimes or errors
302 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
308 /// Use a specific lifetime (if `Some`) or leave it unset (to be
309 /// inferred in a function body or potentially error outside one),
310 /// for the default choice of lifetime in a trait object type.
311 ObjectLifetimeDefault {
312 lifetime: Option<Region>,
319 #[derive(Clone, Debug)]
321 /// Use a fresh anonymous late-bound lifetime each time, by
322 /// incrementing the counter to generate sequential indices.
323 FreshLateAnon(Cell<u32>),
324 /// Always use this one lifetime.
326 /// Less or more than one lifetime were found, error on unspecified.
327 Error(Vec<ElisionFailureInfo>),
330 #[derive(Clone, Debug)]
331 struct ElisionFailureInfo {
332 /// Where we can find the argument pattern.
333 parent: Option<hir::BodyId>,
334 /// The index of the argument in the original definition.
336 lifetime_count: usize,
337 have_bound_regions: bool,
340 type ScopeRef<'a> = &'a Scope<'a>;
342 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
344 pub fn provide(providers: &mut ty::query::Providers<'_>) {
345 *providers = ty::query::Providers {
348 named_region_map: |tcx, id| {
349 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
350 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id).cloned()
353 is_late_bound_map: |tcx, id| {
354 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
355 tcx.resolve_lifetimes(LOCAL_CRATE)
361 object_lifetime_defaults_map: |tcx, id| {
362 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
363 tcx.resolve_lifetimes(LOCAL_CRATE)
364 .object_lifetime_defaults
372 // (*) FIXME the query should be defined to take a LocalDefId
375 /// Computes the `ResolveLifetimes` map that contains data for the
376 /// entire crate. You should not read the result of this query
377 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
379 fn resolve_lifetimes<'tcx>(
380 tcx: TyCtxt<'_, 'tcx, 'tcx>,
382 ) -> Lrc<ResolveLifetimes> {
383 assert_eq!(for_krate, LOCAL_CRATE);
385 let named_region_map = krate(tcx);
387 let mut rl = ResolveLifetimes::default();
389 for (hir_id, v) in named_region_map.defs {
390 let map = rl.defs.entry(hir_id.owner_local_def_id()).or_default();
391 Lrc::get_mut(map).unwrap().insert(hir_id.local_id, v);
393 for hir_id in named_region_map.late_bound {
394 let map = rl.late_bound
395 .entry(hir_id.owner_local_def_id())
397 Lrc::get_mut(map).unwrap().insert(hir_id.local_id);
399 for (hir_id, v) in named_region_map.object_lifetime_defaults {
400 let map = rl.object_lifetime_defaults
401 .entry(hir_id.owner_local_def_id())
405 .insert(hir_id.local_id, Lrc::new(v));
411 fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> NamedRegionMap {
412 let krate = tcx.hir().krate();
413 let mut map = NamedRegionMap {
414 defs: Default::default(),
415 late_bound: Default::default(),
416 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
419 let mut visitor = LifetimeContext {
423 trait_ref_hack: false,
424 is_in_fn_syntax: false,
425 labels_in_fn: vec![],
426 xcrate_object_lifetime_defaults: Default::default(),
427 lifetime_uses: &mut Default::default(),
429 for (_, item) in &krate.items {
430 visitor.visit_item(item);
436 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
437 /// We have to account for this when computing the index of the other generic parameters.
438 /// This function returns whether there is such an implicit parameter defined on the given item.
439 fn sub_items_have_self_param(node: &hir::ItemKind) -> bool {
441 hir::ItemKind::Trait(..) |
442 hir::ItemKind::TraitAlias(..) => true,
447 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
448 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
449 NestedVisitorMap::All(&self.tcx.hir())
452 // We want to nest trait/impl items in their parent, but nothing else.
453 fn visit_nested_item(&mut self, _: hir::ItemId) {}
455 fn visit_nested_body(&mut self, body: hir::BodyId) {
456 // Each body has their own set of labels, save labels.
457 let saved = replace(&mut self.labels_in_fn, vec![]);
458 let body = self.tcx.hir().body(body);
459 extract_labels(self, body);
466 this.visit_body(body);
469 replace(&mut self.labels_in_fn, saved);
472 fn visit_item(&mut self, item: &'tcx hir::Item) {
474 hir::ItemKind::Fn(ref decl, _, ref generics, _) => {
475 self.visit_early_late(None, decl, generics, |this| {
476 intravisit::walk_item(this, item);
480 hir::ItemKind::ExternCrate(_)
481 | hir::ItemKind::Use(..)
482 | hir::ItemKind::Mod(..)
483 | hir::ItemKind::ForeignMod(..)
484 | hir::ItemKind::GlobalAsm(..) => {
485 // These sorts of items have no lifetime parameters at all.
486 intravisit::walk_item(self, item);
488 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
489 // No lifetime parameters, but implied 'static.
490 let scope = Scope::Elision {
491 elide: Elide::Exact(Region::Static),
494 self.with(scope, |_, this| intravisit::walk_item(this, item));
496 hir::ItemKind::Existential(hir::ExistTy {
497 impl_trait_fn: Some(_),
500 // currently existential type declarations are just generated from impl Trait
501 // items. doing anything on this node is irrelevant, as we currently don't need
504 hir::ItemKind::Ty(_, ref generics)
505 | hir::ItemKind::Existential(hir::ExistTy {
510 | hir::ItemKind::Enum(_, ref generics)
511 | hir::ItemKind::Struct(_, ref generics)
512 | hir::ItemKind::Union(_, ref generics)
513 | hir::ItemKind::Trait(_, _, ref generics, ..)
514 | hir::ItemKind::TraitAlias(ref generics, ..)
515 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
516 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
517 // This is not true for other kinds of items.x
518 let track_lifetime_uses = match item.node {
519 hir::ItemKind::Impl(..) => true,
522 // These kinds of items have only early-bound lifetime parameters.
523 let mut index = if sub_items_have_self_param(&item.node) {
524 1 // Self comes before lifetimes
528 let mut non_lifetime_count = 0;
529 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
530 GenericParamKind::Lifetime { .. } => {
531 Some(Region::early(&self.tcx.hir(), &mut index, param))
533 GenericParamKind::Type { .. } |
534 GenericParamKind::Const { .. } => {
535 non_lifetime_count += 1;
539 let scope = Scope::Binder {
541 next_early_index: index + non_lifetime_count,
542 abstract_type_parent: true,
546 self.with(scope, |old_scope, this| {
547 this.check_lifetime_params(old_scope, &generics.params);
548 intravisit::walk_item(this, item);
554 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
556 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
557 self.visit_early_late(None, decl, generics, |this| {
558 intravisit::walk_foreign_item(this, item);
561 hir::ForeignItemKind::Static(..) => {
562 intravisit::walk_foreign_item(self, item);
564 hir::ForeignItemKind::Type => {
565 intravisit::walk_foreign_item(self, item);
570 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
571 debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
573 hir::TyKind::BareFn(ref c) => {
574 let next_early_index = self.next_early_index();
575 let was_in_fn_syntax = self.is_in_fn_syntax;
576 self.is_in_fn_syntax = true;
577 let scope = Scope::Binder {
578 lifetimes: c.generic_params
580 .filter_map(|param| match param.kind {
581 GenericParamKind::Lifetime { .. } => {
582 Some(Region::late(&self.tcx.hir(), param))
589 track_lifetime_uses: true,
590 abstract_type_parent: false,
592 self.with(scope, |old_scope, this| {
593 // a bare fn has no bounds, so everything
594 // contained within is scoped within its binder.
595 this.check_lifetime_params(old_scope, &c.generic_params);
596 intravisit::walk_ty(this, ty);
598 self.is_in_fn_syntax = was_in_fn_syntax;
600 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
601 for bound in bounds {
602 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
604 match lifetime.name {
605 LifetimeName::Implicit => {
606 // If the user does not write *anything*, we
607 // use the object lifetime defaulting
608 // rules. So e.g., `Box<dyn Debug>` becomes
609 // `Box<dyn Debug + 'static>`.
610 self.resolve_object_lifetime_default(lifetime)
612 LifetimeName::Underscore => {
613 // If the user writes `'_`, we use the *ordinary* elision
614 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
615 // resolved the same as the `'_` in `&'_ Foo`.
618 self.resolve_elided_lifetimes(vec![lifetime])
620 LifetimeName::Param(_) | LifetimeName::Static => {
621 // If the user wrote an explicit name, use that.
622 self.visit_lifetime(lifetime);
624 LifetimeName::Error => {}
627 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
628 self.visit_lifetime(lifetime_ref);
629 let scope = Scope::ObjectLifetimeDefault {
630 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
633 self.with(scope, |_, this| this.visit_ty(&mt.ty));
635 hir::TyKind::Def(item_id, ref lifetimes) => {
636 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
637 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
638 // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
639 // ^ ^ this gets resolved in the scope of
640 // the exist_ty generics
641 let (generics, bounds) = match self.tcx.hir().expect_item_by_hir_id(item_id.id).node
643 // named existential types are reached via TyKind::Path
644 // this arm is for `impl Trait` in the types of statics, constants and locals
645 hir::ItemKind::Existential(hir::ExistTy {
649 intravisit::walk_ty(self, ty);
652 // RPIT (return position impl trait)
653 hir::ItemKind::Existential(hir::ExistTy {
657 }) => (generics, bounds),
658 ref i => bug!("impl Trait pointed to non-existential type?? {:#?}", i),
661 // Resolve the lifetimes that are applied to the existential type.
662 // These are resolved in the current scope.
663 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
664 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
665 // ^ ^this gets resolved in the current scope
666 for lifetime in lifetimes {
667 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
668 self.visit_lifetime(lifetime);
670 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
671 // and ban them. Type variables instantiated inside binders aren't
672 // well-supported at the moment, so this doesn't work.
673 // In the future, this should be fixed and this error should be removed.
674 let def = self.map.defs.get(&lifetime.hir_id).cloned();
675 if let Some(Region::LateBound(_, def_id, _)) = def {
676 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
677 // Ensure that the parent of the def is an item, not HRTB
678 let parent_id = self.tcx.hir().get_parent_node_by_hir_id(hir_id);
679 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
680 let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
681 let krate = self.tcx.hir().forest.krate();
683 if !(krate.items.contains_key(&parent_id)
684 || krate.impl_items.contains_key(&parent_impl_id)
685 || krate.trait_items.contains_key(&parent_trait_id))
691 "`impl Trait` can only capture lifetimes \
692 bound at the fn or impl level"
694 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
701 // We want to start our early-bound indices at the end of the parent scope,
702 // not including any parent `impl Trait`s.
703 let mut index = self.next_early_index_for_abstract_type();
704 debug!("visit_ty: index = {}", index);
706 let mut elision = None;
707 let mut lifetimes = FxHashMap::default();
708 let mut non_lifetime_count = 0;
709 for param in &generics.params {
711 GenericParamKind::Lifetime { .. } => {
712 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
713 if let hir::ParamName::Plain(param_name) = name {
714 if param_name.name == keywords::UnderscoreLifetime.name() {
715 // Pick the elided lifetime "definition" if one exists
716 // and use it to make an elision scope.
719 lifetimes.insert(name, reg);
722 lifetimes.insert(name, reg);
725 GenericParamKind::Type { .. } |
726 GenericParamKind::Const { .. } => {
727 non_lifetime_count += 1;
731 let next_early_index = index + non_lifetime_count;
733 if let Some(elision_region) = elision {
734 let scope = Scope::Elision {
735 elide: Elide::Exact(elision_region),
738 self.with(scope, |_old_scope, this| {
739 let scope = Scope::Binder {
743 track_lifetime_uses: true,
744 abstract_type_parent: false,
746 this.with(scope, |_old_scope, this| {
747 this.visit_generics(generics);
748 for bound in bounds {
749 this.visit_param_bound(bound);
754 let scope = Scope::Binder {
758 track_lifetime_uses: true,
759 abstract_type_parent: false,
761 self.with(scope, |_old_scope, this| {
762 this.visit_generics(generics);
763 for bound in bounds {
764 this.visit_param_bound(bound);
769 hir::TyKind::CVarArgs(ref lt) => {
770 // Resolve the generated lifetime for the C-variadic arguments.
771 // The lifetime is generated in AST -> HIR lowering.
772 if lt.name.is_elided() {
773 self.resolve_elided_lifetimes(vec![lt])
776 _ => intravisit::walk_ty(self, ty),
780 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
781 use self::hir::TraitItemKind::*;
782 match trait_item.node {
783 Method(ref sig, _) => {
785 self.visit_early_late(
786 Some(tcx.hir().get_parent_item(trait_item.hir_id)),
788 &trait_item.generics,
789 |this| intravisit::walk_trait_item(this, trait_item),
792 Type(ref bounds, ref ty) => {
793 let generics = &trait_item.generics;
794 let mut index = self.next_early_index();
795 debug!("visit_ty: index = {}", index);
796 let mut non_lifetime_count = 0;
797 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
798 GenericParamKind::Lifetime { .. } => {
799 Some(Region::early(&self.tcx.hir(), &mut index, param))
801 GenericParamKind::Type { .. } |
802 GenericParamKind::Const { .. } => {
803 non_lifetime_count += 1;
807 let scope = Scope::Binder {
809 next_early_index: index + non_lifetime_count,
811 track_lifetime_uses: true,
812 abstract_type_parent: true,
814 self.with(scope, |_old_scope, this| {
815 this.visit_generics(generics);
816 for bound in bounds {
817 this.visit_param_bound(bound);
819 if let Some(ty) = ty {
825 // Only methods and types support generics.
826 assert!(trait_item.generics.params.is_empty());
827 intravisit::walk_trait_item(self, trait_item);
832 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
833 use self::hir::ImplItemKind::*;
834 match impl_item.node {
835 Method(ref sig, _) => {
837 self.visit_early_late(
838 Some(tcx.hir().get_parent_item(impl_item.hir_id)),
841 |this| intravisit::walk_impl_item(this, impl_item),
845 let generics = &impl_item.generics;
846 let mut index = self.next_early_index();
847 let mut non_lifetime_count = 0;
848 debug!("visit_ty: index = {}", index);
849 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
850 GenericParamKind::Lifetime { .. } => {
851 Some(Region::early(&self.tcx.hir(), &mut index, param))
853 GenericParamKind::Const { .. } |
854 GenericParamKind::Type { .. } => {
855 non_lifetime_count += 1;
859 let scope = Scope::Binder {
861 next_early_index: index + non_lifetime_count,
863 track_lifetime_uses: true,
864 abstract_type_parent: true,
866 self.with(scope, |_old_scope, this| {
867 this.visit_generics(generics);
871 Existential(ref bounds) => {
872 let generics = &impl_item.generics;
873 let mut index = self.next_early_index();
874 let mut next_early_index = index;
875 debug!("visit_ty: index = {}", index);
876 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
877 GenericParamKind::Lifetime { .. } => {
878 Some(Region::early(&self.tcx.hir(), &mut index, param))
880 GenericParamKind::Type { .. } => {
881 next_early_index += 1;
884 GenericParamKind::Const { .. } => {
885 next_early_index += 1;
890 let scope = Scope::Binder {
894 track_lifetime_uses: true,
895 abstract_type_parent: true,
897 self.with(scope, |_old_scope, this| {
898 this.visit_generics(generics);
899 for bound in bounds {
900 this.visit_param_bound(bound);
905 // Only methods and types support generics.
906 assert!(impl_item.generics.params.is_empty());
907 intravisit::walk_impl_item(self, impl_item);
912 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
913 if lifetime_ref.is_elided() {
914 self.resolve_elided_lifetimes(vec![lifetime_ref]);
917 if lifetime_ref.is_static() {
918 self.insert_lifetime(lifetime_ref, Region::Static);
921 self.resolve_lifetime_ref(lifetime_ref);
924 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
925 for (i, segment) in path.segments.iter().enumerate() {
926 let depth = path.segments.len() - i - 1;
927 if let Some(ref args) = segment.args {
928 self.visit_segment_args(path.res, depth, args);
933 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
934 let output = match fd.output {
935 hir::DefaultReturn(_) => None,
936 hir::Return(ref ty) => Some(ty),
938 self.visit_fn_like_elision(&fd.inputs, output);
941 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
942 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
943 for param in &generics.params {
945 GenericParamKind::Lifetime { .. } => {}
946 GenericParamKind::Type { ref default, .. } => {
947 walk_list!(self, visit_param_bound, ¶m.bounds);
948 if let Some(ref ty) = default {
952 GenericParamKind::Const { ref ty, .. } => {
953 walk_list!(self, visit_param_bound, ¶m.bounds);
958 for predicate in &generics.where_clause.predicates {
960 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
963 ref bound_generic_params,
966 let lifetimes: FxHashMap<_, _> = bound_generic_params
968 .filter_map(|param| match param.kind {
969 GenericParamKind::Lifetime { .. } => {
970 Some(Region::late(&self.tcx.hir(), param))
975 if !lifetimes.is_empty() {
976 self.trait_ref_hack = true;
977 let next_early_index = self.next_early_index();
978 let scope = Scope::Binder {
982 track_lifetime_uses: true,
983 abstract_type_parent: false,
985 let result = self.with(scope, |old_scope, this| {
986 this.check_lifetime_params(old_scope, &bound_generic_params);
987 this.visit_ty(&bounded_ty);
988 walk_list!(this, visit_param_bound, bounds);
990 self.trait_ref_hack = false;
993 self.visit_ty(&bounded_ty);
994 walk_list!(self, visit_param_bound, bounds);
997 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1002 self.visit_lifetime(lifetime);
1003 walk_list!(self, visit_param_bound, bounds);
1005 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1010 self.visit_ty(lhs_ty);
1011 self.visit_ty(rhs_ty);
1017 fn visit_poly_trait_ref(
1019 trait_ref: &'tcx hir::PolyTraitRef,
1020 _modifier: hir::TraitBoundModifier,
1022 debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
1024 if !self.trait_ref_hack || trait_ref.bound_generic_params.iter().any(|param| {
1026 GenericParamKind::Lifetime { .. } => true,
1030 if self.trait_ref_hack {
1035 "nested quantification of lifetimes"
1038 let next_early_index = self.next_early_index();
1039 let scope = Scope::Binder {
1040 lifetimes: trait_ref
1041 .bound_generic_params
1043 .filter_map(|param| match param.kind {
1044 GenericParamKind::Lifetime { .. } => {
1045 Some(Region::late(&self.tcx.hir(), param))
1052 track_lifetime_uses: true,
1053 abstract_type_parent: false,
1055 self.with(scope, |old_scope, this| {
1056 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1057 walk_list!(this, visit_generic_param, &trait_ref.bound_generic_params);
1058 this.visit_trait_ref(&trait_ref.trait_ref)
1061 self.visit_trait_ref(&trait_ref.trait_ref)
1066 #[derive(Copy, Clone, PartialEq)]
1080 fn original_label(span: Span) -> Original {
1082 kind: ShadowKind::Label,
1086 fn shadower_label(span: Span) -> Shadower {
1088 kind: ShadowKind::Label,
1092 fn original_lifetime(span: Span) -> Original {
1094 kind: ShadowKind::Lifetime,
1098 fn shadower_lifetime(param: &hir::GenericParam) -> Shadower {
1100 kind: ShadowKind::Lifetime,
1106 fn desc(&self) -> &'static str {
1108 ShadowKind::Label => "label",
1109 ShadowKind::Lifetime => "lifetime",
1114 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_, '_, '_>, params: &P<[hir::GenericParam]>) {
1115 let lifetime_params: Vec<_> = params
1117 .filter_map(|param| match param.kind {
1118 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1122 let explicit = lifetime_params
1124 .find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1125 let in_band = lifetime_params
1127 .find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1129 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1134 "cannot mix in-band and explicit lifetime definitions"
1135 ).span_label(*in_band_span, "in-band lifetime definition here")
1136 .span_label(*explicit_span, "explicit lifetime definition here")
1141 fn signal_shadowing_problem(
1142 tcx: TyCtxt<'_, '_, '_>,
1147 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1148 // lifetime/lifetime shadowing is an error
1153 "{} name `{}` shadows a \
1154 {} name that is already in scope",
1155 shadower.kind.desc(),
1160 // shadowing involving a label is only a warning, due to issues with
1161 // labels and lifetimes not being macro-hygienic.
1162 tcx.sess.struct_span_warn(
1165 "{} name `{}` shadows a \
1166 {} name that is already in scope",
1167 shadower.kind.desc(),
1173 err.span_label(orig.span, "first declared here");
1174 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1178 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1179 // if one of the label shadows a lifetime or another label.
1180 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
1181 struct GatherLabels<'a, 'tcx: 'a> {
1182 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1183 scope: ScopeRef<'a>,
1184 labels_in_fn: &'a mut Vec<ast::Ident>,
1187 let mut gather = GatherLabels {
1190 labels_in_fn: &mut ctxt.labels_in_fn,
1192 gather.visit_body(body);
1194 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1195 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1196 NestedVisitorMap::None
1199 fn visit_expr(&mut self, ex: &hir::Expr) {
1200 if let Some(label) = expression_label(ex) {
1201 for prior_label in &self.labels_in_fn[..] {
1202 // FIXME (#24278): non-hygienic comparison
1203 if label.name == prior_label.name {
1204 signal_shadowing_problem(
1207 original_label(prior_label.span),
1208 shadower_label(label.span),
1213 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1215 self.labels_in_fn.push(label);
1217 intravisit::walk_expr(self, ex)
1221 fn expression_label(ex: &hir::Expr) -> Option<ast::Ident> {
1223 hir::ExprKind::While(.., Some(label)) | hir::ExprKind::Loop(_, Some(label), _) => {
1230 fn check_if_label_shadows_lifetime(
1231 tcx: TyCtxt<'_, '_, '_>,
1232 mut scope: ScopeRef<'_>,
1237 Scope::Body { s, .. }
1238 | Scope::Elision { s, .. }
1239 | Scope::ObjectLifetimeDefault { s, .. } => {
1248 ref lifetimes, s, ..
1250 // FIXME (#24278): non-hygienic comparison
1251 if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1252 let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
1254 signal_shadowing_problem(
1257 original_lifetime(tcx.hir().span_by_hir_id(hir_id)),
1258 shadower_label(label.span),
1269 fn compute_object_lifetime_defaults(
1270 tcx: TyCtxt<'_, '_, '_>,
1271 ) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1272 let mut map = HirIdMap::default();
1273 for item in tcx.hir().krate().items.values() {
1275 hir::ItemKind::Struct(_, ref generics)
1276 | hir::ItemKind::Union(_, ref generics)
1277 | hir::ItemKind::Enum(_, ref generics)
1278 | hir::ItemKind::Existential(hir::ExistTy {
1280 impl_trait_fn: None,
1283 | hir::ItemKind::Ty(_, ref generics)
1284 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1285 let result = object_lifetime_defaults_for_item(tcx, generics);
1288 if attr::contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1289 let object_lifetime_default_reprs: String = result
1291 .map(|set| match *set {
1292 Set1::Empty => "BaseDefault".into(),
1293 Set1::One(Region::Static) => "'static".into(),
1294 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1297 .find_map(|param| match param.kind {
1298 GenericParamKind::Lifetime { .. } => {
1300 return Some(param.name.ident().to_string().into());
1308 Set1::One(_) => bug!(),
1309 Set1::Many => "Ambiguous".into(),
1311 .collect::<Vec<Cow<'static, str>>>()
1313 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1316 map.insert(item.hir_id, result);
1324 /// Scan the bounds and where-clauses on parameters to extract bounds
1325 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1326 /// for each type parameter.
1327 fn object_lifetime_defaults_for_item(
1328 tcx: TyCtxt<'_, '_, '_>,
1329 generics: &hir::Generics,
1330 ) -> Vec<ObjectLifetimeDefault> {
1331 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound]) {
1332 for bound in bounds {
1333 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1334 set.insert(lifetime.name.modern());
1342 .filter_map(|param| match param.kind {
1343 GenericParamKind::Lifetime { .. } => None,
1344 GenericParamKind::Type { .. } => {
1345 let mut set = Set1::Empty;
1347 add_bounds(&mut set, ¶m.bounds);
1349 let param_def_id = tcx.hir().local_def_id_from_hir_id(param.hir_id);
1350 for predicate in &generics.where_clause.predicates {
1351 // Look for `type: ...` where clauses.
1352 let data = match *predicate {
1353 hir::WherePredicate::BoundPredicate(ref data) => data,
1357 // Ignore `for<'a> type: ...` as they can change what
1358 // lifetimes mean (although we could "just" handle it).
1359 if !data.bound_generic_params.is_empty() {
1363 let res = match data.bounded_ty.node {
1364 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1368 if res == Res::Def(DefKind::TyParam, param_def_id) {
1369 add_bounds(&mut set, &data.bounds);
1374 Set1::Empty => Set1::Empty,
1375 Set1::One(name) => {
1376 if name == hir::LifetimeName::Static {
1377 Set1::One(Region::Static)
1382 .filter_map(|param| match param.kind {
1383 GenericParamKind::Lifetime { .. } => Some((
1385 hir::LifetimeName::Param(param.name),
1386 LifetimeDefOrigin::from_param(param),
1391 .find(|&(_, (_, lt_name, _))| lt_name == name)
1392 .map_or(Set1::Many, |(i, (id, _, origin))| {
1393 let def_id = tcx.hir().local_def_id_from_hir_id(id);
1394 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1398 Set1::Many => Set1::Many,
1401 GenericParamKind::Const { .. } => {
1402 // Generic consts don't impose any constraints.
1409 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1410 // FIXME(#37666) this works around a limitation in the region inferencer
1411 fn hack<F>(&mut self, f: F)
1413 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1418 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1420 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1422 let LifetimeContext {
1428 let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
1429 let xcrate_object_lifetime_defaults =
1430 replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap::default());
1431 let mut this = LifetimeContext {
1435 trait_ref_hack: self.trait_ref_hack,
1436 is_in_fn_syntax: self.is_in_fn_syntax,
1438 xcrate_object_lifetime_defaults,
1439 lifetime_uses: lifetime_uses,
1441 debug!("entering scope {:?}", this.scope);
1442 f(self.scope, &mut this);
1443 this.check_uses_for_lifetimes_defined_by_scope();
1444 debug!("exiting scope {:?}", this.scope);
1445 self.labels_in_fn = this.labels_in_fn;
1446 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1449 /// helper method to determine the span to remove when suggesting the
1450 /// deletion of a lifetime
1451 fn lifetime_deletion_span(&self, name: ast::Ident, generics: &hir::Generics) -> Option<Span> {
1452 generics.params.iter().enumerate().find_map(|(i, param)| {
1453 if param.name.ident() == name {
1454 let mut in_band = false;
1455 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1456 if let hir::LifetimeParamKind::InBand = kind {
1463 if generics.params.len() == 1 {
1464 // if sole lifetime, remove the entire `<>` brackets
1467 // if removing within `<>` brackets, we also want to
1468 // delete a leading or trailing comma as appropriate
1469 if i >= generics.params.len() - 1 {
1470 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1472 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1482 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1483 fn suggest_eliding_single_use_lifetime(
1484 &self, err: &mut DiagnosticBuilder<'_>, def_id: DefId, lifetime: &hir::Lifetime
1486 // FIXME: future work: also suggest `impl Foo<'_>` for `impl<'a> Foo<'a>`
1487 let name = lifetime.name.ident();
1488 let mut remove_decl = None;
1489 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1490 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1491 remove_decl = self.lifetime_deletion_span(name, generics);
1495 let mut remove_use = None;
1496 let mut find_arg_use_span = |inputs: &hir::HirVec<hir::Ty>| {
1497 for input in inputs {
1498 if let hir::TyKind::Rptr(lt, _) = input.node {
1499 if lt.name.ident() == name {
1500 // include the trailing whitespace between the ampersand and the type name
1501 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1503 self.tcx.sess.source_map()
1504 .span_until_non_whitespace(lt_through_ty_span)
1511 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get_by_hir_id(lifetime.hir_id) {
1512 if let Some(parent) = self.tcx.hir().find_by_hir_id(
1513 self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1516 Node::Item(item) => {
1517 if let hir::ItemKind::Fn(decl, _, _, _) = &item.node {
1518 find_arg_use_span(&decl.inputs);
1521 Node::ImplItem(impl_item) => {
1522 if let hir::ImplItemKind::Method(sig, _) = &impl_item.node {
1523 find_arg_use_span(&sig.decl.inputs);
1531 if let (Some(decl_span), Some(use_span)) = (remove_decl, remove_use) {
1532 // if both declaration and use deletion spans start at the same
1533 // place ("start at" because the latter includes trailing
1534 // whitespace), then this is an in-band lifetime
1535 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1536 err.span_suggestion(
1538 "elide the single-use lifetime",
1540 Applicability::MachineApplicable,
1543 err.multipart_suggestion(
1544 "elide the single-use lifetime",
1545 vec![(decl_span, String::new()), (use_span, String::new())],
1546 Applicability::MachineApplicable,
1552 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1553 let defined_by = match self.scope {
1554 Scope::Binder { lifetimes, .. } => lifetimes,
1556 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1561 let mut def_ids: Vec<_> = defined_by
1563 .flat_map(|region| match region {
1564 Region::EarlyBound(_, def_id, _)
1565 | Region::LateBound(_, def_id, _)
1566 | Region::Free(_, def_id) => Some(*def_id),
1568 Region::LateBoundAnon(..) | Region::Static => None,
1572 // ensure that we issue lints in a repeatable order
1573 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1575 for def_id in def_ids {
1577 "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
1581 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1584 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1588 match lifetimeuseset {
1589 Some(LifetimeUseSet::One(lifetime)) => {
1590 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1591 debug!("hir id first={:?}", hir_id);
1592 if let Some((id, span, name)) = match self.tcx.hir().get_by_hir_id(hir_id) {
1593 Node::Lifetime(hir_lifetime) => Some((
1594 hir_lifetime.hir_id,
1596 hir_lifetime.name.ident(),
1598 Node::GenericParam(param) => {
1599 Some((param.hir_id, param.span, param.name.ident()))
1603 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1605 if name == keywords::UnderscoreLifetime.ident() {
1609 let mut err = self.tcx.struct_span_lint_hir(
1610 lint::builtin::SINGLE_USE_LIFETIMES,
1613 &format!("lifetime parameter `{}` only used once", name),
1616 if span == lifetime.span {
1617 // spans are the same for in-band lifetime declarations
1618 err.span_label(span, "this lifetime is only used here");
1620 err.span_label(span, "this lifetime...");
1621 err.span_label(lifetime.span, "...is used only here");
1623 self.suggest_eliding_single_use_lifetime(&mut err, def_id, lifetime);
1627 Some(LifetimeUseSet::Many) => {
1628 debug!("Not one use lifetime");
1631 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1632 if let Some((id, span, name)) = match self.tcx.hir().get_by_hir_id(hir_id) {
1633 Node::Lifetime(hir_lifetime) => Some((
1634 hir_lifetime.hir_id,
1636 hir_lifetime.name.ident(),
1638 Node::GenericParam(param) => {
1639 Some((param.hir_id, param.span, param.name.ident()))
1643 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1644 let mut err = self.tcx.struct_span_lint_hir(
1645 lint::builtin::UNUSED_LIFETIMES,
1648 &format!("lifetime parameter `{}` never used", name),
1650 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1651 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1652 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1653 if let Some(span) = unused_lt_span {
1654 err.span_suggestion(
1656 "elide the unused lifetime",
1658 Applicability::MachineApplicable,
1670 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1672 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1673 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1674 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1678 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1680 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1681 /// lifetimes may be interspersed together.
1683 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1684 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1685 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1686 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1687 /// ordering is not important there.
1688 fn visit_early_late<F>(
1690 parent_id: Option<hir::HirId>,
1691 decl: &'tcx hir::FnDecl,
1692 generics: &'tcx hir::Generics,
1695 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1697 insert_late_bound_lifetimes(self.map, decl, generics);
1699 // Find the start of nested early scopes, e.g., in methods.
1701 if let Some(parent_id) = parent_id {
1702 let parent = self.tcx.hir().expect_item_by_hir_id(parent_id);
1703 if sub_items_have_self_param(&parent.node) {
1704 index += 1; // Self comes before lifetimes
1707 hir::ItemKind::Trait(_, _, ref generics, ..)
1708 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
1709 index += generics.params.len() as u32;
1715 let mut non_lifetime_count = 0;
1716 let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
1717 GenericParamKind::Lifetime { .. } => {
1718 if self.map.late_bound.contains(¶m.hir_id) {
1719 Some(Region::late(&self.tcx.hir(), param))
1721 Some(Region::early(&self.tcx.hir(), &mut index, param))
1724 GenericParamKind::Type { .. } |
1725 GenericParamKind::Const { .. } => {
1726 non_lifetime_count += 1;
1730 let next_early_index = index + non_lifetime_count;
1732 let scope = Scope::Binder {
1736 abstract_type_parent: true,
1737 track_lifetime_uses: false,
1739 self.with(scope, move |old_scope, this| {
1740 this.check_lifetime_params(old_scope, &generics.params);
1741 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1745 fn next_early_index_helper(&self, only_abstract_type_parent: bool) -> u32 {
1746 let mut scope = self.scope;
1749 Scope::Root => return 0,
1753 abstract_type_parent,
1755 } if (!only_abstract_type_parent || abstract_type_parent) =>
1757 return next_early_index
1760 Scope::Binder { s, .. }
1761 | Scope::Body { s, .. }
1762 | Scope::Elision { s, .. }
1763 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1768 /// Returns the next index one would use for an early-bound-region
1769 /// if extending the current scope.
1770 fn next_early_index(&self) -> u32 {
1771 self.next_early_index_helper(true)
1774 /// Returns the next index one would use for an `impl Trait` that
1775 /// is being converted into an `abstract type`. This will be the
1776 /// next early index from the enclosing item, for the most
1777 /// part. See the `abstract_type_parent` field for more info.
1778 fn next_early_index_for_abstract_type(&self) -> u32 {
1779 self.next_early_index_helper(false)
1782 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1783 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1785 // If we've already reported an error, just ignore `lifetime_ref`.
1786 if let LifetimeName::Error = lifetime_ref.name {
1790 // Walk up the scope chain, tracking the number of fn scopes
1791 // that we pass through, until we find a lifetime with the
1792 // given name or we run out of scopes.
1794 let mut late_depth = 0;
1795 let mut scope = self.scope;
1796 let mut outermost_body = None;
1799 Scope::Body { id, s } => {
1800 outermost_body = Some(id);
1809 ref lifetimes, s, ..
1811 match lifetime_ref.name {
1812 LifetimeName::Param(param_name) => {
1813 if let Some(&def) = lifetimes.get(¶m_name.modern()) {
1814 break Some(def.shifted(late_depth));
1817 _ => bug!("expected LifetimeName::Param"),
1824 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1830 if let Some(mut def) = result {
1831 if let Region::EarlyBound(..) = def {
1832 // Do not free early-bound regions, only late-bound ones.
1833 } else if let Some(body_id) = outermost_body {
1834 let fn_id = self.tcx.hir().body_owner(body_id);
1835 match self.tcx.hir().get(fn_id) {
1836 Node::Item(&hir::Item {
1837 node: hir::ItemKind::Fn(..),
1840 | Node::TraitItem(&hir::TraitItem {
1841 node: hir::TraitItemKind::Method(..),
1844 | Node::ImplItem(&hir::ImplItem {
1845 node: hir::ImplItemKind::Method(..),
1848 let scope = self.tcx.hir().local_def_id(fn_id);
1849 def = Region::Free(scope, def.id().unwrap());
1855 // Check for fn-syntax conflicts with in-band lifetime definitions
1856 if self.is_in_fn_syntax {
1858 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1859 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1864 "lifetimes used in `fn` or `Fn` syntax must be \
1865 explicitly declared using `<...>` binders"
1866 ).span_label(lifetime_ref.span, "in-band lifetime definition")
1871 | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1872 | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1873 | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1874 | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1875 | Region::LateBoundAnon(..)
1876 | Region::Free(..) => {}
1880 self.insert_lifetime(lifetime_ref, def);
1886 "use of undeclared lifetime name `{}`",
1888 ).span_label(lifetime_ref.span, "undeclared lifetime")
1893 fn visit_segment_args(&mut self, res: Res, depth: usize, generic_args: &'tcx hir::GenericArgs) {
1894 if generic_args.parenthesized {
1895 let was_in_fn_syntax = self.is_in_fn_syntax;
1896 self.is_in_fn_syntax = true;
1897 self.visit_fn_like_elision(generic_args.inputs(), Some(&generic_args.bindings[0].ty));
1898 self.is_in_fn_syntax = was_in_fn_syntax;
1902 let mut elide_lifetimes = true;
1903 let lifetimes = generic_args
1906 .filter_map(|arg| match arg {
1907 hir::GenericArg::Lifetime(lt) => {
1908 if !lt.is_elided() {
1909 elide_lifetimes = false;
1916 if elide_lifetimes {
1917 self.resolve_elided_lifetimes(lifetimes);
1919 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1922 // Figure out if this is a type/trait segment,
1923 // which requires object lifetime defaults.
1924 let parent_def_id = |this: &mut Self, def_id: DefId| {
1925 let def_key = this.tcx.def_key(def_id);
1927 krate: def_id.krate,
1928 index: def_key.parent.expect("missing parent"),
1931 let type_def_id = match res {
1932 Res::Def(DefKind::AssociatedTy, def_id)
1933 if depth == 1 => Some(parent_def_id(self, def_id)),
1934 Res::Def(DefKind::Variant, def_id)
1935 if depth == 0 => Some(parent_def_id(self, def_id)),
1936 Res::Def(DefKind::Struct, def_id)
1937 | Res::Def(DefKind::Union, def_id)
1938 | Res::Def(DefKind::Enum, def_id)
1939 | Res::Def(DefKind::TyAlias, def_id)
1940 | Res::Def(DefKind::Trait, def_id) if depth == 0 =>
1947 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1949 let mut scope = self.scope;
1952 Scope::Root => break false,
1954 Scope::Body { .. } => break true,
1956 Scope::Binder { s, .. }
1957 | Scope::Elision { s, .. }
1958 | Scope::ObjectLifetimeDefault { s, .. } => {
1965 let map = &self.map;
1966 let unsubst = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
1967 &map.object_lifetime_defaults[&id]
1970 self.xcrate_object_lifetime_defaults
1972 .or_insert_with(|| {
1973 tcx.generics_of(def_id)
1976 .filter_map(|param| match param.kind {
1977 GenericParamDefKind::Type {
1978 object_lifetime_default,
1980 } => Some(object_lifetime_default),
1981 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1988 .map(|set| match *set {
1989 Set1::Empty => if in_body {
1992 Some(Region::Static)
1995 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1996 GenericArg::Lifetime(lt) => Some(lt),
1999 r.subst(lifetimes, map)
2007 for arg in &generic_args.args {
2009 GenericArg::Lifetime(_) => {}
2010 GenericArg::Type(ty) => {
2011 if let Some(<) = object_lifetime_defaults.get(i) {
2012 let scope = Scope::ObjectLifetimeDefault {
2016 self.with(scope, |_, this| this.visit_ty(ty));
2022 GenericArg::Const(ct) => {
2023 self.visit_anon_const(&ct.value);
2028 for b in &generic_args.bindings {
2029 self.visit_assoc_type_binding(b);
2033 fn visit_fn_like_elision(&mut self, inputs: &'tcx [hir::Ty], output: Option<&'tcx P<hir::Ty>>) {
2034 debug!("visit_fn_like_elision: enter");
2035 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2036 let arg_scope = Scope::Elision {
2037 elide: arg_elide.clone(),
2040 self.with(arg_scope, |_, this| {
2041 for input in inputs {
2042 this.visit_ty(input);
2045 Scope::Elision { ref elide, .. } => {
2046 arg_elide = elide.clone();
2052 let output = match output {
2057 debug!("visit_fn_like_elision: determine output");
2059 // Figure out if there's a body we can get argument names from,
2060 // and whether there's a `self` argument (treated specially).
2061 let mut assoc_item_kind = None;
2062 let mut impl_self = None;
2063 let parent = self.tcx.hir().get_parent_node_by_hir_id(output.hir_id);
2064 let body = match self.tcx.hir().get_by_hir_id(parent) {
2065 // `fn` definitions and methods.
2066 Node::Item(&hir::Item {
2067 node: hir::ItemKind::Fn(.., body),
2071 Node::TraitItem(&hir::TraitItem {
2072 node: hir::TraitItemKind::Method(_, ref m),
2075 if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
2077 .expect_item_by_hir_id(self.tcx.hir().get_parent_item(parent))
2080 assoc_item_kind = trait_items
2082 .find(|ti| ti.id.hir_id == parent)
2086 hir::TraitMethod::Required(_) => None,
2087 hir::TraitMethod::Provided(body) => Some(body),
2091 Node::ImplItem(&hir::ImplItem {
2092 node: hir::ImplItemKind::Method(_, body),
2095 if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
2097 .expect_item_by_hir_id(self.tcx.hir().get_parent_item(parent))
2100 impl_self = Some(self_ty);
2101 assoc_item_kind = impl_items
2103 .find(|ii| ii.id.hir_id == parent)
2109 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2110 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2111 // Everything else (only closures?) doesn't
2112 // actually enjoy elision in return types.
2114 self.visit_ty(output);
2119 let has_self = match assoc_item_kind {
2120 Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
2124 // In accordance with the rules for lifetime elision, we can determine
2125 // what region to use for elision in the output type in two ways.
2126 // First (determined here), if `self` is by-reference, then the
2127 // implied output region is the region of the self parameter.
2129 // Look for `self: &'a Self` - also desugared from `&'a self`,
2130 // and if that matches, use it for elision and return early.
2131 let is_self_ty = |res: Res| {
2132 if let Res::SelfTy(..) = res {
2136 // Can't always rely on literal (or implied) `Self` due
2137 // to the way elision rules were originally specified.
2138 let impl_self = impl_self.map(|ty| &ty.node);
2139 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) = impl_self {
2141 // Whitelist the types that unambiguously always
2142 // result in the same type constructor being used
2143 // (it can't differ between `Self` and `self`).
2144 Res::Def(DefKind::Struct, _)
2145 | Res::Def(DefKind::Union, _)
2146 | Res::Def(DefKind::Enum, _)
2147 | Res::PrimTy(_) => {
2148 return res == path.res
2157 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = inputs[0].node {
2158 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
2159 if is_self_ty(path.res) {
2160 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2161 let scope = Scope::Elision {
2162 elide: Elide::Exact(lifetime),
2165 self.with(scope, |_, this| this.visit_ty(output));
2173 // Second, if there was exactly one lifetime (either a substitution or a
2174 // reference) in the arguments, then any anonymous regions in the output
2175 // have that lifetime.
2176 let mut possible_implied_output_region = None;
2177 let mut lifetime_count = 0;
2178 let arg_lifetimes = inputs
2181 .skip(has_self as usize)
2183 let mut gather = GatherLifetimes {
2185 outer_index: ty::INNERMOST,
2186 have_bound_regions: false,
2187 lifetimes: Default::default(),
2189 gather.visit_ty(input);
2191 lifetime_count += gather.lifetimes.len();
2193 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2194 // there's a chance that the unique lifetime of this
2195 // iteration will be the appropriate lifetime for output
2196 // parameters, so lets store it.
2197 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2200 ElisionFailureInfo {
2203 lifetime_count: gather.lifetimes.len(),
2204 have_bound_regions: gather.have_bound_regions,
2209 let elide = if lifetime_count == 1 {
2210 Elide::Exact(possible_implied_output_region.unwrap())
2212 Elide::Error(arg_lifetimes)
2215 debug!("visit_fn_like_elision: elide={:?}", elide);
2217 let scope = Scope::Elision {
2221 self.with(scope, |_, this| this.visit_ty(output));
2222 debug!("visit_fn_like_elision: exit");
2224 struct GatherLifetimes<'a> {
2225 map: &'a NamedRegionMap,
2226 outer_index: ty::DebruijnIndex,
2227 have_bound_regions: bool,
2228 lifetimes: FxHashSet<Region>,
2231 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2232 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2233 NestedVisitorMap::None
2236 fn visit_ty(&mut self, ty: &hir::Ty) {
2237 if let hir::TyKind::BareFn(_) = ty.node {
2238 self.outer_index.shift_in(1);
2241 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2242 for bound in bounds {
2243 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2246 // Stay on the safe side and don't include the object
2247 // lifetime default (which may not end up being used).
2248 if !lifetime.is_elided() {
2249 self.visit_lifetime(lifetime);
2252 hir::TyKind::CVarArgs(_) => {}
2254 intravisit::walk_ty(self, ty);
2257 if let hir::TyKind::BareFn(_) = ty.node {
2258 self.outer_index.shift_out(1);
2262 fn visit_generic_param(&mut self, param: &hir::GenericParam) {
2263 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2264 // FIXME(eddyb) Do we want this? It only makes a difference
2265 // if this `for<'a>` lifetime parameter is never used.
2266 self.have_bound_regions = true;
2269 intravisit::walk_generic_param(self, param);
2272 fn visit_poly_trait_ref(
2274 trait_ref: &hir::PolyTraitRef,
2275 modifier: hir::TraitBoundModifier,
2277 self.outer_index.shift_in(1);
2278 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2279 self.outer_index.shift_out(1);
2282 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2283 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2285 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2286 if debruijn < self.outer_index =>
2288 self.have_bound_regions = true;
2292 .insert(lifetime.shifted_out_to_binder(self.outer_index));
2300 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2301 if lifetime_refs.is_empty() {
2305 let span = lifetime_refs[0].span;
2306 let mut late_depth = 0;
2307 let mut scope = self.scope;
2308 let mut lifetime_names = FxHashSet::default();
2311 // Do not assign any resolution, it will be inferred.
2312 Scope::Body { .. } => return,
2314 Scope::Root => break None,
2316 Scope::Binder { s, ref lifetimes, .. } => {
2317 // collect named lifetimes for suggestions
2318 for name in lifetimes.keys() {
2319 if let hir::ParamName::Plain(name) = name {
2320 lifetime_names.insert(*name);
2327 Scope::Elision { ref elide, ref s, .. } => {
2328 let lifetime = match *elide {
2329 Elide::FreshLateAnon(ref counter) => {
2330 for lifetime_ref in lifetime_refs {
2331 let lifetime = Region::late_anon(counter).shifted(late_depth);
2332 self.insert_lifetime(lifetime_ref, lifetime);
2336 Elide::Exact(l) => l.shifted(late_depth),
2337 Elide::Error(ref e) => {
2338 if let Scope::Binder { ref lifetimes, .. } = s {
2339 // collect named lifetimes for suggestions
2340 for name in lifetimes.keys() {
2341 if let hir::ParamName::Plain(name) = name {
2342 lifetime_names.insert(*name);
2349 for lifetime_ref in lifetime_refs {
2350 self.insert_lifetime(lifetime_ref, lifetime);
2355 Scope::ObjectLifetimeDefault { s, .. } => {
2361 let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2362 let mut add_label = true;
2364 if let Some(params) = error {
2365 if lifetime_refs.len() == 1 {
2366 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2370 add_missing_lifetime_specifiers_label(
2373 lifetime_refs.len(),
2375 self.tcx.sess.source_map().span_to_snippet(span).ok().as_ref().map(|s| s.as_str()),
2382 fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2383 match self.tcx.sess.source_map().span_to_snippet(span) {
2384 Ok(ref snippet) => {
2385 let (sugg, applicability) = if snippet == "&" {
2386 ("&'static ".to_owned(), Applicability::MachineApplicable)
2387 } else if snippet == "'_" {
2388 ("'static".to_owned(), Applicability::MachineApplicable)
2390 (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2392 db.span_suggestion(span, msg, sugg, applicability);
2402 fn report_elision_failure(
2404 db: &mut DiagnosticBuilder<'_>,
2405 params: &[ElisionFailureInfo],
2408 let mut m = String::new();
2409 let len = params.len();
2411 let elided_params: Vec<_> = params
2414 .filter(|info| info.lifetime_count > 0)
2417 let elided_len = elided_params.len();
2419 for (i, info) in elided_params.into_iter().enumerate() {
2420 let ElisionFailureInfo {
2427 let help_name = if let Some(body) = parent {
2428 let arg = &self.tcx.hir().body(body).arguments[index];
2429 format!("`{}`", self.tcx.hir().hir_to_pretty_string(arg.original_pat().hir_id))
2431 format!("argument {}", index + 1)
2439 "one of {}'s {} {}lifetimes",
2442 if have_bound_regions { "free " } else { "" }
2447 if elided_len == 2 && i == 0 {
2449 } else if i + 2 == elided_len {
2450 m.push_str(", or ");
2451 } else if i != elided_len - 1 {
2459 "this function's return type contains a borrowed value, but \
2460 there is no value for it to be borrowed from"
2462 self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2463 } else if elided_len == 0 {
2466 "this function's return type contains a borrowed value with \
2467 an elided lifetime, but the lifetime cannot be derived from \
2470 let msg = "consider giving it an explicit bounded or 'static lifetime";
2471 self.suggest_lifetime(db, span, msg)
2472 } else if elided_len == 1 {
2475 "this function's return type contains a borrowed value, but \
2476 the signature does not say which {} it is borrowed from",
2483 "this function's return type contains a borrowed value, but \
2484 the signature does not say whether it is borrowed from {}",
2491 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2492 let mut late_depth = 0;
2493 let mut scope = self.scope;
2494 let lifetime = loop {
2496 Scope::Binder { s, .. } => {
2501 Scope::Root | Scope::Elision { .. } => break Region::Static,
2503 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2505 Scope::ObjectLifetimeDefault {
2506 lifetime: Some(l), ..
2510 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2513 fn check_lifetime_params(
2515 old_scope: ScopeRef<'_>,
2516 params: &'tcx [hir::GenericParam],
2518 let lifetimes: Vec<_> = params
2520 .filter_map(|param| match param.kind {
2521 GenericParamKind::Lifetime { .. } => Some((param, param.name)),
2525 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2526 if let hir::ParamName::Plain(_) = lifetime_i_name {
2527 let name = lifetime_i_name.ident().name;
2528 if name == keywords::UnderscoreLifetime.name()
2529 || name == keywords::StaticLifetime.name()
2531 let mut err = struct_span_err!(
2535 "invalid lifetime parameter name: `{}`",
2536 lifetime_i.name.ident(),
2540 format!("{} is a reserved lifetime name", name),
2546 // It is a hard error to shadow a lifetime within the same scope.
2547 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2548 if lifetime_i_name == lifetime_j_name {
2553 "lifetime name `{}` declared twice in the same scope",
2554 lifetime_j.name.ident()
2555 ).span_label(lifetime_j.span, "declared twice")
2556 .span_label(lifetime_i.span, "previous declaration here")
2561 // It is a soft error to shadow a lifetime within a parent scope.
2562 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2564 for bound in &lifetime_i.bounds {
2566 hir::GenericBound::Outlives(lt) => match lt.name {
2567 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2569 "use of `'_` in illegal place, but not caught by lowering",
2571 hir::LifetimeName::Static => {
2572 self.insert_lifetime(lt, Region::Static);
2576 lifetime_i.span.to(lt.span),
2578 "unnecessary lifetime parameter `{}`",
2579 lifetime_i.name.ident(),
2583 "you can use the `'static` lifetime directly, in place of `{}`",
2584 lifetime_i.name.ident(),
2588 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2589 self.resolve_lifetime_ref(lt);
2591 hir::LifetimeName::Error => {
2592 // No need to do anything, error already reported.
2601 fn check_lifetime_param_for_shadowing(
2603 mut old_scope: ScopeRef<'_>,
2604 param: &'tcx hir::GenericParam,
2606 for label in &self.labels_in_fn {
2607 // FIXME (#24278): non-hygienic comparison
2608 if param.name.ident().name == label.name {
2609 signal_shadowing_problem(
2612 original_label(label.span),
2613 shadower_lifetime(¶m),
2621 Scope::Body { s, .. }
2622 | Scope::Elision { s, .. }
2623 | Scope::ObjectLifetimeDefault { s, .. } => {
2632 ref lifetimes, s, ..
2634 if let Some(&def) = lifetimes.get(¶m.name.modern()) {
2635 let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
2637 signal_shadowing_problem(
2639 param.name.ident().name,
2640 original_lifetime(self.tcx.hir().span_by_hir_id(hir_id)),
2641 shadower_lifetime(¶m),
2652 /// Returns `true` if, in the current scope, replacing `'_` would be
2653 /// equivalent to a single-use lifetime.
2654 fn track_lifetime_uses(&self) -> bool {
2655 let mut scope = self.scope;
2658 Scope::Root => break false,
2660 // Inside of items, it depends on the kind of item.
2662 track_lifetime_uses,
2664 } => break track_lifetime_uses,
2666 // Inside a body, `'_` will use an inference variable,
2668 Scope::Body { .. } => break true,
2670 // A lifetime only used in a fn argument could as well
2671 // be replaced with `'_`, as that would generate a
2674 elide: Elide::FreshLateAnon(_),
2678 // In the return type or other such place, `'_` is not
2679 // going to make a fresh name, so we cannot
2680 // necessarily replace a single-use lifetime with
2683 elide: Elide::Exact(_),
2687 elide: Elide::Error(_),
2691 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2696 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2697 if lifetime_ref.hir_id == hir::DUMMY_HIR_ID {
2700 "lifetime reference not renumbered, \
2701 probably a bug in syntax::fold"
2706 "insert_lifetime: {} resolved to {:?} span={:?}",
2707 self.tcx.hir().hir_to_string(lifetime_ref.hir_id),
2709 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2711 self.map.defs.insert(lifetime_ref.hir_id, def);
2714 Region::LateBoundAnon(..) | Region::Static => {
2715 // These are anonymous lifetimes or lifetimes that are not declared.
2718 Region::Free(_, def_id)
2719 | Region::LateBound(_, def_id, _)
2720 | Region::EarlyBound(_, def_id, _) => {
2721 // A lifetime declared by the user.
2722 let track_lifetime_uses = self.track_lifetime_uses();
2724 "insert_lifetime: track_lifetime_uses={}",
2727 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2728 debug!("insert_lifetime: first use of {:?}", def_id);
2730 .insert(def_id, LifetimeUseSet::One(lifetime_ref));
2732 debug!("insert_lifetime: many uses of {:?}", def_id);
2733 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2739 /// Sometimes we resolve a lifetime, but later find that it is an
2740 /// error (esp. around impl trait). In that case, we remove the
2741 /// entry into `map.defs` so as not to confuse later code.
2742 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2743 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2744 assert_eq!(old_value, Some(bad_def));
2748 /// Detects late-bound lifetimes and inserts them into
2749 /// `map.late_bound`.
2751 /// A region declared on a fn is **late-bound** if:
2752 /// - it is constrained by an argument type;
2753 /// - it does not appear in a where-clause.
2755 /// "Constrained" basically means that it appears in any type but
2756 /// not amongst the inputs to a projection. In other words, `<&'a
2757 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2758 fn insert_late_bound_lifetimes(
2759 map: &mut NamedRegionMap,
2761 generics: &hir::Generics,
2764 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2768 let mut constrained_by_input = ConstrainedCollector::default();
2769 for arg_ty in &decl.inputs {
2770 constrained_by_input.visit_ty(arg_ty);
2773 let mut appears_in_output = AllCollector::default();
2774 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2777 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2778 constrained_by_input.regions
2781 // Walk the lifetimes that appear in where clauses.
2783 // Subtle point: because we disallow nested bindings, we can just
2784 // ignore binders here and scrape up all names we see.
2785 let mut appears_in_where_clause = AllCollector::default();
2786 appears_in_where_clause.visit_generics(generics);
2788 for param in &generics.params {
2789 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2790 if !param.bounds.is_empty() {
2791 // `'a: 'b` means both `'a` and `'b` are referenced
2792 appears_in_where_clause
2794 .insert(hir::LifetimeName::Param(param.name.modern()));
2800 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2801 appears_in_where_clause.regions
2804 // Late bound regions are those that:
2805 // - appear in the inputs
2806 // - do not appear in the where-clauses
2807 // - are not implicitly captured by `impl Trait`
2808 for param in &generics.params {
2810 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2812 // Neither types nor consts are late-bound.
2813 hir::GenericParamKind::Type { .. }
2814 | hir::GenericParamKind::Const { .. } => continue,
2817 let lt_name = hir::LifetimeName::Param(param.name.modern());
2818 // appears in the where clauses? early-bound.
2819 if appears_in_where_clause.regions.contains(<_name) {
2823 // does not appear in the inputs, but appears in the return type? early-bound.
2824 if !constrained_by_input.regions.contains(<_name)
2825 && appears_in_output.regions.contains(<_name)
2831 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2836 let inserted = map.late_bound.insert(param.hir_id);
2837 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2843 struct ConstrainedCollector {
2844 regions: FxHashSet<hir::LifetimeName>,
2847 impl<'v> Visitor<'v> for ConstrainedCollector {
2848 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2849 NestedVisitorMap::None
2852 fn visit_ty(&mut self, ty: &'v hir::Ty) {
2854 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2855 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2856 // ignore lifetimes appearing in associated type
2857 // projections, as they are not *constrained*
2861 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2862 // consider only the lifetimes on the final
2863 // segment; I am not sure it's even currently
2864 // valid to have them elsewhere, but even if it
2865 // is, those would be potentially inputs to
2867 if let Some(last_segment) = path.segments.last() {
2868 self.visit_path_segment(path.span, last_segment);
2873 intravisit::walk_ty(self, ty);
2878 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2879 self.regions.insert(lifetime_ref.name.modern());
2884 struct AllCollector {
2885 regions: FxHashSet<hir::LifetimeName>,
2888 impl<'v> Visitor<'v> for AllCollector {
2889 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2890 NestedVisitorMap::None
2893 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2894 self.regions.insert(lifetime_ref.name.modern());
2899 pub fn report_missing_lifetime_specifiers(
2903 ) -> DiagnosticBuilder<'_> {
2908 "missing lifetime specifier{}",
2909 if count > 1 { "s" } else { "" }
2913 fn add_missing_lifetime_specifiers_label(
2914 err: &mut DiagnosticBuilder<'_>,
2917 lifetime_names: &FxHashSet<ast::Ident>,
2918 snippet: Option<&str>,
2921 err.span_label(span, format!("expected {} lifetime parameters", count));
2922 } else if let (1, Some(name), Some("&")) = (
2923 lifetime_names.len(),
2924 lifetime_names.iter().next(),
2927 err.span_suggestion(
2929 "consider using the named lifetime",
2930 format!("&{} ", name),
2931 Applicability::MaybeIncorrect,
2934 err.span_label(span, "expected lifetime parameter");