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.
1302 // We still store a dummy value here to allow generic paramters
1303 // in arbitrary order.
1310 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1311 // FIXME(#37666) this works around a limitation in the region inferencer
1312 fn hack<F>(&mut self, f: F)
1314 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1319 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1321 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1323 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1324 let labels_in_fn = take(&mut self.labels_in_fn);
1325 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1326 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1327 let mut this = LifetimeContext {
1331 trait_ref_hack: self.trait_ref_hack,
1332 is_in_fn_syntax: self.is_in_fn_syntax,
1333 is_in_const_generic: self.is_in_const_generic,
1335 xcrate_object_lifetime_defaults,
1337 missing_named_lifetime_spots,
1339 debug!("entering scope {:?}", this.scope);
1340 f(self.scope, &mut this);
1341 this.check_uses_for_lifetimes_defined_by_scope();
1342 debug!("exiting scope {:?}", this.scope);
1343 self.labels_in_fn = this.labels_in_fn;
1344 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1345 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1348 /// helper method to determine the span to remove when suggesting the
1349 /// deletion of a lifetime
1350 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1351 generics.params.iter().enumerate().find_map(|(i, param)| {
1352 if param.name.ident() == name {
1353 let mut in_band = false;
1354 if let hir::GenericParamKind::Lifetime { kind } = param.kind {
1355 if let hir::LifetimeParamKind::InBand = kind {
1362 if generics.params.len() == 1 {
1363 // if sole lifetime, remove the entire `<>` brackets
1366 // if removing within `<>` brackets, we also want to
1367 // delete a leading or trailing comma as appropriate
1368 if i >= generics.params.len() - 1 {
1369 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1371 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1381 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1382 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1383 fn suggest_eliding_single_use_lifetime(
1385 err: &mut DiagnosticBuilder<'_>,
1387 lifetime: &hir::Lifetime,
1389 let name = lifetime.name.ident();
1390 let mut remove_decl = None;
1391 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1392 if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
1393 remove_decl = self.lifetime_deletion_span(name, generics);
1397 let mut remove_use = None;
1398 let mut elide_use = None;
1399 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1400 for input in inputs {
1402 hir::TyKind::Rptr(lt, _) => {
1403 if lt.name.ident() == name {
1404 // include the trailing whitespace between the lifetime and type names
1405 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1410 .span_until_non_whitespace(lt_through_ty_span),
1415 hir::TyKind::Path(ref qpath) => {
1416 if let QPath::Resolved(_, path) = qpath {
1417 let last_segment = &path.segments[path.segments.len() - 1];
1418 let generics = last_segment.generic_args();
1419 for arg in generics.args.iter() {
1420 if let GenericArg::Lifetime(lt) = arg {
1421 if lt.name.ident() == name {
1422 elide_use = Some(lt.span);
1434 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1435 if let Some(parent) =
1436 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1439 Node::Item(item) => {
1440 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1441 find_arg_use_span(sig.decl.inputs);
1444 Node::ImplItem(impl_item) => {
1445 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1446 find_arg_use_span(sig.decl.inputs);
1454 let msg = "elide the single-use lifetime";
1455 match (remove_decl, remove_use, elide_use) {
1456 (Some(decl_span), Some(use_span), None) => {
1457 // if both declaration and use deletion spans start at the same
1458 // place ("start at" because the latter includes trailing
1459 // whitespace), then this is an in-band lifetime
1460 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1461 err.span_suggestion(
1465 Applicability::MachineApplicable,
1468 err.multipart_suggestion(
1470 vec![(decl_span, String::new()), (use_span, String::new())],
1471 Applicability::MachineApplicable,
1475 (Some(decl_span), None, Some(use_span)) => {
1476 err.multipart_suggestion(
1478 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1479 Applicability::MachineApplicable,
1486 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1487 let defined_by = match self.scope {
1488 Scope::Binder { lifetimes, .. } => lifetimes,
1490 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1495 let mut def_ids: Vec<_> = defined_by
1497 .flat_map(|region| match region {
1498 Region::EarlyBound(_, def_id, _)
1499 | Region::LateBound(_, def_id, _)
1500 | Region::Free(_, def_id) => Some(*def_id),
1502 Region::LateBoundAnon(..) | Region::Static => None,
1506 // ensure that we issue lints in a repeatable order
1507 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
1509 for def_id in def_ids {
1510 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
1512 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1515 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1519 match lifetimeuseset {
1520 Some(LifetimeUseSet::One(lifetime)) => {
1521 let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1522 debug!("hir id first={:?}", hir_id);
1523 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1524 Node::Lifetime(hir_lifetime) => Some((
1525 hir_lifetime.hir_id,
1527 hir_lifetime.name.ident(),
1529 Node::GenericParam(param) => {
1530 Some((param.hir_id, param.span, param.name.ident()))
1534 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
1535 if name.name == kw::UnderscoreLifetime {
1539 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1540 if let Some(def_id) = parent_def_id.as_local() {
1541 let parent_hir_id = self.tcx.hir().as_local_hir_id(def_id);
1542 // lifetimes in `derive` expansions don't count (Issue #53738)
1546 .attrs(parent_hir_id)
1548 .any(|attr| attr.check_name(sym::automatically_derived))
1555 self.tcx.struct_span_lint_hir(
1556 lint::builtin::SINGLE_USE_LIFETIMES,
1560 let mut err = lint.build(&format!(
1561 "lifetime parameter `{}` only used once",
1564 if span == lifetime.span {
1565 // spans are the same for in-band lifetime declarations
1566 err.span_label(span, "this lifetime is only used here");
1568 err.span_label(span, "this lifetime...");
1569 err.span_label(lifetime.span, "...is used only here");
1571 self.suggest_eliding_single_use_lifetime(
1572 &mut err, def_id, lifetime,
1579 Some(LifetimeUseSet::Many) => {
1580 debug!("not one use lifetime");
1583 let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1584 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
1585 Node::Lifetime(hir_lifetime) => Some((
1586 hir_lifetime.hir_id,
1588 hir_lifetime.name.ident(),
1590 Node::GenericParam(param) => {
1591 Some((param.hir_id, param.span, param.name.ident()))
1595 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
1596 self.tcx.struct_span_lint_hir(
1597 lint::builtin::UNUSED_LIFETIMES,
1602 .build(&format!("lifetime parameter `{}` never used", name));
1603 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1604 if let Some(generics) =
1605 self.tcx.hir().get_generics(parent_def_id)
1607 let unused_lt_span =
1608 self.lifetime_deletion_span(name, generics);
1609 if let Some(span) = unused_lt_span {
1610 err.span_suggestion(
1612 "elide the unused lifetime",
1614 Applicability::MachineApplicable,
1628 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1630 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1631 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1632 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1636 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1638 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1639 /// lifetimes may be interspersed together.
1641 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1642 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1643 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1644 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1645 /// ordering is not important there.
1646 fn visit_early_late<F>(
1648 parent_id: Option<hir::HirId>,
1649 decl: &'tcx hir::FnDecl<'tcx>,
1650 generics: &'tcx hir::Generics<'tcx>,
1653 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1655 insert_late_bound_lifetimes(self.map, decl, generics);
1657 // Find the start of nested early scopes, e.g., in methods.
1659 if let Some(parent_id) = parent_id {
1660 let parent = self.tcx.hir().expect_item(parent_id);
1661 if sub_items_have_self_param(&parent.kind) {
1662 index += 1; // Self comes before lifetimes
1665 hir::ItemKind::Trait(_, _, ref generics, ..)
1666 | hir::ItemKind::Impl { ref generics, .. } => {
1667 index += generics.params.len() as u32;
1673 let mut non_lifetime_count = 0;
1674 let lifetimes = generics
1677 .filter_map(|param| match param.kind {
1678 GenericParamKind::Lifetime { .. } => {
1679 if self.map.late_bound.contains(¶m.hir_id) {
1680 Some(Region::late(&self.tcx.hir(), param))
1682 Some(Region::early(&self.tcx.hir(), &mut index, param))
1685 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1686 non_lifetime_count += 1;
1691 let next_early_index = index + non_lifetime_count;
1693 let scope = Scope::Binder {
1697 opaque_type_parent: true,
1698 track_lifetime_uses: false,
1700 self.with(scope, move |old_scope, this| {
1701 this.check_lifetime_params(old_scope, &generics.params);
1702 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1706 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
1707 let mut scope = self.scope;
1710 Scope::Root => return 0,
1712 Scope::Binder { next_early_index, opaque_type_parent, .. }
1713 if (!only_opaque_type_parent || opaque_type_parent) =>
1715 return next_early_index;
1718 Scope::Binder { s, .. }
1719 | Scope::Body { s, .. }
1720 | Scope::Elision { s, .. }
1721 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1726 /// Returns the next index one would use for an early-bound-region
1727 /// if extending the current scope.
1728 fn next_early_index(&self) -> u32 {
1729 self.next_early_index_helper(true)
1732 /// Returns the next index one would use for an `impl Trait` that
1733 /// is being converted into an opaque type alias `impl Trait`. This will be the
1734 /// next early index from the enclosing item, for the most
1735 /// part. See the `opaque_type_parent` field for more info.
1736 fn next_early_index_for_opaque_type(&self) -> u32 {
1737 self.next_early_index_helper(false)
1740 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1741 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1743 // If we've already reported an error, just ignore `lifetime_ref`.
1744 if let LifetimeName::Error = lifetime_ref.name {
1748 // Walk up the scope chain, tracking the number of fn scopes
1749 // that we pass through, until we find a lifetime with the
1750 // given name or we run out of scopes.
1752 let mut late_depth = 0;
1753 let mut scope = self.scope;
1754 let mut outermost_body = None;
1757 Scope::Body { id, s } => {
1758 outermost_body = Some(id);
1766 Scope::Binder { ref lifetimes, s, .. } => {
1767 match lifetime_ref.name {
1768 LifetimeName::Param(param_name) => {
1769 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
1771 break Some(def.shifted(late_depth));
1774 _ => bug!("expected LifetimeName::Param"),
1781 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1787 if let Some(mut def) = result {
1788 if let Region::EarlyBound(..) = def {
1789 // Do not free early-bound regions, only late-bound ones.
1790 } else if let Some(body_id) = outermost_body {
1791 let fn_id = self.tcx.hir().body_owner(body_id);
1792 match self.tcx.hir().get(fn_id) {
1793 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
1794 | Node::TraitItem(&hir::TraitItem {
1795 kind: hir::TraitItemKind::Fn(..), ..
1797 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
1798 let scope = self.tcx.hir().local_def_id(fn_id);
1799 def = Region::Free(scope.to_def_id(), def.id().unwrap());
1805 // Check for fn-syntax conflicts with in-band lifetime definitions
1806 if self.is_in_fn_syntax {
1808 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1809 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1814 "lifetimes used in `fn` or `Fn` syntax must be \
1815 explicitly declared using `<...>` binders"
1817 .span_label(lifetime_ref.span, "in-band lifetime definition")
1822 | Region::EarlyBound(
1825 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1827 | Region::LateBound(
1830 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
1832 | Region::LateBoundAnon(..)
1833 | Region::Free(..) => {}
1837 self.insert_lifetime(lifetime_ref, def);
1839 self.emit_undeclared_lifetime_error(lifetime_ref);
1843 fn visit_segment_args(
1847 generic_args: &'tcx hir::GenericArgs<'tcx>,
1850 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
1851 res, depth, generic_args,
1854 if generic_args.parenthesized {
1855 let was_in_fn_syntax = self.is_in_fn_syntax;
1856 self.is_in_fn_syntax = true;
1857 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
1858 self.is_in_fn_syntax = was_in_fn_syntax;
1862 let mut elide_lifetimes = true;
1863 let lifetimes = generic_args
1866 .filter_map(|arg| match arg {
1867 hir::GenericArg::Lifetime(lt) => {
1868 if !lt.is_elided() {
1869 elide_lifetimes = false;
1876 if elide_lifetimes {
1877 self.resolve_elided_lifetimes(lifetimes);
1879 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1882 // Figure out if this is a type/trait segment,
1883 // which requires object lifetime defaults.
1884 let parent_def_id = |this: &mut Self, def_id: DefId| {
1885 let def_key = this.tcx.def_key(def_id);
1886 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
1888 let type_def_id = match res {
1889 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1890 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1898 ) if depth == 0 => Some(def_id),
1902 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
1904 // Compute a vector of defaults, one for each type parameter,
1905 // per the rules given in RFCs 599 and 1156. Example:
1908 // struct Foo<'a, T: 'a, U> { }
1911 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1912 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1913 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1916 // Therefore, we would compute `object_lifetime_defaults` to a
1917 // vector like `['x, 'static]`. Note that the vector only
1918 // includes type parameters.
1919 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1921 let mut scope = self.scope;
1924 Scope::Root => break false,
1926 Scope::Body { .. } => break true,
1928 Scope::Binder { s, .. }
1929 | Scope::Elision { s, .. }
1930 | Scope::ObjectLifetimeDefault { s, .. } => {
1937 let map = &self.map;
1938 let unsubst = if let Some(def_id) = def_id.as_local() {
1939 let id = self.tcx.hir().as_local_hir_id(def_id);
1940 &map.object_lifetime_defaults[&id]
1943 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
1944 tcx.generics_of(def_id)
1947 .filter_map(|param| match param.kind {
1948 GenericParamDefKind::Type { object_lifetime_default, .. } => {
1949 Some(object_lifetime_default)
1951 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
1956 debug!("visit_segment_args: unsubst={:?}", unsubst);
1959 .map(|set| match *set {
1964 Some(Region::Static)
1968 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1969 GenericArg::Lifetime(lt) => Some(lt),
1972 r.subst(lifetimes, map)
1979 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
1982 for arg in generic_args.args {
1984 GenericArg::Lifetime(_) => {}
1985 GenericArg::Type(ty) => {
1986 if let Some(<) = object_lifetime_defaults.get(i) {
1987 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1988 self.with(scope, |_, this| this.visit_ty(ty));
1994 GenericArg::Const(ct) => {
1995 self.visit_anon_const(&ct.value);
2000 // Hack: when resolving the type `XX` in binding like `dyn
2001 // Foo<'b, Item = XX>`, the current object-lifetime default
2002 // would be to examine the trait `Foo` to check whether it has
2003 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2004 // declared like so, then the default object lifetime bound in
2005 // `XX` should be `'b`:
2013 // but if we just have `type Item;`, then it would be
2014 // `'static`. However, we don't get all of this logic correct.
2016 // Instead, we do something hacky: if there are no lifetime parameters
2017 // to the trait, then we simply use a default object lifetime
2018 // bound of `'static`, because there is no other possibility. On the other hand,
2019 // if there ARE lifetime parameters, then we require the user to give an
2020 // explicit bound for now.
2022 // This is intended to leave room for us to implement the
2023 // correct behavior in the future.
2024 let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
2025 GenericArg::Lifetime(_) => true,
2029 // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
2030 for b in generic_args.bindings {
2031 let scope = Scope::ObjectLifetimeDefault {
2032 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2035 self.with(scope, |_, this| this.visit_assoc_type_binding(b));
2039 fn visit_fn_like_elision(
2041 inputs: &'tcx [hir::Ty<'tcx>],
2042 output: Option<&'tcx hir::Ty<'tcx>>,
2044 debug!("visit_fn_like_elision: enter");
2045 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
2046 let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
2047 self.with(arg_scope, |_, this| {
2048 for input in inputs {
2049 this.visit_ty(input);
2052 Scope::Elision { ref elide, .. } => {
2053 arg_elide = elide.clone();
2059 let output = match output {
2064 debug!("visit_fn_like_elision: determine output");
2066 // Figure out if there's a body we can get argument names from,
2067 // and whether there's a `self` argument (treated specially).
2068 let mut assoc_item_kind = None;
2069 let mut impl_self = None;
2070 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2071 let body = match self.tcx.hir().get(parent) {
2072 // `fn` definitions and methods.
2073 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2075 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2076 if let hir::ItemKind::Trait(.., ref trait_items) =
2077 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2080 trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
2083 hir::TraitFn::Required(_) => None,
2084 hir::TraitFn::Provided(body) => Some(body),
2088 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2089 if let hir::ItemKind::Impl { ref self_ty, ref items, .. } =
2090 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2092 impl_self = Some(self_ty);
2094 items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
2099 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2100 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2101 // Everything else (only closures?) doesn't
2102 // actually enjoy elision in return types.
2104 self.visit_ty(output);
2109 let has_self = match assoc_item_kind {
2110 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2114 // In accordance with the rules for lifetime elision, we can determine
2115 // what region to use for elision in the output type in two ways.
2116 // First (determined here), if `self` is by-reference, then the
2117 // implied output region is the region of the self parameter.
2119 struct SelfVisitor<'a> {
2120 map: &'a NamedRegionMap,
2121 impl_self: Option<&'a hir::TyKind<'a>>,
2122 lifetime: Set1<Region>,
2125 impl SelfVisitor<'_> {
2126 // Look for `self: &'a Self` - also desugared from `&'a self`,
2127 // and if that matches, use it for elision and return early.
2128 fn is_self_ty(&self, res: Res) -> bool {
2129 if let Res::SelfTy(..) = res {
2133 // Can't always rely on literal (or implied) `Self` due
2134 // to the way elision rules were originally specified.
2135 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2139 // Permit the types that unambiguously always
2140 // result in the same type constructor being used
2141 // (it can't differ between `Self` and `self`).
2142 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2143 | Res::PrimTy(_) => return res == path.res,
2152 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2153 type Map = intravisit::ErasedMap<'a>;
2155 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2156 NestedVisitorMap::None
2159 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2160 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2161 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2163 if self.is_self_ty(path.res) {
2164 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2165 self.lifetime.insert(*lifetime);
2170 intravisit::walk_ty(self, ty)
2174 let mut visitor = SelfVisitor {
2176 impl_self: impl_self.map(|ty| &ty.kind),
2177 lifetime: Set1::Empty,
2179 visitor.visit_ty(&inputs[0]);
2180 if let Set1::One(lifetime) = visitor.lifetime {
2181 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2182 self.with(scope, |_, this| this.visit_ty(output));
2187 // Second, if there was exactly one lifetime (either a substitution or a
2188 // reference) in the arguments, then any anonymous regions in the output
2189 // have that lifetime.
2190 let mut possible_implied_output_region = None;
2191 let mut lifetime_count = 0;
2192 let arg_lifetimes = inputs
2195 .skip(has_self as usize)
2197 let mut gather = GatherLifetimes {
2199 outer_index: ty::INNERMOST,
2200 have_bound_regions: false,
2201 lifetimes: Default::default(),
2203 gather.visit_ty(input);
2205 lifetime_count += gather.lifetimes.len();
2207 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2208 // there's a chance that the unique lifetime of this
2209 // iteration will be the appropriate lifetime for output
2210 // parameters, so lets store it.
2211 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2214 ElisionFailureInfo {
2217 lifetime_count: gather.lifetimes.len(),
2218 have_bound_regions: gather.have_bound_regions,
2224 let elide = if lifetime_count == 1 {
2225 Elide::Exact(possible_implied_output_region.unwrap())
2227 Elide::Error(arg_lifetimes)
2230 debug!("visit_fn_like_elision: elide={:?}", elide);
2232 let scope = Scope::Elision { elide, s: self.scope };
2233 self.with(scope, |_, this| this.visit_ty(output));
2234 debug!("visit_fn_like_elision: exit");
2236 struct GatherLifetimes<'a> {
2237 map: &'a NamedRegionMap,
2238 outer_index: ty::DebruijnIndex,
2239 have_bound_regions: bool,
2240 lifetimes: FxHashSet<Region>,
2243 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2244 type Map = intravisit::ErasedMap<'v>;
2246 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2247 NestedVisitorMap::None
2250 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2251 if let hir::TyKind::BareFn(_) = ty.kind {
2252 self.outer_index.shift_in(1);
2255 hir::TyKind::TraitObject(bounds, ref lifetime) => {
2256 for bound in bounds {
2257 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2260 // Stay on the safe side and don't include the object
2261 // lifetime default (which may not end up being used).
2262 if !lifetime.is_elided() {
2263 self.visit_lifetime(lifetime);
2267 intravisit::walk_ty(self, ty);
2270 if let hir::TyKind::BareFn(_) = ty.kind {
2271 self.outer_index.shift_out(1);
2275 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2276 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2277 // FIXME(eddyb) Do we want this? It only makes a difference
2278 // if this `for<'a>` lifetime parameter is never used.
2279 self.have_bound_regions = true;
2282 intravisit::walk_generic_param(self, param);
2285 fn visit_poly_trait_ref(
2287 trait_ref: &hir::PolyTraitRef<'_>,
2288 modifier: hir::TraitBoundModifier,
2290 self.outer_index.shift_in(1);
2291 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2292 self.outer_index.shift_out(1);
2295 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2296 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2298 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2299 if debruijn < self.outer_index =>
2301 self.have_bound_regions = true;
2304 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
2312 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2313 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
2315 if lifetime_refs.is_empty() {
2319 let span = lifetime_refs[0].span;
2320 let mut late_depth = 0;
2321 let mut scope = self.scope;
2322 let mut lifetime_names = FxHashSet::default();
2325 // Do not assign any resolution, it will be inferred.
2326 Scope::Body { .. } => return,
2328 Scope::Root => break None,
2330 Scope::Binder { s, ref lifetimes, .. } => {
2331 // collect named lifetimes for suggestions
2332 for name in lifetimes.keys() {
2333 if let hir::ParamName::Plain(name) = name {
2334 lifetime_names.insert(*name);
2341 Scope::Elision { ref elide, ref s, .. } => {
2342 let lifetime = match *elide {
2343 Elide::FreshLateAnon(ref counter) => {
2344 for lifetime_ref in lifetime_refs {
2345 let lifetime = Region::late_anon(counter).shifted(late_depth);
2346 self.insert_lifetime(lifetime_ref, lifetime);
2350 Elide::Exact(l) => l.shifted(late_depth),
2351 Elide::Error(ref e) => {
2352 if let Scope::Binder { ref lifetimes, .. } = s {
2353 // collect named lifetimes for suggestions
2354 for name in lifetimes.keys() {
2355 if let hir::ParamName::Plain(name) = name {
2356 lifetime_names.insert(*name);
2362 Elide::Forbid => break None,
2364 for lifetime_ref in lifetime_refs {
2365 self.insert_lifetime(lifetime_ref, lifetime);
2370 Scope::ObjectLifetimeDefault { s, .. } => {
2376 let mut err = self.report_missing_lifetime_specifiers(span, lifetime_refs.len());
2378 if let Some(params) = error {
2379 // If there's no lifetime available, suggest `'static`.
2380 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
2381 lifetime_names.insert(Ident::with_dummy_span(kw::StaticLifetime));
2384 self.add_missing_lifetime_specifiers_label(
2387 lifetime_refs.len(),
2389 error.map(|p| &p[..]).unwrap_or(&[]),
2394 fn report_elision_failure(
2396 db: &mut DiagnosticBuilder<'_>,
2397 params: &[ElisionFailureInfo],
2398 ) -> bool /* add `'static` lifetime to lifetime list */ {
2399 let mut m = String::new();
2400 let len = params.len();
2402 let elided_params: Vec<_> =
2403 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2405 let elided_len = elided_params.len();
2407 for (i, info) in elided_params.into_iter().enumerate() {
2408 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2411 db.span_label(span, "");
2412 let help_name = if let Some(ident) =
2413 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2415 format!("`{}`", ident)
2417 format!("argument {}", index + 1)
2425 "one of {}'s {} {}lifetimes",
2428 if have_bound_regions { "free " } else { "" }
2433 if elided_len == 2 && i == 0 {
2435 } else if i + 2 == elided_len {
2436 m.push_str(", or ");
2437 } else if i != elided_len - 1 {
2444 "this function's return type contains a borrowed value, \
2445 but there is no value for it to be borrowed from",
2448 } else if elided_len == 0 {
2450 "this function's return type contains a borrowed value with \
2451 an elided lifetime, but the lifetime cannot be derived from \
2455 } else if elided_len == 1 {
2457 "this function's return type contains a borrowed value, \
2458 but the signature does not say which {} it is borrowed from",
2464 "this function's return type contains a borrowed value, \
2465 but the signature does not say whether it is borrowed from {}",
2472 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2473 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
2474 let mut late_depth = 0;
2475 let mut scope = self.scope;
2476 let lifetime = loop {
2478 Scope::Binder { s, .. } => {
2483 Scope::Root | Scope::Elision { .. } => break Region::Static,
2485 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2487 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
2490 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2493 fn check_lifetime_params(
2495 old_scope: ScopeRef<'_>,
2496 params: &'tcx [hir::GenericParam<'tcx>],
2498 let lifetimes: Vec<_> = params
2500 .filter_map(|param| match param.kind {
2501 GenericParamKind::Lifetime { .. } => {
2502 Some((param, param.name.normalize_to_macros_2_0()))
2507 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2508 if let hir::ParamName::Plain(_) = lifetime_i_name {
2509 let name = lifetime_i_name.ident().name;
2510 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
2511 let mut err = struct_span_err!(
2515 "invalid lifetime parameter name: `{}`",
2516 lifetime_i.name.ident(),
2520 format!("{} is a reserved lifetime name", name),
2526 // It is a hard error to shadow a lifetime within the same scope.
2527 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2528 if lifetime_i_name == lifetime_j_name {
2533 "lifetime name `{}` declared twice in the same scope",
2534 lifetime_j.name.ident()
2536 .span_label(lifetime_j.span, "declared twice")
2537 .span_label(lifetime_i.span, "previous declaration here")
2542 // It is a soft error to shadow a lifetime within a parent scope.
2543 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2545 for bound in lifetime_i.bounds {
2547 hir::GenericBound::Outlives(ref lt) => match lt.name {
2548 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2550 "use of `'_` in illegal place, but not caught by lowering",
2552 hir::LifetimeName::Static => {
2553 self.insert_lifetime(lt, Region::Static);
2557 lifetime_i.span.to(lt.span),
2559 "unnecessary lifetime parameter `{}`",
2560 lifetime_i.name.ident(),
2564 "you can use the `'static` lifetime directly, in place of `{}`",
2565 lifetime_i.name.ident(),
2569 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2570 self.resolve_lifetime_ref(lt);
2572 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2573 self.tcx.sess.delay_span_bug(
2575 "lowering generated `ImplicitObjectLifetimeDefault` \
2576 outside of an object type",
2579 hir::LifetimeName::Error => {
2580 // No need to do anything, error already reported.
2589 fn check_lifetime_param_for_shadowing(
2591 mut old_scope: ScopeRef<'_>,
2592 param: &'tcx hir::GenericParam<'tcx>,
2594 for label in &self.labels_in_fn {
2595 // FIXME (#24278): non-hygienic comparison
2596 if param.name.ident().name == label.name {
2597 signal_shadowing_problem(
2600 original_label(label.span),
2601 shadower_lifetime(¶m),
2609 Scope::Body { s, .. }
2610 | Scope::Elision { s, .. }
2611 | Scope::ObjectLifetimeDefault { s, .. } => {
2619 Scope::Binder { ref lifetimes, s, .. } => {
2620 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
2622 self.tcx.hir().as_local_hir_id(def.id().unwrap().expect_local());
2624 signal_shadowing_problem(
2626 param.name.ident().name,
2627 original_lifetime(self.tcx.hir().span(hir_id)),
2628 shadower_lifetime(¶m),
2639 /// Returns `true` if, in the current scope, replacing `'_` would be
2640 /// equivalent to a single-use lifetime.
2641 fn track_lifetime_uses(&self) -> bool {
2642 let mut scope = self.scope;
2645 Scope::Root => break false,
2647 // Inside of items, it depends on the kind of item.
2648 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
2650 // Inside a body, `'_` will use an inference variable,
2652 Scope::Body { .. } => break true,
2654 // A lifetime only used in a fn argument could as well
2655 // be replaced with `'_`, as that would generate a
2657 Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
2659 // In the return type or other such place, `'_` is not
2660 // going to make a fresh name, so we cannot
2661 // necessarily replace a single-use lifetime with
2664 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
2667 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2672 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2674 "insert_lifetime: {} resolved to {:?} span={:?}",
2675 self.tcx.hir().node_to_string(lifetime_ref.hir_id),
2677 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2679 self.map.defs.insert(lifetime_ref.hir_id, def);
2682 Region::LateBoundAnon(..) | Region::Static => {
2683 // These are anonymous lifetimes or lifetimes that are not declared.
2686 Region::Free(_, def_id)
2687 | Region::LateBound(_, def_id, _)
2688 | Region::EarlyBound(_, def_id, _) => {
2689 // A lifetime declared by the user.
2690 let track_lifetime_uses = self.track_lifetime_uses();
2691 debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
2692 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2693 debug!("insert_lifetime: first use of {:?}", def_id);
2694 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
2696 debug!("insert_lifetime: many uses of {:?}", def_id);
2697 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2703 /// Sometimes we resolve a lifetime, but later find that it is an
2704 /// error (esp. around impl trait). In that case, we remove the
2705 /// entry into `map.defs` so as not to confuse later code.
2706 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2707 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
2708 assert_eq!(old_value, Some(bad_def));
2712 /// Detects late-bound lifetimes and inserts them into
2713 /// `map.late_bound`.
2715 /// A region declared on a fn is **late-bound** if:
2716 /// - it is constrained by an argument type;
2717 /// - it does not appear in a where-clause.
2719 /// "Constrained" basically means that it appears in any type but
2720 /// not amongst the inputs to a projection. In other words, `<&'a
2721 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2722 fn insert_late_bound_lifetimes(
2723 map: &mut NamedRegionMap,
2724 decl: &hir::FnDecl<'_>,
2725 generics: &hir::Generics<'_>,
2727 debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
2729 let mut constrained_by_input = ConstrainedCollector::default();
2730 for arg_ty in decl.inputs {
2731 constrained_by_input.visit_ty(arg_ty);
2734 let mut appears_in_output = AllCollector::default();
2735 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2737 debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
2739 // Walk the lifetimes that appear in where clauses.
2741 // Subtle point: because we disallow nested bindings, we can just
2742 // ignore binders here and scrape up all names we see.
2743 let mut appears_in_where_clause = AllCollector::default();
2744 appears_in_where_clause.visit_generics(generics);
2746 for param in generics.params {
2747 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2748 if !param.bounds.is_empty() {
2749 // `'a: 'b` means both `'a` and `'b` are referenced
2750 appears_in_where_clause
2752 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
2758 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2759 appears_in_where_clause.regions
2762 // Late bound regions are those that:
2763 // - appear in the inputs
2764 // - do not appear in the where-clauses
2765 // - are not implicitly captured by `impl Trait`
2766 for param in generics.params {
2768 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2770 // Neither types nor consts are late-bound.
2771 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2774 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
2775 // appears in the where clauses? early-bound.
2776 if appears_in_where_clause.regions.contains(<_name) {
2780 // does not appear in the inputs, but appears in the return type? early-bound.
2781 if !constrained_by_input.regions.contains(<_name)
2782 && appears_in_output.regions.contains(<_name)
2788 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2793 let inserted = map.late_bound.insert(param.hir_id);
2794 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
2800 struct ConstrainedCollector {
2801 regions: FxHashSet<hir::LifetimeName>,
2804 impl<'v> Visitor<'v> for ConstrainedCollector {
2805 type Map = intravisit::ErasedMap<'v>;
2807 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2808 NestedVisitorMap::None
2811 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2814 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2816 // ignore lifetimes appearing in associated type
2817 // projections, as they are not *constrained*
2821 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2822 // consider only the lifetimes on the final
2823 // segment; I am not sure it's even currently
2824 // valid to have them elsewhere, but even if it
2825 // is, those would be potentially inputs to
2827 if let Some(last_segment) = path.segments.last() {
2828 self.visit_path_segment(path.span, last_segment);
2833 intravisit::walk_ty(self, ty);
2838 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2839 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
2844 struct AllCollector {
2845 regions: FxHashSet<hir::LifetimeName>,
2848 impl<'v> Visitor<'v> for AllCollector {
2849 type Map = intravisit::ErasedMap<'v>;
2851 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2852 NestedVisitorMap::None
2855 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2856 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());