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::late::diagnostics::{ForLifetimeSpanType, MissingLifetimeSpot};
9 use rustc_ast::walk_list;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
13 use rustc_hir::def::{DefKind, Res};
14 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
15 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
16 use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath};
17 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::middle::resolve_lifetime::*;
20 use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
21 use rustc_middle::{bug, span_bug};
22 use rustc_session::lint;
23 use rustc_span::symbol::{kw, sym, Ident, Symbol};
31 // This counts the no of times a lifetime is used
32 #[derive(Clone, Copy, Debug)]
33 pub enum LifetimeUseSet<'tcx> {
34 One(&'tcx hir::Lifetime),
39 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
41 fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
43 fn late_anon(index: &Cell<u32>) -> Region;
45 fn id(&self) -> Option<DefId>;
47 fn shifted(self, amount: u32) -> Region;
49 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
51 fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
53 L: Iterator<Item = &'a hir::Lifetime>;
56 impl RegionExt for Region {
57 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
60 let def_id = hir_map.local_def_id(param.hir_id);
61 let origin = LifetimeDefOrigin::from_param(param);
62 debug!("Region::early: index={} def_id={:?}", i, def_id);
63 (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id(), origin))
66 fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
67 let depth = ty::INNERMOST;
68 let def_id = hir_map.local_def_id(param.hir_id);
69 let origin = LifetimeDefOrigin::from_param(param);
71 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
72 param, depth, def_id, origin,
74 (param.name.normalize_to_macros_2_0(), Region::LateBound(depth, def_id.to_def_id(), origin))
77 fn late_anon(index: &Cell<u32>) -> Region {
80 let depth = ty::INNERMOST;
81 Region::LateBoundAnon(depth, i)
84 fn id(&self) -> Option<DefId> {
86 Region::Static | Region::LateBoundAnon(..) => None,
88 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
94 fn shifted(self, amount: u32) -> Region {
96 Region::LateBound(debruijn, id, origin) => {
97 Region::LateBound(debruijn.shifted_in(amount), id, origin)
99 Region::LateBoundAnon(debruijn, index) => {
100 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
106 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
108 Region::LateBound(debruijn, id, origin) => {
109 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
111 Region::LateBoundAnon(debruijn, index) => {
112 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
118 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
120 L: Iterator<Item = &'a hir::Lifetime>,
122 if let Region::EarlyBound(index, _, _) = self {
123 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
130 /// Maps the id of each lifetime reference to the lifetime decl
131 /// that it corresponds to.
133 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
134 /// actual use. It has the same data, but indexed by `LocalDefId`. This
137 struct NamedRegionMap {
138 // maps from every use of a named (not anonymous) lifetime to a
139 // `Region` describing how that region is bound
140 defs: HirIdMap<Region>,
142 // the set of lifetime def ids that are late-bound; a region can
143 // be late-bound if (a) it does NOT appear in a where-clause and
144 // (b) it DOES appear in the arguments.
145 late_bound: HirIdSet,
147 // For each type and trait definition, maps type parameters
148 // to the trait object lifetime defaults computed from them.
149 object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
152 crate struct LifetimeContext<'a, 'tcx> {
153 crate tcx: TyCtxt<'tcx>,
154 map: &'a mut NamedRegionMap,
157 /// This is slightly complicated. Our representation for poly-trait-refs contains a single
158 /// binder and thus we only allow a single level of quantification. However,
159 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
160 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
161 /// correct when representing these constraints, we should only introduce one
162 /// scope. However, we want to support both locations for the quantifier and
163 /// during lifetime resolution we want precise information (so we can't
164 /// desugar in an earlier phase).
166 /// So, if we encounter a quantifier at the outer scope, we set
167 /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
168 /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
169 /// then we introduce the scope at the inner quantifier.
170 trait_ref_hack: bool,
172 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
173 is_in_fn_syntax: bool,
175 is_in_const_generic: bool,
177 /// List of labels in the function/method currently under analysis.
178 labels_in_fn: Vec<Ident>,
180 /// Cache for cross-crate per-definition object lifetime defaults.
181 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
183 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
185 /// When encountering an undefined named lifetime, we will suggest introducing it in these
187 crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
192 /// Declares lifetimes, and each can be early-bound or late-bound.
193 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
194 /// it should be shifted by the number of `Binder`s in between the
195 /// declaration `Binder` and the location it's referenced from.
197 lifetimes: FxHashMap<hir::ParamName, Region>,
199 /// if we extend this scope with another scope, what is the next index
200 /// we should use for an early-bound region?
201 next_early_index: u32,
203 /// Flag is set to true if, in this binder, `'_` would be
204 /// equivalent to a "single-use region". This is true on
205 /// impls, but not other kinds of items.
206 track_lifetime_uses: bool,
208 /// Whether or not this binder would serve as the parent
209 /// binder for opaque types introduced within. For example:
212 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
215 /// Here, the opaque types we create for the `impl Trait`
216 /// and `impl Trait2` references will both have the `foo` item
217 /// as their parent. When we get to `impl Trait2`, we find
218 /// that it is nested within the `for<>` binder -- this flag
219 /// allows us to skip that when looking for the parent binder
220 /// of the resulting opaque type.
221 opaque_type_parent: bool,
226 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
227 /// if this is a fn body, otherwise the original definitions are used.
228 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
229 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
235 /// A scope which either determines unspecified lifetimes or errors
236 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
242 /// Use a specific lifetime (if `Some`) or leave it unset (to be
243 /// inferred in a function body or potentially error outside one),
244 /// for the default choice of lifetime in a trait object type.
245 ObjectLifetimeDefault {
246 lifetime: Option<Region>,
253 #[derive(Clone, Debug)]
255 /// Use a fresh anonymous late-bound lifetime each time, by
256 /// incrementing the counter to generate sequential indices.
257 FreshLateAnon(Cell<u32>),
258 /// Always use this one lifetime.
260 /// Less or more than one lifetime were found, error on unspecified.
261 Error(Vec<ElisionFailureInfo>),
262 /// Forbid lifetime elision inside of a larger scope where it would be
263 /// permitted. For example, in let position impl trait.
267 #[derive(Clone, Debug)]
268 crate struct ElisionFailureInfo {
269 /// Where we can find the argument pattern.
270 parent: Option<hir::BodyId>,
271 /// The index of the argument in the original definition.
273 lifetime_count: usize,
274 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| tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id),
287 is_late_bound_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&id),
288 object_lifetime_defaults_map: |tcx, id| {
289 tcx.resolve_lifetimes(LOCAL_CRATE).object_lifetime_defaults.get(&id)
296 /// Computes the `ResolveLifetimes` map that contains data for the
297 /// entire crate. You should not read the result of this query
298 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
300 fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> ResolveLifetimes {
301 assert_eq!(for_krate, LOCAL_CRATE);
303 let named_region_map = krate(tcx);
305 let mut rl = ResolveLifetimes::default();
307 for (hir_id, v) in named_region_map.defs {
308 let map = rl.defs.entry(hir_id.owner).or_default();
309 map.insert(hir_id.local_id, v);
311 for hir_id in named_region_map.late_bound {
312 let map = rl.late_bound.entry(hir_id.owner).or_default();
313 map.insert(hir_id.local_id);
315 for (hir_id, v) in named_region_map.object_lifetime_defaults {
316 let map = rl.object_lifetime_defaults.entry(hir_id.owner).or_default();
317 map.insert(hir_id.local_id, v);
323 fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap {
324 let krate = tcx.hir().krate();
325 let mut map = NamedRegionMap {
326 defs: Default::default(),
327 late_bound: Default::default(),
328 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
331 let mut visitor = LifetimeContext {
335 trait_ref_hack: false,
336 is_in_fn_syntax: false,
337 is_in_const_generic: false,
338 labels_in_fn: vec![],
339 xcrate_object_lifetime_defaults: Default::default(),
340 lifetime_uses: &mut Default::default(),
341 missing_named_lifetime_spots: vec![],
343 for item in krate.items.values() {
344 visitor.visit_item(item);
350 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
351 /// We have to account for this when computing the index of the other generic parameters.
352 /// This function returns whether there is such an implicit parameter defined on the given item.
353 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
355 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true,
360 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
361 type Map = Map<'tcx>;
363 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
364 NestedVisitorMap::All(self.tcx.hir())
367 // We want to nest trait/impl items in their parent, but nothing else.
368 fn visit_nested_item(&mut self, _: hir::ItemId) {}
370 fn visit_nested_body(&mut self, body: hir::BodyId) {
371 // Each body has their own set of labels, save labels.
372 let saved = take(&mut self.labels_in_fn);
373 let body = self.tcx.hir().body(body);
374 extract_labels(self, body);
375 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
376 this.visit_body(body);
378 self.labels_in_fn = saved;
381 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
383 hir::ItemKind::Fn(ref sig, ref generics, _) => {
384 self.missing_named_lifetime_spots.push(generics.into());
385 self.visit_early_late(None, &sig.decl, generics, |this| {
386 intravisit::walk_item(this, item);
388 self.missing_named_lifetime_spots.pop();
391 hir::ItemKind::ExternCrate(_)
392 | hir::ItemKind::Use(..)
393 | hir::ItemKind::Mod(..)
394 | hir::ItemKind::ForeignMod(..)
395 | hir::ItemKind::GlobalAsm(..) => {
396 // These sorts of items have no lifetime parameters at all.
397 intravisit::walk_item(self, item);
399 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
400 // No lifetime parameters, but implied 'static.
401 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
402 self.with(scope, |_, this| intravisit::walk_item(this, item));
404 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
405 // Opaque types are visited when we visit the
406 // `TyKind::OpaqueDef`, so that they have the lifetimes from
407 // their parent opaque_ty in scope.
409 hir::ItemKind::TyAlias(_, ref generics)
410 | hir::ItemKind::Enum(_, ref generics)
411 | hir::ItemKind::Struct(_, ref generics)
412 | hir::ItemKind::Union(_, ref generics)
413 | hir::ItemKind::Trait(_, _, ref generics, ..)
414 | hir::ItemKind::TraitAlias(ref generics, ..)
415 | hir::ItemKind::Impl { ref generics, .. } => {
416 self.missing_named_lifetime_spots.push(generics.into());
418 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
419 // This is not true for other kinds of items.x
420 let track_lifetime_uses = match item.kind {
421 hir::ItemKind::Impl { .. } => true,
424 // These kinds of items have only early-bound lifetime parameters.
425 let mut index = if sub_items_have_self_param(&item.kind) {
426 1 // Self comes before lifetimes
430 let mut non_lifetime_count = 0;
431 let lifetimes = generics
434 .filter_map(|param| match param.kind {
435 GenericParamKind::Lifetime { .. } => {
436 Some(Region::early(&self.tcx.hir(), &mut index, param))
438 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
439 non_lifetime_count += 1;
444 let scope = Scope::Binder {
446 next_early_index: index + non_lifetime_count,
447 opaque_type_parent: true,
451 self.with(scope, |old_scope, this| {
452 this.check_lifetime_params(old_scope, &generics.params);
453 intravisit::walk_item(this, item);
455 self.missing_named_lifetime_spots.pop();
460 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
462 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
463 self.visit_early_late(None, decl, generics, |this| {
464 intravisit::walk_foreign_item(this, item);
467 hir::ForeignItemKind::Static(..) => {
468 intravisit::walk_foreign_item(self, item);
470 hir::ForeignItemKind::Type => {
471 intravisit::walk_foreign_item(self, item);
476 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
477 debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
478 debug!("visit_ty: ty.kind={:?}", ty.kind);
480 hir::TyKind::BareFn(ref c) => {
481 let next_early_index = self.next_early_index();
482 let was_in_fn_syntax = self.is_in_fn_syntax;
483 self.is_in_fn_syntax = true;
484 let lifetime_span: Option<Span> =
485 c.generic_params.iter().rev().find_map(|param| match param.kind {
486 GenericParamKind::Lifetime { .. } => Some(param.span),
489 let (span, span_type) = if let Some(span) = lifetime_span {
490 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
492 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
494 self.missing_named_lifetime_spots
495 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
496 let scope = Scope::Binder {
500 .filter_map(|param| match param.kind {
501 GenericParamKind::Lifetime { .. } => {
502 Some(Region::late(&self.tcx.hir(), param))
509 track_lifetime_uses: true,
510 opaque_type_parent: false,
512 self.with(scope, |old_scope, this| {
513 // a bare fn has no bounds, so everything
514 // contained within is scoped within its binder.
515 this.check_lifetime_params(old_scope, &c.generic_params);
516 intravisit::walk_ty(this, ty);
518 self.missing_named_lifetime_spots.pop();
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 implicit",);
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::OpaqueDef(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 opaque_ty = self.tcx.hir().expect_item(item_id.id);
569 let (generics, bounds) = match opaque_ty.kind {
570 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
571 // This arm is for `impl Trait` in the types of statics, constants and locals.
572 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
573 intravisit::walk_ty(self, ty);
575 // Elided lifetimes are not allowed in non-return
576 // position impl Trait
577 let scope = Scope::Elision { elide: Elide::Forbid, s: self.scope };
578 self.with(scope, |_, this| {
579 intravisit::walk_item(this, opaque_ty);
584 // RPIT (return position impl trait)
585 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
586 impl_trait_fn: Some(_),
590 }) => (generics, bounds),
591 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
594 // Resolve the lifetimes that are applied to the opaque type.
595 // These are resolved in the current scope.
596 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
597 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
598 // ^ ^this gets resolved in the current scope
599 for lifetime in lifetimes {
600 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
601 self.visit_lifetime(lifetime);
603 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
604 // and ban them. Type variables instantiated inside binders aren't
605 // well-supported at the moment, so this doesn't work.
606 // In the future, this should be fixed and this error should be removed.
607 let def = self.map.defs.get(&lifetime.hir_id).cloned();
608 if let Some(Region::LateBound(_, def_id, _)) = def {
609 if let Some(def_id) = def_id.as_local() {
610 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
611 // Ensure that the parent of the def is an item, not HRTB
612 let parent_id = self.tcx.hir().get_parent_node(hir_id);
613 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
614 let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
615 let krate = self.tcx.hir().krate();
617 if !(krate.items.contains_key(&parent_id)
618 || krate.impl_items.contains_key(&parent_impl_id)
619 || krate.trait_items.contains_key(&parent_trait_id))
625 "`impl Trait` can only capture lifetimes \
626 bound at the fn or impl level"
629 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
636 // We want to start our early-bound indices at the end of the parent scope,
637 // not including any parent `impl Trait`s.
638 let mut index = self.next_early_index_for_opaque_type();
639 debug!("visit_ty: index = {}", index);
641 let mut elision = None;
642 let mut lifetimes = FxHashMap::default();
643 let mut non_lifetime_count = 0;
644 for param in generics.params {
646 GenericParamKind::Lifetime { .. } => {
647 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
648 let def_id = if let Region::EarlyBound(_, def_id, _) = reg {
653 if let hir::ParamName::Plain(param_name) = name {
654 if param_name.name == kw::UnderscoreLifetime {
655 // Pick the elided lifetime "definition" if one exists
656 // and use it to make an elision scope.
657 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
660 lifetimes.insert(name, reg);
663 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
664 lifetimes.insert(name, reg);
667 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
668 non_lifetime_count += 1;
672 let next_early_index = index + non_lifetime_count;
674 if let Some(elision_region) = elision {
676 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
677 self.with(scope, |_old_scope, this| {
678 let scope = Scope::Binder {
682 track_lifetime_uses: true,
683 opaque_type_parent: false,
685 this.with(scope, |_old_scope, this| {
686 this.visit_generics(generics);
687 for bound in bounds {
688 this.visit_param_bound(bound);
693 let scope = Scope::Binder {
697 track_lifetime_uses: true,
698 opaque_type_parent: false,
700 self.with(scope, |_old_scope, this| {
701 this.visit_generics(generics);
702 for bound in bounds {
703 this.visit_param_bound(bound);
708 _ => intravisit::walk_ty(self, ty),
712 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
713 use self::hir::TraitItemKind::*;
714 match trait_item.kind {
716 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
718 self.visit_early_late(
719 Some(tcx.hir().get_parent_item(trait_item.hir_id)),
721 &trait_item.generics,
722 |this| intravisit::walk_trait_item(this, trait_item),
724 self.missing_named_lifetime_spots.pop();
726 Type(bounds, ref ty) => {
727 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
728 let generics = &trait_item.generics;
729 let mut index = self.next_early_index();
730 debug!("visit_ty: index = {}", index);
731 let mut non_lifetime_count = 0;
732 let lifetimes = generics
735 .filter_map(|param| match param.kind {
736 GenericParamKind::Lifetime { .. } => {
737 Some(Region::early(&self.tcx.hir(), &mut index, param))
739 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
740 non_lifetime_count += 1;
745 let scope = Scope::Binder {
747 next_early_index: index + non_lifetime_count,
749 track_lifetime_uses: true,
750 opaque_type_parent: true,
752 self.with(scope, |old_scope, this| {
753 this.check_lifetime_params(old_scope, &generics.params);
754 this.visit_generics(generics);
755 for bound in bounds {
756 this.visit_param_bound(bound);
758 if let Some(ty) = ty {
762 self.missing_named_lifetime_spots.pop();
765 // Only methods and types support generics.
766 assert!(trait_item.generics.params.is_empty());
767 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
768 intravisit::walk_trait_item(self, trait_item);
769 self.missing_named_lifetime_spots.pop();
774 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
775 use self::hir::ImplItemKind::*;
776 match impl_item.kind {
778 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
780 self.visit_early_late(
781 Some(tcx.hir().get_parent_item(impl_item.hir_id)),
784 |this| intravisit::walk_impl_item(this, impl_item),
786 self.missing_named_lifetime_spots.pop();
789 let generics = &impl_item.generics;
790 self.missing_named_lifetime_spots.push(generics.into());
791 let mut index = self.next_early_index();
792 let mut non_lifetime_count = 0;
793 debug!("visit_ty: index = {}", index);
794 let lifetimes = generics
797 .filter_map(|param| match param.kind {
798 GenericParamKind::Lifetime { .. } => {
799 Some(Region::early(&self.tcx.hir(), &mut index, param))
801 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
802 non_lifetime_count += 1;
807 let scope = Scope::Binder {
809 next_early_index: index + non_lifetime_count,
811 track_lifetime_uses: true,
812 opaque_type_parent: true,
814 self.with(scope, |old_scope, this| {
815 this.check_lifetime_params(old_scope, &generics.params);
816 this.visit_generics(generics);
819 self.missing_named_lifetime_spots.pop();
822 // Only methods and types support generics.
823 assert!(impl_item.generics.params.is_empty());
824 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
825 intravisit::walk_impl_item(self, impl_item);
826 self.missing_named_lifetime_spots.pop();
831 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
832 debug!("visit_lifetime(lifetime_ref={:?})", lifetime_ref);
833 if lifetime_ref.is_elided() {
834 self.resolve_elided_lifetimes(vec![lifetime_ref]);
837 if lifetime_ref.is_static() {
838 self.insert_lifetime(lifetime_ref, Region::Static);
841 if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
842 self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
845 self.resolve_lifetime_ref(lifetime_ref);
848 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
849 for (i, segment) in path.segments.iter().enumerate() {
850 let depth = path.segments.len() - i - 1;
851 if let Some(ref args) = segment.args {
852 self.visit_segment_args(path.res, depth, args);
857 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
858 let output = match fd.output {
859 hir::FnRetTy::DefaultReturn(_) => None,
860 hir::FnRetTy::Return(ref ty) => Some(&**ty),
862 self.visit_fn_like_elision(&fd.inputs, output);
865 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
866 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
867 for param in generics.params {
869 GenericParamKind::Lifetime { .. } => {}
870 GenericParamKind::Type { ref default, .. } => {
871 walk_list!(self, visit_param_bound, param.bounds);
872 if let Some(ref ty) = default {
876 GenericParamKind::Const { ref ty, .. } => {
877 let was_in_const_generic = self.is_in_const_generic;
878 self.is_in_const_generic = true;
879 walk_list!(self, visit_param_bound, param.bounds);
881 self.is_in_const_generic = was_in_const_generic;
885 for predicate in generics.where_clause.predicates {
887 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
890 ref bound_generic_params,
893 let lifetimes: FxHashMap<_, _> = bound_generic_params
895 .filter_map(|param| match param.kind {
896 GenericParamKind::Lifetime { .. } => {
897 Some(Region::late(&self.tcx.hir(), param))
902 if !lifetimes.is_empty() {
903 let next_early_index = self.next_early_index();
904 let scope = Scope::Binder {
908 track_lifetime_uses: true,
909 opaque_type_parent: false,
911 let result = self.with(scope, |old_scope, this| {
912 this.check_lifetime_params(old_scope, &bound_generic_params);
913 this.visit_ty(&bounded_ty);
914 this.trait_ref_hack = true;
915 walk_list!(this, visit_param_bound, bounds);
916 this.trait_ref_hack = false;
920 self.visit_ty(&bounded_ty);
921 walk_list!(self, visit_param_bound, bounds);
924 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
929 self.visit_lifetime(lifetime);
930 walk_list!(self, visit_param_bound, bounds);
932 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
937 self.visit_ty(lhs_ty);
938 self.visit_ty(rhs_ty);
944 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
946 hir::GenericBound::LangItemTrait { .. } if !self.trait_ref_hack => {
947 let scope = Scope::Binder {
948 lifetimes: FxHashMap::default(),
950 next_early_index: self.next_early_index(),
951 track_lifetime_uses: true,
952 opaque_type_parent: false,
954 self.with(scope, |_, this| {
955 intravisit::walk_param_bound(this, bound);
958 _ => intravisit::walk_param_bound(self, bound),
962 fn visit_poly_trait_ref(
964 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
965 _modifier: hir::TraitBoundModifier,
967 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
969 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
971 let trait_ref_hack = take(&mut self.trait_ref_hack);
973 || trait_ref.bound_generic_params.iter().any(|param| match param.kind {
974 GenericParamKind::Lifetime { .. } => true,
983 "nested quantification of lifetimes"
987 let next_early_index = self.next_early_index();
988 let scope = Scope::Binder {
990 .bound_generic_params
992 .filter_map(|param| match param.kind {
993 GenericParamKind::Lifetime { .. } => {
994 Some(Region::late(&self.tcx.hir(), param))
1001 track_lifetime_uses: true,
1002 opaque_type_parent: false,
1004 self.with(scope, |old_scope, this| {
1005 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1006 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1007 this.visit_trait_ref(&trait_ref.trait_ref);
1010 self.visit_trait_ref(&trait_ref.trait_ref);
1012 self.trait_ref_hack = trait_ref_hack;
1013 if should_pop_missing_lt {
1014 self.missing_named_lifetime_spots.pop();
1019 #[derive(Copy, Clone, PartialEq)]
1033 fn original_label(span: Span) -> Original {
1034 Original { kind: ShadowKind::Label, span }
1036 fn shadower_label(span: Span) -> Shadower {
1037 Shadower { kind: ShadowKind::Label, span }
1039 fn original_lifetime(span: Span) -> Original {
1040 Original { kind: ShadowKind::Lifetime, span }
1042 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1043 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1047 fn desc(&self) -> &'static str {
1049 ShadowKind::Label => "label",
1050 ShadowKind::Lifetime => "lifetime",
1055 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1056 let lifetime_params: Vec<_> = params
1058 .filter_map(|param| match param.kind {
1059 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1063 let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1064 let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1066 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1071 "cannot mix in-band and explicit lifetime definitions"
1073 .span_label(*in_band_span, "in-band lifetime definition here")
1074 .span_label(*explicit_span, "explicit lifetime definition here")
1079 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1080 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1081 // lifetime/lifetime shadowing is an error
1086 "{} name `{}` shadows a \
1087 {} name that is already in scope",
1088 shadower.kind.desc(),
1093 // shadowing involving a label is only a warning, due to issues with
1094 // labels and lifetimes not being macro-hygienic.
1095 tcx.sess.struct_span_warn(
1098 "{} name `{}` shadows a \
1099 {} name that is already in scope",
1100 shadower.kind.desc(),
1106 err.span_label(orig.span, "first declared here");
1107 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1111 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1112 // if one of the label shadows a lifetime or another label.
1113 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1114 struct GatherLabels<'a, 'tcx> {
1116 scope: ScopeRef<'a>,
1117 labels_in_fn: &'a mut Vec<Ident>,
1121 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1122 gather.visit_body(body);
1124 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1125 type Map = intravisit::ErasedMap<'v>;
1127 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1128 NestedVisitorMap::None
1131 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1132 if let Some(label) = expression_label(ex) {
1133 for prior_label in &self.labels_in_fn[..] {
1134 // FIXME (#24278): non-hygienic comparison
1135 if label.name == prior_label.name {
1136 signal_shadowing_problem(
1139 original_label(prior_label.span),
1140 shadower_label(label.span),
1145 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1147 self.labels_in_fn.push(label);
1149 intravisit::walk_expr(self, ex)
1153 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1154 if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { Some(label.ident) } else { None }
1157 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1160 Scope::Body { s, .. }
1161 | Scope::Elision { s, .. }
1162 | Scope::ObjectLifetimeDefault { s, .. } => {
1170 Scope::Binder { ref lifetimes, s, .. } => {
1171 // FIXME (#24278): non-hygienic comparison
1173 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1176 tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
1178 signal_shadowing_problem(
1181 original_lifetime(tcx.hir().span(hir_id)),
1182 shadower_label(label.span),
1193 fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1194 let mut map = HirIdMap::default();
1195 for item in tcx.hir().krate().items.values() {
1197 hir::ItemKind::Struct(_, ref generics)
1198 | hir::ItemKind::Union(_, ref generics)
1199 | hir::ItemKind::Enum(_, ref generics)
1200 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1201 ref generics, impl_trait_fn: None, ..
1203 | hir::ItemKind::TyAlias(_, ref generics)
1204 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1205 let result = object_lifetime_defaults_for_item(tcx, generics);
1208 if tcx.sess.contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1209 let object_lifetime_default_reprs: String = result
1211 .map(|set| match *set {
1212 Set1::Empty => "BaseDefault".into(),
1213 Set1::One(Region::Static) => "'static".into(),
1214 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1217 .find_map(|param| match param.kind {
1218 GenericParamKind::Lifetime { .. } => {
1220 return Some(param.name.ident().to_string().into());
1228 Set1::One(_) => bug!(),
1229 Set1::Many => "Ambiguous".into(),
1231 .collect::<Vec<Cow<'static, str>>>()
1233 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1236 map.insert(item.hir_id, result);
1244 /// Scan the bounds and where-clauses on parameters to extract bounds
1245 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1246 /// for each type parameter.
1247 fn object_lifetime_defaults_for_item(
1249 generics: &hir::Generics<'_>,
1250 ) -> Vec<ObjectLifetimeDefault> {
1251 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1252 for bound in bounds {
1253 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1254 set.insert(lifetime.name.normalize_to_macros_2_0());
1262 .filter_map(|param| match param.kind {
1263 GenericParamKind::Lifetime { .. } => None,
1264 GenericParamKind::Type { .. } => {
1265 let mut set = Set1::Empty;
1267 add_bounds(&mut set, ¶m.bounds);
1269 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1270 for predicate in generics.where_clause.predicates {
1271 // Look for `type: ...` where clauses.
1272 let data = match *predicate {
1273 hir::WherePredicate::BoundPredicate(ref data) => data,
1277 // Ignore `for<'a> type: ...` as they can change what
1278 // lifetimes mean (although we could "just" handle it).
1279 if !data.bound_generic_params.is_empty() {
1283 let res = match data.bounded_ty.kind {
1284 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1288 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1289 add_bounds(&mut set, &data.bounds);
1294 Set1::Empty => Set1::Empty,
1295 Set1::One(name) => {
1296 if name == hir::LifetimeName::Static {
1297 Set1::One(Region::Static)
1302 .filter_map(|param| match param.kind {
1303 GenericParamKind::Lifetime { .. } => Some((
1305 hir::LifetimeName::Param(param.name),
1306 LifetimeDefOrigin::from_param(param),
1311 .find(|&(_, (_, lt_name, _))| lt_name == name)
1312 .map_or(Set1::Many, |(i, (id, _, origin))| {
1313 let def_id = tcx.hir().local_def_id(id);
1314 Set1::One(Region::EarlyBound(
1322 Set1::Many => Set1::Many,
1325 GenericParamKind::Const { .. } => {
1326 // Generic consts don't impose any constraints.
1328 // We still store a dummy value here to allow generic parameters
1329 // in an arbitrary order.
1336 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1337 // FIXME(#37666) this works around a limitation in the region inferencer
1338 fn hack<F>(&mut self, f: F)
1340 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1345 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1347 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1349 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1350 let labels_in_fn = take(&mut self.labels_in_fn);
1351 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1352 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1353 let mut this = LifetimeContext {
1357 trait_ref_hack: self.trait_ref_hack,
1358 is_in_fn_syntax: self.is_in_fn_syntax,
1359 is_in_const_generic: self.is_in_const_generic,
1361 xcrate_object_lifetime_defaults,
1363 missing_named_lifetime_spots,
1365 debug!("entering scope {:?}", this.scope);
1366 f(self.scope, &mut this);
1367 this.check_uses_for_lifetimes_defined_by_scope();
1368 debug!("exiting scope {:?}", this.scope);
1369 self.labels_in_fn = this.labels_in_fn;
1370 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1371 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1374 /// helper method to determine the span to remove when suggesting the
1375 /// deletion of a lifetime
1376 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1377 generics.params.iter().enumerate().find_map(|(i, param)| {
1378 if param.name.ident() == name {
1379 let mut in_band = false;
1380 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1381 if let hir::LifetimeParamKind::InBand = kind {
1388 if generics.params.len() == 1 {
1389 // if sole lifetime, remove the entire `<>` brackets
1392 // if removing within `<>` brackets, we also want to
1393 // delete a leading or trailing comma as appropriate
1394 if i >= generics.params.len() - 1 {
1395 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1397 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1407 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1408 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1409 fn suggest_eliding_single_use_lifetime(
1411 err: &mut DiagnosticBuilder<'_>,
1413 lifetime: &hir::Lifetime,
1415 let name = lifetime.name.ident();
1416 let mut remove_decl = None;
1417 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1418 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1419 remove_decl = self.lifetime_deletion_span(name, generics);
1423 let mut remove_use = None;
1424 let mut elide_use = None;
1425 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1426 for input in inputs {
1428 hir::TyKind::Rptr(lt, _) => {
1429 if lt.name.ident() == name {
1430 // include the trailing whitespace between the lifetime and type names
1431 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1436 .span_until_non_whitespace(lt_through_ty_span),
1441 hir::TyKind::Path(ref qpath) => {
1442 if let QPath::Resolved(_, path) = qpath {
1443 let last_segment = &path.segments[path.segments.len() - 1];
1444 let generics = last_segment.generic_args();
1445 for arg in generics.args.iter() {
1446 if let GenericArg::Lifetime(lt) = arg {
1447 if lt.name.ident() == name {
1448 elide_use = Some(lt.span);
1460 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1461 if let Some(parent) =
1462 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1465 Node::Item(item) => {
1466 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1467 find_arg_use_span(sig.decl.inputs);
1470 Node::ImplItem(impl_item) => {
1471 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1472 find_arg_use_span(sig.decl.inputs);
1480 let msg = "elide the single-use lifetime";
1481 match (remove_decl, remove_use, elide_use) {
1482 (Some(decl_span), Some(use_span), None) => {
1483 // if both declaration and use deletion spans start at the same
1484 // place ("start at" because the latter includes trailing
1485 // whitespace), then this is an in-band lifetime
1486 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1487 err.span_suggestion(
1491 Applicability::MachineApplicable,
1494 err.multipart_suggestion(
1496 vec![(decl_span, String::new()), (use_span, String::new())],
1497 Applicability::MachineApplicable,
1501 (Some(decl_span), None, Some(use_span)) => {
1502 err.multipart_suggestion(
1504 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1505 Applicability::MachineApplicable,
1512 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1513 let defined_by = match self.scope {
1514 Scope::Binder { lifetimes, .. } => lifetimes,
1516 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1521 let mut def_ids: Vec<_> = defined_by
1523 .flat_map(|region| match region {
1524 Region::EarlyBound(_, def_id, _)
1525 | Region::LateBound(_, def_id, _)
1526 | Region::Free(_, def_id) => Some(*def_id),
1528 Region::LateBoundAnon(..) | Region::Static => None,
1532 // ensure that we issue lints in a repeatable order
1533 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1535 for def_id in def_ids {
1536 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1538 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1541 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1545 match lifetimeuseset {
1546 Some(LifetimeUseSet::One(lifetime)) => {
1547 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1548 debug!("hir id first={:?}", hir_id);
1549 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1550 Node::Lifetime(hir_lifetime) => Some((
1551 hir_lifetime.hir_id,
1553 hir_lifetime.name.ident(),
1555 Node::GenericParam(param) => {
1556 Some((param.hir_id, param.span, param.name.ident()))
1560 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1561 if name.name == kw::UnderscoreLifetime {
1565 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1566 if let Some(def_id) = parent_def_id.as_local() {
1567 let parent_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1568 // lifetimes in `derive` expansions don't count (Issue #53738)
1569 if self.tcx.hir().attrs(parent_hir_id).iter().any(|attr| {
1570 self.tcx.sess.check_name(attr, sym::automatically_derived)
1577 self.tcx.struct_span_lint_hir(
1578 lint::builtin::SINGLE_USE_LIFETIMES,
1582 let mut err = lint.build(&format!(
1583 "lifetime parameter `{}` only used once",
1586 if span == lifetime.span {
1587 // spans are the same for in-band lifetime declarations
1588 err.span_label(span, "this lifetime is only used here");
1590 err.span_label(span, "this lifetime...");
1591 err.span_label(lifetime.span, "...is used only here");
1593 self.suggest_eliding_single_use_lifetime(
1594 &mut err, def_id, lifetime,
1601 Some(LifetimeUseSet::Many) => {
1602 debug!("not one use lifetime");
1605 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1606 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1607 Node::Lifetime(hir_lifetime) => Some((
1608 hir_lifetime.hir_id,
1610 hir_lifetime.name.ident(),
1612 Node::GenericParam(param) => {
1613 Some((param.hir_id, param.span, param.name.ident()))
1617 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1618 self.tcx.struct_span_lint_hir(
1619 lint::builtin::UNUSED_LIFETIMES,
1624 .build(&format!("lifetime parameter `{}` never used", name));
1625 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1626 if let Some(generics) =
1627 self.tcx.hir().get_generics(parent_def_id)
1629 let unused_lt_span =
1630 self.lifetime_deletion_span(name, generics);
1631 if let Some(span) = unused_lt_span {
1632 err.span_suggestion(
1634 "elide the unused lifetime",
1636 Applicability::MachineApplicable,
1650 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1652 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1653 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1654 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1658 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1660 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1661 /// lifetimes may be interspersed together.
1663 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1664 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1665 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1666 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1667 /// ordering is not important there.
1668 fn visit_early_late<F>(
1670 parent_id: Option<hir::HirId>,
1671 decl: &'tcx hir::FnDecl<'tcx>,
1672 generics: &'tcx hir::Generics<'tcx>,
1675 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1677 insert_late_bound_lifetimes(self.map, decl, generics);
1679 // Find the start of nested early scopes, e.g., in methods.
1681 if let Some(parent_id) = parent_id {
1682 let parent = self.tcx.hir().expect_item(parent_id);
1683 if sub_items_have_self_param(&parent.kind) {
1684 index += 1; // Self comes before lifetimes
1687 hir::ItemKind::Trait(_, _, ref generics, ..)
1688 | hir::ItemKind::Impl { ref generics, .. } => {
1689 index += generics.params.len() as u32;
1695 let mut non_lifetime_count = 0;
1696 let lifetimes = generics
1699 .filter_map(|param| match param.kind {
1700 GenericParamKind::Lifetime { .. } => {
1701 if self.map.late_bound.contains(¶m.hir_id) {
1702 Some(Region::late(&self.tcx.hir(), param))
1704 Some(Region::early(&self.tcx.hir(), &mut index, param))
1707 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1708 non_lifetime_count += 1;
1713 let next_early_index = index + non_lifetime_count;
1715 let scope = Scope::Binder {
1719 opaque_type_parent: true,
1720 track_lifetime_uses: false,
1722 self.with(scope, move |old_scope, this| {
1723 this.check_lifetime_params(old_scope, &generics.params);
1724 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1728 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1729 let mut scope = self.scope;
1732 Scope::Root => return 0,
1734 Scope::Binder { next_early_index, opaque_type_parent, .. }
1735 if (!only_opaque_type_parent || opaque_type_parent) =>
1737 return next_early_index;
1740 Scope::Binder { s, .. }
1741 | Scope::Body { s, .. }
1742 | Scope::Elision { s, .. }
1743 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1748 /// Returns the next index one would use for an early-bound-region
1749 /// if extending the current scope.
1750 fn next_early_index(&self) -> u32 {
1751 self.next_early_index_helper(true)
1754 /// Returns the next index one would use for an `impl Trait` that
1755 /// is being converted into an opaque type alias `impl Trait`. This will be the
1756 /// next early index from the enclosing item, for the most
1757 /// part. See the `opaque_type_parent` field for more info.
1758 fn next_early_index_for_opaque_type(&self) -> u32 {
1759 self.next_early_index_helper(false)
1762 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1763 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1765 // If we've already reported an error, just ignore `lifetime_ref`.
1766 if let LifetimeName::Error = lifetime_ref.name {
1770 // Walk up the scope chain, tracking the number of fn scopes
1771 // that we pass through, until we find a lifetime with the
1772 // given name or we run out of scopes.
1774 let mut late_depth = 0;
1775 let mut scope = self.scope;
1776 let mut outermost_body = None;
1779 Scope::Body { id, s } => {
1780 outermost_body = Some(id);
1788 Scope::Binder { ref lifetimes, s, .. } => {
1789 match lifetime_ref.name {
1790 LifetimeName::Param(param_name) => {
1791 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
1793 break Some(def.shifted(late_depth));
1796 _ => bug!("expected LifetimeName::Param"),
1803 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1809 if let Some(mut def) = result {
1810 if let Region::EarlyBound(..) = def {
1811 // Do not free early-bound regions, only late-bound ones.
1812 } else if let Some(body_id) = outermost_body {
1813 let fn_id = self.tcx.hir().body_owner(body_id);
1814 match self.tcx.hir().get(fn_id) {
1815 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1816 | Node::TraitItem(&hir::TraitItem {
1817 kind: hir::TraitItemKind::Fn(..), ..
1819 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
1820 let scope = self.tcx.hir().local_def_id(fn_id);
1821 def = Region::Free(scope.to_def_id(), def.id().unwrap());
1827 // Check for fn-syntax conflicts with in-band lifetime definitions
1828 if self.is_in_fn_syntax {
1830 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1831 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1836 "lifetimes used in `fn` or `Fn` syntax must be \
1837 explicitly declared using `<...>` binders"
1839 .span_label(lifetime_ref.span, "in-band lifetime definition")
1844 | Region::EarlyBound(
1847 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1849 | Region::LateBound(
1852 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1854 | Region::LateBoundAnon(..)
1855 | Region::Free(..) => {}
1859 self.insert_lifetime(lifetime_ref, def);
1861 self.emit_undeclared_lifetime_error(lifetime_ref);
1865 fn visit_segment_args(
1869 generic_args: &'tcx hir::GenericArgs<'tcx>,
1872 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1873 res, depth, generic_args,
1876 if generic_args.parenthesized {
1877 let was_in_fn_syntax = self.is_in_fn_syntax;
1878 self.is_in_fn_syntax = true;
1879 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1880 self.is_in_fn_syntax = was_in_fn_syntax;
1884 let mut elide_lifetimes = true;
1885 let lifetimes = generic_args
1888 .filter_map(|arg| match arg {
1889 hir::GenericArg::Lifetime(lt) => {
1890 if !lt.is_elided() {
1891 elide_lifetimes = false;
1898 if elide_lifetimes {
1899 self.resolve_elided_lifetimes(lifetimes);
1901 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1904 // Figure out if this is a type/trait segment,
1905 // which requires object lifetime defaults.
1906 let parent_def_id = |this: &mut Self, def_id: DefId| {
1907 let def_key = this.tcx.def_key(def_id);
1908 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1910 let type_def_id = match res {
1911 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1912 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1920 ) if depth == 0 => Some(def_id),
1924 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1926 // Compute a vector of defaults, one for each type parameter,
1927 // per the rules given in RFCs 599 and 1156. Example:
1930 // struct Foo<'a, T: 'a, U> { }
1933 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1934 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1935 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1938 // Therefore, we would compute `object_lifetime_defaults` to a
1939 // vector like `['x, 'static]`. Note that the vector only
1940 // includes type parameters.
1941 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1943 let mut scope = self.scope;
1946 Scope::Root => break false,
1948 Scope::Body { .. } => break true,
1950 Scope::Binder { s, .. }
1951 | Scope::Elision { s, .. }
1952 | Scope::ObjectLifetimeDefault { s, .. } => {
1959 let map = &self.map;
1960 let unsubst = if let Some(def_id) = def_id.as_local() {
1961 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1962 &map.object_lifetime_defaults[&id]
1965 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
1966 tcx.generics_of(def_id)
1969 .filter_map(|param| match param.kind {
1970 GenericParamDefKind::Type { object_lifetime_default, .. } => {
1971 Some(object_lifetime_default)
1973 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1978 debug!("visit_segment_args: unsubst={:?}", unsubst);
1981 .map(|set| match *set {
1986 Some(Region::Static)
1990 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1991 GenericArg::Lifetime(lt) => Some(lt),
1994 r.subst(lifetimes, map)
2001 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2004 for arg in generic_args.args {
2006 GenericArg::Lifetime(_) => {}
2007 GenericArg::Type(ty) => {
2008 if let Some(<) = object_lifetime_defaults.get(i) {
2009 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2010 self.with(scope, |_, this| this.visit_ty(ty));
2016 GenericArg::Const(ct) => {
2017 self.visit_anon_const(&ct.value);
2022 // Hack: when resolving the type `XX` in binding like `dyn
2023 // Foo<'b, Item = XX>`, the current object-lifetime default
2024 // would be to examine the trait `Foo` to check whether it has
2025 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2026 // declared like so, then the default object lifetime bound in
2027 // `XX` should be `'b`:
2035 // but if we just have `type Item;`, then it would be
2036 // `'static`. However, we don't get all of this logic correct.
2038 // Instead, we do something hacky: if there are no lifetime parameters
2039 // to the trait, then we simply use a default object lifetime
2040 // bound of `'static`, because there is no other possibility. On the other hand,
2041 // if there ARE lifetime parameters, then we require the user to give an
2042 // explicit bound for now.
2044 // This is intended to leave room for us to implement the
2045 // correct behavior in the future.
2046 let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
2047 GenericArg::Lifetime(_) => true,
2051 // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2052 for b in generic_args.bindings {
2053 let scope = Scope::ObjectLifetimeDefault {
2054 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2057 self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2061 fn visit_fn_like_elision(
2063 inputs: &'tcx [hir::Ty<'tcx>],
2064 output: Option<&'tcx hir::Ty<'tcx>>,
2066 debug!("visit_fn_like_elision: enter");
2067 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2068 let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
2069 self.with(arg_scope, |_, this| {
2070 for input in inputs {
2071 this.visit_ty(input);
2074 Scope::Elision { ref elide, .. } => {
2075 arg_elide = elide.clone();
2081 let output = match output {
2086 debug!("visit_fn_like_elision: determine output");
2088 // Figure out if there's a body we can get argument names from,
2089 // and whether there's a `self` argument (treated specially).
2090 let mut assoc_item_kind = None;
2091 let mut impl_self = None;
2092 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2093 let body = match self.tcx.hir().get(parent) {
2094 // `fn` definitions and methods.
2095 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2097 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2098 if let hir::ItemKind::Trait(.., ref trait_items) =
2099 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2102 trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
2105 hir::TraitFn::Required(_) => None,
2106 hir::TraitFn::Provided(body) => Some(body),
2110 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2111 if let hir::ItemKind::Impl { ref self_ty, ref items, .. } =
2112 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2114 impl_self = Some(self_ty);
2116 items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
2121 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2122 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2123 // Everything else (only closures?) doesn't
2124 // actually enjoy elision in return types.
2126 self.visit_ty(output);
2131 let has_self = match assoc_item_kind {
2132 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2136 // In accordance with the rules for lifetime elision, we can determine
2137 // what region to use for elision in the output type in two ways.
2138 // First (determined here), if `self` is by-reference, then the
2139 // implied output region is the region of the self parameter.
2141 struct SelfVisitor<'a> {
2142 map: &'a NamedRegionMap,
2143 impl_self: Option<&'a hir::TyKind<'a>>,
2144 lifetime: Set1<Region>,
2147 impl SelfVisitor<'_> {
2148 // Look for `self: &'a Self` - also desugared from `&'a self`,
2149 // and if that matches, use it for elision and return early.
2150 fn is_self_ty(&self, res: Res) -> bool {
2151 if let Res::SelfTy(..) = res {
2155 // Can't always rely on literal (or implied) `Self` due
2156 // to the way elision rules were originally specified.
2157 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2161 // Permit the types that unambiguously always
2162 // result in the same type constructor being used
2163 // (it can't differ between `Self` and `self`).
2164 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2165 | Res::PrimTy(_) => return res == path.res,
2174 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2175 type Map = intravisit::ErasedMap<'a>;
2177 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2178 NestedVisitorMap::None
2181 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2182 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2183 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2185 if self.is_self_ty(path.res) {
2186 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2187 self.lifetime.insert(*lifetime);
2192 intravisit::walk_ty(self, ty)
2196 let mut visitor = SelfVisitor {
2198 impl_self: impl_self.map(|ty| &ty.kind),
2199 lifetime: Set1::Empty,
2201 visitor.visit_ty(&inputs[0]);
2202 if let Set1::One(lifetime) = visitor.lifetime {
2203 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2204 self.with(scope, |_, this| this.visit_ty(output));
2209 // Second, if there was exactly one lifetime (either a substitution or a
2210 // reference) in the arguments, then any anonymous regions in the output
2211 // have that lifetime.
2212 let mut possible_implied_output_region = None;
2213 let mut lifetime_count = 0;
2214 let arg_lifetimes = inputs
2217 .skip(has_self as usize)
2219 let mut gather = GatherLifetimes {
2221 outer_index: ty::INNERMOST,
2222 have_bound_regions: false,
2223 lifetimes: Default::default(),
2225 gather.visit_ty(input);
2227 lifetime_count += gather.lifetimes.len();
2229 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2230 // there's a chance that the unique lifetime of this
2231 // iteration will be the appropriate lifetime for output
2232 // parameters, so lets store it.
2233 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2236 ElisionFailureInfo {
2239 lifetime_count: gather.lifetimes.len(),
2240 have_bound_regions: gather.have_bound_regions,
2246 let elide = if lifetime_count == 1 {
2247 Elide::Exact(possible_implied_output_region.unwrap())
2249 Elide::Error(arg_lifetimes)
2252 debug!("visit_fn_like_elision: elide={:?}", elide);
2254 let scope = Scope::Elision { elide, s: self.scope };
2255 self.with(scope, |_, this| this.visit_ty(output));
2256 debug!("visit_fn_like_elision: exit");
2258 struct GatherLifetimes<'a> {
2259 map: &'a NamedRegionMap,
2260 outer_index: ty::DebruijnIndex,
2261 have_bound_regions: bool,
2262 lifetimes: FxHashSet<Region>,
2265 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2266 type Map = intravisit::ErasedMap<'v>;
2268 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2269 NestedVisitorMap::None
2272 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2273 if let hir::TyKind::BareFn(_) = ty.kind {
2274 self.outer_index.shift_in(1);
2277 hir::TyKind::TraitObject(bounds, ref lifetime) => {
2278 for bound in bounds {
2279 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2282 // Stay on the safe side and don't include the object
2283 // lifetime default (which may not end up being used).
2284 if !lifetime.is_elided() {
2285 self.visit_lifetime(lifetime);
2289 intravisit::walk_ty(self, ty);
2292 if let hir::TyKind::BareFn(_) = ty.kind {
2293 self.outer_index.shift_out(1);
2297 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2298 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2299 // FIXME(eddyb) Do we want this? It only makes a difference
2300 // if this `for<'a>` lifetime parameter is never used.
2301 self.have_bound_regions = true;
2304 intravisit::walk_generic_param(self, param);
2307 fn visit_poly_trait_ref(
2309 trait_ref: &hir::PolyTraitRef<'_>,
2310 modifier: hir::TraitBoundModifier,
2312 self.outer_index.shift_in(1);
2313 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2314 self.outer_index.shift_out(1);
2317 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2318 if let hir::GenericBound::LangItemTrait { .. } = bound {
2319 self.outer_index.shift_in(1);
2320 intravisit::walk_param_bound(self, bound);
2321 self.outer_index.shift_out(1);
2323 intravisit::walk_param_bound(self, bound);
2327 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2328 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2330 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2331 if debruijn < self.outer_index =>
2333 self.have_bound_regions = true;
2336 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2344 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2345 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2347 if lifetime_refs.is_empty() {
2351 let span = lifetime_refs[0].span;
2352 let mut late_depth = 0;
2353 let mut scope = self.scope;
2354 let mut lifetime_names = FxHashSet::default();
2355 let mut lifetime_spans = vec![];
2358 // Do not assign any resolution, it will be inferred.
2359 Scope::Body { .. } => return,
2361 Scope::Root => break None,
2363 Scope::Binder { s, ref lifetimes, .. } => {
2364 // collect named lifetimes for suggestions
2365 for name in lifetimes.keys() {
2366 if let hir::ParamName::Plain(name) = name {
2367 lifetime_names.insert(name.name);
2368 lifetime_spans.push(name.span);
2375 Scope::Elision { ref elide, ref s, .. } => {
2376 let lifetime = match *elide {
2377 Elide::FreshLateAnon(ref counter) => {
2378 for lifetime_ref in lifetime_refs {
2379 let lifetime = Region::late_anon(counter).shifted(late_depth);
2380 self.insert_lifetime(lifetime_ref, lifetime);
2384 Elide::Exact(l) => l.shifted(late_depth),
2385 Elide::Error(ref e) => {
2389 Scope::Binder { ref lifetimes, s, .. } => {
2390 // Collect named lifetimes for suggestions.
2391 for name in lifetimes.keys() {
2392 if let hir::ParamName::Plain(name) = name {
2393 lifetime_names.insert(name.name);
2394 lifetime_spans.push(name.span);
2399 Scope::ObjectLifetimeDefault { ref s, .. }
2400 | Scope::Elision { ref s, .. } => {
2408 Elide::Forbid => break None,
2410 for lifetime_ref in lifetime_refs {
2411 self.insert_lifetime(lifetime_ref, lifetime);
2416 Scope::ObjectLifetimeDefault { s, .. } => {
2422 let mut err = self.report_missing_lifetime_specifiers(span, lifetime_refs.len());
2424 if let Some(params) = error {
2425 // If there's no lifetime available, suggest `'static`.
2426 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
2427 lifetime_names.insert(kw::StaticLifetime);
2430 self.add_missing_lifetime_specifiers_label(
2433 lifetime_refs.len(),
2436 error.map(|p| &p[..]).unwrap_or(&[]),
2441 fn report_elision_failure(
2443 db: &mut DiagnosticBuilder<'_>,
2444 params: &[ElisionFailureInfo],
2445 ) -> bool /* add `'static` lifetime to lifetime list */ {
2446 let mut m = String::new();
2447 let len = params.len();
2449 let elided_params: Vec<_> =
2450 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2452 let elided_len = elided_params.len();
2454 for (i, info) in elided_params.into_iter().enumerate() {
2455 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2458 db.span_label(span, "");
2459 let help_name = if let Some(ident) =
2460 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2462 format!("`{}`", ident)
2464 format!("argument {}", index + 1)
2472 "one of {}'s {} {}lifetimes",
2475 if have_bound_regions { "free " } else { "" }
2480 if elided_len == 2 && i == 0 {
2482 } else if i + 2 == elided_len {
2483 m.push_str(", or ");
2484 } else if i != elided_len - 1 {
2491 "this function's return type contains a borrowed value, \
2492 but there is no value for it to be borrowed from",
2495 } else if elided_len == 0 {
2497 "this function's return type contains a borrowed value with \
2498 an elided lifetime, but the lifetime cannot be derived from \
2502 } else if elided_len == 1 {
2504 "this function's return type contains a borrowed value, \
2505 but the signature does not say which {} it is borrowed from",
2511 "this function's return type contains a borrowed value, \
2512 but the signature does not say whether it is borrowed from {}",
2519 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2520 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2521 let mut late_depth = 0;
2522 let mut scope = self.scope;
2523 let lifetime = loop {
2525 Scope::Binder { s, .. } => {
2530 Scope::Root | Scope::Elision { .. } => break Region::Static,
2532 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2534 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2537 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2540 fn check_lifetime_params(
2542 old_scope: ScopeRef<'_>,
2543 params: &'tcx [hir::GenericParam<'tcx>],
2545 let lifetimes: Vec<_> = params
2547 .filter_map(|param| match param.kind {
2548 GenericParamKind::Lifetime { .. } => {
2549 Some((param, param.name.normalize_to_macros_2_0()))
2554 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2555 if let hir::ParamName::Plain(_) = lifetime_i_name {
2556 let name = lifetime_i_name.ident().name;
2557 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
2558 let mut err = struct_span_err!(
2562 "invalid lifetime parameter name: `{}`",
2563 lifetime_i.name.ident(),
2567 format!("{} is a reserved lifetime name", name),
2573 // It is a hard error to shadow a lifetime within the same scope.
2574 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2575 if lifetime_i_name == lifetime_j_name {
2580 "lifetime name `{}` declared twice in the same scope",
2581 lifetime_j.name.ident()
2583 .span_label(lifetime_j.span, "declared twice")
2584 .span_label(lifetime_i.span, "previous declaration here")
2589 // It is a soft error to shadow a lifetime within a parent scope.
2590 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2592 for bound in lifetime_i.bounds {
2594 hir::GenericBound::Outlives(ref lt) => match lt.name {
2595 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2597 "use of `'_` in illegal place, but not caught by lowering",
2599 hir::LifetimeName::Static => {
2600 self.insert_lifetime(lt, Region::Static);
2604 lifetime_i.span.to(lt.span),
2606 "unnecessary lifetime parameter `{}`",
2607 lifetime_i.name.ident(),
2611 "you can use the `'static` lifetime directly, in place of `{}`",
2612 lifetime_i.name.ident(),
2616 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2617 self.resolve_lifetime_ref(lt);
2619 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2620 self.tcx.sess.delay_span_bug(
2622 "lowering generated `ImplicitObjectLifetimeDefault` \
2623 outside of an object type",
2626 hir::LifetimeName::Error => {
2627 // No need to do anything, error already reported.
2636 fn check_lifetime_param_for_shadowing(
2638 mut old_scope: ScopeRef<'_>,
2639 param: &'tcx hir::GenericParam<'tcx>,
2641 for label in &self.labels_in_fn {
2642 // FIXME (#24278): non-hygienic comparison
2643 if param.name.ident().name == label.name {
2644 signal_shadowing_problem(
2647 original_label(label.span),
2648 shadower_lifetime(¶m),
2656 Scope::Body { s, .. }
2657 | Scope::Elision { s, .. }
2658 | Scope::ObjectLifetimeDefault { s, .. } => {
2666 Scope::Binder { ref lifetimes, s, .. } => {
2667 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
2669 self.tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
2671 signal_shadowing_problem(
2673 param.name.ident().name,
2674 original_lifetime(self.tcx.hir().span(hir_id)),
2675 shadower_lifetime(¶m),
2686 /// Returns `true` if, in the current scope, replacing `'_` would be
2687 /// equivalent to a single-use lifetime.
2688 fn track_lifetime_uses(&self) -> bool {
2689 let mut scope = self.scope;
2692 Scope::Root => break false,
2694 // Inside of items, it depends on the kind of item.
2695 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
2697 // Inside a body, `'_` will use an inference variable,
2699 Scope::Body { .. } => break true,
2701 // A lifetime only used in a fn argument could as well
2702 // be replaced with `'_`, as that would generate a
2704 Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
2706 // In the return type or other such place, `'_` is not
2707 // going to make a fresh name, so we cannot
2708 // necessarily replace a single-use lifetime with
2711 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
2714 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2719 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2721 "insert_lifetime: {} resolved to {:?} span={:?}",
2722 self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2724 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2726 self.map.defs.insert(lifetime_ref.hir_id, def);
2729 Region::LateBoundAnon(..) | Region::Static => {
2730 // These are anonymous lifetimes or lifetimes that are not declared.
2733 Region::Free(_, def_id)
2734 | Region::LateBound(_, def_id, _)
2735 | Region::EarlyBound(_, def_id, _) => {
2736 // A lifetime declared by the user.
2737 let track_lifetime_uses = self.track_lifetime_uses();
2738 debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
2739 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2740 debug!("insert_lifetime: first use of {:?}", def_id);
2741 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
2743 debug!("insert_lifetime: many uses of {:?}", def_id);
2744 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2750 /// Sometimes we resolve a lifetime, but later find that it is an
2751 /// error (esp. around impl trait). In that case, we remove the
2752 /// entry into `map.defs` so as not to confuse later code.
2753 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2754 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2755 assert_eq!(old_value, Some(bad_def));
2759 /// Detects late-bound lifetimes and inserts them into
2760 /// `map.late_bound`.
2762 /// A region declared on a fn is **late-bound** if:
2763 /// - it is constrained by an argument type;
2764 /// - it does not appear in a where-clause.
2766 /// "Constrained" basically means that it appears in any type but
2767 /// not amongst the inputs to a projection. In other words, `<&'a
2768 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2769 fn insert_late_bound_lifetimes(
2770 map: &mut NamedRegionMap,
2771 decl: &hir::FnDecl<'_>,
2772 generics: &hir::Generics<'_>,
2774 debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
2776 let mut constrained_by_input = ConstrainedCollector::default();
2777 for arg_ty in decl.inputs {
2778 constrained_by_input.visit_ty(arg_ty);
2781 let mut appears_in_output = AllCollector::default();
2782 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2784 debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
2786 // Walk the lifetimes that appear in where clauses.
2788 // Subtle point: because we disallow nested bindings, we can just
2789 // ignore binders here and scrape up all names we see.
2790 let mut appears_in_where_clause = AllCollector::default();
2791 appears_in_where_clause.visit_generics(generics);
2793 for param in generics.params {
2794 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2795 if !param.bounds.is_empty() {
2796 // `'a: 'b` means both `'a` and `'b` are referenced
2797 appears_in_where_clause
2799 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
2805 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2806 appears_in_where_clause.regions
2809 // Late bound regions are those that:
2810 // - appear in the inputs
2811 // - do not appear in the where-clauses
2812 // - are not implicitly captured by `impl Trait`
2813 for param in generics.params {
2815 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2817 // Neither types nor consts are late-bound.
2818 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2821 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
2822 // appears in the where clauses? early-bound.
2823 if appears_in_where_clause.regions.contains(<_name) {
2827 // does not appear in the inputs, but appears in the return type? early-bound.
2828 if !constrained_by_input.regions.contains(<_name)
2829 && appears_in_output.regions.contains(<_name)
2835 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2840 let inserted = map.late_bound.insert(param.hir_id);
2841 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2847 struct ConstrainedCollector {
2848 regions: FxHashSet<hir::LifetimeName>,
2851 impl<'v> Visitor<'v> for ConstrainedCollector {
2852 type Map = intravisit::ErasedMap<'v>;
2854 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2855 NestedVisitorMap::None
2858 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2861 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2863 // ignore lifetimes appearing in associated type
2864 // projections, as they are not *constrained*
2868 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2869 // consider only the lifetimes on the final
2870 // segment; I am not sure it's even currently
2871 // valid to have them elsewhere, but even if it
2872 // is, those would be potentially inputs to
2874 if let Some(last_segment) = path.segments.last() {
2875 self.visit_path_segment(path.span, last_segment);
2880 intravisit::walk_ty(self, ty);
2885 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2886 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
2891 struct AllCollector {
2892 regions: FxHashSet<hir::LifetimeName>,
2895 impl<'v> Visitor<'v> for AllCollector {
2896 type Map = intravisit::ErasedMap<'v>;
2898 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2899 NestedVisitorMap::None
2902 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2903 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());