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::diagnostics::{
9 add_missing_lifetime_specifiers_label, report_missing_lifetime_specifiers,
11 use rustc::hir::map::Map;
13 use rustc::middle::resolve_lifetime::*;
14 use rustc::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
15 use rustc::{bug, span_bug};
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
19 use rustc_hir::def::{DefKind, Res};
20 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
21 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
22 use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath};
23 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
24 use rustc_span::symbol::{kw, sym};
28 use std::mem::{replace, take};
31 use syntax::walk_list;
35 use rustc_error_codes::*;
37 // This counts the no of times a lifetime is used
38 #[derive(Clone, Copy, Debug)]
39 pub enum LifetimeUseSet<'tcx> {
40 One(&'tcx hir::Lifetime),
45 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
47 fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
49 fn late_anon(index: &Cell<u32>) -> Region;
51 fn id(&self) -> Option<DefId>;
53 fn shifted(self, amount: u32) -> Region;
55 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
57 fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
59 L: Iterator<Item = &'a hir::Lifetime>;
62 impl RegionExt for Region {
63 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
66 let def_id = hir_map.local_def_id(param.hir_id);
67 let origin = LifetimeDefOrigin::from_param(param);
68 debug!("Region::early: index={} def_id={:?}", i, def_id);
69 (param.name.modern(), Region::EarlyBound(i, def_id, origin))
72 fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
73 let depth = ty::INNERMOST;
74 let def_id = hir_map.local_def_id(param.hir_id);
75 let origin = LifetimeDefOrigin::from_param(param);
77 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
78 param, depth, def_id, origin,
80 (param.name.modern(), Region::LateBound(depth, def_id, origin))
83 fn late_anon(index: &Cell<u32>) -> Region {
86 let depth = ty::INNERMOST;
87 Region::LateBoundAnon(depth, i)
90 fn id(&self) -> Option<DefId> {
92 Region::Static | Region::LateBoundAnon(..) => None,
94 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
100 fn shifted(self, amount: u32) -> Region {
102 Region::LateBound(debruijn, id, origin) => {
103 Region::LateBound(debruijn.shifted_in(amount), id, origin)
105 Region::LateBoundAnon(debruijn, index) => {
106 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
112 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
114 Region::LateBound(debruijn, id, origin) => {
115 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
117 Region::LateBoundAnon(debruijn, index) => {
118 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
124 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
126 L: Iterator<Item = &'a hir::Lifetime>,
128 if let Region::EarlyBound(index, _, _) = self {
129 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
136 /// Maps the id of each lifetime reference to the lifetime decl
137 /// that it corresponds to.
139 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
140 /// actual use. It has the same data, but indexed by `DefIndex`. This
143 struct NamedRegionMap {
144 // maps from every use of a named (not anonymous) lifetime to a
145 // `Region` describing how that region is bound
146 defs: HirIdMap<Region>,
148 // the set of lifetime def ids that are late-bound; a region can
149 // be late-bound if (a) it does NOT appear in a where-clause and
150 // (b) it DOES appear in the arguments.
151 late_bound: HirIdSet,
153 // For each type and trait definition, maps type parameters
154 // to the trait object lifetime defaults computed from them.
155 object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
158 struct LifetimeContext<'a, 'tcx> {
160 map: &'a mut NamedRegionMap,
163 /// This is slightly complicated. Our representation for poly-trait-refs contains a single
164 /// binder and thus we only allow a single level of quantification. However,
165 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
166 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
167 /// correct when representing these constraints, we should only introduce one
168 /// scope. However, we want to support both locations for the quantifier and
169 /// during lifetime resolution we want precise information (so we can't
170 /// desugar in an earlier phase).
172 /// So, if we encounter a quantifier at the outer scope, we set
173 /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
174 /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
175 /// then we introduce the scope at the inner quantifier.
176 trait_ref_hack: bool,
178 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
179 is_in_fn_syntax: bool,
181 /// List of labels in the function/method currently under analysis.
182 labels_in_fn: Vec<ast::Ident>,
184 /// Cache for cross-crate per-definition object lifetime defaults.
185 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
187 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
189 /// When encountering an undefined named lifetime, we will suggest introducing it in these
191 missing_named_lifetime_spots: Vec<&'tcx hir::Generics<'tcx>>,
196 /// Declares lifetimes, and each can be early-bound or late-bound.
197 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
198 /// it should be shifted by the number of `Binder`s in between the
199 /// declaration `Binder` and the location it's referenced from.
201 lifetimes: FxHashMap<hir::ParamName, Region>,
203 /// if we extend this scope with another scope, what is the next index
204 /// we should use for an early-bound region?
205 next_early_index: u32,
207 /// Flag is set to true if, in this binder, `'_` would be
208 /// equivalent to a "single-use region". This is true on
209 /// impls, but not other kinds of items.
210 track_lifetime_uses: bool,
212 /// Whether or not this binder would serve as the parent
213 /// binder for opaque types introduced within. For example:
216 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
219 /// Here, the opaque types we create for the `impl Trait`
220 /// and `impl Trait2` references will both have the `foo` item
221 /// as their parent. When we get to `impl Trait2`, we find
222 /// that it is nested within the `for<>` binder -- this flag
223 /// allows us to skip that when looking for the parent binder
224 /// of the resulting opaque type.
225 opaque_type_parent: bool,
230 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
231 /// if this is a fn body, otherwise the original definitions are used.
232 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
233 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
239 /// A scope which either determines unspecified lifetimes or errors
240 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
246 /// Use a specific lifetime (if `Some`) or leave it unset (to be
247 /// inferred in a function body or potentially error outside one),
248 /// for the default choice of lifetime in a trait object type.
249 ObjectLifetimeDefault {
250 lifetime: Option<Region>,
257 #[derive(Clone, Debug)]
259 /// Use a fresh anonymous late-bound lifetime each time, by
260 /// incrementing the counter to generate sequential indices.
261 FreshLateAnon(Cell<u32>),
262 /// Always use this one lifetime.
264 /// Less or more than one lifetime were found, error on unspecified.
265 Error(Vec<ElisionFailureInfo>),
268 #[derive(Clone, Debug)]
269 struct ElisionFailureInfo {
270 /// Where we can find the argument pattern.
271 parent: Option<hir::BodyId>,
272 /// The index of the argument in the original definition.
274 lifetime_count: usize,
275 have_bound_regions: bool,
278 type ScopeRef<'a> = &'a Scope<'a>;
280 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
282 pub fn provide(providers: &mut ty::query::Providers<'_>) {
283 *providers = ty::query::Providers {
286 named_region_map: |tcx, id| {
287 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
288 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id)
291 is_late_bound_map: |tcx, id| {
292 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
293 tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&id)
296 object_lifetime_defaults_map: |tcx, id| {
297 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
298 tcx.resolve_lifetimes(LOCAL_CRATE).object_lifetime_defaults.get(&id)
304 // (*) FIXME the query should be defined to take a LocalDefId
307 /// Computes the `ResolveLifetimes` map that contains data for the
308 /// entire crate. You should not read the result of this query
309 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
311 fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> &ResolveLifetimes {
312 assert_eq!(for_krate, LOCAL_CRATE);
314 let named_region_map = krate(tcx);
316 let mut rl = ResolveLifetimes::default();
318 for (hir_id, v) in named_region_map.defs {
319 let map = rl.defs.entry(hir_id.owner_local_def_id()).or_default();
320 map.insert(hir_id.local_id, v);
322 for hir_id in named_region_map.late_bound {
323 let map = rl.late_bound.entry(hir_id.owner_local_def_id()).or_default();
324 map.insert(hir_id.local_id);
326 for (hir_id, v) in named_region_map.object_lifetime_defaults {
327 let map = rl.object_lifetime_defaults.entry(hir_id.owner_local_def_id()).or_default();
328 map.insert(hir_id.local_id, v);
334 fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap {
335 let krate = tcx.hir().krate();
336 let mut map = NamedRegionMap {
337 defs: Default::default(),
338 late_bound: Default::default(),
339 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
342 let mut visitor = LifetimeContext {
346 trait_ref_hack: false,
347 is_in_fn_syntax: false,
348 labels_in_fn: vec![],
349 xcrate_object_lifetime_defaults: Default::default(),
350 lifetime_uses: &mut Default::default(),
351 missing_named_lifetime_spots: vec![],
353 for (_, item) in &krate.items {
354 visitor.visit_item(item);
360 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
361 /// We have to account for this when computing the index of the other generic parameters.
362 /// This function returns whether there is such an implicit parameter defined on the given item.
363 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
365 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true,
370 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
371 type Map = Map<'tcx>;
373 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
374 NestedVisitorMap::All(&self.tcx.hir())
377 // We want to nest trait/impl items in their parent, but nothing else.
378 fn visit_nested_item(&mut self, _: hir::ItemId) {}
380 fn visit_nested_body(&mut self, body: hir::BodyId) {
381 // Each body has their own set of labels, save labels.
382 let saved = take(&mut self.labels_in_fn);
383 let body = self.tcx.hir().body(body);
384 extract_labels(self, body);
385 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
386 this.visit_body(body);
388 replace(&mut self.labels_in_fn, saved);
391 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
393 hir::ItemKind::Fn(ref sig, ref generics, _) => {
394 self.missing_named_lifetime_spots.push(generics);
395 self.visit_early_late(None, &sig.decl, generics, |this| {
396 intravisit::walk_item(this, item);
398 self.missing_named_lifetime_spots.pop();
401 hir::ItemKind::ExternCrate(_)
402 | hir::ItemKind::Use(..)
403 | hir::ItemKind::Mod(..)
404 | hir::ItemKind::ForeignMod(..)
405 | hir::ItemKind::GlobalAsm(..) => {
406 // These sorts of items have no lifetime parameters at all.
407 intravisit::walk_item(self, item);
409 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
410 // No lifetime parameters, but implied 'static.
411 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
412 self.with(scope, |_, this| intravisit::walk_item(this, item));
414 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {
415 // Currently opaque type declarations are just generated from `impl Trait`
416 // items. Doing anything on this node is irrelevant, as we currently don't need
419 hir::ItemKind::TyAlias(_, ref generics)
420 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
421 impl_trait_fn: None, ref generics, ..
423 | hir::ItemKind::Enum(_, ref generics)
424 | hir::ItemKind::Struct(_, ref generics)
425 | hir::ItemKind::Union(_, ref generics)
426 | hir::ItemKind::Trait(_, _, ref generics, ..)
427 | hir::ItemKind::TraitAlias(ref generics, ..)
428 | hir::ItemKind::Impl { ref generics, .. } => {
429 self.missing_named_lifetime_spots.push(generics);
431 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
432 // This is not true for other kinds of items.x
433 let track_lifetime_uses = match item.kind {
434 hir::ItemKind::Impl { .. } => true,
437 // These kinds of items have only early-bound lifetime parameters.
438 let mut index = if sub_items_have_self_param(&item.kind) {
439 1 // Self comes before lifetimes
443 let mut non_lifetime_count = 0;
444 let lifetimes = generics
447 .filter_map(|param| match param.kind {
448 GenericParamKind::Lifetime { .. } => {
449 Some(Region::early(&self.tcx.hir(), &mut index, param))
451 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
452 non_lifetime_count += 1;
457 let scope = Scope::Binder {
459 next_early_index: index + non_lifetime_count,
460 opaque_type_parent: true,
464 self.with(scope, |old_scope, this| {
465 this.check_lifetime_params(old_scope, &generics.params);
466 intravisit::walk_item(this, item);
468 self.missing_named_lifetime_spots.pop();
473 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
475 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
476 self.visit_early_late(None, decl, generics, |this| {
477 intravisit::walk_foreign_item(this, item);
480 hir::ForeignItemKind::Static(..) => {
481 intravisit::walk_foreign_item(self, item);
483 hir::ForeignItemKind::Type => {
484 intravisit::walk_foreign_item(self, item);
489 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
490 debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
491 debug!("visit_ty: ty.kind={:?}", ty.kind);
493 hir::TyKind::BareFn(ref c) => {
494 let next_early_index = self.next_early_index();
495 let was_in_fn_syntax = self.is_in_fn_syntax;
496 self.is_in_fn_syntax = true;
497 let scope = Scope::Binder {
501 .filter_map(|param| match param.kind {
502 GenericParamKind::Lifetime { .. } => {
503 Some(Region::late(&self.tcx.hir(), param))
510 track_lifetime_uses: true,
511 opaque_type_parent: false,
513 self.with(scope, |old_scope, this| {
514 // a bare fn has no bounds, so everything
515 // contained within is scoped within its binder.
516 this.check_lifetime_params(old_scope, &c.generic_params);
517 intravisit::walk_ty(this, ty);
519 self.is_in_fn_syntax = was_in_fn_syntax;
521 hir::TyKind::TraitObject(bounds, ref lifetime) => {
522 debug!("visit_ty: TraitObject(bounds={:?}, lifetime={:?})", bounds, lifetime);
523 for bound in bounds {
524 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
526 match lifetime.name {
527 LifetimeName::Implicit => {
528 // For types like `dyn Foo`, we should
529 // generate a special form of elided.
530 span_bug!(ty.span, "object-lifetime-default expected, not implict",);
532 LifetimeName::ImplicitObjectLifetimeDefault => {
533 // If the user does not write *anything*, we
534 // use the object lifetime defaulting
535 // rules. So e.g., `Box<dyn Debug>` becomes
536 // `Box<dyn Debug + 'static>`.
537 self.resolve_object_lifetime_default(lifetime)
539 LifetimeName::Underscore => {
540 // If the user writes `'_`, we use the *ordinary* elision
541 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
542 // resolved the same as the `'_` in `&'_ Foo`.
545 self.resolve_elided_lifetimes(vec![lifetime])
547 LifetimeName::Param(_) | LifetimeName::Static => {
548 // If the user wrote an explicit name, use that.
549 self.visit_lifetime(lifetime);
551 LifetimeName::Error => {}
554 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
555 self.visit_lifetime(lifetime_ref);
556 let scope = Scope::ObjectLifetimeDefault {
557 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
560 self.with(scope, |_, this| this.visit_ty(&mt.ty));
562 hir::TyKind::Def(item_id, lifetimes) => {
563 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
564 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
565 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
566 // ^ ^ this gets resolved in the scope of
567 // the opaque_ty generics
568 let (generics, bounds) = match self.tcx.hir().expect_item(item_id.id).kind {
569 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
570 // This arm is for `impl Trait` in the types of statics, constants and locals.
571 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
572 intravisit::walk_ty(self, ty);
575 // RPIT (return position impl trait)
576 hir::ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, bounds, .. }) => {
579 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
582 // Resolve the lifetimes that are applied to the opaque type.
583 // These are resolved in the current scope.
584 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
585 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
586 // ^ ^this gets resolved in the current scope
587 for lifetime in lifetimes {
588 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
589 self.visit_lifetime(lifetime);
591 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
592 // and ban them. Type variables instantiated inside binders aren't
593 // well-supported at the moment, so this doesn't work.
594 // In the future, this should be fixed and this error should be removed.
595 let def = self.map.defs.get(&lifetime.hir_id).cloned();
596 if let Some(Region::LateBound(_, def_id, _)) = def {
597 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
598 // Ensure that the parent of the def is an item, not HRTB
599 let parent_id = self.tcx.hir().get_parent_node(hir_id);
600 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
601 let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
602 let krate = self.tcx.hir().forest.krate();
604 if !(krate.items.contains_key(&parent_id)
605 || krate.impl_items.contains_key(&parent_impl_id)
606 || krate.trait_items.contains_key(&parent_trait_id))
612 "`impl Trait` can only capture lifetimes \
613 bound at the fn or impl level"
616 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
623 // We want to start our early-bound indices at the end of the parent scope,
624 // not including any parent `impl Trait`s.
625 let mut index = self.next_early_index_for_opaque_type();
626 debug!("visit_ty: index = {}", index);
628 let mut elision = None;
629 let mut lifetimes = FxHashMap::default();
630 let mut non_lifetime_count = 0;
631 for param in generics.params {
633 GenericParamKind::Lifetime { .. } => {
634 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
635 let def_id = if let Region::EarlyBound(_, def_id, _) = reg {
640 if let hir::ParamName::Plain(param_name) = name {
641 if param_name.name == kw::UnderscoreLifetime {
642 // Pick the elided lifetime "definition" if one exists
643 // and use it to make an elision scope.
644 self.lifetime_uses.insert(def_id.clone(), LifetimeUseSet::Many);
647 lifetimes.insert(name, reg);
650 self.lifetime_uses.insert(def_id.clone(), LifetimeUseSet::Many);
651 lifetimes.insert(name, reg);
654 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
655 non_lifetime_count += 1;
659 let next_early_index = index + non_lifetime_count;
661 if let Some(elision_region) = elision {
663 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
664 self.with(scope, |_old_scope, this| {
665 let scope = Scope::Binder {
669 track_lifetime_uses: true,
670 opaque_type_parent: false,
672 this.with(scope, |_old_scope, this| {
673 this.visit_generics(generics);
674 for bound in bounds {
675 this.visit_param_bound(bound);
680 let scope = Scope::Binder {
684 track_lifetime_uses: true,
685 opaque_type_parent: false,
687 self.with(scope, |_old_scope, this| {
688 this.visit_generics(generics);
689 for bound in bounds {
690 this.visit_param_bound(bound);
695 _ => intravisit::walk_ty(self, ty),
699 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
700 use self::hir::TraitItemKind::*;
701 self.missing_named_lifetime_spots.push(&trait_item.generics);
702 match trait_item.kind {
703 Method(ref sig, _) => {
705 self.visit_early_late(
706 Some(tcx.hir().get_parent_item(trait_item.hir_id)),
708 &trait_item.generics,
709 |this| intravisit::walk_trait_item(this, trait_item),
712 Type(bounds, ref ty) => {
713 let generics = &trait_item.generics;
714 let mut index = self.next_early_index();
715 debug!("visit_ty: index = {}", index);
716 let mut non_lifetime_count = 0;
717 let lifetimes = generics
720 .filter_map(|param| match param.kind {
721 GenericParamKind::Lifetime { .. } => {
722 Some(Region::early(&self.tcx.hir(), &mut index, param))
724 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
725 non_lifetime_count += 1;
730 let scope = Scope::Binder {
732 next_early_index: index + non_lifetime_count,
734 track_lifetime_uses: true,
735 opaque_type_parent: true,
737 self.with(scope, |_old_scope, this| {
738 this.visit_generics(generics);
739 for bound in bounds {
740 this.visit_param_bound(bound);
742 if let Some(ty) = ty {
748 // Only methods and types support generics.
749 assert!(trait_item.generics.params.is_empty());
750 intravisit::walk_trait_item(self, trait_item);
753 self.missing_named_lifetime_spots.pop();
756 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
757 use self::hir::ImplItemKind::*;
758 self.missing_named_lifetime_spots.push(&impl_item.generics);
759 match impl_item.kind {
760 Method(ref sig, _) => {
762 self.visit_early_late(
763 Some(tcx.hir().get_parent_item(impl_item.hir_id)),
766 |this| intravisit::walk_impl_item(this, impl_item),
770 let generics = &impl_item.generics;
771 let mut index = self.next_early_index();
772 let mut non_lifetime_count = 0;
773 debug!("visit_ty: index = {}", index);
774 let lifetimes = generics
777 .filter_map(|param| match param.kind {
778 GenericParamKind::Lifetime { .. } => {
779 Some(Region::early(&self.tcx.hir(), &mut index, param))
781 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
782 non_lifetime_count += 1;
787 let scope = Scope::Binder {
789 next_early_index: index + non_lifetime_count,
791 track_lifetime_uses: true,
792 opaque_type_parent: true,
794 self.with(scope, |_old_scope, this| {
795 this.visit_generics(generics);
799 OpaqueTy(bounds) => {
800 let generics = &impl_item.generics;
801 let mut index = self.next_early_index();
802 let mut next_early_index = index;
803 debug!("visit_ty: index = {}", index);
804 let lifetimes = generics
807 .filter_map(|param| match param.kind {
808 GenericParamKind::Lifetime { .. } => {
809 Some(Region::early(&self.tcx.hir(), &mut index, param))
811 GenericParamKind::Type { .. } => {
812 next_early_index += 1;
815 GenericParamKind::Const { .. } => {
816 next_early_index += 1;
822 let scope = Scope::Binder {
826 track_lifetime_uses: true,
827 opaque_type_parent: true,
829 self.with(scope, |_old_scope, this| {
830 this.visit_generics(generics);
831 for bound in bounds {
832 this.visit_param_bound(bound);
837 // Only methods and types support generics.
838 assert!(impl_item.generics.params.is_empty());
839 intravisit::walk_impl_item(self, impl_item);
842 self.missing_named_lifetime_spots.pop();
845 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
846 debug!("visit_lifetime(lifetime_ref={:?})", lifetime_ref);
847 if lifetime_ref.is_elided() {
848 self.resolve_elided_lifetimes(vec![lifetime_ref]);
851 if lifetime_ref.is_static() {
852 self.insert_lifetime(lifetime_ref, Region::Static);
855 self.resolve_lifetime_ref(lifetime_ref);
858 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
859 for (i, segment) in path.segments.iter().enumerate() {
860 let depth = path.segments.len() - i - 1;
861 if let Some(ref args) = segment.args {
862 self.visit_segment_args(path.res, depth, args);
867 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
868 let output = match fd.output {
869 hir::FunctionRetTy::DefaultReturn(_) => None,
870 hir::FunctionRetTy::Return(ref ty) => Some(&**ty),
872 self.visit_fn_like_elision(&fd.inputs, output);
875 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
876 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
877 for param in generics.params {
879 GenericParamKind::Lifetime { .. } => {}
880 GenericParamKind::Type { ref default, .. } => {
881 walk_list!(self, visit_param_bound, param.bounds);
882 if let Some(ref ty) = default {
886 GenericParamKind::Const { ref ty, .. } => {
887 walk_list!(self, visit_param_bound, param.bounds);
892 for predicate in generics.where_clause.predicates {
894 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
897 ref bound_generic_params,
900 let lifetimes: FxHashMap<_, _> = bound_generic_params
902 .filter_map(|param| match param.kind {
903 GenericParamKind::Lifetime { .. } => {
904 Some(Region::late(&self.tcx.hir(), param))
909 if !lifetimes.is_empty() {
910 self.trait_ref_hack = true;
911 let next_early_index = self.next_early_index();
912 let scope = Scope::Binder {
916 track_lifetime_uses: true,
917 opaque_type_parent: false,
919 let result = self.with(scope, |old_scope, this| {
920 this.check_lifetime_params(old_scope, &bound_generic_params);
921 this.visit_ty(&bounded_ty);
922 walk_list!(this, visit_param_bound, bounds);
924 self.trait_ref_hack = false;
927 self.visit_ty(&bounded_ty);
928 walk_list!(self, visit_param_bound, bounds);
931 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
936 self.visit_lifetime(lifetime);
937 walk_list!(self, visit_param_bound, bounds);
939 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
944 self.visit_ty(lhs_ty);
945 self.visit_ty(rhs_ty);
951 fn visit_poly_trait_ref(
953 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
954 _modifier: hir::TraitBoundModifier,
956 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
958 if !self.trait_ref_hack
959 || trait_ref.bound_generic_params.iter().any(|param| match param.kind {
960 GenericParamKind::Lifetime { .. } => true,
964 if self.trait_ref_hack {
969 "nested quantification of lifetimes"
973 let next_early_index = self.next_early_index();
974 let scope = Scope::Binder {
976 .bound_generic_params
978 .filter_map(|param| match param.kind {
979 GenericParamKind::Lifetime { .. } => {
980 Some(Region::late(&self.tcx.hir(), param))
987 track_lifetime_uses: true,
988 opaque_type_parent: false,
990 self.with(scope, |old_scope, this| {
991 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
992 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
993 this.visit_trait_ref(&trait_ref.trait_ref)
996 self.visit_trait_ref(&trait_ref.trait_ref)
1001 #[derive(Copy, Clone, PartialEq)]
1015 fn original_label(span: Span) -> Original {
1016 Original { kind: ShadowKind::Label, span: span }
1018 fn shadower_label(span: Span) -> Shadower {
1019 Shadower { kind: ShadowKind::Label, span: span }
1021 fn original_lifetime(span: Span) -> Original {
1022 Original { kind: ShadowKind::Lifetime, span: span }
1024 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1025 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1029 fn desc(&self) -> &'static str {
1031 ShadowKind::Label => "label",
1032 ShadowKind::Lifetime => "lifetime",
1037 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1038 let lifetime_params: Vec<_> = params
1040 .filter_map(|param| match param.kind {
1041 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1045 let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1046 let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1048 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1053 "cannot mix in-band and explicit lifetime definitions"
1055 .span_label(*in_band_span, "in-band lifetime definition here")
1056 .span_label(*explicit_span, "explicit lifetime definition here")
1061 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: ast::Name, orig: Original, shadower: Shadower) {
1062 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1063 // lifetime/lifetime shadowing is an error
1068 "{} name `{}` shadows a \
1069 {} name that is already in scope",
1070 shadower.kind.desc(),
1075 // shadowing involving a label is only a warning, due to issues with
1076 // labels and lifetimes not being macro-hygienic.
1077 tcx.sess.struct_span_warn(
1080 "{} name `{}` shadows a \
1081 {} name that is already in scope",
1082 shadower.kind.desc(),
1088 err.span_label(orig.span, "first declared here");
1089 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1093 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1094 // if one of the label shadows a lifetime or another label.
1095 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1096 struct GatherLabels<'a, 'tcx> {
1098 scope: ScopeRef<'a>,
1099 labels_in_fn: &'a mut Vec<ast::Ident>,
1103 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1104 gather.visit_body(body);
1106 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1109 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1110 NestedVisitorMap::None
1113 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1114 if let Some(label) = expression_label(ex) {
1115 for prior_label in &self.labels_in_fn[..] {
1116 // FIXME (#24278): non-hygienic comparison
1117 if label.name == prior_label.name {
1118 signal_shadowing_problem(
1121 original_label(prior_label.span),
1122 shadower_label(label.span),
1127 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1129 self.labels_in_fn.push(label);
1131 intravisit::walk_expr(self, ex)
1135 fn expression_label(ex: &hir::Expr<'_>) -> Option<ast::Ident> {
1136 if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { Some(label.ident) } else { None }
1139 fn check_if_label_shadows_lifetime(
1141 mut scope: ScopeRef<'_>,
1146 Scope::Body { s, .. }
1147 | Scope::Elision { s, .. }
1148 | Scope::ObjectLifetimeDefault { s, .. } => {
1156 Scope::Binder { ref lifetimes, s, .. } => {
1157 // FIXME (#24278): non-hygienic comparison
1158 if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1159 let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
1161 signal_shadowing_problem(
1164 original_lifetime(tcx.hir().span(hir_id)),
1165 shadower_label(label.span),
1176 fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1177 let mut map = HirIdMap::default();
1178 for item in tcx.hir().krate().items.values() {
1180 hir::ItemKind::Struct(_, ref generics)
1181 | hir::ItemKind::Union(_, ref generics)
1182 | hir::ItemKind::Enum(_, ref generics)
1183 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1184 ref generics, impl_trait_fn: None, ..
1186 | hir::ItemKind::TyAlias(_, ref generics)
1187 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1188 let result = object_lifetime_defaults_for_item(tcx, generics);
1191 if attr::contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1192 let object_lifetime_default_reprs: String = result
1194 .map(|set| match *set {
1195 Set1::Empty => "BaseDefault".into(),
1196 Set1::One(Region::Static) => "'static".into(),
1197 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1200 .find_map(|param| match param.kind {
1201 GenericParamKind::Lifetime { .. } => {
1203 return Some(param.name.ident().to_string().into());
1211 Set1::One(_) => bug!(),
1212 Set1::Many => "Ambiguous".into(),
1214 .collect::<Vec<Cow<'static, str>>>()
1216 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1219 map.insert(item.hir_id, result);
1227 /// Scan the bounds and where-clauses on parameters to extract bounds
1228 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1229 /// for each type parameter.
1230 fn object_lifetime_defaults_for_item(
1232 generics: &hir::Generics<'_>,
1233 ) -> Vec<ObjectLifetimeDefault> {
1234 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1235 for bound in bounds {
1236 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1237 set.insert(lifetime.name.modern());
1245 .filter_map(|param| match param.kind {
1246 GenericParamKind::Lifetime { .. } => None,
1247 GenericParamKind::Type { .. } => {
1248 let mut set = Set1::Empty;
1250 add_bounds(&mut set, ¶m.bounds);
1252 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1253 for predicate in generics.where_clause.predicates {
1254 // Look for `type: ...` where clauses.
1255 let data = match *predicate {
1256 hir::WherePredicate::BoundPredicate(ref data) => data,
1260 // Ignore `for<'a> type: ...` as they can change what
1261 // lifetimes mean (although we could "just" handle it).
1262 if !data.bound_generic_params.is_empty() {
1266 let res = match data.bounded_ty.kind {
1267 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1271 if res == Res::Def(DefKind::TyParam, param_def_id) {
1272 add_bounds(&mut set, &data.bounds);
1277 Set1::Empty => Set1::Empty,
1278 Set1::One(name) => {
1279 if name == hir::LifetimeName::Static {
1280 Set1::One(Region::Static)
1285 .filter_map(|param| match param.kind {
1286 GenericParamKind::Lifetime { .. } => Some((
1288 hir::LifetimeName::Param(param.name),
1289 LifetimeDefOrigin::from_param(param),
1294 .find(|&(_, (_, lt_name, _))| lt_name == name)
1295 .map_or(Set1::Many, |(i, (id, _, origin))| {
1296 let def_id = tcx.hir().local_def_id(id);
1297 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1301 Set1::Many => Set1::Many,
1304 GenericParamKind::Const { .. } => {
1305 // Generic consts don't impose any constraints.
1312 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1313 // FIXME(#37666) this works around a limitation in the region inferencer
1314 fn hack<F>(&mut self, f: F)
1316 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1321 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1323 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1325 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1326 let labels_in_fn = take(&mut self.labels_in_fn);
1327 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1328 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1329 let mut this = LifetimeContext {
1333 trait_ref_hack: self.trait_ref_hack,
1334 is_in_fn_syntax: self.is_in_fn_syntax,
1336 xcrate_object_lifetime_defaults,
1338 missing_named_lifetime_spots,
1340 debug!("entering scope {:?}", this.scope);
1341 f(self.scope, &mut this);
1342 this.check_uses_for_lifetimes_defined_by_scope();
1343 debug!("exiting scope {:?}", this.scope);
1344 self.labels_in_fn = this.labels_in_fn;
1345 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1346 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1349 /// helper method to determine the span to remove when suggesting the
1350 /// deletion of a lifetime
1351 fn lifetime_deletion_span(
1354 generics: &hir::Generics<'_>,
1356 generics.params.iter().enumerate().find_map(|(i, param)| {
1357 if param.name.ident() == name {
1358 let mut in_band = false;
1359 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1360 if let hir::LifetimeParamKind::InBand = kind {
1367 if generics.params.len() == 1 {
1368 // if sole lifetime, remove the entire `<>` brackets
1371 // if removing within `<>` brackets, we also want to
1372 // delete a leading or trailing comma as appropriate
1373 if i >= generics.params.len() - 1 {
1374 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1376 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1386 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1387 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1388 fn suggest_eliding_single_use_lifetime(
1390 err: &mut DiagnosticBuilder<'_>,
1392 lifetime: &hir::Lifetime,
1394 let name = lifetime.name.ident();
1395 let mut remove_decl = None;
1396 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1397 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1398 remove_decl = self.lifetime_deletion_span(name, generics);
1402 let mut remove_use = None;
1403 let mut elide_use = None;
1404 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1405 for input in inputs {
1407 hir::TyKind::Rptr(lt, _) => {
1408 if lt.name.ident() == name {
1409 // include the trailing whitespace between the lifetime and type names
1410 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1415 .span_until_non_whitespace(lt_through_ty_span),
1420 hir::TyKind::Path(ref qpath) => {
1421 if let QPath::Resolved(_, path) = qpath {
1422 let last_segment = &path.segments[path.segments.len() - 1];
1423 let generics = last_segment.generic_args();
1424 for arg in generics.args.iter() {
1425 if let GenericArg::Lifetime(lt) = arg {
1426 if lt.name.ident() == name {
1427 elide_use = Some(lt.span);
1439 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1440 if let Some(parent) =
1441 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1444 Node::Item(item) => {
1445 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1446 find_arg_use_span(sig.decl.inputs);
1449 Node::ImplItem(impl_item) => {
1450 if let hir::ImplItemKind::Method(sig, _) = &impl_item.kind {
1451 find_arg_use_span(sig.decl.inputs);
1459 let msg = "elide the single-use lifetime";
1460 match (remove_decl, remove_use, elide_use) {
1461 (Some(decl_span), Some(use_span), None) => {
1462 // if both declaration and use deletion spans start at the same
1463 // place ("start at" because the latter includes trailing
1464 // whitespace), then this is an in-band lifetime
1465 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1466 err.span_suggestion(
1470 Applicability::MachineApplicable,
1473 err.multipart_suggestion(
1475 vec![(decl_span, String::new()), (use_span, String::new())],
1476 Applicability::MachineApplicable,
1480 (Some(decl_span), None, Some(use_span)) => {
1481 err.multipart_suggestion(
1483 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1484 Applicability::MachineApplicable,
1491 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1492 let defined_by = match self.scope {
1493 Scope::Binder { lifetimes, .. } => lifetimes,
1495 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1500 let mut def_ids: Vec<_> = defined_by
1502 .flat_map(|region| match region {
1503 Region::EarlyBound(_, def_id, _)
1504 | Region::LateBound(_, def_id, _)
1505 | Region::Free(_, def_id) => Some(*def_id),
1507 Region::LateBoundAnon(..) | Region::Static => None,
1511 // ensure that we issue lints in a repeatable order
1512 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1514 for def_id in def_ids {
1515 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1517 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1520 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1524 match lifetimeuseset {
1525 Some(LifetimeUseSet::One(lifetime)) => {
1526 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1527 debug!("hir id first={:?}", hir_id);
1528 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1529 Node::Lifetime(hir_lifetime) => Some((
1530 hir_lifetime.hir_id,
1532 hir_lifetime.name.ident(),
1534 Node::GenericParam(param) => {
1535 Some((param.hir_id, param.span, param.name.ident()))
1539 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1540 if name.name == kw::UnderscoreLifetime {
1544 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1545 if let Some(parent_hir_id) =
1546 self.tcx.hir().as_local_hir_id(parent_def_id)
1548 // lifetimes in `derive` expansions don't count (Issue #53738)
1552 .attrs(parent_hir_id)
1554 .any(|attr| attr.check_name(sym::automatically_derived))
1561 let mut err = self.tcx.struct_span_lint_hir(
1562 lint::builtin::SINGLE_USE_LIFETIMES,
1565 &format!("lifetime parameter `{}` only used once", name),
1568 if span == lifetime.span {
1569 // spans are the same for in-band lifetime declarations
1570 err.span_label(span, "this lifetime is only used here");
1572 err.span_label(span, "this lifetime...");
1573 err.span_label(lifetime.span, "...is used only here");
1575 self.suggest_eliding_single_use_lifetime(&mut err, def_id, lifetime);
1579 Some(LifetimeUseSet::Many) => {
1580 debug!("not one use lifetime");
1583 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1584 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1585 Node::Lifetime(hir_lifetime) => Some((
1586 hir_lifetime.hir_id,
1588 hir_lifetime.name.ident(),
1590 Node::GenericParam(param) => {
1591 Some((param.hir_id, param.span, param.name.ident()))
1595 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1596 let mut err = self.tcx.struct_span_lint_hir(
1597 lint::builtin::UNUSED_LIFETIMES,
1600 &format!("lifetime parameter `{}` never used", name),
1602 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1603 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1604 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1605 if let Some(span) = unused_lt_span {
1606 err.span_suggestion(
1608 "elide the unused lifetime",
1610 Applicability::MachineApplicable,
1622 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1624 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1625 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1626 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1630 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1632 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1633 /// lifetimes may be interspersed together.
1635 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1636 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1637 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1638 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1639 /// ordering is not important there.
1640 fn visit_early_late<F>(
1642 parent_id: Option<hir::HirId>,
1643 decl: &'tcx hir::FnDecl<'tcx>,
1644 generics: &'tcx hir::Generics<'tcx>,
1647 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1649 insert_late_bound_lifetimes(self.map, decl, generics);
1651 // Find the start of nested early scopes, e.g., in methods.
1653 if let Some(parent_id) = parent_id {
1654 let parent = self.tcx.hir().expect_item(parent_id);
1655 if sub_items_have_self_param(&parent.kind) {
1656 index += 1; // Self comes before lifetimes
1659 hir::ItemKind::Trait(_, _, ref generics, ..)
1660 | hir::ItemKind::Impl { ref generics, .. } => {
1661 index += generics.params.len() as u32;
1667 let mut non_lifetime_count = 0;
1668 let lifetimes = generics
1671 .filter_map(|param| match param.kind {
1672 GenericParamKind::Lifetime { .. } => {
1673 if self.map.late_bound.contains(¶m.hir_id) {
1674 Some(Region::late(&self.tcx.hir(), param))
1676 Some(Region::early(&self.tcx.hir(), &mut index, param))
1679 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1680 non_lifetime_count += 1;
1685 let next_early_index = index + non_lifetime_count;
1687 let scope = Scope::Binder {
1691 opaque_type_parent: true,
1692 track_lifetime_uses: false,
1694 self.with(scope, move |old_scope, this| {
1695 this.check_lifetime_params(old_scope, &generics.params);
1696 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1700 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1701 let mut scope = self.scope;
1704 Scope::Root => return 0,
1706 Scope::Binder { next_early_index, opaque_type_parent, .. }
1707 if (!only_opaque_type_parent || opaque_type_parent) =>
1709 return next_early_index;
1712 Scope::Binder { s, .. }
1713 | Scope::Body { s, .. }
1714 | Scope::Elision { s, .. }
1715 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1720 /// Returns the next index one would use for an early-bound-region
1721 /// if extending the current scope.
1722 fn next_early_index(&self) -> u32 {
1723 self.next_early_index_helper(true)
1726 /// Returns the next index one would use for an `impl Trait` that
1727 /// is being converted into an opaque type alias `impl Trait`. This will be the
1728 /// next early index from the enclosing item, for the most
1729 /// part. See the `opaque_type_parent` field for more info.
1730 fn next_early_index_for_opaque_type(&self) -> u32 {
1731 self.next_early_index_helper(false)
1734 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1735 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1737 // If we've already reported an error, just ignore `lifetime_ref`.
1738 if let LifetimeName::Error = lifetime_ref.name {
1742 // Walk up the scope chain, tracking the number of fn scopes
1743 // that we pass through, until we find a lifetime with the
1744 // given name or we run out of scopes.
1746 let mut late_depth = 0;
1747 let mut scope = self.scope;
1748 let mut outermost_body = None;
1751 Scope::Body { id, s } => {
1752 outermost_body = Some(id);
1760 Scope::Binder { ref lifetimes, s, .. } => {
1761 match lifetime_ref.name {
1762 LifetimeName::Param(param_name) => {
1763 if let Some(&def) = lifetimes.get(¶m_name.modern()) {
1764 break Some(def.shifted(late_depth));
1767 _ => bug!("expected LifetimeName::Param"),
1774 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1780 if let Some(mut def) = result {
1781 if let Region::EarlyBound(..) = def {
1782 // Do not free early-bound regions, only late-bound ones.
1783 } else if let Some(body_id) = outermost_body {
1784 let fn_id = self.tcx.hir().body_owner(body_id);
1785 match self.tcx.hir().get(fn_id) {
1786 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1787 | Node::TraitItem(&hir::TraitItem {
1788 kind: hir::TraitItemKind::Method(..),
1791 | Node::ImplItem(&hir::ImplItem {
1792 kind: hir::ImplItemKind::Method(..), ..
1794 let scope = self.tcx.hir().local_def_id(fn_id);
1795 def = Region::Free(scope, def.id().unwrap());
1801 // Check for fn-syntax conflicts with in-band lifetime definitions
1802 if self.is_in_fn_syntax {
1804 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1805 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1810 "lifetimes used in `fn` or `Fn` syntax must be \
1811 explicitly declared using `<...>` binders"
1813 .span_label(lifetime_ref.span, "in-band lifetime definition")
1818 | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1819 | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1820 | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1821 | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1822 | Region::LateBoundAnon(..)
1823 | Region::Free(..) => {}
1827 self.insert_lifetime(lifetime_ref, def);
1829 let mut err = struct_span_err!(
1833 "use of undeclared lifetime name `{}`",
1836 err.span_label(lifetime_ref.span, "undeclared lifetime");
1837 if !self.is_in_fn_syntax {
1838 for generics in &self.missing_named_lifetime_spots {
1839 let (span, sugg) = match &generics.params {
1840 [] => (generics.span, format!("<{}>", lifetime_ref)),
1841 [param, ..] => (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref)),
1843 err.span_suggestion(
1845 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1847 Applicability::MaybeIncorrect,
1855 fn visit_segment_args(
1859 generic_args: &'tcx hir::GenericArgs<'tcx>,
1862 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1863 res, depth, generic_args,
1866 if generic_args.parenthesized {
1867 let was_in_fn_syntax = self.is_in_fn_syntax;
1868 self.is_in_fn_syntax = true;
1869 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1870 self.is_in_fn_syntax = was_in_fn_syntax;
1874 let mut elide_lifetimes = true;
1875 let lifetimes = generic_args
1878 .filter_map(|arg| match arg {
1879 hir::GenericArg::Lifetime(lt) => {
1880 if !lt.is_elided() {
1881 elide_lifetimes = false;
1888 if elide_lifetimes {
1889 self.resolve_elided_lifetimes(lifetimes);
1891 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1894 // Figure out if this is a type/trait segment,
1895 // which requires object lifetime defaults.
1896 let parent_def_id = |this: &mut Self, def_id: DefId| {
1897 let def_key = this.tcx.def_key(def_id);
1898 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1900 let type_def_id = match res {
1901 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1902 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1903 Res::Def(DefKind::Struct, def_id)
1904 | Res::Def(DefKind::Union, def_id)
1905 | Res::Def(DefKind::Enum, def_id)
1906 | Res::Def(DefKind::TyAlias, def_id)
1907 | Res::Def(DefKind::Trait, def_id)
1915 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1917 // Compute a vector of defaults, one for each type parameter,
1918 // per the rules given in RFCs 599 and 1156. Example:
1921 // struct Foo<'a, T: 'a, U> { }
1924 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1925 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1926 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1929 // Therefore, we would compute `object_lifetime_defaults` to a
1930 // vector like `['x, 'static]`. Note that the vector only
1931 // includes type parameters.
1932 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1934 let mut scope = self.scope;
1937 Scope::Root => break false,
1939 Scope::Body { .. } => break true,
1941 Scope::Binder { s, .. }
1942 | Scope::Elision { s, .. }
1943 | Scope::ObjectLifetimeDefault { s, .. } => {
1950 let map = &self.map;
1951 let unsubst = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
1952 &map.object_lifetime_defaults[&id]
1955 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
1956 tcx.generics_of(def_id)
1959 .filter_map(|param| match param.kind {
1960 GenericParamDefKind::Type { object_lifetime_default, .. } => {
1961 Some(object_lifetime_default)
1963 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1968 debug!("visit_segment_args: unsubst={:?}", unsubst);
1971 .map(|set| match *set {
1976 Some(Region::Static)
1980 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1981 GenericArg::Lifetime(lt) => Some(lt),
1984 r.subst(lifetimes, map)
1991 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
1994 for arg in generic_args.args {
1996 GenericArg::Lifetime(_) => {}
1997 GenericArg::Type(ty) => {
1998 if let Some(<) = object_lifetime_defaults.get(i) {
1999 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2000 self.with(scope, |_, this| this.visit_ty(ty));
2006 GenericArg::Const(ct) => {
2007 self.visit_anon_const(&ct.value);
2012 // Hack: when resolving the type `XX` in binding like `dyn
2013 // Foo<'b, Item = XX>`, the current object-lifetime default
2014 // would be to examine the trait `Foo` to check whether it has
2015 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2016 // declared like so, then the default object lifetime bound in
2017 // `XX` should be `'b`:
2025 // but if we just have `type Item;`, then it would be
2026 // `'static`. However, we don't get all of this logic correct.
2028 // Instead, we do something hacky: if there are no lifetime parameters
2029 // to the trait, then we simply use a default object lifetime
2030 // bound of `'static`, because there is no other possibility. On the other hand,
2031 // if there ARE lifetime parameters, then we require the user to give an
2032 // explicit bound for now.
2034 // This is intended to leave room for us to implement the
2035 // correct behavior in the future.
2036 let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
2037 GenericArg::Lifetime(_) => true,
2041 // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2042 for b in generic_args.bindings {
2043 let scope = Scope::ObjectLifetimeDefault {
2044 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2047 self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2051 fn visit_fn_like_elision(
2053 inputs: &'tcx [hir::Ty<'tcx>],
2054 output: Option<&'tcx hir::Ty<'tcx>>,
2056 debug!("visit_fn_like_elision: enter");
2057 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2058 let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
2059 self.with(arg_scope, |_, this| {
2060 for input in inputs {
2061 this.visit_ty(input);
2064 Scope::Elision { ref elide, .. } => {
2065 arg_elide = elide.clone();
2071 let output = match output {
2076 debug!("visit_fn_like_elision: determine output");
2078 // Figure out if there's a body we can get argument names from,
2079 // and whether there's a `self` argument (treated specially).
2080 let mut assoc_item_kind = None;
2081 let mut impl_self = None;
2082 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2083 let body = match self.tcx.hir().get(parent) {
2084 // `fn` definitions and methods.
2085 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2087 Node::TraitItem(&hir::TraitItem {
2088 kind: hir::TraitItemKind::Method(_, ref m), ..
2090 if let hir::ItemKind::Trait(.., ref trait_items) =
2091 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2094 trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
2097 hir::TraitMethod::Required(_) => None,
2098 hir::TraitMethod::Provided(body) => Some(body),
2102 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(_, body), .. }) => {
2103 if let hir::ItemKind::Impl { ref self_ty, ref items, .. } =
2104 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2106 impl_self = Some(self_ty);
2108 items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
2113 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2114 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2115 // Everything else (only closures?) doesn't
2116 // actually enjoy elision in return types.
2118 self.visit_ty(output);
2123 let has_self = match assoc_item_kind {
2124 Some(hir::AssocItemKind::Method { has_self }) => has_self,
2128 // In accordance with the rules for lifetime elision, we can determine
2129 // what region to use for elision in the output type in two ways.
2130 // First (determined here), if `self` is by-reference, then the
2131 // implied output region is the region of the self parameter.
2133 struct SelfVisitor<'a> {
2134 map: &'a NamedRegionMap,
2135 impl_self: Option<&'a hir::TyKind<'a>>,
2136 lifetime: Set1<Region>,
2139 impl SelfVisitor<'_> {
2140 // Look for `self: &'a Self` - also desugared from `&'a self`,
2141 // and if that matches, use it for elision and return early.
2142 fn is_self_ty(&self, res: Res) -> bool {
2143 if let Res::SelfTy(..) = res {
2147 // Can't always rely on literal (or implied) `Self` due
2148 // to the way elision rules were originally specified.
2149 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2153 // Whitelist the types that unambiguously always
2154 // result in the same type constructor being used
2155 // (it can't differ between `Self` and `self`).
2156 Res::Def(DefKind::Struct, _)
2157 | Res::Def(DefKind::Union, _)
2158 | Res::Def(DefKind::Enum, _)
2159 | Res::PrimTy(_) => return res == path.res,
2168 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2171 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
2172 NestedVisitorMap::None
2175 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2176 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2177 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2179 if self.is_self_ty(path.res) {
2180 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2181 self.lifetime.insert(*lifetime);
2186 intravisit::walk_ty(self, ty)
2190 let mut visitor = SelfVisitor {
2192 impl_self: impl_self.map(|ty| &ty.kind),
2193 lifetime: Set1::Empty,
2195 visitor.visit_ty(&inputs[0]);
2196 if let Set1::One(lifetime) = visitor.lifetime {
2197 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2198 self.with(scope, |_, this| this.visit_ty(output));
2203 // Second, if there was exactly one lifetime (either a substitution or a
2204 // reference) in the arguments, then any anonymous regions in the output
2205 // have that lifetime.
2206 let mut possible_implied_output_region = None;
2207 let mut lifetime_count = 0;
2208 let arg_lifetimes = inputs
2211 .skip(has_self as usize)
2213 let mut gather = GatherLifetimes {
2215 outer_index: ty::INNERMOST,
2216 have_bound_regions: false,
2217 lifetimes: Default::default(),
2219 gather.visit_ty(input);
2221 lifetime_count += gather.lifetimes.len();
2223 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2224 // there's a chance that the unique lifetime of this
2225 // iteration will be the appropriate lifetime for output
2226 // parameters, so lets store it.
2227 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2230 ElisionFailureInfo {
2233 lifetime_count: gather.lifetimes.len(),
2234 have_bound_regions: gather.have_bound_regions,
2239 let elide = if lifetime_count == 1 {
2240 Elide::Exact(possible_implied_output_region.unwrap())
2242 Elide::Error(arg_lifetimes)
2245 debug!("visit_fn_like_elision: elide={:?}", elide);
2247 let scope = Scope::Elision { elide, s: self.scope };
2248 self.with(scope, |_, this| this.visit_ty(output));
2249 debug!("visit_fn_like_elision: exit");
2251 struct GatherLifetimes<'a> {
2252 map: &'a NamedRegionMap,
2253 outer_index: ty::DebruijnIndex,
2254 have_bound_regions: bool,
2255 lifetimes: FxHashSet<Region>,
2258 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2261 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
2262 NestedVisitorMap::None
2265 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2266 if let hir::TyKind::BareFn(_) = ty.kind {
2267 self.outer_index.shift_in(1);
2270 hir::TyKind::TraitObject(bounds, ref lifetime) => {
2271 for bound in bounds {
2272 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2275 // Stay on the safe side and don't include the object
2276 // lifetime default (which may not end up being used).
2277 if !lifetime.is_elided() {
2278 self.visit_lifetime(lifetime);
2282 intravisit::walk_ty(self, ty);
2285 if let hir::TyKind::BareFn(_) = ty.kind {
2286 self.outer_index.shift_out(1);
2290 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2291 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2292 // FIXME(eddyb) Do we want this? It only makes a difference
2293 // if this `for<'a>` lifetime parameter is never used.
2294 self.have_bound_regions = true;
2297 intravisit::walk_generic_param(self, param);
2300 fn visit_poly_trait_ref(
2302 trait_ref: &hir::PolyTraitRef<'_>,
2303 modifier: hir::TraitBoundModifier,
2305 self.outer_index.shift_in(1);
2306 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2307 self.outer_index.shift_out(1);
2310 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2311 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2313 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2314 if debruijn < self.outer_index =>
2316 self.have_bound_regions = true;
2319 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2327 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2328 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2330 if lifetime_refs.is_empty() {
2334 let span = lifetime_refs[0].span;
2335 let mut late_depth = 0;
2336 let mut scope = self.scope;
2337 let mut lifetime_names = FxHashSet::default();
2340 // Do not assign any resolution, it will be inferred.
2341 Scope::Body { .. } => return,
2343 Scope::Root => break None,
2345 Scope::Binder { s, ref lifetimes, .. } => {
2346 // collect named lifetimes for suggestions
2347 for name in lifetimes.keys() {
2348 if let hir::ParamName::Plain(name) = name {
2349 lifetime_names.insert(*name);
2356 Scope::Elision { ref elide, ref s, .. } => {
2357 let lifetime = match *elide {
2358 Elide::FreshLateAnon(ref counter) => {
2359 for lifetime_ref in lifetime_refs {
2360 let lifetime = Region::late_anon(counter).shifted(late_depth);
2361 self.insert_lifetime(lifetime_ref, lifetime);
2365 Elide::Exact(l) => l.shifted(late_depth),
2366 Elide::Error(ref e) => {
2367 if let Scope::Binder { ref lifetimes, .. } = s {
2368 // collect named lifetimes for suggestions
2369 for name in lifetimes.keys() {
2370 if let hir::ParamName::Plain(name) = name {
2371 lifetime_names.insert(*name);
2378 for lifetime_ref in lifetime_refs {
2379 self.insert_lifetime(lifetime_ref, lifetime);
2384 Scope::ObjectLifetimeDefault { s, .. } => {
2390 let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2391 let mut add_label = true;
2393 if let Some(params) = error {
2394 if lifetime_refs.len() == 1 {
2395 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2399 add_missing_lifetime_specifiers_label(
2402 lifetime_refs.len(),
2404 self.tcx.sess.source_map().span_to_snippet(span).ok().as_ref().map(|s| s.as_str()),
2405 &self.missing_named_lifetime_spots,
2412 fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2413 match self.tcx.sess.source_map().span_to_snippet(span) {
2414 Ok(ref snippet) => {
2415 let (sugg, applicability) = if snippet == "&" {
2416 ("&'static ".to_owned(), Applicability::MachineApplicable)
2417 } else if snippet == "'_" {
2418 ("'static".to_owned(), Applicability::MachineApplicable)
2420 (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2422 db.span_suggestion(span, msg, sugg, applicability);
2432 fn report_elision_failure(
2434 db: &mut DiagnosticBuilder<'_>,
2435 params: &[ElisionFailureInfo],
2438 let mut m = String::new();
2439 let len = params.len();
2441 let elided_params: Vec<_> =
2442 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2444 let elided_len = elided_params.len();
2446 for (i, info) in elided_params.into_iter().enumerate() {
2447 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions } = info;
2449 let help_name = if let Some(ident) =
2450 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2452 format!("`{}`", ident)
2454 format!("argument {}", index + 1)
2462 "one of {}'s {} {}lifetimes",
2465 if have_bound_regions { "free " } else { "" }
2470 if elided_len == 2 && i == 0 {
2472 } else if i + 2 == elided_len {
2473 m.push_str(", or ");
2474 } else if i != elided_len - 1 {
2481 "this function's return type contains a borrowed value, \
2482 but there is no value for it to be borrowed from",
2484 self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2485 } else if elided_len == 0 {
2487 "this function's return type contains a borrowed value with \
2488 an elided lifetime, but the lifetime cannot be derived from \
2491 let msg = "consider giving it an explicit bounded or 'static lifetime";
2492 self.suggest_lifetime(db, span, msg)
2493 } else if elided_len == 1 {
2495 "this function's return type contains a borrowed value, \
2496 but the signature does not say which {} it is borrowed from",
2502 "this function's return type contains a borrowed value, \
2503 but the signature does not say whether it is borrowed from {}",
2510 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2511 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2512 let mut late_depth = 0;
2513 let mut scope = self.scope;
2514 let lifetime = loop {
2516 Scope::Binder { s, .. } => {
2521 Scope::Root | Scope::Elision { .. } => break Region::Static,
2523 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2525 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2528 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2531 fn check_lifetime_params(
2533 old_scope: ScopeRef<'_>,
2534 params: &'tcx [hir::GenericParam<'tcx>],
2536 let lifetimes: Vec<_> = params
2538 .filter_map(|param| match param.kind {
2539 GenericParamKind::Lifetime { .. } => Some((param, param.name.modern())),
2543 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2544 if let hir::ParamName::Plain(_) = lifetime_i_name {
2545 let name = lifetime_i_name.ident().name;
2546 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
2547 let mut err = struct_span_err!(
2551 "invalid lifetime parameter name: `{}`",
2552 lifetime_i.name.ident(),
2556 format!("{} is a reserved lifetime name", name),
2562 // It is a hard error to shadow a lifetime within the same scope.
2563 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2564 if lifetime_i_name == lifetime_j_name {
2569 "lifetime name `{}` declared twice in the same scope",
2570 lifetime_j.name.ident()
2572 .span_label(lifetime_j.span, "declared twice")
2573 .span_label(lifetime_i.span, "previous declaration here")
2578 // It is a soft error to shadow a lifetime within a parent scope.
2579 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2581 for bound in lifetime_i.bounds {
2583 hir::GenericBound::Outlives(ref lt) => match lt.name {
2584 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2586 "use of `'_` in illegal place, but not caught by lowering",
2588 hir::LifetimeName::Static => {
2589 self.insert_lifetime(lt, Region::Static);
2593 lifetime_i.span.to(lt.span),
2595 "unnecessary lifetime parameter `{}`",
2596 lifetime_i.name.ident(),
2600 "you can use the `'static` lifetime directly, in place of `{}`",
2601 lifetime_i.name.ident(),
2605 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2606 self.resolve_lifetime_ref(lt);
2608 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2609 self.tcx.sess.delay_span_bug(
2611 "lowering generated `ImplicitObjectLifetimeDefault` \
2612 outside of an object type",
2615 hir::LifetimeName::Error => {
2616 // No need to do anything, error already reported.
2625 fn check_lifetime_param_for_shadowing(
2627 mut old_scope: ScopeRef<'_>,
2628 param: &'tcx hir::GenericParam<'tcx>,
2630 for label in &self.labels_in_fn {
2631 // FIXME (#24278): non-hygienic comparison
2632 if param.name.ident().name == label.name {
2633 signal_shadowing_problem(
2636 original_label(label.span),
2637 shadower_lifetime(¶m),
2645 Scope::Body { s, .. }
2646 | Scope::Elision { s, .. }
2647 | Scope::ObjectLifetimeDefault { s, .. } => {
2655 Scope::Binder { ref lifetimes, s, .. } => {
2656 if let Some(&def) = lifetimes.get(¶m.name.modern()) {
2657 let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
2659 signal_shadowing_problem(
2661 param.name.ident().name,
2662 original_lifetime(self.tcx.hir().span(hir_id)),
2663 shadower_lifetime(¶m),
2674 /// Returns `true` if, in the current scope, replacing `'_` would be
2675 /// equivalent to a single-use lifetime.
2676 fn track_lifetime_uses(&self) -> bool {
2677 let mut scope = self.scope;
2680 Scope::Root => break false,
2682 // Inside of items, it depends on the kind of item.
2683 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
2685 // Inside a body, `'_` will use an inference variable,
2687 Scope::Body { .. } => break true,
2689 // A lifetime only used in a fn argument could as well
2690 // be replaced with `'_`, as that would generate a
2692 Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
2694 // In the return type or other such place, `'_` is not
2695 // going to make a fresh name, so we cannot
2696 // necessarily replace a single-use lifetime with
2698 Scope::Elision { elide: Elide::Exact(_), .. } => break false,
2699 Scope::Elision { elide: Elide::Error(_), .. } => break false,
2701 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2706 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2707 if lifetime_ref.hir_id == hir::DUMMY_HIR_ID {
2710 "lifetime reference not renumbered, \
2711 probably a bug in syntax::fold"
2716 "insert_lifetime: {} resolved to {:?} span={:?}",
2717 self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2719 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2721 self.map.defs.insert(lifetime_ref.hir_id, def);
2724 Region::LateBoundAnon(..) | Region::Static => {
2725 // These are anonymous lifetimes or lifetimes that are not declared.
2728 Region::Free(_, def_id)
2729 | Region::LateBound(_, def_id, _)
2730 | Region::EarlyBound(_, def_id, _) => {
2731 // A lifetime declared by the user.
2732 let track_lifetime_uses = self.track_lifetime_uses();
2733 debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
2734 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2735 debug!("insert_lifetime: first use of {:?}", def_id);
2736 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
2738 debug!("insert_lifetime: many uses of {:?}", def_id);
2739 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2745 /// Sometimes we resolve a lifetime, but later find that it is an
2746 /// error (esp. around impl trait). In that case, we remove the
2747 /// entry into `map.defs` so as not to confuse later code.
2748 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2749 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2750 assert_eq!(old_value, Some(bad_def));
2754 /// Detects late-bound lifetimes and inserts them into
2755 /// `map.late_bound`.
2757 /// A region declared on a fn is **late-bound** if:
2758 /// - it is constrained by an argument type;
2759 /// - it does not appear in a where-clause.
2761 /// "Constrained" basically means that it appears in any type but
2762 /// not amongst the inputs to a projection. In other words, `<&'a
2763 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2764 fn insert_late_bound_lifetimes(
2765 map: &mut NamedRegionMap,
2766 decl: &hir::FnDecl<'_>,
2767 generics: &hir::Generics<'_>,
2769 debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
2771 let mut constrained_by_input = ConstrainedCollector::default();
2772 for arg_ty in decl.inputs {
2773 constrained_by_input.visit_ty(arg_ty);
2776 let mut appears_in_output = AllCollector::default();
2777 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2779 debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", 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 { .. } | hir::GenericParamKind::Const { .. } => continue,
2816 let lt_name = hir::LifetimeName::Param(param.name.modern());
2817 // appears in the where clauses? early-bound.
2818 if appears_in_where_clause.regions.contains(<_name) {
2822 // does not appear in the inputs, but appears in the return type? early-bound.
2823 if !constrained_by_input.regions.contains(<_name)
2824 && appears_in_output.regions.contains(<_name)
2830 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2835 let inserted = map.late_bound.insert(param.hir_id);
2836 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2842 struct ConstrainedCollector {
2843 regions: FxHashSet<hir::LifetimeName>,
2846 impl<'v> Visitor<'v> for ConstrainedCollector {
2849 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
2850 NestedVisitorMap::None
2853 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2855 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2856 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2857 // ignore lifetimes appearing in associated type
2858 // projections, as they are not *constrained*
2862 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2863 // consider only the lifetimes on the final
2864 // segment; I am not sure it's even currently
2865 // valid to have them elsewhere, but even if it
2866 // is, those would be potentially inputs to
2868 if let Some(last_segment) = path.segments.last() {
2869 self.visit_path_segment(path.span, last_segment);
2874 intravisit::walk_ty(self, ty);
2879 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2880 self.regions.insert(lifetime_ref.name.modern());
2885 struct AllCollector {
2886 regions: FxHashSet<hir::LifetimeName>,
2889 impl<'v> Visitor<'v> for AllCollector {
2892 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
2893 NestedVisitorMap::None
2896 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2897 self.regions.insert(lifetime_ref.name.modern());