1 // ignore-tidy-filelength
2 //! Name resolution for lifetimes.
4 //! Name resolution for lifetimes follows *much* simpler rules than the
5 //! full resolve. For example, lifetime names are never exported or
6 //! used between functions, and they operate in a purely top-down
7 //! way. Therefore, we break lifetime name resolution into a separate pass.
9 use crate::late::diagnostics::{ForLifetimeSpanType, MissingLifetimeSpot};
10 use rustc_ast::walk_list;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::{DefIdMap, LocalDefId};
16 use rustc_hir::hir_id::ItemLocalId;
17 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
18 use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath};
19 use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::middle::resolve_lifetime::*;
22 use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
23 use rustc_middle::{bug, span_bug};
24 use rustc_session::lint;
25 use rustc_span::def_id::DefId;
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
33 use tracing::{debug, span, Level};
35 // This counts the no of times a lifetime is used
36 #[derive(Clone, Copy, Debug)]
37 pub enum LifetimeUseSet<'tcx> {
38 One(&'tcx hir::Lifetime),
43 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
45 fn late(index: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
47 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region;
49 fn id(&self) -> Option<DefId>;
51 fn shifted(self, amount: u32) -> Region;
53 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
55 fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
57 L: Iterator<Item = &'a hir::Lifetime>;
60 impl RegionExt for Region {
61 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
64 let def_id = hir_map.local_def_id(param.hir_id);
65 let origin = LifetimeDefOrigin::from_param(param);
66 debug!("Region::early: index={} def_id={:?}", i, def_id);
67 (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id(), origin))
70 fn late(idx: u32, hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
71 let depth = ty::INNERMOST;
72 let def_id = hir_map.local_def_id(param.hir_id);
73 let origin = LifetimeDefOrigin::from_param(param);
75 "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?} origin={:?}",
76 idx, param, depth, def_id, origin,
79 param.name.normalize_to_macros_2_0(),
80 Region::LateBound(depth, idx, def_id.to_def_id(), origin),
84 fn late_anon(named_late_bound_vars: u32, index: &Cell<u32>) -> Region {
87 let depth = ty::INNERMOST;
88 Region::LateBoundAnon(depth, named_late_bound_vars + i, i)
91 fn id(&self) -> Option<DefId> {
93 Region::Static | Region::LateBoundAnon(..) => None,
95 Region::EarlyBound(_, id, _) | Region::LateBound(_, _, id, _) | Region::Free(_, id) => {
101 fn shifted(self, amount: u32) -> Region {
103 Region::LateBound(debruijn, idx, id, origin) => {
104 Region::LateBound(debruijn.shifted_in(amount), idx, id, origin)
106 Region::LateBoundAnon(debruijn, index, anon_index) => {
107 Region::LateBoundAnon(debruijn.shifted_in(amount), index, anon_index)
113 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
115 Region::LateBound(debruijn, index, id, origin) => {
116 Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id, origin)
118 Region::LateBoundAnon(debruijn, index, anon_index) => {
119 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index, anon_index)
125 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
127 L: Iterator<Item = &'a hir::Lifetime>,
129 if let Region::EarlyBound(index, _, _) = self {
130 params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
137 /// Maps the id of each lifetime reference to the lifetime decl
138 /// that it corresponds to.
140 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
141 /// actual use. It has the same data, but indexed by `LocalDefId`. This
143 #[derive(Debug, Default)]
144 struct NamedRegionMap {
145 // maps from every use of a named (not anonymous) lifetime to a
146 // `Region` describing how that region is bound
147 defs: HirIdMap<Region>,
149 // the set of lifetime def ids that are late-bound; a region can
150 // be late-bound if (a) it does NOT appear in a where-clause and
151 // (b) it DOES appear in the arguments.
152 late_bound: HirIdSet,
154 // Maps relevant hir items to the bound vars on them. These include:
156 // - function pointers
159 // - bound types (like `T` in `for<'a> T<'a>: Foo`)
160 late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
162 // maps `PathSegment` `HirId`s to lifetime scopes.
163 scope_for_path: Option<FxHashMap<LocalDefId, FxHashMap<ItemLocalId, LifetimeScopeForPath>>>,
166 crate struct LifetimeContext<'a, 'tcx> {
167 crate tcx: TyCtxt<'tcx>,
168 map: &'a mut NamedRegionMap,
171 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
172 is_in_fn_syntax: bool,
174 is_in_const_generic: bool,
176 /// Indicates that we only care about the definition of a trait. This should
177 /// be false if the `Item` we are resolving lifetimes for is not a trait or
178 /// we eventually need lifetimes resolve for trait items.
179 trait_definition_only: bool,
181 /// List of labels in the function/method currently under analysis.
182 labels_in_fn: Vec<Ident>,
184 /// Cache for cross-crate per-definition object lifetime defaults.
185 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
187 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
189 /// When encountering an undefined named lifetime, we will suggest introducing it in these
191 crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
196 /// Declares lifetimes, and each can be early-bound or late-bound.
197 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
198 /// it should be shifted by the number of `Binder`s in between the
199 /// declaration `Binder` and the location it's referenced from.
201 /// We use an IndexMap here because we want these lifetimes in order
203 lifetimes: FxIndexMap<hir::ParamName, Region>,
205 /// if we extend this scope with another scope, what is the next index
206 /// we should use for an early-bound region?
207 next_early_index: u32,
209 /// Flag is set to true if, in this binder, `'_` would be
210 /// equivalent to a "single-use region". This is true on
211 /// impls, but not other kinds of items.
212 track_lifetime_uses: bool,
214 /// Whether or not this binder would serve as the parent
215 /// binder for opaque types introduced within. For example:
218 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
221 /// Here, the opaque types we create for the `impl Trait`
222 /// and `impl Trait2` references will both have the `foo` item
223 /// as their parent. When we get to `impl Trait2`, we find
224 /// that it is nested within the `for<>` binder -- this flag
225 /// allows us to skip that when looking for the parent binder
226 /// of the resulting opaque type.
227 opaque_type_parent: bool,
229 scope_type: BinderScopeType,
231 /// The late bound vars for a given item are stored by `HirId` to be
232 /// queried later. However, if we enter an elision scope, we have to
233 /// later append the elided bound vars to the list and need to know what
240 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
241 /// if this is a fn body, otherwise the original definitions are used.
242 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
243 /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
249 /// A scope which either determines unspecified lifetimes or errors
250 /// on them (e.g., due to ambiguity). For more details, see `Elide`.
256 /// Use a specific lifetime (if `Some`) or leave it unset (to be
257 /// inferred in a function body or potentially error outside one),
258 /// for the default choice of lifetime in a trait object type.
259 ObjectLifetimeDefault {
260 lifetime: Option<Region>,
264 /// When we have nested trait refs, we concanetate late bound vars for inner
265 /// trait refs from outer ones. But we also need to include any HRTB
266 /// lifetimes encountered when identifying the trait that an associated type
269 lifetimes: Vec<ty::BoundVariableKind>,
280 #[derive(Copy, Clone, Debug)]
281 enum BinderScopeType {
282 /// Any non-concatenating binder scopes.
284 /// Within a syntactic trait ref, there may be multiple poly trait refs that
285 /// are nested (under the `associcated_type_bounds` feature). The binders of
286 /// the innner poly trait refs are extended from the outer poly trait refs
287 /// and don't increase the late bound depth. If you had
288 /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
289 /// would be `Concatenating`. This also used in trait refs in where clauses
290 /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
291 /// out any lifetimes because they aren't needed to show the two scopes).
292 /// The inner `for<>` has a scope of `Concatenating`.
296 // A helper struct for debugging scopes without printing parent scopes
297 struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
299 impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 .debug_struct("Binder")
312 .field("lifetimes", lifetimes)
313 .field("next_early_index", next_early_index)
314 .field("track_lifetime_uses", track_lifetime_uses)
315 .field("opaque_type_parent", opaque_type_parent)
316 .field("scope_type", scope_type)
317 .field("hir_id", hir_id)
320 Scope::Body { id, s: _ } => {
321 f.debug_struct("Body").field("id", id).field("s", &"..").finish()
323 Scope::Elision { elide, s: _ } => {
324 f.debug_struct("Elision").field("elide", elide).field("s", &"..").finish()
326 Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
327 .debug_struct("ObjectLifetimeDefault")
328 .field("lifetime", lifetime)
331 Scope::Supertrait { lifetimes, s: _ } => f
332 .debug_struct("Supertrait")
333 .field("lifetimes", lifetimes)
336 Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
337 Scope::Root => f.debug_struct("Root").finish(),
342 #[derive(Clone, Debug)]
344 /// Use a fresh anonymous late-bound lifetime each time, by
345 /// incrementing the counter to generate sequential indices. All
346 /// anonymous lifetimes must start *after* named bound vars.
347 FreshLateAnon(u32, Cell<u32>),
348 /// Always use this one lifetime.
350 /// Less or more than one lifetime were found, error on unspecified.
351 Error(Vec<ElisionFailureInfo>),
352 /// Forbid lifetime elision inside of a larger scope where it would be
353 /// permitted. For example, in let position impl trait.
357 #[derive(Clone, Debug)]
358 crate struct ElisionFailureInfo {
359 /// Where we can find the argument pattern.
360 crate parent: Option<hir::BodyId>,
361 /// The index of the argument in the original definition.
363 crate lifetime_count: usize,
364 crate have_bound_regions: bool,
368 type ScopeRef<'a> = &'a Scope<'a>;
370 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
372 pub fn provide(providers: &mut ty::query::Providers) {
373 *providers = ty::query::Providers {
374 resolve_lifetimes_trait_definition,
377 named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
379 object_lifetime_defaults_map: |tcx, id| match tcx.hir().find_by_def_id(id) {
380 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
383 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
384 lifetime_scope_map: |tcx, id| {
385 let item_id = item_for(tcx, id);
386 do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
393 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
394 /// Also does not generate any diagnostics.
396 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
397 /// resolves lifetimes only within the trait "header" -- that is, the trait
398 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
399 /// lifetimes within the trait and its items. There is room to refactor this,
400 /// for example to resolve lifetimes for each trait item in separate queries,
401 /// but it's convenient to do the entire trait at once because the lifetimes
402 /// from the trait definition are in scope within the trait items as well.
404 /// The reason for this separate call is to resolve what would otherwise
405 /// be a cycle. Consider this example:
411 /// trait Sub<'b>: for<'a> Base<'a> {
412 /// type SubItem: Sub<BaseItem = &'b u32>;
416 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
417 /// To figure out the index of `'b`, we have to know about the supertraits
418 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
419 /// (This is because we -- currently at least -- flatten all the late-bound
420 /// lifetimes into a single binder.) This requires us to resolve the
421 /// *trait definition* of `Sub`; basically just enough lifetime information
422 /// to look at the supertraits.
423 #[tracing::instrument(level = "debug", skip(tcx))]
424 fn resolve_lifetimes_trait_definition(
426 local_def_id: LocalDefId,
427 ) -> ResolveLifetimes {
428 convert_named_region_map(do_resolve(tcx, local_def_id, true, false))
431 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
432 /// You should not read the result of this query directly, but rather use
433 /// `named_region_map`, `is_late_bound_map`, etc.
434 #[tracing::instrument(level = "debug", skip(tcx))]
435 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
436 convert_named_region_map(do_resolve(tcx, local_def_id, false, false))
441 local_def_id: LocalDefId,
442 trait_definition_only: bool,
443 with_scope_for_path: bool,
444 ) -> NamedRegionMap {
445 let item = tcx.hir().expect_item(local_def_id);
446 let mut named_region_map = NamedRegionMap {
447 defs: Default::default(),
448 late_bound: Default::default(),
449 late_bound_vars: Default::default(),
450 scope_for_path: with_scope_for_path.then(|| Default::default()),
452 let mut visitor = LifetimeContext {
454 map: &mut named_region_map,
456 is_in_fn_syntax: false,
457 is_in_const_generic: false,
458 trait_definition_only,
459 labels_in_fn: vec![],
460 xcrate_object_lifetime_defaults: Default::default(),
461 lifetime_uses: &mut Default::default(),
462 missing_named_lifetime_spots: vec![],
464 visitor.visit_item(item);
469 fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes {
470 let mut rl = ResolveLifetimes::default();
472 for (hir_id, v) in named_region_map.defs {
473 let map = rl.defs.entry(hir_id.owner).or_default();
474 map.insert(hir_id.local_id, v);
476 for hir_id in named_region_map.late_bound {
477 let map = rl.late_bound.entry(hir_id.owner).or_default();
478 map.insert(hir_id.local_id);
480 for (hir_id, v) in named_region_map.late_bound_vars {
481 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
482 map.insert(hir_id.local_id, v);
489 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
490 /// There are two important things this does.
491 /// First, we have to resolve lifetimes for
492 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
493 /// where we can have relevant lifetimes.
494 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
495 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
496 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
497 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
498 /// `resolve_lifetimes`.
499 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
500 let item_id = item_for(tcx, def_id);
501 if item_id == def_id {
502 let item = tcx.hir().item(hir::ItemId { def_id: item_id });
504 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
505 _ => tcx.resolve_lifetimes(item_id),
508 tcx.resolve_lifetimes(item_id)
512 /// Finds the `Item` that contains the given `LocalDefId`
513 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
514 match tcx.hir().find_by_def_id(local_def_id) {
515 Some(Node::Item(item)) => {
521 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
522 let mut parent_iter = tcx.hir().parent_iter(hir_id);
524 let node = parent_iter.next().map(|n| n.1);
526 Some(hir::Node::Item(item)) => break item.def_id,
527 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
535 fn is_late_bound_map<'tcx>(
538 ) -> Option<(LocalDefId, &'tcx FxHashSet<ItemLocalId>)> {
539 match tcx.def_kind(def_id) {
540 DefKind::AnonConst | DefKind::InlineConst => {
542 .parent(def_id.to_def_id())
543 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
544 // We search for the next outer anon const or fn here
545 // while skipping closures.
547 // Note that for `AnonConst` we still just recurse until we
548 // find a function body, but who cares :shrug:
549 while tcx.is_closure(def_id) {
552 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
555 tcx.is_late_bound_map(def_id.expect_local())
557 _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
561 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
562 /// We have to account for this when computing the index of the other generic parameters.
563 /// This function returns whether there is such an implicit parameter defined on the given item.
564 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
565 matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
568 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
570 Region::LateBound(_, _, def_id, _) => {
571 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
572 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
574 Region::LateBoundAnon(_, _, anon_idx) => {
575 ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
577 _ => bug!("{:?} is not a late region", region),
581 #[tracing::instrument(level = "debug")]
582 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
583 let mut available_lifetimes = vec![];
586 Scope::Binder { lifetimes, s, .. } => {
587 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
588 hir::ParamName::Plain(ident) => Some(ident.name.to_string()),
593 Scope::Body { s, .. } => {
596 Scope::Elision { elide, s } => {
597 if let Elide::Exact(_) = elide {
598 return LifetimeScopeForPath::Elided;
603 Scope::ObjectLifetimeDefault { s, .. } => {
607 return LifetimeScopeForPath::NonElided(available_lifetimes);
609 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
616 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
617 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
618 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
619 let mut scope = self.scope;
620 let mut supertrait_lifetimes = vec![];
623 Scope::Body { .. } | Scope::Root => {
624 break (vec![], BinderScopeType::Normal);
627 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
631 Scope::Supertrait { s, lifetimes } => {
632 supertrait_lifetimes = lifetimes.clone();
636 Scope::TraitRefBoundary { .. } => {
637 // We should only see super trait lifetimes if there is a `Binder` above
638 assert!(supertrait_lifetimes.is_empty());
639 break (vec![], BinderScopeType::Normal);
642 Scope::Binder { hir_id, .. } => {
643 // Nested poly trait refs have the binders concatenated
644 let mut full_binders =
645 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
646 full_binders.extend(supertrait_lifetimes.into_iter());
647 break (full_binders, BinderScopeType::Concatenating);
653 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
654 type Map = Map<'tcx>;
656 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
657 NestedVisitorMap::All(self.tcx.hir())
660 // We want to nest trait/impl items in their parent, but nothing else.
661 fn visit_nested_item(&mut self, _: hir::ItemId) {}
663 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
664 if !self.trait_definition_only {
665 intravisit::walk_trait_item_ref(self, ii)
669 fn visit_nested_body(&mut self, body: hir::BodyId) {
670 // Each body has their own set of labels, save labels.
671 let saved = take(&mut self.labels_in_fn);
672 let body = self.tcx.hir().body(body);
673 extract_labels(self, body);
674 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
675 this.visit_body(body);
677 self.labels_in_fn = saved;
682 fk: intravisit::FnKind<'tcx>,
683 fd: &'tcx hir::FnDecl<'tcx>,
688 let name = match fk {
689 intravisit::FnKind::ItemFn(id, _, _, _) => id.name,
690 intravisit::FnKind::Method(id, _, _) => id.name,
691 intravisit::FnKind::Closure => sym::closure,
693 let name = name.as_str();
694 let span = span!(Level::DEBUG, "visit_fn", name);
695 let _enter = span.enter();
697 // Any `Binders` are handled elsewhere
698 intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
699 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
701 intravisit::FnKind::Closure => {
702 self.map.late_bound_vars.insert(hir_id, vec![]);
703 let scope = Scope::Binder {
705 lifetimes: FxIndexMap::default(),
706 next_early_index: self.next_early_index(),
708 track_lifetime_uses: true,
709 opaque_type_parent: false,
710 scope_type: BinderScopeType::Normal,
712 self.with(scope, move |_old_scope, this| {
713 intravisit::walk_fn(this, fk, fd, b, s, hir_id)
719 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
721 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
722 if let Some(of_trait) = of_trait {
723 self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
729 hir::ItemKind::Fn(ref sig, ref generics, _) => {
730 self.missing_named_lifetime_spots.push(generics.into());
731 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
732 intravisit::walk_item(this, item);
734 self.missing_named_lifetime_spots.pop();
737 hir::ItemKind::ExternCrate(_)
738 | hir::ItemKind::Use(..)
739 | hir::ItemKind::Macro(..)
740 | hir::ItemKind::Mod(..)
741 | hir::ItemKind::ForeignMod { .. }
742 | hir::ItemKind::GlobalAsm(..) => {
743 // These sorts of items have no lifetime parameters at all.
744 intravisit::walk_item(self, item);
746 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
747 // No lifetime parameters, but implied 'static.
748 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
749 self.with(scope, |_, this| intravisit::walk_item(this, item));
751 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
752 // Opaque types are visited when we visit the
753 // `TyKind::OpaqueDef`, so that they have the lifetimes from
754 // their parent opaque_ty in scope.
756 // The core idea here is that since OpaqueTys are generated with the impl Trait as
757 // their owner, we can keep going until we find the Item that owns that. We then
758 // conservatively add all resolved lifetimes. Otherwise we run into problems in
759 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
760 for (_hir_id, node) in
761 self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
764 hir::Node::Item(parent_item) => {
765 let resolved_lifetimes: &ResolveLifetimes =
766 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
767 // We need to add *all* deps, since opaque tys may want them from *us*
768 for (&owner, defs) in resolved_lifetimes.defs.iter() {
769 defs.iter().for_each(|(&local_id, region)| {
770 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
773 for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
774 late_bound.iter().for_each(|&local_id| {
775 self.map.late_bound.insert(hir::HirId { owner, local_id });
778 for (&owner, late_bound_vars) in
779 resolved_lifetimes.late_bound_vars.iter()
781 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
782 self.map.late_bound_vars.insert(
783 hir::HirId { owner, local_id },
784 late_bound_vars.clone(),
790 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
795 hir::ItemKind::TyAlias(_, ref generics)
796 | hir::ItemKind::Enum(_, ref generics)
797 | hir::ItemKind::Struct(_, ref generics)
798 | hir::ItemKind::Union(_, ref generics)
799 | hir::ItemKind::Trait(_, _, ref generics, ..)
800 | hir::ItemKind::TraitAlias(ref generics, ..)
801 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
802 self.missing_named_lifetime_spots.push(generics.into());
804 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
805 // This is not true for other kinds of items.
806 let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
807 // These kinds of items have only early-bound lifetime parameters.
808 let mut index = if sub_items_have_self_param(&item.kind) {
809 1 // Self comes before lifetimes
813 let mut non_lifetime_count = 0;
814 let lifetimes = generics
817 .filter_map(|param| match param.kind {
818 GenericParamKind::Lifetime { .. } => {
819 Some(Region::early(&self.tcx.hir(), &mut index, param))
821 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
822 non_lifetime_count += 1;
827 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
828 let scope = Scope::Binder {
829 hir_id: item.hir_id(),
831 next_early_index: index + non_lifetime_count,
832 opaque_type_parent: true,
834 scope_type: BinderScopeType::Normal,
837 self.with(scope, |old_scope, this| {
838 this.check_lifetime_params(old_scope, &generics.params);
839 let scope = Scope::TraitRefBoundary { s: this.scope };
840 this.with(scope, |_, this| {
841 intravisit::walk_item(this, item);
844 self.missing_named_lifetime_spots.pop();
849 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
851 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
852 self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
853 intravisit::walk_foreign_item(this, item);
856 hir::ForeignItemKind::Static(..) => {
857 intravisit::walk_foreign_item(self, item);
859 hir::ForeignItemKind::Type => {
860 intravisit::walk_foreign_item(self, item);
865 #[tracing::instrument(level = "debug", skip(self))]
866 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
868 hir::TyKind::BareFn(ref c) => {
869 let next_early_index = self.next_early_index();
870 let was_in_fn_syntax = self.is_in_fn_syntax;
871 self.is_in_fn_syntax = true;
872 let lifetime_span: Option<Span> =
873 c.generic_params.iter().rev().find_map(|param| match param.kind {
874 GenericParamKind::Lifetime { .. } => Some(param.span),
877 let (span, span_type) = if let Some(span) = lifetime_span {
878 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
880 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
882 self.missing_named_lifetime_spots
883 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
884 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
887 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
889 .map(|(late_bound_idx, param)| {
890 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
891 let r = late_region_as_bound_region(self.tcx, &pair.1);
895 self.map.late_bound_vars.insert(ty.hir_id, binders);
896 let scope = Scope::Binder {
901 track_lifetime_uses: true,
902 opaque_type_parent: false,
903 scope_type: BinderScopeType::Normal,
905 self.with(scope, |old_scope, this| {
906 // a bare fn has no bounds, so everything
907 // contained within is scoped within its binder.
908 this.check_lifetime_params(old_scope, &c.generic_params);
909 intravisit::walk_ty(this, ty);
911 self.missing_named_lifetime_spots.pop();
912 self.is_in_fn_syntax = was_in_fn_syntax;
914 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
915 debug!(?bounds, ?lifetime, "TraitObject");
916 let scope = Scope::TraitRefBoundary { s: self.scope };
917 self.with(scope, |_, this| {
918 for bound in bounds {
919 this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
922 match lifetime.name {
923 LifetimeName::Implicit(_) => {
924 // For types like `dyn Foo`, we should
925 // generate a special form of elided.
926 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
928 LifetimeName::ImplicitObjectLifetimeDefault => {
929 // If the user does not write *anything*, we
930 // use the object lifetime defaulting
931 // rules. So e.g., `Box<dyn Debug>` becomes
932 // `Box<dyn Debug + 'static>`.
933 self.resolve_object_lifetime_default(lifetime)
935 LifetimeName::Underscore => {
936 // If the user writes `'_`, we use the *ordinary* elision
937 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
938 // resolved the same as the `'_` in `&'_ Foo`.
941 self.resolve_elided_lifetimes(&[lifetime])
943 LifetimeName::Param(_) | LifetimeName::Static => {
944 // If the user wrote an explicit name, use that.
945 self.visit_lifetime(lifetime);
947 LifetimeName::Error => {}
950 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
951 self.visit_lifetime(lifetime_ref);
952 let scope = Scope::ObjectLifetimeDefault {
953 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
956 self.with(scope, |_, this| this.visit_ty(&mt.ty));
958 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
959 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
960 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
961 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
962 // ^ ^ this gets resolved in the scope of
963 // the opaque_ty generics
964 let opaque_ty = self.tcx.hir().item(item_id);
965 let (generics, bounds) = match opaque_ty.kind {
966 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
967 // This arm is for `impl Trait` in the types of statics, constants and locals.
968 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
969 origin: hir::OpaqueTyOrigin::TyAlias,
972 intravisit::walk_ty(self, ty);
974 // Elided lifetimes are not allowed in non-return
975 // position impl Trait
976 let scope = Scope::TraitRefBoundary { s: self.scope };
977 self.with(scope, |_, this| {
978 let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
979 this.with(scope, |_, this| {
980 intravisit::walk_item(this, opaque_ty);
986 // RPIT (return position impl trait)
987 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
988 origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
992 }) => (generics, bounds),
993 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
996 // Resolve the lifetimes that are applied to the opaque type.
997 // These are resolved in the current scope.
998 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
999 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
1000 // ^ ^this gets resolved in the current scope
1001 for lifetime in lifetimes {
1002 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
1003 self.visit_lifetime(lifetime);
1005 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1006 // and ban them. Type variables instantiated inside binders aren't
1007 // well-supported at the moment, so this doesn't work.
1008 // In the future, this should be fixed and this error should be removed.
1009 let def = self.map.defs.get(&lifetime.hir_id).cloned();
1010 if let Some(Region::LateBound(_, _, def_id, _)) = def {
1011 if let Some(def_id) = def_id.as_local() {
1012 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1013 // Ensure that the parent of the def is an item, not HRTB
1014 let parent_id = self.tcx.hir().get_parent_node(hir_id);
1015 // FIXME(cjgillot) Can this check be replaced by
1016 // `let parent_is_item = parent_id.is_owner();`?
1017 let parent_is_item =
1018 if let Some(parent_def_id) = parent_id.as_owner() {
1020 self.tcx.hir().krate().owners.get(parent_def_id),
1027 if !parent_is_item {
1028 if !self.trait_definition_only {
1033 "`impl Trait` can only capture lifetimes \
1034 bound at the fn or impl level"
1038 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1045 // We want to start our early-bound indices at the end of the parent scope,
1046 // not including any parent `impl Trait`s.
1047 let mut index = self.next_early_index_for_opaque_type();
1050 let mut elision = None;
1051 let mut lifetimes = FxIndexMap::default();
1052 let mut non_lifetime_count = 0;
1053 for param in generics.params {
1055 GenericParamKind::Lifetime { .. } => {
1056 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
1057 let Region::EarlyBound(_, def_id, _) = reg else {
1060 // We cannot predict what lifetimes are unused in opaque type.
1061 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
1062 if let hir::ParamName::Plain(Ident {
1063 name: kw::UnderscoreLifetime,
1067 // Pick the elided lifetime "definition" if one exists
1068 // and use it to make an elision scope.
1069 elision = Some(reg);
1071 lifetimes.insert(name, reg);
1074 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1075 non_lifetime_count += 1;
1079 let next_early_index = index + non_lifetime_count;
1080 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1082 if let Some(elision_region) = elision {
1084 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1085 self.with(scope, |_old_scope, this| {
1086 let scope = Scope::Binder {
1091 track_lifetime_uses: true,
1092 opaque_type_parent: false,
1093 scope_type: BinderScopeType::Normal,
1095 this.with(scope, |_old_scope, this| {
1096 this.visit_generics(generics);
1097 let scope = Scope::TraitRefBoundary { s: this.scope };
1098 this.with(scope, |_, this| {
1099 for bound in bounds {
1100 this.visit_param_bound(bound);
1106 let scope = Scope::Binder {
1111 track_lifetime_uses: true,
1112 opaque_type_parent: false,
1113 scope_type: BinderScopeType::Normal,
1115 self.with(scope, |_old_scope, this| {
1116 let scope = Scope::TraitRefBoundary { s: this.scope };
1117 this.with(scope, |_, this| {
1118 this.visit_generics(generics);
1119 for bound in bounds {
1120 this.visit_param_bound(bound);
1126 _ => intravisit::walk_ty(self, ty),
1130 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1131 use self::hir::TraitItemKind::*;
1132 match trait_item.kind {
1134 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1136 self.visit_early_late(
1137 Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1138 trait_item.hir_id(),
1140 &trait_item.generics,
1141 |this| intravisit::walk_trait_item(this, trait_item),
1143 self.missing_named_lifetime_spots.pop();
1145 Type(bounds, ref ty) => {
1146 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1147 let generics = &trait_item.generics;
1148 let mut index = self.next_early_index();
1149 debug!("visit_ty: index = {}", index);
1150 let mut non_lifetime_count = 0;
1151 let lifetimes = generics
1154 .filter_map(|param| match param.kind {
1155 GenericParamKind::Lifetime { .. } => {
1156 Some(Region::early(&self.tcx.hir(), &mut index, param))
1158 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1159 non_lifetime_count += 1;
1164 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1165 let scope = Scope::Binder {
1166 hir_id: trait_item.hir_id(),
1168 next_early_index: index + non_lifetime_count,
1170 track_lifetime_uses: true,
1171 opaque_type_parent: true,
1172 scope_type: BinderScopeType::Normal,
1174 self.with(scope, |old_scope, this| {
1175 this.check_lifetime_params(old_scope, &generics.params);
1176 let scope = Scope::TraitRefBoundary { s: this.scope };
1177 this.with(scope, |_, this| {
1178 this.visit_generics(generics);
1179 for bound in bounds {
1180 this.visit_param_bound(bound);
1182 if let Some(ty) = ty {
1187 self.missing_named_lifetime_spots.pop();
1190 // Only methods and types support generics.
1191 assert!(trait_item.generics.params.is_empty());
1192 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1193 intravisit::walk_trait_item(self, trait_item);
1194 self.missing_named_lifetime_spots.pop();
1199 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1200 use self::hir::ImplItemKind::*;
1201 match impl_item.kind {
1203 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1205 self.visit_early_late(
1206 Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1209 &impl_item.generics,
1210 |this| intravisit::walk_impl_item(this, impl_item),
1212 self.missing_named_lifetime_spots.pop();
1214 TyAlias(ref ty) => {
1215 let generics = &impl_item.generics;
1216 self.missing_named_lifetime_spots.push(generics.into());
1217 let mut index = self.next_early_index();
1218 let mut non_lifetime_count = 0;
1219 debug!("visit_ty: index = {}", index);
1220 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1223 .filter_map(|param| match param.kind {
1224 GenericParamKind::Lifetime { .. } => {
1225 Some(Region::early(&self.tcx.hir(), &mut index, param))
1227 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1228 non_lifetime_count += 1;
1233 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1234 let scope = Scope::Binder {
1237 next_early_index: index + non_lifetime_count,
1239 track_lifetime_uses: true,
1240 opaque_type_parent: true,
1241 scope_type: BinderScopeType::Normal,
1243 self.with(scope, |old_scope, this| {
1244 this.check_lifetime_params(old_scope, &generics.params);
1245 let scope = Scope::TraitRefBoundary { s: this.scope };
1246 this.with(scope, |_, this| {
1247 this.visit_generics(generics);
1251 self.missing_named_lifetime_spots.pop();
1254 // Only methods and types support generics.
1255 assert!(impl_item.generics.params.is_empty());
1256 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1257 intravisit::walk_impl_item(self, impl_item);
1258 self.missing_named_lifetime_spots.pop();
1263 #[tracing::instrument(level = "debug", skip(self))]
1264 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1265 if lifetime_ref.is_elided() {
1266 self.resolve_elided_lifetimes(&[lifetime_ref]);
1269 if lifetime_ref.is_static() {
1270 self.insert_lifetime(lifetime_ref, Region::Static);
1273 if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
1274 self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
1277 self.resolve_lifetime_ref(lifetime_ref);
1280 fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1281 let scope = self.scope;
1282 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1283 // We add lifetime scope information for `Ident`s in associated type bindings and use
1284 // the `HirId` of the type binding as the key in `LifetimeMap`
1285 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1286 let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1287 map.insert(type_binding.hir_id.local_id, lifetime_scope);
1289 hir::intravisit::walk_assoc_type_binding(self, type_binding);
1292 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1293 for (i, segment) in path.segments.iter().enumerate() {
1294 let depth = path.segments.len() - i - 1;
1295 if let Some(ref args) = segment.args {
1296 self.visit_segment_args(path.res, depth, args);
1299 let scope = self.scope;
1300 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1301 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1302 // here because that call would yield to resolution problems due to `walk_path_segment`
1303 // being called, which processes the path segments generic args, which we have already
1304 // processed using `visit_segment_args`.
1305 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1306 if let Some(hir_id) = segment.hir_id {
1307 let map = scope_for_path.entry(hir_id.owner).or_default();
1308 map.insert(hir_id.local_id, lifetime_scope);
1314 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1315 let scope = self.scope;
1316 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1317 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1318 if let Some(hir_id) = path_segment.hir_id {
1319 let map = scope_for_path.entry(hir_id.owner).or_default();
1320 map.insert(hir_id.local_id, lifetime_scope);
1324 intravisit::walk_path_segment(self, path_span, path_segment);
1327 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1328 let output = match fd.output {
1329 hir::FnRetTy::DefaultReturn(_) => None,
1330 hir::FnRetTy::Return(ref ty) => Some(&**ty),
1332 self.visit_fn_like_elision(&fd.inputs, output);
1335 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1336 if !self.trait_definition_only {
1337 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
1339 let scope = Scope::TraitRefBoundary { s: self.scope };
1340 self.with(scope, |_, this| {
1341 for param in generics.params {
1343 GenericParamKind::Lifetime { .. } => {}
1344 GenericParamKind::Type { ref default, .. } => {
1345 walk_list!(this, visit_param_bound, param.bounds);
1346 if let Some(ref ty) = default {
1350 GenericParamKind::Const { ref ty, .. } => {
1351 let was_in_const_generic = this.is_in_const_generic;
1352 this.is_in_const_generic = true;
1353 walk_list!(this, visit_param_bound, param.bounds);
1355 this.is_in_const_generic = was_in_const_generic;
1359 for predicate in generics.where_clause.predicates {
1361 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1364 ref bound_generic_params,
1367 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1368 bound_generic_params
1371 matches!(param.kind, GenericParamKind::Lifetime { .. })
1374 .map(|(late_bound_idx, param)| {
1376 Region::late(late_bound_idx as u32, &this.tcx.hir(), param);
1377 let r = late_region_as_bound_region(this.tcx, &pair.1);
1381 this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1382 let next_early_index = this.next_early_index();
1383 // Even if there are no lifetimes defined here, we still wrap it in a binder
1384 // scope. If there happens to be a nested poly trait ref (an error), that
1385 // will be `Concatenating` anyways, so we don't have to worry about the depth
1387 let scope = Scope::Binder {
1388 hir_id: bounded_ty.hir_id,
1392 track_lifetime_uses: true,
1393 opaque_type_parent: false,
1394 scope_type: BinderScopeType::Normal,
1396 this.with(scope, |old_scope, this| {
1397 this.check_lifetime_params(old_scope, &bound_generic_params);
1398 this.visit_ty(&bounded_ty);
1399 walk_list!(this, visit_param_bound, bounds);
1402 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1407 this.visit_lifetime(lifetime);
1408 walk_list!(this, visit_param_bound, bounds);
1410 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1415 this.visit_ty(lhs_ty);
1416 this.visit_ty(rhs_ty);
1423 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1425 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1426 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1427 // through the regular poly trait ref code, so we don't get another
1428 // chance to introduce a binder. For now, I'm keeping the existing logic
1429 // of "if there isn't a Binder scope above us, add one", but I
1430 // imagine there's a better way to go about this.
1431 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1433 self.map.late_bound_vars.insert(*hir_id, binders);
1434 let scope = Scope::Binder {
1436 lifetimes: FxIndexMap::default(),
1438 next_early_index: self.next_early_index(),
1439 track_lifetime_uses: true,
1440 opaque_type_parent: false,
1443 self.with(scope, |_, this| {
1444 intravisit::walk_param_bound(this, bound);
1447 _ => intravisit::walk_param_bound(self, bound),
1451 fn visit_poly_trait_ref(
1453 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1454 _modifier: hir::TraitBoundModifier,
1456 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1458 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1460 let next_early_index = self.next_early_index();
1461 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1463 let initial_bound_vars = binders.len() as u32;
1464 let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1465 let binders_iter = trait_ref
1466 .bound_generic_params
1468 .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
1470 .map(|(late_bound_idx, param)| {
1471 let pair = Region::late(
1472 initial_bound_vars + late_bound_idx as u32,
1476 let r = late_region_as_bound_region(self.tcx, &pair.1);
1477 lifetimes.insert(pair.0, pair.1);
1480 binders.extend(binders_iter);
1483 self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1485 // Always introduce a scope here, even if this is in a where clause and
1486 // we introduced the binders around the bounded Ty. In that case, we
1487 // just reuse the concatenation functionality also present in nested trait
1489 let scope = Scope::Binder {
1490 hir_id: trait_ref.trait_ref.hir_ref_id,
1494 track_lifetime_uses: true,
1495 opaque_type_parent: false,
1498 self.with(scope, |old_scope, this| {
1499 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1500 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1501 this.visit_trait_ref(&trait_ref.trait_ref);
1504 if should_pop_missing_lt {
1505 self.missing_named_lifetime_spots.pop();
1510 #[derive(Copy, Clone, PartialEq)]
1524 fn original_label(span: Span) -> Original {
1525 Original { kind: ShadowKind::Label, span }
1527 fn shadower_label(span: Span) -> Shadower {
1528 Shadower { kind: ShadowKind::Label, span }
1530 fn original_lifetime(span: Span) -> Original {
1531 Original { kind: ShadowKind::Lifetime, span }
1533 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1534 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1538 fn desc(&self) -> &'static str {
1540 ShadowKind::Label => "label",
1541 ShadowKind::Lifetime => "lifetime",
1546 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1547 let lifetime_params: Vec<_> = params
1549 .filter_map(|param| match param.kind {
1550 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1554 let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1555 let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1557 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1562 "cannot mix in-band and explicit lifetime definitions"
1564 .span_label(*in_band_span, "in-band lifetime definition here")
1565 .span_label(*explicit_span, "explicit lifetime definition here")
1570 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1571 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1572 // lifetime/lifetime shadowing is an error
1577 "{} name `{}` shadows a \
1578 {} name that is already in scope",
1579 shadower.kind.desc(),
1584 // shadowing involving a label is only a warning, due to issues with
1585 // labels and lifetimes not being macro-hygienic.
1586 tcx.sess.struct_span_warn(
1589 "{} name `{}` shadows a \
1590 {} name that is already in scope",
1591 shadower.kind.desc(),
1597 err.span_label(orig.span, "first declared here");
1598 err.span_label(shadower.span, format!("{} `{}` already in scope", orig.kind.desc(), name));
1602 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1603 // if one of the label shadows a lifetime or another label.
1604 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1605 struct GatherLabels<'a, 'tcx> {
1607 scope: ScopeRef<'a>,
1608 labels_in_fn: &'a mut Vec<Ident>,
1612 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1613 gather.visit_body(body);
1615 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1616 type Map = intravisit::ErasedMap<'v>;
1618 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1619 NestedVisitorMap::None
1622 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1623 if let Some(label) = expression_label(ex) {
1624 for prior_label in &self.labels_in_fn[..] {
1625 // FIXME (#24278): non-hygienic comparison
1626 if label.name == prior_label.name {
1627 signal_shadowing_problem(
1630 original_label(prior_label.span),
1631 shadower_label(label.span),
1636 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1638 self.labels_in_fn.push(label);
1640 intravisit::walk_expr(self, ex)
1644 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1646 hir::ExprKind::Loop(_, Some(label), ..) => Some(label.ident),
1647 hir::ExprKind::Block(_, Some(label)) => Some(label.ident),
1652 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1655 Scope::Body { s, .. }
1656 | Scope::Elision { s, .. }
1657 | Scope::ObjectLifetimeDefault { s, .. }
1658 | Scope::Supertrait { s, .. }
1659 | Scope::TraitRefBoundary { s, .. } => {
1667 Scope::Binder { ref lifetimes, s, .. } => {
1668 // FIXME (#24278): non-hygienic comparison
1670 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1672 signal_shadowing_problem(
1675 original_lifetime(tcx.def_span(def.id().unwrap().expect_local())),
1676 shadower_label(label.span),
1687 fn compute_object_lifetime_defaults(
1689 item: &hir::Item<'_>,
1690 ) -> Option<Vec<ObjectLifetimeDefault>> {
1692 hir::ItemKind::Struct(_, ref generics)
1693 | hir::ItemKind::Union(_, ref generics)
1694 | hir::ItemKind::Enum(_, ref generics)
1695 | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1697 origin: hir::OpaqueTyOrigin::TyAlias,
1700 | hir::ItemKind::TyAlias(_, ref generics)
1701 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1702 let result = object_lifetime_defaults_for_item(tcx, generics);
1705 let attrs = tcx.hir().attrs(item.hir_id());
1706 if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1707 let object_lifetime_default_reprs: String = result
1709 .map(|set| match *set {
1710 Set1::Empty => "BaseDefault".into(),
1711 Set1::One(Region::Static) => "'static".into(),
1712 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1715 .find_map(|param| match param.kind {
1716 GenericParamKind::Lifetime { .. } => {
1718 return Some(param.name.ident().to_string().into());
1726 Set1::One(_) => bug!(),
1727 Set1::Many => "Ambiguous".into(),
1729 .collect::<Vec<Cow<'static, str>>>()
1731 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1740 /// Scan the bounds and where-clauses on parameters to extract bounds
1741 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1742 /// for each type parameter.
1743 fn object_lifetime_defaults_for_item(
1745 generics: &hir::Generics<'_>,
1746 ) -> Vec<ObjectLifetimeDefault> {
1747 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1748 for bound in bounds {
1749 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1750 set.insert(lifetime.name.normalize_to_macros_2_0());
1758 .filter_map(|param| match param.kind {
1759 GenericParamKind::Lifetime { .. } => None,
1760 GenericParamKind::Type { .. } => {
1761 let mut set = Set1::Empty;
1763 add_bounds(&mut set, ¶m.bounds);
1765 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1766 for predicate in generics.where_clause.predicates {
1767 // Look for `type: ...` where clauses.
1768 let data = match *predicate {
1769 hir::WherePredicate::BoundPredicate(ref data) => data,
1773 // Ignore `for<'a> type: ...` as they can change what
1774 // lifetimes mean (although we could "just" handle it).
1775 if !data.bound_generic_params.is_empty() {
1779 let res = match data.bounded_ty.kind {
1780 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1784 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1785 add_bounds(&mut set, &data.bounds);
1790 Set1::Empty => Set1::Empty,
1791 Set1::One(name) => {
1792 if name == hir::LifetimeName::Static {
1793 Set1::One(Region::Static)
1798 .filter_map(|param| match param.kind {
1799 GenericParamKind::Lifetime { .. } => Some((
1801 hir::LifetimeName::Param(param.name),
1802 LifetimeDefOrigin::from_param(param),
1807 .find(|&(_, (_, lt_name, _))| lt_name == name)
1808 .map_or(Set1::Many, |(i, (id, _, origin))| {
1809 let def_id = tcx.hir().local_def_id(id);
1810 Set1::One(Region::EarlyBound(
1818 Set1::Many => Set1::Many,
1821 GenericParamKind::Const { .. } => {
1822 // Generic consts don't impose any constraints.
1824 // We still store a dummy value here to allow generic parameters
1825 // in an arbitrary order.
1832 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1833 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1835 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1837 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1838 let labels_in_fn = take(&mut self.labels_in_fn);
1839 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1840 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1841 let mut this = LifetimeContext {
1845 is_in_fn_syntax: self.is_in_fn_syntax,
1846 is_in_const_generic: self.is_in_const_generic,
1847 trait_definition_only: self.trait_definition_only,
1849 xcrate_object_lifetime_defaults,
1851 missing_named_lifetime_spots,
1853 let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1855 let _enter = span.enter();
1856 f(self.scope, &mut this);
1857 if !self.trait_definition_only {
1858 this.check_uses_for_lifetimes_defined_by_scope();
1861 self.labels_in_fn = this.labels_in_fn;
1862 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1863 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1866 /// helper method to determine the span to remove when suggesting the
1867 /// deletion of a lifetime
1868 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1869 generics.params.iter().enumerate().find_map(|(i, param)| {
1870 if param.name.ident() == name {
1871 let in_band = matches!(
1873 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::InBand }
1877 } else if generics.params.len() == 1 {
1878 // if sole lifetime, remove the entire `<>` brackets
1881 // if removing within `<>` brackets, we also want to
1882 // delete a leading or trailing comma as appropriate
1883 if i >= generics.params.len() - 1 {
1884 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1886 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1895 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1896 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1897 fn suggest_eliding_single_use_lifetime(
1899 err: &mut DiagnosticBuilder<'_>,
1901 lifetime: &hir::Lifetime,
1903 let name = lifetime.name.ident();
1904 let remove_decl = self
1907 .and_then(|parent_def_id| parent_def_id.as_local())
1908 .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id))
1909 .and_then(|generics| self.lifetime_deletion_span(name, generics));
1911 let mut remove_use = None;
1912 let mut elide_use = None;
1913 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1914 for input in inputs {
1916 hir::TyKind::Rptr(lt, _) => {
1917 if lt.name.ident() == name {
1918 // include the trailing whitespace between the lifetime and type names
1919 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1924 .span_until_non_whitespace(lt_through_ty_span),
1929 hir::TyKind::Path(QPath::Resolved(_, path)) => {
1930 let last_segment = &path.segments[path.segments.len() - 1];
1931 let generics = last_segment.args();
1932 for arg in generics.args.iter() {
1933 if let GenericArg::Lifetime(lt) = arg {
1934 if lt.name.ident() == name {
1935 elide_use = Some(lt.span);
1946 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1947 if let Some(parent) =
1948 self.tcx.hir().find_by_def_id(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1951 Node::Item(item) => {
1952 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1953 find_arg_use_span(sig.decl.inputs);
1956 Node::ImplItem(impl_item) => {
1957 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1958 find_arg_use_span(sig.decl.inputs);
1966 let msg = "elide the single-use lifetime";
1967 match (remove_decl, remove_use, elide_use) {
1968 (Some(decl_span), Some(use_span), None) => {
1969 // if both declaration and use deletion spans start at the same
1970 // place ("start at" because the latter includes trailing
1971 // whitespace), then this is an in-band lifetime
1972 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1973 err.span_suggestion(
1977 Applicability::MachineApplicable,
1980 err.multipart_suggestion(
1982 vec![(decl_span, String::new()), (use_span, String::new())],
1983 Applicability::MachineApplicable,
1987 (Some(decl_span), None, Some(use_span)) => {
1988 err.multipart_suggestion(
1990 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1991 Applicability::MachineApplicable,
1998 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1999 let defined_by = match self.scope {
2000 Scope::Binder { lifetimes, .. } => lifetimes,
2002 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
2007 let def_ids: Vec<_> = defined_by
2009 .flat_map(|region| match region {
2010 Region::EarlyBound(_, def_id, _)
2011 | Region::LateBound(_, _, def_id, _)
2012 | Region::Free(_, def_id) => Some(*def_id),
2014 Region::LateBoundAnon(..) | Region::Static => None,
2018 'lifetimes: for def_id in def_ids {
2019 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
2021 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
2024 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
2028 match lifetimeuseset {
2029 Some(LifetimeUseSet::One(lifetime)) => {
2031 if let Some((id, span, name)) =
2032 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
2033 Node::Lifetime(hir_lifetime) => Some((
2034 hir_lifetime.hir_id,
2036 hir_lifetime.name.ident(),
2038 Node::GenericParam(param) => {
2039 Some((param.hir_id, param.span, param.name.ident()))
2044 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
2045 if name.name == kw::UnderscoreLifetime {
2049 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2050 if let Some(def_id) = parent_def_id.as_local() {
2051 // lifetimes in `derive` expansions don't count (Issue #53738)
2054 .get_attrs(def_id.to_def_id())
2056 .any(|attr| attr.has_name(sym::automatically_derived))
2061 // opaque types generated when desugaring an async function can have a single
2062 // use lifetime even if it is explicitly denied (Issue #77175)
2063 if let hir::Node::Item(hir::Item {
2064 kind: hir::ItemKind::OpaqueTy(ref opaque),
2066 }) = self.tcx.hir().get_by_def_id(def_id)
2068 if !matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn(..)) {
2069 continue 'lifetimes;
2071 // We want to do this only if the liftime identifier is already defined
2072 // in the async function that generated this. Otherwise it could be
2073 // an opaque type defined by the developer and we still want this
2074 // lint to fail compilation
2075 for p in opaque.generics.params {
2076 if defined_by.contains_key(&p.name) {
2077 continue 'lifetimes;
2084 self.tcx.struct_span_lint_hir(
2085 lint::builtin::SINGLE_USE_LIFETIMES,
2089 let mut err = lint.build(&format!(
2090 "lifetime parameter `{}` only used once",
2093 if span == lifetime.span {
2094 // spans are the same for in-band lifetime declarations
2095 err.span_label(span, "this lifetime is only used here");
2097 err.span_label(span, "this lifetime...");
2098 err.span_label(lifetime.span, "...is used only here");
2100 self.suggest_eliding_single_use_lifetime(
2101 &mut err, def_id, lifetime,
2108 Some(LifetimeUseSet::Many) => {
2109 debug!("not one use lifetime");
2112 if let Some((id, span, name)) =
2113 match self.tcx.hir().get_by_def_id(def_id.expect_local()) {
2114 Node::Lifetime(hir_lifetime) => Some((
2115 hir_lifetime.hir_id,
2117 hir_lifetime.name.ident(),
2119 Node::GenericParam(param) => {
2120 Some((param.hir_id, param.span, param.name.ident()))
2125 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
2126 self.tcx.struct_span_lint_hir(
2127 lint::builtin::UNUSED_LIFETIMES,
2132 .build(&format!("lifetime parameter `{}` never used", name));
2133 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2134 if let Some(generics) =
2135 self.tcx.hir().get_generics(parent_def_id.expect_local())
2137 let unused_lt_span =
2138 self.lifetime_deletion_span(name, generics);
2139 if let Some(span) = unused_lt_span {
2140 err.span_suggestion(
2142 "elide the unused lifetime",
2144 Applicability::MachineApplicable,
2158 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
2160 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
2161 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
2162 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
2166 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
2168 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
2169 /// lifetimes may be interspersed together.
2171 /// If early bound lifetimes are present, we separate them into their own list (and likewise
2172 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
2173 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
2174 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
2175 /// ordering is not important there.
2176 fn visit_early_late<F>(
2178 parent_id: Option<LocalDefId>,
2180 decl: &'tcx hir::FnDecl<'tcx>,
2181 generics: &'tcx hir::Generics<'tcx>,
2184 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
2186 insert_late_bound_lifetimes(self.map, decl, generics);
2188 // Find the start of nested early scopes, e.g., in methods.
2189 let mut next_early_index = 0;
2190 if let Some(parent_id) = parent_id {
2191 let parent = self.tcx.hir().expect_item(parent_id);
2192 if sub_items_have_self_param(&parent.kind) {
2193 next_early_index += 1; // Self comes before lifetimes
2196 hir::ItemKind::Trait(_, _, ref generics, ..)
2197 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
2198 next_early_index += generics.params.len() as u32;
2204 let mut non_lifetime_count = 0;
2205 let mut named_late_bound_vars = 0;
2206 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
2209 .filter_map(|param| match param.kind {
2210 GenericParamKind::Lifetime { .. } => {
2211 if self.map.late_bound.contains(¶m.hir_id) {
2212 let late_bound_idx = named_late_bound_vars;
2213 named_late_bound_vars += 1;
2214 Some(Region::late(late_bound_idx, &self.tcx.hir(), param))
2216 Some(Region::early(&self.tcx.hir(), &mut next_early_index, param))
2219 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
2220 non_lifetime_count += 1;
2225 let next_early_index = next_early_index + non_lifetime_count;
2227 let binders: Vec<_> = generics
2231 matches!(param.kind, GenericParamKind::Lifetime { .. })
2232 && self.map.late_bound.contains(¶m.hir_id)
2235 .map(|(late_bound_idx, param)| {
2236 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
2237 late_region_as_bound_region(self.tcx, &pair.1)
2240 self.map.late_bound_vars.insert(hir_id, binders);
2241 let scope = Scope::Binder {
2246 opaque_type_parent: true,
2247 track_lifetime_uses: false,
2248 scope_type: BinderScopeType::Normal,
2250 self.with(scope, move |old_scope, this| {
2251 this.check_lifetime_params(old_scope, &generics.params);
2256 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
2257 let mut scope = self.scope;
2260 Scope::Root => return 0,
2262 Scope::Binder { next_early_index, opaque_type_parent, .. }
2263 if (!only_opaque_type_parent || opaque_type_parent) =>
2265 return next_early_index;
2268 Scope::Binder { s, .. }
2269 | Scope::Body { s, .. }
2270 | Scope::Elision { s, .. }
2271 | Scope::ObjectLifetimeDefault { s, .. }
2272 | Scope::Supertrait { s, .. }
2273 | Scope::TraitRefBoundary { s, .. } => scope = s,
2278 /// Returns the next index one would use for an early-bound-region
2279 /// if extending the current scope.
2280 fn next_early_index(&self) -> u32 {
2281 self.next_early_index_helper(true)
2284 /// Returns the next index one would use for an `impl Trait` that
2285 /// is being converted into an opaque type alias `impl Trait`. This will be the
2286 /// next early index from the enclosing item, for the most
2287 /// part. See the `opaque_type_parent` field for more info.
2288 fn next_early_index_for_opaque_type(&self) -> u32 {
2289 self.next_early_index_helper(false)
2292 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2293 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
2295 // If we've already reported an error, just ignore `lifetime_ref`.
2296 if let LifetimeName::Error = lifetime_ref.name {
2300 // Walk up the scope chain, tracking the number of fn scopes
2301 // that we pass through, until we find a lifetime with the
2302 // given name or we run out of scopes.
2304 let mut late_depth = 0;
2305 let mut scope = self.scope;
2306 let mut outermost_body = None;
2309 Scope::Body { id, s } => {
2310 // Non-static lifetimes are prohibited in anonymous constants without
2311 // `generic_const_exprs`.
2312 self.maybe_emit_forbidden_non_static_lifetime_error(id, lifetime_ref);
2314 outermost_body = Some(id);
2322 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
2323 match lifetime_ref.name {
2324 LifetimeName::Param(param_name) => {
2325 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
2327 break Some(def.shifted(late_depth));
2330 _ => bug!("expected LifetimeName::Param"),
2333 BinderScopeType::Normal => late_depth += 1,
2334 BinderScopeType::Concatenating => {}
2339 Scope::Elision { s, .. }
2340 | Scope::ObjectLifetimeDefault { s, .. }
2341 | Scope::Supertrait { s, .. }
2342 | Scope::TraitRefBoundary { s, .. } => {
2348 if let Some(mut def) = result {
2349 if let Region::EarlyBound(..) = def {
2350 // Do not free early-bound regions, only late-bound ones.
2351 } else if let Some(body_id) = outermost_body {
2352 let fn_id = self.tcx.hir().body_owner(body_id);
2353 match self.tcx.hir().get(fn_id) {
2354 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
2355 | Node::TraitItem(&hir::TraitItem {
2356 kind: hir::TraitItemKind::Fn(..), ..
2358 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
2359 let scope = self.tcx.hir().local_def_id(fn_id);
2360 def = Region::Free(scope.to_def_id(), def.id().unwrap());
2366 // Check for fn-syntax conflicts with in-band lifetime definitions
2367 if !self.trait_definition_only && self.is_in_fn_syntax {
2369 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
2370 | Region::LateBound(_, _, _, LifetimeDefOrigin::InBand) => {
2375 "lifetimes used in `fn` or `Fn` syntax must be \
2376 explicitly declared using `<...>` binders"
2378 .span_label(lifetime_ref.span, "in-band lifetime definition")
2383 | Region::EarlyBound(
2386 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2388 | Region::LateBound(
2392 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2394 | Region::LateBoundAnon(..)
2395 | Region::Free(..) => {}
2399 self.insert_lifetime(lifetime_ref, def);
2401 self.emit_undeclared_lifetime_error(lifetime_ref);
2405 fn visit_segment_args(
2409 generic_args: &'tcx hir::GenericArgs<'tcx>,
2412 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
2413 res, depth, generic_args,
2416 if generic_args.parenthesized {
2417 let was_in_fn_syntax = self.is_in_fn_syntax;
2418 self.is_in_fn_syntax = true;
2419 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
2420 self.is_in_fn_syntax = was_in_fn_syntax;
2424 let mut elide_lifetimes = true;
2425 let lifetimes: Vec<_> = generic_args
2428 .filter_map(|arg| match arg {
2429 hir::GenericArg::Lifetime(lt) => {
2430 if !lt.is_elided() {
2431 elide_lifetimes = false;
2438 // We short-circuit here if all are elided in order to pluralize
2440 if elide_lifetimes {
2441 self.resolve_elided_lifetimes(&lifetimes);
2443 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
2446 // Figure out if this is a type/trait segment,
2447 // which requires object lifetime defaults.
2448 let parent_def_id = |this: &mut Self, def_id: DefId| {
2449 let def_key = this.tcx.def_key(def_id);
2450 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
2452 let type_def_id = match res {
2453 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
2454 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
2462 ) if depth == 0 => Some(def_id),
2466 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
2468 // Compute a vector of defaults, one for each type parameter,
2469 // per the rules given in RFCs 599 and 1156. Example:
2472 // struct Foo<'a, T: 'a, U> { }
2475 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
2476 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
2477 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
2480 // Therefore, we would compute `object_lifetime_defaults` to a
2481 // vector like `['x, 'static]`. Note that the vector only
2482 // includes type parameters.
2483 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
2485 let mut scope = self.scope;
2488 Scope::Root => break false,
2490 Scope::Body { .. } => break true,
2492 Scope::Binder { s, .. }
2493 | Scope::Elision { s, .. }
2494 | Scope::ObjectLifetimeDefault { s, .. }
2495 | Scope::Supertrait { s, .. }
2496 | Scope::TraitRefBoundary { s, .. } => {
2503 let map = &self.map;
2504 let set_to_region = |set: &ObjectLifetimeDefault| match *set {
2509 Some(Region::Static)
2513 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2514 GenericArg::Lifetime(lt) => Some(lt),
2517 r.subst(lifetimes, map)
2521 if let Some(def_id) = def_id.as_local() {
2522 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2523 self.tcx.object_lifetime_defaults(id).unwrap().iter().map(set_to_region).collect()
2526 self.xcrate_object_lifetime_defaults
2528 .or_insert_with(|| {
2529 tcx.generics_of(def_id)
2532 .filter_map(|param| match param.kind {
2533 GenericParamDefKind::Type { object_lifetime_default, .. } => {
2534 Some(object_lifetime_default)
2536 GenericParamDefKind::Const { .. } => Some(Set1::Empty),
2537 GenericParamDefKind::Lifetime => None,
2547 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2550 for arg in generic_args.args {
2552 GenericArg::Lifetime(_) => {}
2553 GenericArg::Type(ty) => {
2554 if let Some(<) = object_lifetime_defaults.get(i) {
2555 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2556 self.with(scope, |_, this| this.visit_ty(ty));
2562 GenericArg::Const(ct) => {
2563 self.visit_anon_const(&ct.value);
2566 GenericArg::Infer(inf) => {
2567 self.visit_id(inf.hir_id);
2573 // Hack: when resolving the type `XX` in binding like `dyn
2574 // Foo<'b, Item = XX>`, the current object-lifetime default
2575 // would be to examine the trait `Foo` to check whether it has
2576 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2577 // declared like so, then the default object lifetime bound in
2578 // `XX` should be `'b`:
2586 // but if we just have `type Item;`, then it would be
2587 // `'static`. However, we don't get all of this logic correct.
2589 // Instead, we do something hacky: if there are no lifetime parameters
2590 // to the trait, then we simply use a default object lifetime
2591 // bound of `'static`, because there is no other possibility. On the other hand,
2592 // if there ARE lifetime parameters, then we require the user to give an
2593 // explicit bound for now.
2595 // This is intended to leave room for us to implement the
2596 // correct behavior in the future.
2597 let has_lifetime_parameter =
2598 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2600 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2601 // in the trait ref `YY<...>` in `Item: YY<...>`.
2602 for binding in generic_args.bindings {
2603 let scope = Scope::ObjectLifetimeDefault {
2604 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2607 if let Some(type_def_id) = type_def_id {
2608 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2613 self.with(scope, |_, this| {
2614 let scope = Scope::Supertrait {
2615 lifetimes: lifetimes.unwrap_or_default(),
2618 this.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2621 self.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2626 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2627 /// associated type name and starting trait.
2628 /// For example, imagine we have
2630 /// trait Foo<'a, 'b> {
2633 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2634 /// trait Bar: for<'b> Bar<'b> {}
2636 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2637 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2638 fn supertrait_hrtb_lifetimes(
2642 ) -> Option<Vec<ty::BoundVariableKind>> {
2643 let trait_defines_associated_type_named = |trait_def_id: DefId| {
2644 tcx.associated_items(trait_def_id)
2645 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2649 use smallvec::{smallvec, SmallVec};
2650 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2651 smallvec![(def_id, smallvec![])];
2652 let mut visited: FxHashSet<DefId> = FxHashSet::default();
2654 let (def_id, bound_vars) = match stack.pop() {
2658 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2659 // there being no supertrait HRTBs.
2660 match tcx.def_kind(def_id) {
2661 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2665 if trait_defines_associated_type_named(def_id) {
2666 break Some(bound_vars.into_iter().collect());
2669 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2670 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2671 let bound_predicate = pred.kind();
2672 match bound_predicate.skip_binder() {
2673 ty::PredicateKind::Trait(data) => {
2674 // The order here needs to match what we would get from `subst_supertrait`
2675 let pred_bound_vars = bound_predicate.bound_vars();
2676 let mut all_bound_vars = bound_vars.clone();
2677 all_bound_vars.extend(pred_bound_vars.iter());
2678 let super_def_id = data.trait_ref.def_id;
2679 Some((super_def_id, all_bound_vars))
2685 let obligations = obligations.filter(|o| visited.insert(o.0));
2686 stack.extend(obligations);
2690 #[tracing::instrument(level = "debug", skip(self))]
2691 fn visit_fn_like_elision(
2693 inputs: &'tcx [hir::Ty<'tcx>],
2694 output: Option<&'tcx hir::Ty<'tcx>>,
2696 debug!("visit_fn_like_elision: enter");
2697 let mut scope = &*self.scope;
2700 Scope::Binder { hir_id, .. } => {
2703 Scope::ObjectLifetimeDefault { ref s, .. }
2704 | Scope::Elision { ref s, .. }
2705 | Scope::Supertrait { ref s, .. }
2706 | Scope::TraitRefBoundary { ref s, .. } => {
2709 Scope::Root | Scope::Body { .. } => {
2710 // See issues #83907 and #83693. Just bail out from looking inside.
2711 self.tcx.sess.delay_span_bug(
2712 rustc_span::DUMMY_SP,
2713 "In fn_like_elision without appropriate scope above",
2719 // While not strictly necessary, we gather anon lifetimes *before* actually
2720 // visiting the argument types.
2721 let mut gather = GatherAnonLifetimes { anon_count: 0 };
2722 for input in inputs {
2723 gather.visit_ty(input);
2725 trace!(?gather.anon_count);
2726 let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2727 let named_late_bound_vars = late_bound_vars.len() as u32;
2728 late_bound_vars.extend(
2729 (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2731 let arg_scope = Scope::Elision {
2732 elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2735 self.with(arg_scope, |_, this| {
2736 for input in inputs {
2737 this.visit_ty(input);
2741 let output = match output {
2746 debug!("determine output");
2748 // Figure out if there's a body we can get argument names from,
2749 // and whether there's a `self` argument (treated specially).
2750 let mut assoc_item_kind = None;
2751 let mut impl_self = None;
2752 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2753 let body = match self.tcx.hir().get(parent) {
2754 // `fn` definitions and methods.
2755 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2757 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2758 if let hir::ItemKind::Trait(.., ref trait_items) =
2759 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2762 trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2765 hir::TraitFn::Required(_) => None,
2766 hir::TraitFn::Provided(body) => Some(body),
2770 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2771 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2772 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2774 impl_self = Some(self_ty);
2776 items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2781 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2782 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2783 // Everything else (only closures?) doesn't
2784 // actually enjoy elision in return types.
2786 self.visit_ty(output);
2791 let has_self = match assoc_item_kind {
2792 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2796 // In accordance with the rules for lifetime elision, we can determine
2797 // what region to use for elision in the output type in two ways.
2798 // First (determined here), if `self` is by-reference, then the
2799 // implied output region is the region of the self parameter.
2801 struct SelfVisitor<'a> {
2802 map: &'a NamedRegionMap,
2803 impl_self: Option<&'a hir::TyKind<'a>>,
2804 lifetime: Set1<Region>,
2807 impl SelfVisitor<'_> {
2808 // Look for `self: &'a Self` - also desugared from `&'a self`,
2809 // and if that matches, use it for elision and return early.
2810 fn is_self_ty(&self, res: Res) -> bool {
2811 if let Res::SelfTy(..) = res {
2815 // Can't always rely on literal (or implied) `Self` due
2816 // to the way elision rules were originally specified.
2817 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2821 // Permit the types that unambiguously always
2822 // result in the same type constructor being used
2823 // (it can't differ between `Self` and `self`).
2824 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2825 | Res::PrimTy(_) => return res == path.res,
2834 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2835 type Map = intravisit::ErasedMap<'a>;
2837 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2838 NestedVisitorMap::None
2841 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2842 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2843 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2845 if self.is_self_ty(path.res) {
2846 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2847 self.lifetime.insert(*lifetime);
2852 intravisit::walk_ty(self, ty)
2856 let mut visitor = SelfVisitor {
2858 impl_self: impl_self.map(|ty| &ty.kind),
2859 lifetime: Set1::Empty,
2861 visitor.visit_ty(&inputs[0]);
2862 if let Set1::One(lifetime) = visitor.lifetime {
2863 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2864 self.with(scope, |_, this| this.visit_ty(output));
2869 // Second, if there was exactly one lifetime (either a substitution or a
2870 // reference) in the arguments, then any anonymous regions in the output
2871 // have that lifetime.
2872 let mut possible_implied_output_region = None;
2873 let mut lifetime_count = 0;
2874 let arg_lifetimes = inputs
2877 .skip(has_self as usize)
2879 let mut gather = GatherLifetimes {
2881 outer_index: ty::INNERMOST,
2882 have_bound_regions: false,
2883 lifetimes: Default::default(),
2885 gather.visit_ty(input);
2887 lifetime_count += gather.lifetimes.len();
2889 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2890 // there's a chance that the unique lifetime of this
2891 // iteration will be the appropriate lifetime for output
2892 // parameters, so lets store it.
2893 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2896 ElisionFailureInfo {
2899 lifetime_count: gather.lifetimes.len(),
2900 have_bound_regions: gather.have_bound_regions,
2906 let elide = if lifetime_count == 1 {
2907 Elide::Exact(possible_implied_output_region.unwrap())
2909 Elide::Error(arg_lifetimes)
2914 let scope = Scope::Elision { elide, s: self.scope };
2915 self.with(scope, |_, this| this.visit_ty(output));
2917 struct GatherLifetimes<'a> {
2918 map: &'a NamedRegionMap,
2919 outer_index: ty::DebruijnIndex,
2920 have_bound_regions: bool,
2921 lifetimes: FxHashSet<Region>,
2924 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2925 type Map = intravisit::ErasedMap<'v>;
2927 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2928 NestedVisitorMap::None
2931 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2932 if let hir::TyKind::BareFn(_) = ty.kind {
2933 self.outer_index.shift_in(1);
2936 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2937 for bound in bounds {
2938 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2941 // Stay on the safe side and don't include the object
2942 // lifetime default (which may not end up being used).
2943 if !lifetime.is_elided() {
2944 self.visit_lifetime(lifetime);
2948 intravisit::walk_ty(self, ty);
2951 if let hir::TyKind::BareFn(_) = ty.kind {
2952 self.outer_index.shift_out(1);
2956 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2957 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2958 // FIXME(eddyb) Do we want this? It only makes a difference
2959 // if this `for<'a>` lifetime parameter is never used.
2960 self.have_bound_regions = true;
2963 intravisit::walk_generic_param(self, param);
2966 fn visit_poly_trait_ref(
2968 trait_ref: &hir::PolyTraitRef<'_>,
2969 modifier: hir::TraitBoundModifier,
2971 self.outer_index.shift_in(1);
2972 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2973 self.outer_index.shift_out(1);
2976 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2977 if let hir::GenericBound::LangItemTrait { .. } = bound {
2978 self.outer_index.shift_in(1);
2979 intravisit::walk_param_bound(self, bound);
2980 self.outer_index.shift_out(1);
2982 intravisit::walk_param_bound(self, bound);
2986 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2987 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2989 Region::LateBound(debruijn, _, _, _)
2990 | Region::LateBoundAnon(debruijn, _, _)
2991 if debruijn < self.outer_index =>
2993 self.have_bound_regions = true;
2996 // FIXME(jackh726): nested trait refs?
2997 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
3004 struct GatherAnonLifetimes {
3007 impl<'v> Visitor<'v> for GatherAnonLifetimes {
3008 type Map = intravisit::ErasedMap<'v>;
3010 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3011 NestedVisitorMap::None
3014 #[instrument(skip(self), level = "trace")]
3015 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
3016 // If we enter a `BareFn`, then we enter a *new* binding scope
3017 if let hir::TyKind::BareFn(_) = ty.kind {
3020 intravisit::walk_ty(self, ty);
3023 fn visit_generic_args(
3026 generic_args: &'v hir::GenericArgs<'v>,
3028 // parenthesized args enter a new elison scope
3029 if generic_args.parenthesized {
3032 intravisit::walk_generic_args(self, path_span, generic_args)
3035 #[instrument(skip(self), level = "trace")]
3036 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
3037 if lifetime_ref.is_elided() {
3038 self.anon_count += 1;
3044 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
3045 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
3047 if lifetime_refs.is_empty() {
3051 let mut late_depth = 0;
3052 let mut scope = self.scope;
3053 let mut lifetime_names = FxHashSet::default();
3054 let mut lifetime_spans = vec![];
3057 // Do not assign any resolution, it will be inferred.
3058 Scope::Body { .. } => break Ok(()),
3060 Scope::Root => break Err(None),
3062 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
3063 // collect named lifetimes for suggestions
3064 for name in lifetimes.keys() {
3065 if let hir::ParamName::Plain(name) = name {
3066 lifetime_names.insert(name.name);
3067 lifetime_spans.push(name.span);
3071 BinderScopeType::Normal => late_depth += 1,
3072 BinderScopeType::Concatenating => {}
3078 elide: Elide::FreshLateAnon(named_late_bound_vars, ref counter),
3081 for lifetime_ref in lifetime_refs {
3083 Region::late_anon(named_late_bound_vars, counter).shifted(late_depth);
3085 self.insert_lifetime(lifetime_ref, lifetime);
3090 Scope::Elision { elide: Elide::Exact(l), .. } => {
3091 let lifetime = l.shifted(late_depth);
3092 for lifetime_ref in lifetime_refs {
3093 self.insert_lifetime(lifetime_ref, lifetime);
3098 Scope::Elision { elide: Elide::Error(ref e), ref s, .. } => {
3102 Scope::Binder { ref lifetimes, s, .. } => {
3103 // Collect named lifetimes for suggestions.
3104 for name in lifetimes.keys() {
3105 if let hir::ParamName::Plain(name) = name {
3106 lifetime_names.insert(name.name);
3107 lifetime_spans.push(name.span);
3112 Scope::ObjectLifetimeDefault { ref s, .. }
3113 | Scope::Elision { ref s, .. }
3114 | Scope::TraitRefBoundary { ref s, .. } => {
3120 break Err(Some(&e[..]));
3123 Scope::Elision { elide: Elide::Forbid, .. } => break Err(None),
3125 Scope::ObjectLifetimeDefault { s, .. }
3126 | Scope::Supertrait { s, .. }
3127 | Scope::TraitRefBoundary { s, .. } => {
3133 let error = match error {
3135 self.report_elided_lifetime_in_ty(lifetime_refs);
3138 Err(error) => error,
3141 // If we specifically need the `scope_for_path` map, then we're in the
3142 // diagnostic pass and we don't want to emit more errors.
3143 if self.map.scope_for_path.is_some() {
3144 self.tcx.sess.delay_span_bug(
3145 rustc_span::DUMMY_SP,
3146 "Encountered unexpected errors during diagnostics related part",
3151 let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3153 let mut spans_dedup = spans.clone();
3154 spans_dedup.dedup();
3155 let spans_with_counts: Vec<_> = spans_dedup
3157 .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
3160 let mut err = self.report_missing_lifetime_specifiers(spans.clone(), lifetime_refs.len());
3162 if let Some(params) = error {
3163 // If there's no lifetime available, suggest `'static`.
3164 if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
3165 lifetime_names.insert(kw::StaticLifetime);
3169 self.add_missing_lifetime_specifiers_label(
3174 error.unwrap_or(&[]),
3179 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
3180 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
3181 let mut late_depth = 0;
3182 let mut scope = self.scope;
3183 let lifetime = loop {
3185 Scope::Binder { s, scope_type, .. } => {
3187 BinderScopeType::Normal => late_depth += 1,
3188 BinderScopeType::Concatenating => {}
3193 Scope::Root | Scope::Elision { .. } => break Region::Static,
3195 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
3197 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
3199 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
3204 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
3207 fn check_lifetime_params(
3209 old_scope: ScopeRef<'_>,
3210 params: &'tcx [hir::GenericParam<'tcx>],
3212 let lifetimes: Vec<_> = params
3214 .filter_map(|param| match param.kind {
3215 GenericParamKind::Lifetime { .. } => {
3216 Some((param, param.name.normalize_to_macros_2_0()))
3221 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
3222 if let hir::ParamName::Plain(_) = lifetime_i_name {
3223 let name = lifetime_i_name.ident().name;
3224 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
3225 let mut err = struct_span_err!(
3229 "invalid lifetime parameter name: `{}`",
3230 lifetime_i.name.ident(),
3234 format!("{} is a reserved lifetime name", name),
3240 // It is a hard error to shadow a lifetime within the same scope.
3241 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
3242 if lifetime_i_name == lifetime_j_name {
3247 "lifetime name `{}` declared twice in the same scope",
3248 lifetime_j.name.ident()
3250 .span_label(lifetime_j.span, "declared twice")
3251 .span_label(lifetime_i.span, "previous declaration here")
3256 // It is a soft error to shadow a lifetime within a parent scope.
3257 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
3259 for bound in lifetime_i.bounds {
3261 hir::GenericBound::Outlives(ref lt) => match lt.name {
3262 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
3264 "use of `'_` in illegal place, but not caught by lowering",
3266 hir::LifetimeName::Static => {
3267 self.insert_lifetime(lt, Region::Static);
3271 lifetime_i.span.to(lt.span),
3273 "unnecessary lifetime parameter `{}`",
3274 lifetime_i.name.ident(),
3278 "you can use the `'static` lifetime directly, in place of `{}`",
3279 lifetime_i.name.ident(),
3283 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit(_) => {
3284 self.resolve_lifetime_ref(lt);
3286 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
3287 self.tcx.sess.delay_span_bug(
3289 "lowering generated `ImplicitObjectLifetimeDefault` \
3290 outside of an object type",
3293 hir::LifetimeName::Error => {
3294 // No need to do anything, error already reported.
3303 fn check_lifetime_param_for_shadowing(
3305 mut old_scope: ScopeRef<'_>,
3306 param: &'tcx hir::GenericParam<'tcx>,
3308 for label in &self.labels_in_fn {
3309 // FIXME (#24278): non-hygienic comparison
3310 if param.name.ident().name == label.name {
3311 signal_shadowing_problem(
3314 original_label(label.span),
3315 shadower_lifetime(¶m),
3323 Scope::Body { s, .. }
3324 | Scope::Elision { s, .. }
3325 | Scope::ObjectLifetimeDefault { s, .. }
3326 | Scope::Supertrait { s, .. }
3327 | Scope::TraitRefBoundary { s, .. } => {
3335 Scope::Binder { ref lifetimes, s, .. } => {
3336 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
3337 signal_shadowing_problem(
3339 param.name.ident().name,
3340 original_lifetime(self.tcx.def_span(def.id().unwrap())),
3341 shadower_lifetime(¶m),
3352 /// Returns `true` if, in the current scope, replacing `'_` would be
3353 /// equivalent to a single-use lifetime.
3354 fn track_lifetime_uses(&self) -> bool {
3355 let mut scope = self.scope;
3358 Scope::Root => break false,
3360 // Inside of items, it depends on the kind of item.
3361 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
3363 // Inside a body, `'_` will use an inference variable,
3365 Scope::Body { .. } => break true,
3367 // A lifetime only used in a fn argument could as well
3368 // be replaced with `'_`, as that would generate a
3370 Scope::Elision { elide: Elide::FreshLateAnon(..), .. } => break true,
3372 // In the return type or other such place, `'_` is not
3373 // going to make a fresh name, so we cannot
3374 // necessarily replace a single-use lifetime with
3377 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
3380 Scope::ObjectLifetimeDefault { s, .. }
3381 | Scope::Supertrait { s, .. }
3382 | Scope::TraitRefBoundary { s, .. } => scope = s,
3387 #[tracing::instrument(level = "debug", skip(self))]
3388 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
3390 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
3391 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
3393 self.map.defs.insert(lifetime_ref.hir_id, def);
3396 Region::LateBoundAnon(..) | Region::Static => {
3397 // These are anonymous lifetimes or lifetimes that are not declared.
3400 Region::Free(_, def_id)
3401 | Region::LateBound(_, _, def_id, _)
3402 | Region::EarlyBound(_, def_id, _) => {
3403 // A lifetime declared by the user.
3404 let track_lifetime_uses = self.track_lifetime_uses();
3405 debug!(?track_lifetime_uses);
3406 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
3407 debug!("first use of {:?}", def_id);
3408 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
3410 debug!("many uses of {:?}", def_id);
3411 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
3417 /// Sometimes we resolve a lifetime, but later find that it is an
3418 /// error (esp. around impl trait). In that case, we remove the
3419 /// entry into `map.defs` so as not to confuse later code.
3420 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
3421 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
3422 assert_eq!(old_value, Some(bad_def));
3426 /// Detects late-bound lifetimes and inserts them into
3427 /// `map.late_bound`.
3429 /// A region declared on a fn is **late-bound** if:
3430 /// - it is constrained by an argument type;
3431 /// - it does not appear in a where-clause.
3433 /// "Constrained" basically means that it appears in any type but
3434 /// not amongst the inputs to a projection. In other words, `<&'a
3435 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
3436 #[tracing::instrument(level = "debug", skip(map))]
3437 fn insert_late_bound_lifetimes(
3438 map: &mut NamedRegionMap,
3439 decl: &hir::FnDecl<'_>,
3440 generics: &hir::Generics<'_>,
3442 let mut constrained_by_input = ConstrainedCollector::default();
3443 for arg_ty in decl.inputs {
3444 constrained_by_input.visit_ty(arg_ty);
3447 let mut appears_in_output = AllCollector::default();
3448 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
3450 debug!(?constrained_by_input.regions);
3452 // Walk the lifetimes that appear in where clauses.
3454 // Subtle point: because we disallow nested bindings, we can just
3455 // ignore binders here and scrape up all names we see.
3456 let mut appears_in_where_clause = AllCollector::default();
3457 appears_in_where_clause.visit_generics(generics);
3459 for param in generics.params {
3460 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
3461 if !param.bounds.is_empty() {
3462 // `'a: 'b` means both `'a` and `'b` are referenced
3463 appears_in_where_clause
3465 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
3470 debug!(?appears_in_where_clause.regions);
3472 // Late bound regions are those that:
3473 // - appear in the inputs
3474 // - do not appear in the where-clauses
3475 // - are not implicitly captured by `impl Trait`
3476 for param in generics.params {
3478 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
3480 // Neither types nor consts are late-bound.
3481 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
3484 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
3485 // appears in the where clauses? early-bound.
3486 if appears_in_where_clause.regions.contains(<_name) {
3490 // does not appear in the inputs, but appears in the return type? early-bound.
3491 if !constrained_by_input.regions.contains(<_name)
3492 && appears_in_output.regions.contains(<_name)
3497 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
3499 let inserted = map.late_bound.insert(param.hir_id);
3500 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
3506 struct ConstrainedCollector {
3507 regions: FxHashSet<hir::LifetimeName>,
3510 impl<'v> Visitor<'v> for ConstrainedCollector {
3511 type Map = intravisit::ErasedMap<'v>;
3513 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3514 NestedVisitorMap::None
3517 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3520 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
3522 // ignore lifetimes appearing in associated type
3523 // projections, as they are not *constrained*
3527 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
3528 // consider only the lifetimes on the final
3529 // segment; I am not sure it's even currently
3530 // valid to have them elsewhere, but even if it
3531 // is, those would be potentially inputs to
3533 if let Some(last_segment) = path.segments.last() {
3534 self.visit_path_segment(path.span, last_segment);
3539 intravisit::walk_ty(self, ty);
3544 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3545 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3550 struct AllCollector {
3551 regions: FxHashSet<hir::LifetimeName>,
3554 impl<'v> Visitor<'v> for AllCollector {
3555 type Map = intravisit::ErasedMap<'v>;
3557 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3558 NestedVisitorMap::None
3561 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3562 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());