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};
10 use rustc_ast::walk_list;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
16 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
17 use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath};
18 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::middle::resolve_lifetime::*;
21 use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
22 use rustc_middle::{bug, span_bug};
23 use rustc_session::lint;
24 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 // This counts the no of times a lifetime is used
33 #[derive(Clone, Copy, Debug)]
34 pub enum LifetimeUseSet<'tcx> {
35 One(&'tcx hir::Lifetime),
40 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
42 fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
44 fn late_anon(index: &Cell<u32>) -> Region;
46 fn id(&self) -> Option<DefId>;
48 fn shifted(self, amount: u32) -> Region;
50 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
52 fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
54 L: Iterator<Item = &'a hir::Lifetime>;
57 impl RegionExt for Region {
58 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
61 let def_id = hir_map.local_def_id(param.hir_id);
62 let origin = LifetimeDefOrigin::from_param(param);
63 debug!("Region::early: index={} def_id={:?}", i, def_id);
64 (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id(), origin))
67 fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
68 let depth = ty::INNERMOST;
69 let def_id = hir_map.local_def_id(param.hir_id);
70 let origin = LifetimeDefOrigin::from_param(param);
72 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
73 param, depth, def_id, origin,
75 (param.name.normalize_to_macros_2_0(), Region::LateBound(depth, def_id.to_def_id(), origin))
78 fn late_anon(index: &Cell<u32>) -> Region {
81 let depth = ty::INNERMOST;
82 Region::LateBoundAnon(depth, i)
85 fn id(&self) -> Option<DefId> {
87 Region::Static | Region::LateBoundAnon(..) => None,
89 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
95 fn shifted(self, amount: u32) -> Region {
97 Region::LateBound(debruijn, id, origin) => {
98 Region::LateBound(debruijn.shifted_in(amount), id, origin)
100 Region::LateBoundAnon(debruijn, index) => {
101 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
107 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
109 Region::LateBound(debruijn, id, origin) => {
110 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
112 Region::LateBoundAnon(debruijn, index) => {
113 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
119 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
121 L: Iterator<Item = &'a hir::Lifetime>,
123 if let Region::EarlyBound(index, _, _) = self {
124 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
131 /// Maps the id of each lifetime reference to the lifetime decl
132 /// that it corresponds to.
134 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
135 /// actual use. It has the same data, but indexed by `LocalDefId`. This
138 struct NamedRegionMap {
139 // maps from every use of a named (not anonymous) lifetime to a
140 // `Region` describing how that region is bound
141 defs: HirIdMap<Region>,
143 // the set of lifetime def ids that are late-bound; a region can
144 // be late-bound if (a) it does NOT appear in a where-clause and
145 // (b) it DOES appear in the arguments.
146 late_bound: HirIdSet,
148 // For each type and trait definition, maps type parameters
149 // to the trait object lifetime defaults computed from them.
150 object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
153 crate struct LifetimeContext<'a, 'tcx> {
154 crate tcx: TyCtxt<'tcx>,
155 map: &'a mut NamedRegionMap,
158 /// This is slightly complicated. Our representation for poly-trait-refs contains a single
159 /// binder and thus we only allow a single level of quantification. However,
160 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
161 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
162 /// correct when representing these constraints, we should only introduce one
163 /// scope. However, we want to support both locations for the quantifier and
164 /// during lifetime resolution we want precise information (so we can't
165 /// desugar in an earlier phase).
167 /// So, if we encounter a quantifier at the outer scope, we set
168 /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
169 /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
170 /// then we introduce the scope at the inner quantifier.
171 trait_ref_hack: bool,
173 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
174 is_in_fn_syntax: bool,
176 is_in_const_generic: bool,
178 /// List of labels in the function/method currently under analysis.
179 labels_in_fn: Vec<Ident>,
181 /// Cache for cross-crate per-definition object lifetime defaults.
182 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
184 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
186 /// When encountering an undefined named lifetime, we will suggest introducing it in these
188 crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
193 /// Declares lifetimes, and each can be early-bound or late-bound.
194 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
195 /// it should be shifted by the number of `Binder`s in between the
196 /// declaration `Binder` and the location it's referenced from.
198 lifetimes: FxHashMap<hir::ParamName, Region>,
200 /// if we extend this scope with another scope, what is the next index
201 /// we should use for an early-bound region?
202 next_early_index: u32,
204 /// Flag is set to true if, in this binder, `'_` would be
205 /// equivalent to a "single-use region". This is true on
206 /// impls, but not other kinds of items.
207 track_lifetime_uses: bool,
209 /// Whether or not this binder would serve as the parent
210 /// binder for opaque types introduced within. For example:
213 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
216 /// Here, the opaque types we create for the `impl Trait`
217 /// and `impl Trait2` references will both have the `foo` item
218 /// as their parent. When we get to `impl Trait2`, we find
219 /// that it is nested within the `for<>` binder -- this flag
220 /// allows us to skip that when looking for the parent binder
221 /// of the resulting opaque type.
222 opaque_type_parent: bool,
227 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
228 /// if this is a fn body, otherwise the original definitions are used.
229 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
230 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
236 /// A scope which either determines unspecified lifetimes or errors
237 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
243 /// Use a specific lifetime (if `Some`) or leave it unset (to be
244 /// inferred in a function body or potentially error outside one),
245 /// for the default choice of lifetime in a trait object type.
246 ObjectLifetimeDefault {
247 lifetime: Option<Region>,
254 #[derive(Clone, Debug)]
256 /// Use a fresh anonymous late-bound lifetime each time, by
257 /// incrementing the counter to generate sequential indices.
258 FreshLateAnon(Cell<u32>),
259 /// Always use this one lifetime.
261 /// Less or more than one lifetime were found, error on unspecified.
262 Error(Vec<ElisionFailureInfo>),
263 /// Forbid lifetime elision inside of a larger scope where it would be
264 /// permitted. For example, in let position impl trait.
268 #[derive(Clone, Debug)]
269 crate 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,
279 type ScopeRef<'a> = &'a Scope<'a>;
281 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
283 pub fn provide(providers: &mut ty::query::Providers) {
284 *providers = ty::query::Providers {
287 named_region_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id),
288 is_late_bound_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&id),
289 object_lifetime_defaults_map: |tcx, id| {
290 tcx.resolve_lifetimes(LOCAL_CRATE).object_lifetime_defaults.get(&id)
297 /// Computes the `ResolveLifetimes` map that contains data for the
298 /// entire crate. You should not read the result of this query
299 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
301 fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> ResolveLifetimes {
302 assert_eq!(for_krate, LOCAL_CRATE);
304 let named_region_map = krate(tcx);
306 let mut rl = ResolveLifetimes::default();
308 for (hir_id, v) in named_region_map.defs {
309 let map = rl.defs.entry(hir_id.owner).or_default();
310 map.insert(hir_id.local_id, v);
312 for hir_id in named_region_map.late_bound {
313 let map = rl.late_bound.entry(hir_id.owner).or_default();
314 map.insert(hir_id.local_id);
316 for (hir_id, v) in named_region_map.object_lifetime_defaults {
317 let map = rl.object_lifetime_defaults.entry(hir_id.owner).or_default();
318 map.insert(hir_id.local_id, v);
324 fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap {
325 let krate = tcx.hir().krate();
326 let mut map = NamedRegionMap {
327 defs: Default::default(),
328 late_bound: Default::default(),
329 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
332 let mut visitor = LifetimeContext {
336 trait_ref_hack: false,
337 is_in_fn_syntax: false,
338 is_in_const_generic: false,
339 labels_in_fn: vec![],
340 xcrate_object_lifetime_defaults: Default::default(),
341 lifetime_uses: &mut Default::default(),
342 missing_named_lifetime_spots: vec![],
344 for item in krate.items.values() {
345 visitor.visit_item(item);
351 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
352 /// We have to account for this when computing the index of the other generic parameters.
353 /// This function returns whether there is such an implicit parameter defined on the given item.
354 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
356 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true,
361 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
362 type Map = Map<'tcx>;
364 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
365 NestedVisitorMap::All(self.tcx.hir())
368 // We want to nest trait/impl items in their parent, but nothing else.
369 fn visit_nested_item(&mut self, _: hir::ItemId) {}
371 fn visit_nested_body(&mut self, body: hir::BodyId) {
372 // Each body has their own set of labels, save labels.
373 let saved = take(&mut self.labels_in_fn);
374 let body = self.tcx.hir().body(body);
375 extract_labels(self, body);
376 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
377 this.visit_body(body);
379 self.labels_in_fn = saved;
382 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
384 hir::ItemKind::Fn(ref sig, ref generics, _) => {
385 self.missing_named_lifetime_spots.push(generics.into());
386 self.visit_early_late(None, &sig.decl, generics, |this| {
387 intravisit::walk_item(this, item);
389 self.missing_named_lifetime_spots.pop();
392 hir::ItemKind::ExternCrate(_)
393 | hir::ItemKind::Use(..)
394 | hir::ItemKind::Mod(..)
395 | hir::ItemKind::ForeignMod(..)
396 | hir::ItemKind::GlobalAsm(..) => {
397 // These sorts of items have no lifetime parameters at all.
398 intravisit::walk_item(self, item);
400 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
401 // No lifetime parameters, but implied 'static.
402 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
403 self.with(scope, |_, this| intravisit::walk_item(this, item));
405 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
406 // Opaque types are visited when we visit the
407 // `TyKind::OpaqueDef`, so that they have the lifetimes from
408 // their parent opaque_ty in scope.
410 hir::ItemKind::TyAlias(_, ref generics)
411 | hir::ItemKind::Enum(_, ref generics)
412 | hir::ItemKind::Struct(_, ref generics)
413 | hir::ItemKind::Union(_, ref generics)
414 | hir::ItemKind::Trait(_, _, ref generics, ..)
415 | hir::ItemKind::TraitAlias(ref generics, ..)
416 | hir::ItemKind::Impl { ref generics, .. } => {
417 self.missing_named_lifetime_spots.push(generics.into());
419 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
420 // This is not true for other kinds of items.x
421 let track_lifetime_uses = match item.kind {
422 hir::ItemKind::Impl { .. } => true,
425 // These kinds of items have only early-bound lifetime parameters.
426 let mut index = if sub_items_have_self_param(&item.kind) {
427 1 // Self comes before lifetimes
431 let mut non_lifetime_count = 0;
432 let lifetimes = generics
435 .filter_map(|param| match param.kind {
436 GenericParamKind::Lifetime { .. } => {
437 Some(Region::early(&self.tcx.hir(), &mut index, param))
439 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
440 non_lifetime_count += 1;
445 let scope = Scope::Binder {
447 next_early_index: index + non_lifetime_count,
448 opaque_type_parent: true,
452 self.with(scope, |old_scope, this| {
453 this.check_lifetime_params(old_scope, &generics.params);
454 intravisit::walk_item(this, item);
456 self.missing_named_lifetime_spots.pop();
461 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
463 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
464 self.visit_early_late(None, decl, generics, |this| {
465 intravisit::walk_foreign_item(this, item);
468 hir::ForeignItemKind::Static(..) => {
469 intravisit::walk_foreign_item(self, item);
471 hir::ForeignItemKind::Type => {
472 intravisit::walk_foreign_item(self, item);
477 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
478 debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
479 debug!("visit_ty: ty.kind={:?}", ty.kind);
481 hir::TyKind::BareFn(ref c) => {
482 let next_early_index = self.next_early_index();
483 let was_in_fn_syntax = self.is_in_fn_syntax;
484 self.is_in_fn_syntax = true;
485 let lifetime_span: Option<Span> =
486 c.generic_params.iter().rev().find_map(|param| match param.kind {
487 GenericParamKind::Lifetime { .. } => Some(param.span),
490 let (span, span_type) = if let Some(span) = lifetime_span {
491 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
493 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
495 self.missing_named_lifetime_spots
496 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
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.missing_named_lifetime_spots.pop();
520 self.is_in_fn_syntax = was_in_fn_syntax;
522 hir::TyKind::TraitObject(bounds, ref lifetime) => {
523 debug!("visit_ty: TraitObject(bounds={:?}, lifetime={:?})", bounds, lifetime);
524 for bound in bounds {
525 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
527 match lifetime.name {
528 LifetimeName::Implicit => {
529 // For types like `dyn Foo`, we should
530 // generate a special form of elided.
531 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
533 LifetimeName::ImplicitObjectLifetimeDefault => {
534 // If the user does not write *anything*, we
535 // use the object lifetime defaulting
536 // rules. So e.g., `Box<dyn Debug>` becomes
537 // `Box<dyn Debug + 'static>`.
538 self.resolve_object_lifetime_default(lifetime)
540 LifetimeName::Underscore => {
541 // If the user writes `'_`, we use the *ordinary* elision
542 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
543 // resolved the same as the `'_` in `&'_ Foo`.
546 self.resolve_elided_lifetimes(vec![lifetime])
548 LifetimeName::Param(_) | LifetimeName::Static => {
549 // If the user wrote an explicit name, use that.
550 self.visit_lifetime(lifetime);
552 LifetimeName::Error => {}
555 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
556 self.visit_lifetime(lifetime_ref);
557 let scope = Scope::ObjectLifetimeDefault {
558 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
561 self.with(scope, |_, this| this.visit_ty(&mt.ty));
563 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
564 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
565 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
566 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
567 // ^ ^ this gets resolved in the scope of
568 // the opaque_ty generics
569 let opaque_ty = self.tcx.hir().expect_item(item_id.id);
570 let (generics, bounds) = match opaque_ty.kind {
571 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
572 // This arm is for `impl Trait` in the types of statics, constants and locals.
573 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
574 intravisit::walk_ty(self, ty);
576 // Elided lifetimes are not allowed in non-return
577 // position impl Trait
578 let scope = Scope::Elision { elide: Elide::Forbid, s: self.scope };
579 self.with(scope, |_, this| {
580 intravisit::walk_item(this, opaque_ty);
585 // RPIT (return position impl trait)
586 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
587 impl_trait_fn: Some(_),
591 }) => (generics, bounds),
592 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
595 // Resolve the lifetimes that are applied to the opaque type.
596 // These are resolved in the current scope.
597 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
598 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
599 // ^ ^this gets resolved in the current scope
600 for lifetime in lifetimes {
601 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
602 self.visit_lifetime(lifetime);
604 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
605 // and ban them. Type variables instantiated inside binders aren't
606 // well-supported at the moment, so this doesn't work.
607 // In the future, this should be fixed and this error should be removed.
608 let def = self.map.defs.get(&lifetime.hir_id).cloned();
609 if let Some(Region::LateBound(_, def_id, _)) = def {
610 if let Some(def_id) = def_id.as_local() {
611 let hir_id = self.tcx.hir().as_local_hir_id(def_id);
612 // Ensure that the parent of the def is an item, not HRTB
613 let parent_id = self.tcx.hir().get_parent_node(hir_id);
614 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
615 let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
616 let krate = self.tcx.hir().krate();
618 if !(krate.items.contains_key(&parent_id)
619 || krate.impl_items.contains_key(&parent_impl_id)
620 || krate.trait_items.contains_key(&parent_trait_id))
626 "`impl Trait` can only capture lifetimes \
627 bound at the fn or impl level"
630 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
637 // We want to start our early-bound indices at the end of the parent scope,
638 // not including any parent `impl Trait`s.
639 let mut index = self.next_early_index_for_opaque_type();
640 debug!("visit_ty: index = {}", index);
642 let mut elision = None;
643 let mut lifetimes = FxHashMap::default();
644 let mut non_lifetime_count = 0;
645 for param in generics.params {
647 GenericParamKind::Lifetime { .. } => {
648 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
649 let def_id = if let Region::EarlyBound(_, def_id, _) = reg {
654 if let hir::ParamName::Plain(param_name) = name {
655 if param_name.name == kw::UnderscoreLifetime {
656 // Pick the elided lifetime "definition" if one exists
657 // and use it to make an elision scope.
658 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
661 lifetimes.insert(name, reg);
664 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
665 lifetimes.insert(name, reg);
668 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
669 non_lifetime_count += 1;
673 let next_early_index = index + non_lifetime_count;
675 if let Some(elision_region) = elision {
677 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
678 self.with(scope, |_old_scope, this| {
679 let scope = Scope::Binder {
683 track_lifetime_uses: true,
684 opaque_type_parent: false,
686 this.with(scope, |_old_scope, this| {
687 this.visit_generics(generics);
688 for bound in bounds {
689 this.visit_param_bound(bound);
694 let scope = Scope::Binder {
698 track_lifetime_uses: true,
699 opaque_type_parent: false,
701 self.with(scope, |_old_scope, this| {
702 this.visit_generics(generics);
703 for bound in bounds {
704 this.visit_param_bound(bound);
709 _ => intravisit::walk_ty(self, ty),
713 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
714 use self::hir::TraitItemKind::*;
715 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
716 match trait_item.kind {
719 self.visit_early_late(
720 Some(tcx.hir().get_parent_item(trait_item.hir_id)),
722 &trait_item.generics,
723 |this| intravisit::walk_trait_item(this, trait_item),
726 Type(bounds, ref ty) => {
727 let generics = &trait_item.generics;
728 let mut index = self.next_early_index();
729 debug!("visit_ty: index = {}", index);
730 let mut non_lifetime_count = 0;
731 let lifetimes = generics
734 .filter_map(|param| match param.kind {
735 GenericParamKind::Lifetime { .. } => {
736 Some(Region::early(&self.tcx.hir(), &mut index, param))
738 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
739 non_lifetime_count += 1;
744 let scope = Scope::Binder {
746 next_early_index: index + non_lifetime_count,
748 track_lifetime_uses: true,
749 opaque_type_parent: true,
751 self.with(scope, |old_scope, this| {
752 this.check_lifetime_params(old_scope, &generics.params);
753 this.visit_generics(generics);
754 for bound in bounds {
755 this.visit_param_bound(bound);
757 if let Some(ty) = ty {
763 // Only methods and types support generics.
764 assert!(trait_item.generics.params.is_empty());
765 intravisit::walk_trait_item(self, trait_item);
768 self.missing_named_lifetime_spots.pop();
771 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
772 use self::hir::ImplItemKind::*;
773 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
774 match impl_item.kind {
777 self.visit_early_late(
778 Some(tcx.hir().get_parent_item(impl_item.hir_id)),
781 |this| intravisit::walk_impl_item(this, impl_item),
785 let generics = &impl_item.generics;
786 let mut index = self.next_early_index();
787 let mut non_lifetime_count = 0;
788 debug!("visit_ty: index = {}", index);
789 let lifetimes = generics
792 .filter_map(|param| match param.kind {
793 GenericParamKind::Lifetime { .. } => {
794 Some(Region::early(&self.tcx.hir(), &mut index, param))
796 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
797 non_lifetime_count += 1;
802 let scope = Scope::Binder {
804 next_early_index: index + non_lifetime_count,
806 track_lifetime_uses: true,
807 opaque_type_parent: true,
809 self.with(scope, |old_scope, this| {
810 this.check_lifetime_params(old_scope, &generics.params);
811 this.visit_generics(generics);
816 // Only methods and types support generics.
817 assert!(impl_item.generics.params.is_empty());
818 intravisit::walk_impl_item(self, impl_item);
821 self.missing_named_lifetime_spots.pop();
824 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
825 debug!("visit_lifetime(lifetime_ref={:?})", lifetime_ref);
826 if lifetime_ref.is_elided() {
827 self.resolve_elided_lifetimes(vec![lifetime_ref]);
830 if lifetime_ref.is_static() {
831 self.insert_lifetime(lifetime_ref, Region::Static);
834 if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
835 self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
838 self.resolve_lifetime_ref(lifetime_ref);
841 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
842 for (i, segment) in path.segments.iter().enumerate() {
843 let depth = path.segments.len() - i - 1;
844 if let Some(ref args) = segment.args {
845 self.visit_segment_args(path.res, depth, args);
850 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
851 let output = match fd.output {
852 hir::FnRetTy::DefaultReturn(_) => None,
853 hir::FnRetTy::Return(ref ty) => Some(&**ty),
855 self.visit_fn_like_elision(&fd.inputs, output);
858 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
859 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
860 for param in generics.params {
862 GenericParamKind::Lifetime { .. } => {}
863 GenericParamKind::Type { ref default, .. } => {
864 walk_list!(self, visit_param_bound, param.bounds);
865 if let Some(ref ty) = default {
869 GenericParamKind::Const { ref ty, .. } => {
870 let was_in_const_generic = self.is_in_const_generic;
871 self.is_in_const_generic = true;
872 walk_list!(self, visit_param_bound, param.bounds);
874 self.is_in_const_generic = was_in_const_generic;
878 for predicate in generics.where_clause.predicates {
880 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
883 ref bound_generic_params,
886 let lifetimes: FxHashMap<_, _> = bound_generic_params
888 .filter_map(|param| match param.kind {
889 GenericParamKind::Lifetime { .. } => {
890 Some(Region::late(&self.tcx.hir(), param))
895 if !lifetimes.is_empty() {
896 let next_early_index = self.next_early_index();
897 let scope = Scope::Binder {
901 track_lifetime_uses: true,
902 opaque_type_parent: false,
904 let result = self.with(scope, |old_scope, this| {
905 this.check_lifetime_params(old_scope, &bound_generic_params);
906 this.visit_ty(&bounded_ty);
907 this.trait_ref_hack = true;
908 walk_list!(this, visit_param_bound, bounds);
909 this.trait_ref_hack = false;
913 self.visit_ty(&bounded_ty);
914 walk_list!(self, visit_param_bound, bounds);
917 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
922 self.visit_lifetime(lifetime);
923 walk_list!(self, visit_param_bound, bounds);
925 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
930 self.visit_ty(lhs_ty);
931 self.visit_ty(rhs_ty);
937 fn visit_poly_trait_ref(
939 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
940 _modifier: hir::TraitBoundModifier,
942 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
944 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
946 let trait_ref_hack = take(&mut self.trait_ref_hack);
948 || trait_ref.bound_generic_params.iter().any(|param| match param.kind {
949 GenericParamKind::Lifetime { .. } => true,
958 "nested quantification of lifetimes"
962 let next_early_index = self.next_early_index();
963 let scope = Scope::Binder {
965 .bound_generic_params
967 .filter_map(|param| match param.kind {
968 GenericParamKind::Lifetime { .. } => {
969 Some(Region::late(&self.tcx.hir(), param))
976 track_lifetime_uses: true,
977 opaque_type_parent: false,
979 self.with(scope, |old_scope, this| {
980 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
981 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
982 this.visit_trait_ref(&trait_ref.trait_ref);
985 self.visit_trait_ref(&trait_ref.trait_ref);
987 self.trait_ref_hack = trait_ref_hack;
988 if should_pop_missing_lt {
989 self.missing_named_lifetime_spots.pop();
994 #[derive(Copy, Clone, PartialEq)]
1008 fn original_label(span: Span) -> Original {
1009 Original { kind: ShadowKind::Label, span }
1011 fn shadower_label(span: Span) -> Shadower {
1012 Shadower { kind: ShadowKind::Label, span }
1014 fn original_lifetime(span: Span) -> Original {
1015 Original { kind: ShadowKind::Lifetime, span }
1017 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1018 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1022 fn desc(&self) -> &'static str {
1024 ShadowKind::Label => "label",
1025 ShadowKind::Lifetime => "lifetime",
1030 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1031 let lifetime_params: Vec<_> = params
1033 .filter_map(|param| match param.kind {
1034 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1038 let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1039 let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1041 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1046 "cannot mix in-band and explicit lifetime definitions"
1048 .span_label(*in_band_span, "in-band lifetime definition here")
1049 .span_label(*explicit_span, "explicit lifetime definition here")
1054 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1055 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1056 // lifetime/lifetime shadowing is an error
1061 "{} name `{}` shadows a \
1062 {} name that is already in scope",
1063 shadower.kind.desc(),
1068 // shadowing involving a label is only a warning, due to issues with
1069 // labels and lifetimes not being macro-hygienic.
1070 tcx.sess.struct_span_warn(
1073 "{} name `{}` shadows a \
1074 {} name that is already in scope",
1075 shadower.kind.desc(),
1081 err.span_label(orig.span, "first declared here");
1082 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1086 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1087 // if one of the label shadows a lifetime or another label.
1088 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1089 struct GatherLabels<'a, 'tcx> {
1091 scope: ScopeRef<'a>,
1092 labels_in_fn: &'a mut Vec<Ident>,
1096 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1097 gather.visit_body(body);
1099 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1100 type Map = intravisit::ErasedMap<'v>;
1102 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1103 NestedVisitorMap::None
1106 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1107 if let Some(label) = expression_label(ex) {
1108 for prior_label in &self.labels_in_fn[..] {
1109 // FIXME (#24278): non-hygienic comparison
1110 if label.name == prior_label.name {
1111 signal_shadowing_problem(
1114 original_label(prior_label.span),
1115 shadower_label(label.span),
1120 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1122 self.labels_in_fn.push(label);
1124 intravisit::walk_expr(self, ex)
1128 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1129 if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { Some(label.ident) } else { None }
1132 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1135 Scope::Body { s, .. }
1136 | Scope::Elision { s, .. }
1137 | Scope::ObjectLifetimeDefault { s, .. } => {
1145 Scope::Binder { ref lifetimes, s, .. } => {
1146 // FIXME (#24278): non-hygienic comparison
1148 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1150 let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap().expect_local());
1152 signal_shadowing_problem(
1155 original_lifetime(tcx.hir().span(hir_id)),
1156 shadower_label(label.span),
1167 fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
1168 let mut map = HirIdMap::default();
1169 for item in tcx.hir().krate().items.values() {
1171 hir::ItemKind::Struct(_, ref generics)
1172 | hir::ItemKind::Union(_, ref generics)
1173 | hir::ItemKind::Enum(_, ref generics)
1174 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1175 ref generics, impl_trait_fn: None, ..
1177 | hir::ItemKind::TyAlias(_, ref generics)
1178 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1179 let result = object_lifetime_defaults_for_item(tcx, generics);
1182 if attr::contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
1183 let object_lifetime_default_reprs: String = result
1185 .map(|set| match *set {
1186 Set1::Empty => "BaseDefault".into(),
1187 Set1::One(Region::Static) => "'static".into(),
1188 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1191 .find_map(|param| match param.kind {
1192 GenericParamKind::Lifetime { .. } => {
1194 return Some(param.name.ident().to_string().into());
1202 Set1::One(_) => bug!(),
1203 Set1::Many => "Ambiguous".into(),
1205 .collect::<Vec<Cow<'static, str>>>()
1207 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1210 map.insert(item.hir_id, result);
1218 /// Scan the bounds and where-clauses on parameters to extract bounds
1219 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1220 /// for each type parameter.
1221 fn object_lifetime_defaults_for_item(
1223 generics: &hir::Generics<'_>,
1224 ) -> Vec<ObjectLifetimeDefault> {
1225 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1226 for bound in bounds {
1227 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1228 set.insert(lifetime.name.normalize_to_macros_2_0());
1236 .filter_map(|param| match param.kind {
1237 GenericParamKind::Lifetime { .. } => None,
1238 GenericParamKind::Type { .. } => {
1239 let mut set = Set1::Empty;
1241 add_bounds(&mut set, ¶m.bounds);
1243 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1244 for predicate in generics.where_clause.predicates {
1245 // Look for `type: ...` where clauses.
1246 let data = match *predicate {
1247 hir::WherePredicate::BoundPredicate(ref data) => data,
1251 // Ignore `for<'a> type: ...` as they can change what
1252 // lifetimes mean (although we could "just" handle it).
1253 if !data.bound_generic_params.is_empty() {
1257 let res = match data.bounded_ty.kind {
1258 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1262 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1263 add_bounds(&mut set, &data.bounds);
1268 Set1::Empty => Set1::Empty,
1269 Set1::One(name) => {
1270 if name == hir::LifetimeName::Static {
1271 Set1::One(Region::Static)
1276 .filter_map(|param| match param.kind {
1277 GenericParamKind::Lifetime { .. } => Some((
1279 hir::LifetimeName::Param(param.name),
1280 LifetimeDefOrigin::from_param(param),
1285 .find(|&(_, (_, lt_name, _))| lt_name == name)
1286 .map_or(Set1::Many, |(i, (id, _, origin))| {
1287 let def_id = tcx.hir().local_def_id(id);
1288 Set1::One(Region::EarlyBound(
1296 Set1::Many => Set1::Many,
1299 GenericParamKind::Const { .. } => {
1300 // Generic consts don't impose any constraints.
1307 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1308 // FIXME(#37666) this works around a limitation in the region inferencer
1309 fn hack<F>(&mut self, f: F)
1311 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1316 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1318 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1320 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1321 let labels_in_fn = take(&mut self.labels_in_fn);
1322 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1323 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1324 let mut this = LifetimeContext {
1328 trait_ref_hack: self.trait_ref_hack,
1329 is_in_fn_syntax: self.is_in_fn_syntax,
1330 is_in_const_generic: self.is_in_const_generic,
1332 xcrate_object_lifetime_defaults,
1334 missing_named_lifetime_spots,
1336 debug!("entering scope {:?}", this.scope);
1337 f(self.scope, &mut this);
1338 this.check_uses_for_lifetimes_defined_by_scope();
1339 debug!("exiting scope {:?}", this.scope);
1340 self.labels_in_fn = this.labels_in_fn;
1341 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1342 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1345 /// helper method to determine the span to remove when suggesting the
1346 /// deletion of a lifetime
1347 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1348 generics.params.iter().enumerate().find_map(|(i, param)| {
1349 if param.name.ident() == name {
1350 let mut in_band = false;
1351 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1352 if let hir::LifetimeParamKind::InBand = kind {
1359 if generics.params.len() == 1 {
1360 // if sole lifetime, remove the entire `<>` brackets
1363 // if removing within `<>` brackets, we also want to
1364 // delete a leading or trailing comma as appropriate
1365 if i >= generics.params.len() - 1 {
1366 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1368 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1378 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1379 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1380 fn suggest_eliding_single_use_lifetime(
1382 err: &mut DiagnosticBuilder<'_>,
1384 lifetime: &hir::Lifetime,
1386 let name = lifetime.name.ident();
1387 let mut remove_decl = None;
1388 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1389 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1390 remove_decl = self.lifetime_deletion_span(name, generics);
1394 let mut remove_use = None;
1395 let mut elide_use = None;
1396 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1397 for input in inputs {
1399 hir::TyKind::Rptr(lt, _) => {
1400 if lt.name.ident() == name {
1401 // include the trailing whitespace between the lifetime and type names
1402 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1407 .span_until_non_whitespace(lt_through_ty_span),
1412 hir::TyKind::Path(ref qpath) => {
1413 if let QPath::Resolved(_, path) = qpath {
1414 let last_segment = &path.segments[path.segments.len() - 1];
1415 let generics = last_segment.generic_args();
1416 for arg in generics.args.iter() {
1417 if let GenericArg::Lifetime(lt) = arg {
1418 if lt.name.ident() == name {
1419 elide_use = Some(lt.span);
1431 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1432 if let Some(parent) =
1433 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1436 Node::Item(item) => {
1437 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1438 find_arg_use_span(sig.decl.inputs);
1441 Node::ImplItem(impl_item) => {
1442 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1443 find_arg_use_span(sig.decl.inputs);
1451 let msg = "elide the single-use lifetime";
1452 match (remove_decl, remove_use, elide_use) {
1453 (Some(decl_span), Some(use_span), None) => {
1454 // if both declaration and use deletion spans start at the same
1455 // place ("start at" because the latter includes trailing
1456 // whitespace), then this is an in-band lifetime
1457 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1458 err.span_suggestion(
1462 Applicability::MachineApplicable,
1465 err.multipart_suggestion(
1467 vec![(decl_span, String::new()), (use_span, String::new())],
1468 Applicability::MachineApplicable,
1472 (Some(decl_span), None, Some(use_span)) => {
1473 err.multipart_suggestion(
1475 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1476 Applicability::MachineApplicable,
1483 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1484 let defined_by = match self.scope {
1485 Scope::Binder { lifetimes, .. } => lifetimes,
1487 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1492 let mut def_ids: Vec<_> = defined_by
1494 .flat_map(|region| match region {
1495 Region::EarlyBound(_, def_id, _)
1496 | Region::LateBound(_, def_id, _)
1497 | Region::Free(_, def_id) => Some(*def_id),
1499 Region::LateBoundAnon(..) | Region::Static => None,
1503 // ensure that we issue lints in a repeatable order
1504 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1506 for def_id in def_ids {
1507 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1509 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1512 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1516 match lifetimeuseset {
1517 Some(LifetimeUseSet::One(lifetime)) => {
1518 let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1519 debug!("hir id first={:?}", hir_id);
1520 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1521 Node::Lifetime(hir_lifetime) => Some((
1522 hir_lifetime.hir_id,
1524 hir_lifetime.name.ident(),
1526 Node::GenericParam(param) => {
1527 Some((param.hir_id, param.span, param.name.ident()))
1531 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1532 if name.name == kw::UnderscoreLifetime {
1536 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1537 if let Some(def_id) = parent_def_id.as_local() {
1538 let parent_hir_id = self.tcx.hir().as_local_hir_id(def_id);
1539 // lifetimes in `derive` expansions don't count (Issue #53738)
1543 .attrs(parent_hir_id)
1545 .any(|attr| attr.check_name(sym::automatically_derived))
1552 self.tcx.struct_span_lint_hir(
1553 lint::builtin::SINGLE_USE_LIFETIMES,
1557 let mut err = lint.build(&format!(
1558 "lifetime parameter `{}` only used once",
1561 if span == lifetime.span {
1562 // spans are the same for in-band lifetime declarations
1563 err.span_label(span, "this lifetime is only used here");
1565 err.span_label(span, "this lifetime...");
1566 err.span_label(lifetime.span, "...is used only here");
1568 self.suggest_eliding_single_use_lifetime(
1569 &mut err, def_id, lifetime,
1576 Some(LifetimeUseSet::Many) => {
1577 debug!("not one use lifetime");
1580 let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1581 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1582 Node::Lifetime(hir_lifetime) => Some((
1583 hir_lifetime.hir_id,
1585 hir_lifetime.name.ident(),
1587 Node::GenericParam(param) => {
1588 Some((param.hir_id, param.span, param.name.ident()))
1592 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1593 self.tcx.struct_span_lint_hir(
1594 lint::builtin::UNUSED_LIFETIMES,
1599 .build(&format!("lifetime parameter `{}` never used", name));
1600 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1601 if let Some(generics) =
1602 self.tcx.hir().get_generics(parent_def_id)
1604 let unused_lt_span =
1605 self.lifetime_deletion_span(name, generics);
1606 if let Some(span) = unused_lt_span {
1607 err.span_suggestion(
1609 "elide the unused lifetime",
1611 Applicability::MachineApplicable,
1625 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1627 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1628 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1629 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1633 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1635 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1636 /// lifetimes may be interspersed together.
1638 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1639 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1640 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1641 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1642 /// ordering is not important there.
1643 fn visit_early_late<F>(
1645 parent_id: Option<hir::HirId>,
1646 decl: &'tcx hir::FnDecl<'tcx>,
1647 generics: &'tcx hir::Generics<'tcx>,
1650 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1652 insert_late_bound_lifetimes(self.map, decl, generics);
1654 // Find the start of nested early scopes, e.g., in methods.
1656 if let Some(parent_id) = parent_id {
1657 let parent = self.tcx.hir().expect_item(parent_id);
1658 if sub_items_have_self_param(&parent.kind) {
1659 index += 1; // Self comes before lifetimes
1662 hir::ItemKind::Trait(_, _, ref generics, ..)
1663 | hir::ItemKind::Impl { ref generics, .. } => {
1664 index += generics.params.len() as u32;
1670 let mut non_lifetime_count = 0;
1671 let lifetimes = generics
1674 .filter_map(|param| match param.kind {
1675 GenericParamKind::Lifetime { .. } => {
1676 if self.map.late_bound.contains(¶m.hir_id) {
1677 Some(Region::late(&self.tcx.hir(), param))
1679 Some(Region::early(&self.tcx.hir(), &mut index, param))
1682 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1683 non_lifetime_count += 1;
1688 let next_early_index = index + non_lifetime_count;
1690 let scope = Scope::Binder {
1694 opaque_type_parent: true,
1695 track_lifetime_uses: false,
1697 self.with(scope, move |old_scope, this| {
1698 this.check_lifetime_params(old_scope, &generics.params);
1699 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1703 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1704 let mut scope = self.scope;
1707 Scope::Root => return 0,
1709 Scope::Binder { next_early_index, opaque_type_parent, .. }
1710 if (!only_opaque_type_parent || opaque_type_parent) =>
1712 return next_early_index;
1715 Scope::Binder { s, .. }
1716 | Scope::Body { s, .. }
1717 | Scope::Elision { s, .. }
1718 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1723 /// Returns the next index one would use for an early-bound-region
1724 /// if extending the current scope.
1725 fn next_early_index(&self) -> u32 {
1726 self.next_early_index_helper(true)
1729 /// Returns the next index one would use for an `impl Trait` that
1730 /// is being converted into an opaque type alias `impl Trait`. This will be the
1731 /// next early index from the enclosing item, for the most
1732 /// part. See the `opaque_type_parent` field for more info.
1733 fn next_early_index_for_opaque_type(&self) -> u32 {
1734 self.next_early_index_helper(false)
1737 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1738 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1740 // If we've already reported an error, just ignore `lifetime_ref`.
1741 if let LifetimeName::Error = lifetime_ref.name {
1745 // Walk up the scope chain, tracking the number of fn scopes
1746 // that we pass through, until we find a lifetime with the
1747 // given name or we run out of scopes.
1749 let mut late_depth = 0;
1750 let mut scope = self.scope;
1751 let mut outermost_body = None;
1754 Scope::Body { id, s } => {
1755 outermost_body = Some(id);
1763 Scope::Binder { ref lifetimes, s, .. } => {
1764 match lifetime_ref.name {
1765 LifetimeName::Param(param_name) => {
1766 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
1768 break Some(def.shifted(late_depth));
1771 _ => bug!("expected LifetimeName::Param"),
1778 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1784 if let Some(mut def) = result {
1785 if let Region::EarlyBound(..) = def {
1786 // Do not free early-bound regions, only late-bound ones.
1787 } else if let Some(body_id) = outermost_body {
1788 let fn_id = self.tcx.hir().body_owner(body_id);
1789 match self.tcx.hir().get(fn_id) {
1790 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1791 | Node::TraitItem(&hir::TraitItem {
1792 kind: hir::TraitItemKind::Fn(..), ..
1794 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
1795 let scope = self.tcx.hir().local_def_id(fn_id);
1796 def = Region::Free(scope.to_def_id(), def.id().unwrap());
1802 // Check for fn-syntax conflicts with in-band lifetime definitions
1803 if self.is_in_fn_syntax {
1805 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1806 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1811 "lifetimes used in `fn` or `Fn` syntax must be \
1812 explicitly declared using `<...>` binders"
1814 .span_label(lifetime_ref.span, "in-band lifetime definition")
1819 | Region::EarlyBound(
1822 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1824 | Region::LateBound(
1827 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1829 | Region::LateBoundAnon(..)
1830 | Region::Free(..) => {}
1834 self.insert_lifetime(lifetime_ref, def);
1836 self.emit_undeclared_lifetime_error(lifetime_ref);
1840 fn visit_segment_args(
1844 generic_args: &'tcx hir::GenericArgs<'tcx>,
1847 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1848 res, depth, generic_args,
1851 if generic_args.parenthesized {
1852 let was_in_fn_syntax = self.is_in_fn_syntax;
1853 self.is_in_fn_syntax = true;
1854 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1855 self.is_in_fn_syntax = was_in_fn_syntax;
1859 let mut elide_lifetimes = true;
1860 let lifetimes = generic_args
1863 .filter_map(|arg| match arg {
1864 hir::GenericArg::Lifetime(lt) => {
1865 if !lt.is_elided() {
1866 elide_lifetimes = false;
1873 if elide_lifetimes {
1874 self.resolve_elided_lifetimes(lifetimes);
1876 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1879 // Figure out if this is a type/trait segment,
1880 // which requires object lifetime defaults.
1881 let parent_def_id = |this: &mut Self, def_id: DefId| {
1882 let def_key = this.tcx.def_key(def_id);
1883 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1885 let type_def_id = match res {
1886 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1887 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1895 ) if depth == 0 => Some(def_id),
1899 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1901 // Compute a vector of defaults, one for each type parameter,
1902 // per the rules given in RFCs 599 and 1156. Example:
1905 // struct Foo<'a, T: 'a, U> { }
1908 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1909 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1910 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1913 // Therefore, we would compute `object_lifetime_defaults` to a
1914 // vector like `['x, 'static]`. Note that the vector only
1915 // includes type parameters.
1916 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1918 let mut scope = self.scope;
1921 Scope::Root => break false,
1923 Scope::Body { .. } => break true,
1925 Scope::Binder { s, .. }
1926 | Scope::Elision { s, .. }
1927 | Scope::ObjectLifetimeDefault { s, .. } => {
1934 let map = &self.map;
1935 let unsubst = if let Some(def_id) = def_id.as_local() {
1936 let id = self.tcx.hir().as_local_hir_id(def_id);
1937 &map.object_lifetime_defaults[&id]
1940 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
1941 tcx.generics_of(def_id)
1944 .filter_map(|param| match param.kind {
1945 GenericParamDefKind::Type { object_lifetime_default, .. } => {
1946 Some(object_lifetime_default)
1948 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1953 debug!("visit_segment_args: unsubst={:?}", unsubst);
1956 .map(|set| match *set {
1961 Some(Region::Static)
1965 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1966 GenericArg::Lifetime(lt) => Some(lt),
1969 r.subst(lifetimes, map)
1976 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
1979 for arg in generic_args.args {
1981 GenericArg::Lifetime(_) => {}
1982 GenericArg::Type(ty) => {
1983 if let Some(<) = object_lifetime_defaults.get(i) {
1984 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1985 self.with(scope, |_, this| this.visit_ty(ty));
1991 GenericArg::Const(ct) => {
1992 self.visit_anon_const(&ct.value);
1997 // Hack: when resolving the type `XX` in binding like `dyn
1998 // Foo<'b, Item = XX>`, the current object-lifetime default
1999 // would be to examine the trait `Foo` to check whether it has
2000 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2001 // declared like so, then the default object lifetime bound in
2002 // `XX` should be `'b`:
2010 // but if we just have `type Item;`, then it would be
2011 // `'static`. However, we don't get all of this logic correct.
2013 // Instead, we do something hacky: if there are no lifetime parameters
2014 // to the trait, then we simply use a default object lifetime
2015 // bound of `'static`, because there is no other possibility. On the other hand,
2016 // if there ARE lifetime parameters, then we require the user to give an
2017 // explicit bound for now.
2019 // This is intended to leave room for us to implement the
2020 // correct behavior in the future.
2021 let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
2022 GenericArg::Lifetime(_) => true,
2026 // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2027 for b in generic_args.bindings {
2028 let scope = Scope::ObjectLifetimeDefault {
2029 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2032 self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2036 fn visit_fn_like_elision(
2038 inputs: &'tcx [hir::Ty<'tcx>],
2039 output: Option<&'tcx hir::Ty<'tcx>>,
2041 debug!("visit_fn_like_elision: enter");
2042 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2043 let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
2044 self.with(arg_scope, |_, this| {
2045 for input in inputs {
2046 this.visit_ty(input);
2049 Scope::Elision { ref elide, .. } => {
2050 arg_elide = elide.clone();
2056 let output = match output {
2061 debug!("visit_fn_like_elision: determine output");
2063 // Figure out if there's a body we can get argument names from,
2064 // and whether there's a `self` argument (treated specially).
2065 let mut assoc_item_kind = None;
2066 let mut impl_self = None;
2067 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2068 let body = match self.tcx.hir().get(parent) {
2069 // `fn` definitions and methods.
2070 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2072 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2073 if let hir::ItemKind::Trait(.., ref trait_items) =
2074 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2077 trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
2080 hir::TraitFn::Required(_) => None,
2081 hir::TraitFn::Provided(body) => Some(body),
2085 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2086 if let hir::ItemKind::Impl { ref self_ty, ref items, .. } =
2087 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2089 impl_self = Some(self_ty);
2091 items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
2096 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2097 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2098 // Everything else (only closures?) doesn't
2099 // actually enjoy elision in return types.
2101 self.visit_ty(output);
2106 let has_self = match assoc_item_kind {
2107 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2111 // In accordance with the rules for lifetime elision, we can determine
2112 // what region to use for elision in the output type in two ways.
2113 // First (determined here), if `self` is by-reference, then the
2114 // implied output region is the region of the self parameter.
2116 struct SelfVisitor<'a> {
2117 map: &'a NamedRegionMap,
2118 impl_self: Option<&'a hir::TyKind<'a>>,
2119 lifetime: Set1<Region>,
2122 impl SelfVisitor<'_> {
2123 // Look for `self: &'a Self` - also desugared from `&'a self`,
2124 // and if that matches, use it for elision and return early.
2125 fn is_self_ty(&self, res: Res) -> bool {
2126 if let Res::SelfTy(..) = res {
2130 // Can't always rely on literal (or implied) `Self` due
2131 // to the way elision rules were originally specified.
2132 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2136 // Permit the types that unambiguously always
2137 // result in the same type constructor being used
2138 // (it can't differ between `Self` and `self`).
2139 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2140 | Res::PrimTy(_) => return res == path.res,
2149 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2150 type Map = intravisit::ErasedMap<'a>;
2152 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2153 NestedVisitorMap::None
2156 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2157 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2158 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2160 if self.is_self_ty(path.res) {
2161 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2162 self.lifetime.insert(*lifetime);
2167 intravisit::walk_ty(self, ty)
2171 let mut visitor = SelfVisitor {
2173 impl_self: impl_self.map(|ty| &ty.kind),
2174 lifetime: Set1::Empty,
2176 visitor.visit_ty(&inputs[0]);
2177 if let Set1::One(lifetime) = visitor.lifetime {
2178 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2179 self.with(scope, |_, this| this.visit_ty(output));
2184 // Second, if there was exactly one lifetime (either a substitution or a
2185 // reference) in the arguments, then any anonymous regions in the output
2186 // have that lifetime.
2187 let mut possible_implied_output_region = None;
2188 let mut lifetime_count = 0;
2189 let arg_lifetimes = inputs
2192 .skip(has_self as usize)
2194 let mut gather = GatherLifetimes {
2196 outer_index: ty::INNERMOST,
2197 have_bound_regions: false,
2198 lifetimes: Default::default(),
2200 gather.visit_ty(input);
2202 lifetime_count += gather.lifetimes.len();
2204 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2205 // there's a chance that the unique lifetime of this
2206 // iteration will be the appropriate lifetime for output
2207 // parameters, so lets store it.
2208 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2211 ElisionFailureInfo {
2214 lifetime_count: gather.lifetimes.len(),
2215 have_bound_regions: gather.have_bound_regions,
2221 let elide = if lifetime_count == 1 {
2222 Elide::Exact(possible_implied_output_region.unwrap())
2224 Elide::Error(arg_lifetimes)
2227 debug!("visit_fn_like_elision: elide={:?}", elide);
2229 let scope = Scope::Elision { elide, s: self.scope };
2230 self.with(scope, |_, this| this.visit_ty(output));
2231 debug!("visit_fn_like_elision: exit");
2233 struct GatherLifetimes<'a> {
2234 map: &'a NamedRegionMap,
2235 outer_index: ty::DebruijnIndex,
2236 have_bound_regions: bool,
2237 lifetimes: FxHashSet<Region>,
2240 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2241 type Map = intravisit::ErasedMap<'v>;
2243 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2244 NestedVisitorMap::None
2247 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2248 if let hir::TyKind::BareFn(_) = ty.kind {
2249 self.outer_index.shift_in(1);
2252 hir::TyKind::TraitObject(bounds, ref lifetime) => {
2253 for bound in bounds {
2254 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2257 // Stay on the safe side and don't include the object
2258 // lifetime default (which may not end up being used).
2259 if !lifetime.is_elided() {
2260 self.visit_lifetime(lifetime);
2264 intravisit::walk_ty(self, ty);
2267 if let hir::TyKind::BareFn(_) = ty.kind {
2268 self.outer_index.shift_out(1);
2272 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2273 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2274 // FIXME(eddyb) Do we want this? It only makes a difference
2275 // if this `for<'a>` lifetime parameter is never used.
2276 self.have_bound_regions = true;
2279 intravisit::walk_generic_param(self, param);
2282 fn visit_poly_trait_ref(
2284 trait_ref: &hir::PolyTraitRef<'_>,
2285 modifier: hir::TraitBoundModifier,
2287 self.outer_index.shift_in(1);
2288 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2289 self.outer_index.shift_out(1);
2292 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2293 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2295 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2296 if debruijn < self.outer_index =>
2298 self.have_bound_regions = true;
2301 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2309 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2310 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2312 if lifetime_refs.is_empty() {
2316 let span = lifetime_refs[0].span;
2317 let mut late_depth = 0;
2318 let mut scope = self.scope;
2319 let mut lifetime_names = FxHashSet::default();
2322 // Do not assign any resolution, it will be inferred.
2323 Scope::Body { .. } => return,
2325 Scope::Root => break None,
2327 Scope::Binder { s, ref lifetimes, .. } => {
2328 // collect named lifetimes for suggestions
2329 for name in lifetimes.keys() {
2330 if let hir::ParamName::Plain(name) = name {
2331 lifetime_names.insert(*name);
2338 Scope::Elision { ref elide, ref s, .. } => {
2339 let lifetime = match *elide {
2340 Elide::FreshLateAnon(ref counter) => {
2341 for lifetime_ref in lifetime_refs {
2342 let lifetime = Region::late_anon(counter).shifted(late_depth);
2343 self.insert_lifetime(lifetime_ref, lifetime);
2347 Elide::Exact(l) => l.shifted(late_depth),
2348 Elide::Error(ref e) => {
2349 if let Scope::Binder { ref lifetimes, .. } = s {
2350 // collect named lifetimes for suggestions
2351 for name in lifetimes.keys() {
2352 if let hir::ParamName::Plain(name) = name {
2353 lifetime_names.insert(*name);
2359 Elide::Forbid => break None,
2361 for lifetime_ref in lifetime_refs {
2362 self.insert_lifetime(lifetime_ref, lifetime);
2367 Scope::ObjectLifetimeDefault { s, .. } => {
2373 let mut err = self.report_missing_lifetime_specifiers(span, lifetime_refs.len());
2375 if let Some(params) = error {
2376 // If there's no lifetime available, suggest `'static`.
2377 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
2378 lifetime_names.insert(Ident::with_dummy_span(kw::StaticLifetime));
2381 self.add_missing_lifetime_specifiers_label(
2384 lifetime_refs.len(),
2386 error.map(|p| &p[..]).unwrap_or(&[]),
2391 fn report_elision_failure(
2393 db: &mut DiagnosticBuilder<'_>,
2394 params: &[ElisionFailureInfo],
2395 ) -> bool /* add `'static` lifetime to lifetime list */ {
2396 let mut m = String::new();
2397 let len = params.len();
2399 let elided_params: Vec<_> =
2400 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2402 let elided_len = elided_params.len();
2404 for (i, info) in elided_params.into_iter().enumerate() {
2405 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2408 db.span_label(span, "");
2409 let help_name = if let Some(ident) =
2410 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2412 format!("`{}`", ident)
2414 format!("argument {}", index + 1)
2422 "one of {}'s {} {}lifetimes",
2425 if have_bound_regions { "free " } else { "" }
2430 if elided_len == 2 && i == 0 {
2432 } else if i + 2 == elided_len {
2433 m.push_str(", or ");
2434 } else if i != elided_len - 1 {
2441 "this function's return type contains a borrowed value, \
2442 but there is no value for it to be borrowed from",
2445 } else if elided_len == 0 {
2447 "this function's return type contains a borrowed value with \
2448 an elided lifetime, but the lifetime cannot be derived from \
2452 } else if elided_len == 1 {
2454 "this function's return type contains a borrowed value, \
2455 but the signature does not say which {} it is borrowed from",
2461 "this function's return type contains a borrowed value, \
2462 but the signature does not say whether it is borrowed from {}",
2469 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2470 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2471 let mut late_depth = 0;
2472 let mut scope = self.scope;
2473 let lifetime = loop {
2475 Scope::Binder { s, .. } => {
2480 Scope::Root | Scope::Elision { .. } => break Region::Static,
2482 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2484 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2487 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2490 fn check_lifetime_params(
2492 old_scope: ScopeRef<'_>,
2493 params: &'tcx [hir::GenericParam<'tcx>],
2495 let lifetimes: Vec<_> = params
2497 .filter_map(|param| match param.kind {
2498 GenericParamKind::Lifetime { .. } => {
2499 Some((param, param.name.normalize_to_macros_2_0()))
2504 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2505 if let hir::ParamName::Plain(_) = lifetime_i_name {
2506 let name = lifetime_i_name.ident().name;
2507 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
2508 let mut err = struct_span_err!(
2512 "invalid lifetime parameter name: `{}`",
2513 lifetime_i.name.ident(),
2517 format!("{} is a reserved lifetime name", name),
2523 // It is a hard error to shadow a lifetime within the same scope.
2524 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2525 if lifetime_i_name == lifetime_j_name {
2530 "lifetime name `{}` declared twice in the same scope",
2531 lifetime_j.name.ident()
2533 .span_label(lifetime_j.span, "declared twice")
2534 .span_label(lifetime_i.span, "previous declaration here")
2539 // It is a soft error to shadow a lifetime within a parent scope.
2540 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2542 for bound in lifetime_i.bounds {
2544 hir::GenericBound::Outlives(ref lt) => match lt.name {
2545 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2547 "use of `'_` in illegal place, but not caught by lowering",
2549 hir::LifetimeName::Static => {
2550 self.insert_lifetime(lt, Region::Static);
2554 lifetime_i.span.to(lt.span),
2556 "unnecessary lifetime parameter `{}`",
2557 lifetime_i.name.ident(),
2561 "you can use the `'static` lifetime directly, in place of `{}`",
2562 lifetime_i.name.ident(),
2566 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2567 self.resolve_lifetime_ref(lt);
2569 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2570 self.tcx.sess.delay_span_bug(
2572 "lowering generated `ImplicitObjectLifetimeDefault` \
2573 outside of an object type",
2576 hir::LifetimeName::Error => {
2577 // No need to do anything, error already reported.
2586 fn check_lifetime_param_for_shadowing(
2588 mut old_scope: ScopeRef<'_>,
2589 param: &'tcx hir::GenericParam<'tcx>,
2591 for label in &self.labels_in_fn {
2592 // FIXME (#24278): non-hygienic comparison
2593 if param.name.ident().name == label.name {
2594 signal_shadowing_problem(
2597 original_label(label.span),
2598 shadower_lifetime(¶m),
2606 Scope::Body { s, .. }
2607 | Scope::Elision { s, .. }
2608 | Scope::ObjectLifetimeDefault { s, .. } => {
2616 Scope::Binder { ref lifetimes, s, .. } => {
2617 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
2619 self.tcx.hir().as_local_hir_id(def.id().unwrap().expect_local());
2621 signal_shadowing_problem(
2623 param.name.ident().name,
2624 original_lifetime(self.tcx.hir().span(hir_id)),
2625 shadower_lifetime(¶m),
2636 /// Returns `true` if, in the current scope, replacing `'_` would be
2637 /// equivalent to a single-use lifetime.
2638 fn track_lifetime_uses(&self) -> bool {
2639 let mut scope = self.scope;
2642 Scope::Root => break false,
2644 // Inside of items, it depends on the kind of item.
2645 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
2647 // Inside a body, `'_` will use an inference variable,
2649 Scope::Body { .. } => break true,
2651 // A lifetime only used in a fn argument could as well
2652 // be replaced with `'_`, as that would generate a
2654 Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
2656 // In the return type or other such place, `'_` is not
2657 // going to make a fresh name, so we cannot
2658 // necessarily replace a single-use lifetime with
2661 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
2664 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2669 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2671 "insert_lifetime: {} resolved to {:?} span={:?}",
2672 self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2674 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2676 self.map.defs.insert(lifetime_ref.hir_id, def);
2679 Region::LateBoundAnon(..) | Region::Static => {
2680 // These are anonymous lifetimes or lifetimes that are not declared.
2683 Region::Free(_, def_id)
2684 | Region::LateBound(_, def_id, _)
2685 | Region::EarlyBound(_, def_id, _) => {
2686 // A lifetime declared by the user.
2687 let track_lifetime_uses = self.track_lifetime_uses();
2688 debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
2689 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2690 debug!("insert_lifetime: first use of {:?}", def_id);
2691 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
2693 debug!("insert_lifetime: many uses of {:?}", def_id);
2694 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2700 /// Sometimes we resolve a lifetime, but later find that it is an
2701 /// error (esp. around impl trait). In that case, we remove the
2702 /// entry into `map.defs` so as not to confuse later code.
2703 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2704 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2705 assert_eq!(old_value, Some(bad_def));
2709 /// Detects late-bound lifetimes and inserts them into
2710 /// `map.late_bound`.
2712 /// A region declared on a fn is **late-bound** if:
2713 /// - it is constrained by an argument type;
2714 /// - it does not appear in a where-clause.
2716 /// "Constrained" basically means that it appears in any type but
2717 /// not amongst the inputs to a projection. In other words, `<&'a
2718 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2719 fn insert_late_bound_lifetimes(
2720 map: &mut NamedRegionMap,
2721 decl: &hir::FnDecl<'_>,
2722 generics: &hir::Generics<'_>,
2724 debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
2726 let mut constrained_by_input = ConstrainedCollector::default();
2727 for arg_ty in decl.inputs {
2728 constrained_by_input.visit_ty(arg_ty);
2731 let mut appears_in_output = AllCollector::default();
2732 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2734 debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
2736 // Walk the lifetimes that appear in where clauses.
2738 // Subtle point: because we disallow nested bindings, we can just
2739 // ignore binders here and scrape up all names we see.
2740 let mut appears_in_where_clause = AllCollector::default();
2741 appears_in_where_clause.visit_generics(generics);
2743 for param in generics.params {
2744 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2745 if !param.bounds.is_empty() {
2746 // `'a: 'b` means both `'a` and `'b` are referenced
2747 appears_in_where_clause
2749 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
2755 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2756 appears_in_where_clause.regions
2759 // Late bound regions are those that:
2760 // - appear in the inputs
2761 // - do not appear in the where-clauses
2762 // - are not implicitly captured by `impl Trait`
2763 for param in generics.params {
2765 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2767 // Neither types nor consts are late-bound.
2768 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2771 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
2772 // appears in the where clauses? early-bound.
2773 if appears_in_where_clause.regions.contains(<_name) {
2777 // does not appear in the inputs, but appears in the return type? early-bound.
2778 if !constrained_by_input.regions.contains(<_name)
2779 && appears_in_output.regions.contains(<_name)
2785 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2790 let inserted = map.late_bound.insert(param.hir_id);
2791 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2797 struct ConstrainedCollector {
2798 regions: FxHashSet<hir::LifetimeName>,
2801 impl<'v> Visitor<'v> for ConstrainedCollector {
2802 type Map = intravisit::ErasedMap<'v>;
2804 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2805 NestedVisitorMap::None
2808 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2811 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2813 // ignore lifetimes appearing in associated type
2814 // projections, as they are not *constrained*
2818 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2819 // consider only the lifetimes on the final
2820 // segment; I am not sure it's even currently
2821 // valid to have them elsewhere, but even if it
2822 // is, those would be potentially inputs to
2824 if let Some(last_segment) = path.segments.last() {
2825 self.visit_path_segment(path.span, last_segment);
2830 intravisit::walk_ty(self, ty);
2835 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2836 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
2841 struct AllCollector {
2842 regions: FxHashSet<hir::LifetimeName>,
2845 impl<'v> Visitor<'v> for AllCollector {
2846 type Map = intravisit::ErasedMap<'v>;
2848 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2849 NestedVisitorMap::None
2852 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2853 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());