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 parent: Option<hir::BodyId>,
361 /// The index of the argument in the original definition.
363 lifetime_count: usize,
364 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| {
380 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
381 match tcx.hir().find(hir_id) {
382 Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
386 late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
387 lifetime_scope_map: |tcx, id| {
388 let item_id = item_for(tcx, id);
389 do_resolve(tcx, item_id, false, true).scope_for_path.unwrap().remove(&id)
396 /// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
397 /// Also does not generate any diagnostics.
399 /// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
400 /// resolves lifetimes only within the trait "header" -- that is, the trait
401 /// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
402 /// lifetimes within the trait and its items. There is room to refactor this,
403 /// for example to resolve lifetimes for each trait item in separate queries,
404 /// but it's convenient to do the entire trait at once because the lifetimes
405 /// from the trait definition are in scope within the trait items as well.
407 /// The reason for this separate call is to resolve what would otherwise
408 /// be a cycle. Consider this example:
414 /// trait Sub<'b>: for<'a> Base<'a> {
415 /// type SubItem: Sub<BaseItem = &'b u32>;
419 /// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
420 /// To figure out the index of `'b`, we have to know about the supertraits
421 /// of `Sub` so that we can determine that the `for<'a>` will be in scope.
422 /// (This is because we -- currently at least -- flatten all the late-bound
423 /// lifetimes into a single binder.) This requires us to resolve the
424 /// *trait definition* of `Sub`; basically just enough lifetime information
425 /// to look at the supertraits.
426 #[tracing::instrument(level = "debug", skip(tcx))]
427 fn resolve_lifetimes_trait_definition(
429 local_def_id: LocalDefId,
430 ) -> ResolveLifetimes {
431 convert_named_region_map(do_resolve(tcx, local_def_id, true, false))
434 /// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
435 /// You should not read the result of this query directly, but rather use
436 /// `named_region_map`, `is_late_bound_map`, etc.
437 #[tracing::instrument(level = "debug", skip(tcx))]
438 fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
439 convert_named_region_map(do_resolve(tcx, local_def_id, false, false))
444 local_def_id: LocalDefId,
445 trait_definition_only: bool,
446 with_scope_for_path: bool,
447 ) -> NamedRegionMap {
448 let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(local_def_id));
449 let mut named_region_map = NamedRegionMap {
450 defs: Default::default(),
451 late_bound: Default::default(),
452 late_bound_vars: Default::default(),
453 scope_for_path: with_scope_for_path.then(|| Default::default()),
455 let mut visitor = LifetimeContext {
457 map: &mut named_region_map,
459 is_in_fn_syntax: false,
460 is_in_const_generic: false,
461 trait_definition_only,
462 labels_in_fn: vec![],
463 xcrate_object_lifetime_defaults: Default::default(),
464 lifetime_uses: &mut Default::default(),
465 missing_named_lifetime_spots: vec![],
467 visitor.visit_item(item);
472 fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes {
473 let mut rl = ResolveLifetimes::default();
475 for (hir_id, v) in named_region_map.defs {
476 let map = rl.defs.entry(hir_id.owner).or_default();
477 map.insert(hir_id.local_id, v);
479 for hir_id in named_region_map.late_bound {
480 let map = rl.late_bound.entry(hir_id.owner).or_default();
481 map.insert(hir_id.local_id);
483 for (hir_id, v) in named_region_map.late_bound_vars {
484 let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
485 map.insert(hir_id.local_id, v);
492 /// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
493 /// There are two important things this does.
494 /// First, we have to resolve lifetimes for
495 /// the entire *`Item`* that contains this owner, because that's the largest "scope"
496 /// where we can have relevant lifetimes.
497 /// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
498 /// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
499 /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
500 /// other than the trait itself (like the trait methods or associated types), then we just use the regular
501 /// `resolve_lifetimes`.
502 fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
503 let item_id = item_for(tcx, def_id);
504 if item_id == def_id {
505 let item = tcx.hir().item(hir::ItemId { def_id: item_id });
507 hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
508 _ => tcx.resolve_lifetimes(item_id),
511 tcx.resolve_lifetimes(item_id)
515 /// Finds the `Item` that contains the given `LocalDefId`
516 fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
517 let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
518 match tcx.hir().find(hir_id) {
519 Some(Node::Item(item)) => {
526 let mut parent_iter = hir.parent_iter(hir_id);
528 let node = parent_iter.next().map(|n| n.1);
530 Some(hir::Node::Item(item)) => break item.def_id,
531 Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
539 fn is_late_bound_map<'tcx>(
542 ) -> Option<(LocalDefId, &'tcx FxHashSet<ItemLocalId>)> {
543 match tcx.def_kind(def_id) {
544 DefKind::AnonConst => {
546 .parent(def_id.to_def_id())
547 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
548 // We search for the next outer anon const or fn here
549 // while skipping closures.
551 // Note that for `AnonConst` we still just recurse until we
552 // find a function body, but who cares :shrug:
553 while tcx.is_closure(def_id) {
556 .unwrap_or_else(|| bug!("anon const or closure without a parent"));
559 tcx.is_late_bound_map(def_id.expect_local())
561 _ => resolve_lifetimes_for(tcx, def_id).late_bound.get(&def_id).map(|lt| (def_id, lt)),
565 /// In traits, there is an implicit `Self` type parameter which comes before the generics.
566 /// We have to account for this when computing the index of the other generic parameters.
567 /// This function returns whether there is such an implicit parameter defined on the given item.
568 fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
569 matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
572 fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
574 Region::LateBound(_, _, def_id, _) => {
575 let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
576 ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
578 Region::LateBoundAnon(_, _, anon_idx) => {
579 ty::BoundVariableKind::Region(ty::BrAnon(*anon_idx))
581 _ => bug!("{:?} is not a late region", region),
585 #[tracing::instrument(level = "debug")]
586 fn get_lifetime_scopes_for_path(mut scope: &Scope<'_>) -> LifetimeScopeForPath {
587 let mut available_lifetimes = vec![];
590 Scope::Binder { lifetimes, s, .. } => {
591 available_lifetimes.extend(lifetimes.keys().filter_map(|p| match p {
592 hir::ParamName::Plain(ident) => Some(ident.name.to_string()),
597 Scope::Body { s, .. } => {
600 Scope::Elision { elide, s } => {
601 if let Elide::Exact(_) = elide {
602 return LifetimeScopeForPath::Elided;
607 Scope::ObjectLifetimeDefault { s, .. } => {
611 return LifetimeScopeForPath::NonElided(available_lifetimes);
613 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
620 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
621 /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
622 fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
623 let mut scope = self.scope;
624 let mut supertrait_lifetimes = vec![];
627 Scope::Body { .. } | Scope::Root => {
628 break (vec![], BinderScopeType::Normal);
631 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
635 Scope::Supertrait { s, lifetimes } => {
636 supertrait_lifetimes = lifetimes.clone();
640 Scope::TraitRefBoundary { .. } => {
641 // We should only see super trait lifetimes if there is a `Binder` above
642 assert!(supertrait_lifetimes.is_empty());
643 break (vec![], BinderScopeType::Normal);
646 Scope::Binder { hir_id, .. } => {
647 // Nested poly trait refs have the binders concatenated
648 let mut full_binders =
649 self.map.late_bound_vars.entry(*hir_id).or_default().clone();
650 full_binders.extend(supertrait_lifetimes.into_iter());
651 break (full_binders, BinderScopeType::Concatenating);
657 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
658 type Map = Map<'tcx>;
660 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
661 NestedVisitorMap::All(self.tcx.hir())
664 // We want to nest trait/impl items in their parent, but nothing else.
665 fn visit_nested_item(&mut self, _: hir::ItemId) {}
667 fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
668 if !self.trait_definition_only {
669 intravisit::walk_trait_item_ref(self, ii)
673 fn visit_nested_body(&mut self, body: hir::BodyId) {
674 // Each body has their own set of labels, save labels.
675 let saved = take(&mut self.labels_in_fn);
676 let body = self.tcx.hir().body(body);
677 extract_labels(self, body);
678 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
679 this.visit_body(body);
681 self.labels_in_fn = saved;
686 fk: intravisit::FnKind<'tcx>,
687 fd: &'tcx hir::FnDecl<'tcx>,
692 let name = match fk {
693 intravisit::FnKind::ItemFn(id, _, _, _) => id.as_str(),
694 intravisit::FnKind::Method(id, _, _) => id.as_str(),
695 intravisit::FnKind::Closure => Symbol::intern("closure").as_str(),
697 let name: &str = &name;
698 let span = span!(Level::DEBUG, "visit_fn", name);
699 let _enter = span.enter();
701 // Any `Binders` are handled elsewhere
702 intravisit::FnKind::ItemFn(..) | intravisit::FnKind::Method(..) => {
703 intravisit::walk_fn(self, fk, fd, b, s, hir_id)
705 intravisit::FnKind::Closure => {
706 self.map.late_bound_vars.insert(hir_id, vec![]);
707 let scope = Scope::Binder {
709 lifetimes: FxIndexMap::default(),
710 next_early_index: self.next_early_index(),
712 track_lifetime_uses: true,
713 opaque_type_parent: false,
714 scope_type: BinderScopeType::Normal,
716 self.with(scope, move |_old_scope, this| {
717 intravisit::walk_fn(this, fk, fd, b, s, hir_id)
723 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
725 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
726 if let Some(of_trait) = of_trait {
727 self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
733 hir::ItemKind::Fn(ref sig, ref generics, _) => {
734 self.missing_named_lifetime_spots.push(generics.into());
735 self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
736 intravisit::walk_item(this, item);
738 self.missing_named_lifetime_spots.pop();
741 hir::ItemKind::ExternCrate(_)
742 | hir::ItemKind::Use(..)
743 | hir::ItemKind::Macro(..)
744 | hir::ItemKind::Mod(..)
745 | hir::ItemKind::ForeignMod { .. }
746 | hir::ItemKind::GlobalAsm(..) => {
747 // These sorts of items have no lifetime parameters at all.
748 intravisit::walk_item(self, item);
750 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
751 // No lifetime parameters, but implied 'static.
752 let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
753 self.with(scope, |_, this| intravisit::walk_item(this, item));
755 hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
756 // Opaque types are visited when we visit the
757 // `TyKind::OpaqueDef`, so that they have the lifetimes from
758 // their parent opaque_ty in scope.
760 // The core idea here is that since OpaqueTys are generated with the impl Trait as
761 // their owner, we can keep going until we find the Item that owns that. We then
762 // conservatively add all resolved lifetimes. Otherwise we run into problems in
763 // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
764 for (_hir_id, node) in
765 self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
768 hir::Node::Item(parent_item) => {
769 let resolved_lifetimes: &ResolveLifetimes =
770 self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
771 // We need to add *all* deps, since opaque tys may want them from *us*
772 for (&owner, defs) in resolved_lifetimes.defs.iter() {
773 defs.iter().for_each(|(&local_id, region)| {
774 self.map.defs.insert(hir::HirId { owner, local_id }, *region);
777 for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() {
778 late_bound.iter().for_each(|&local_id| {
779 self.map.late_bound.insert(hir::HirId { owner, local_id });
782 for (&owner, late_bound_vars) in
783 resolved_lifetimes.late_bound_vars.iter()
785 late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
786 self.map.late_bound_vars.insert(
787 hir::HirId { owner, local_id },
788 late_bound_vars.clone(),
794 hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
799 hir::ItemKind::TyAlias(_, ref generics)
800 | hir::ItemKind::Enum(_, ref generics)
801 | hir::ItemKind::Struct(_, ref generics)
802 | hir::ItemKind::Union(_, ref generics)
803 | hir::ItemKind::Trait(_, _, ref generics, ..)
804 | hir::ItemKind::TraitAlias(ref generics, ..)
805 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
806 self.missing_named_lifetime_spots.push(generics.into());
808 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
809 // This is not true for other kinds of items.
810 let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
811 // These kinds of items have only early-bound lifetime parameters.
812 let mut index = if sub_items_have_self_param(&item.kind) {
813 1 // Self comes before lifetimes
817 let mut non_lifetime_count = 0;
818 let lifetimes = generics
821 .filter_map(|param| match param.kind {
822 GenericParamKind::Lifetime { .. } => {
823 Some(Region::early(&self.tcx.hir(), &mut index, param))
825 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
826 non_lifetime_count += 1;
831 self.map.late_bound_vars.insert(item.hir_id(), vec![]);
832 let scope = Scope::Binder {
833 hir_id: item.hir_id(),
835 next_early_index: index + non_lifetime_count,
836 opaque_type_parent: true,
838 scope_type: BinderScopeType::Normal,
841 self.with(scope, |old_scope, this| {
842 this.check_lifetime_params(old_scope, &generics.params);
843 let scope = Scope::TraitRefBoundary { s: this.scope };
844 this.with(scope, |_, this| {
845 intravisit::walk_item(this, item);
848 self.missing_named_lifetime_spots.pop();
853 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
855 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
856 self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
857 intravisit::walk_foreign_item(this, item);
860 hir::ForeignItemKind::Static(..) => {
861 intravisit::walk_foreign_item(self, item);
863 hir::ForeignItemKind::Type => {
864 intravisit::walk_foreign_item(self, item);
869 #[tracing::instrument(level = "debug", skip(self))]
870 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
872 hir::TyKind::BareFn(ref c) => {
873 let next_early_index = self.next_early_index();
874 let was_in_fn_syntax = self.is_in_fn_syntax;
875 self.is_in_fn_syntax = true;
876 let lifetime_span: Option<Span> =
877 c.generic_params.iter().rev().find_map(|param| match param.kind {
878 GenericParamKind::Lifetime { .. } => Some(param.span),
881 let (span, span_type) = if let Some(span) = lifetime_span {
882 (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
884 (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
886 self.missing_named_lifetime_spots
887 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
888 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
891 .filter_map(|param| match param.kind {
892 GenericParamKind::Lifetime { .. } => Some(param),
896 .map(|(late_bound_idx, param)| {
897 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
898 let r = late_region_as_bound_region(self.tcx, &pair.1);
902 self.map.late_bound_vars.insert(ty.hir_id, binders);
903 let scope = Scope::Binder {
908 track_lifetime_uses: true,
909 opaque_type_parent: false,
910 scope_type: BinderScopeType::Normal,
912 self.with(scope, |old_scope, this| {
913 // a bare fn has no bounds, so everything
914 // contained within is scoped within its binder.
915 this.check_lifetime_params(old_scope, &c.generic_params);
916 intravisit::walk_ty(this, ty);
918 self.missing_named_lifetime_spots.pop();
919 self.is_in_fn_syntax = was_in_fn_syntax;
921 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
922 debug!(?bounds, ?lifetime, "TraitObject");
923 let scope = Scope::TraitRefBoundary { s: self.scope };
924 self.with(scope, |_, this| {
925 for bound in bounds {
926 this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
929 match lifetime.name {
930 LifetimeName::Implicit => {
931 // For types like `dyn Foo`, we should
932 // generate a special form of elided.
933 span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
935 LifetimeName::ImplicitObjectLifetimeDefault => {
936 // If the user does not write *anything*, we
937 // use the object lifetime defaulting
938 // rules. So e.g., `Box<dyn Debug>` becomes
939 // `Box<dyn Debug + 'static>`.
940 self.resolve_object_lifetime_default(lifetime)
942 LifetimeName::Underscore => {
943 // If the user writes `'_`, we use the *ordinary* elision
944 // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
945 // resolved the same as the `'_` in `&'_ Foo`.
948 self.resolve_elided_lifetimes(&[lifetime])
950 LifetimeName::Param(_) | LifetimeName::Static => {
951 // If the user wrote an explicit name, use that.
952 self.visit_lifetime(lifetime);
954 LifetimeName::Error => {}
957 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
958 self.visit_lifetime(lifetime_ref);
959 let scope = Scope::ObjectLifetimeDefault {
960 lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
963 self.with(scope, |_, this| this.visit_ty(&mt.ty));
965 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
966 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
967 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
968 // `type MyAnonTy<'b> = impl MyTrait<'b>;`
969 // ^ ^ this gets resolved in the scope of
970 // the opaque_ty generics
971 let opaque_ty = self.tcx.hir().item(item_id);
972 let (generics, bounds) = match opaque_ty.kind {
973 // Named opaque `impl Trait` types are reached via `TyKind::Path`.
974 // This arm is for `impl Trait` in the types of statics, constants and locals.
975 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
976 intravisit::walk_ty(self, ty);
978 // Elided lifetimes are not allowed in non-return
979 // position impl Trait
980 let scope = Scope::TraitRefBoundary { s: self.scope };
981 self.with(scope, |_, this| {
982 let scope = Scope::Elision { elide: Elide::Forbid, s: this.scope };
983 this.with(scope, |_, this| {
984 intravisit::walk_item(this, opaque_ty);
990 // RPIT (return position impl trait)
991 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
992 impl_trait_fn: Some(_),
996 }) => (generics, bounds),
997 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
1000 // Resolve the lifetimes that are applied to the opaque type.
1001 // These are resolved in the current scope.
1002 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
1003 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
1004 // ^ ^this gets resolved in the current scope
1005 for lifetime in lifetimes {
1006 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
1007 self.visit_lifetime(lifetime);
1009 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1010 // and ban them. Type variables instantiated inside binders aren't
1011 // well-supported at the moment, so this doesn't work.
1012 // In the future, this should be fixed and this error should be removed.
1013 let def = self.map.defs.get(&lifetime.hir_id).cloned();
1014 if let Some(Region::LateBound(_, _, def_id, _)) = def {
1015 if let Some(def_id) = def_id.as_local() {
1016 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1017 // Ensure that the parent of the def is an item, not HRTB
1018 let parent_id = self.tcx.hir().get_parent_node(hir_id);
1019 // FIXME(cjgillot) Can this check be replaced by
1020 // `let parent_is_item = parent_id.is_owner();`?
1021 let parent_is_item =
1022 if let Some(parent_def_id) = parent_id.as_owner() {
1024 self.tcx.hir().krate().owners.get(parent_def_id),
1031 if !parent_is_item {
1032 if !self.trait_definition_only {
1037 "`impl Trait` can only capture lifetimes \
1038 bound at the fn or impl level"
1042 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
1049 // We want to start our early-bound indices at the end of the parent scope,
1050 // not including any parent `impl Trait`s.
1051 let mut index = self.next_early_index_for_opaque_type();
1054 let mut elision = None;
1055 let mut lifetimes = FxIndexMap::default();
1056 let mut non_lifetime_count = 0;
1057 for param in generics.params {
1059 GenericParamKind::Lifetime { .. } => {
1060 let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m);
1061 let def_id = if let Region::EarlyBound(_, def_id, _) = reg {
1066 // We cannot predict what lifetimes are unused in opaque type.
1067 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
1068 if let hir::ParamName::Plain(Ident {
1069 name: kw::UnderscoreLifetime,
1073 // Pick the elided lifetime "definition" if one exists
1074 // and use it to make an elision scope.
1075 elision = Some(reg);
1077 lifetimes.insert(name, reg);
1080 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1081 non_lifetime_count += 1;
1085 let next_early_index = index + non_lifetime_count;
1086 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1088 if let Some(elision_region) = elision {
1090 Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
1091 self.with(scope, |_old_scope, this| {
1092 let scope = Scope::Binder {
1097 track_lifetime_uses: true,
1098 opaque_type_parent: false,
1099 scope_type: BinderScopeType::Normal,
1101 this.with(scope, |_old_scope, this| {
1102 this.visit_generics(generics);
1103 let scope = Scope::TraitRefBoundary { s: this.scope };
1104 this.with(scope, |_, this| {
1105 for bound in bounds {
1106 this.visit_param_bound(bound);
1112 let scope = Scope::Binder {
1117 track_lifetime_uses: true,
1118 opaque_type_parent: false,
1119 scope_type: BinderScopeType::Normal,
1121 self.with(scope, |_old_scope, this| {
1122 let scope = Scope::TraitRefBoundary { s: this.scope };
1123 this.with(scope, |_, this| {
1124 this.visit_generics(generics);
1125 for bound in bounds {
1126 this.visit_param_bound(bound);
1132 _ => intravisit::walk_ty(self, ty),
1136 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1137 use self::hir::TraitItemKind::*;
1138 match trait_item.kind {
1140 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1142 self.visit_early_late(
1143 Some(tcx.hir().get_parent_item(trait_item.hir_id())),
1144 trait_item.hir_id(),
1146 &trait_item.generics,
1147 |this| intravisit::walk_trait_item(this, trait_item),
1149 self.missing_named_lifetime_spots.pop();
1151 Type(bounds, ref ty) => {
1152 self.missing_named_lifetime_spots.push((&trait_item.generics).into());
1153 let generics = &trait_item.generics;
1154 let mut index = self.next_early_index();
1155 debug!("visit_ty: index = {}", index);
1156 let mut non_lifetime_count = 0;
1157 let lifetimes = generics
1160 .filter_map(|param| match param.kind {
1161 GenericParamKind::Lifetime { .. } => {
1162 Some(Region::early(&self.tcx.hir(), &mut index, param))
1164 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1165 non_lifetime_count += 1;
1170 self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
1171 let scope = Scope::Binder {
1172 hir_id: trait_item.hir_id(),
1174 next_early_index: index + non_lifetime_count,
1176 track_lifetime_uses: true,
1177 opaque_type_parent: true,
1178 scope_type: BinderScopeType::Normal,
1180 self.with(scope, |old_scope, this| {
1181 this.check_lifetime_params(old_scope, &generics.params);
1182 let scope = Scope::TraitRefBoundary { s: this.scope };
1183 this.with(scope, |_, this| {
1184 this.visit_generics(generics);
1185 for bound in bounds {
1186 this.visit_param_bound(bound);
1188 if let Some(ty) = ty {
1193 self.missing_named_lifetime_spots.pop();
1196 // Only methods and types support generics.
1197 assert!(trait_item.generics.params.is_empty());
1198 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1199 intravisit::walk_trait_item(self, trait_item);
1200 self.missing_named_lifetime_spots.pop();
1205 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1206 use self::hir::ImplItemKind::*;
1207 match impl_item.kind {
1209 self.missing_named_lifetime_spots.push((&impl_item.generics).into());
1211 self.visit_early_late(
1212 Some(tcx.hir().get_parent_item(impl_item.hir_id())),
1215 &impl_item.generics,
1216 |this| intravisit::walk_impl_item(this, impl_item),
1218 self.missing_named_lifetime_spots.pop();
1220 TyAlias(ref ty) => {
1221 let generics = &impl_item.generics;
1222 self.missing_named_lifetime_spots.push(generics.into());
1223 let mut index = self.next_early_index();
1224 let mut non_lifetime_count = 0;
1225 debug!("visit_ty: index = {}", index);
1226 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
1229 .filter_map(|param| match param.kind {
1230 GenericParamKind::Lifetime { .. } => {
1231 Some(Region::early(&self.tcx.hir(), &mut index, param))
1233 GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
1234 non_lifetime_count += 1;
1239 self.map.late_bound_vars.insert(ty.hir_id, vec![]);
1240 let scope = Scope::Binder {
1243 next_early_index: index + non_lifetime_count,
1245 track_lifetime_uses: true,
1246 opaque_type_parent: true,
1247 scope_type: BinderScopeType::Normal,
1249 self.with(scope, |old_scope, this| {
1250 this.check_lifetime_params(old_scope, &generics.params);
1251 let scope = Scope::TraitRefBoundary { s: this.scope };
1252 this.with(scope, |_, this| {
1253 this.visit_generics(generics);
1257 self.missing_named_lifetime_spots.pop();
1260 // Only methods and types support generics.
1261 assert!(impl_item.generics.params.is_empty());
1262 self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
1263 intravisit::walk_impl_item(self, impl_item);
1264 self.missing_named_lifetime_spots.pop();
1269 #[tracing::instrument(level = "debug", skip(self))]
1270 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1271 if lifetime_ref.is_elided() {
1272 self.resolve_elided_lifetimes(&[lifetime_ref]);
1275 if lifetime_ref.is_static() {
1276 self.insert_lifetime(lifetime_ref, Region::Static);
1279 if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
1280 self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
1283 self.resolve_lifetime_ref(lifetime_ref);
1286 fn visit_assoc_type_binding(&mut self, type_binding: &'tcx hir::TypeBinding<'_>) {
1287 let scope = self.scope;
1288 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1289 // We add lifetime scope information for `Ident`s in associated type bindings and use
1290 // the `HirId` of the type binding as the key in `LifetimeMap`
1291 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1292 let map = scope_for_path.entry(type_binding.hir_id.owner).or_default();
1293 map.insert(type_binding.hir_id.local_id, lifetime_scope);
1295 hir::intravisit::walk_assoc_type_binding(self, type_binding);
1298 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
1299 for (i, segment) in path.segments.iter().enumerate() {
1300 let depth = path.segments.len() - i - 1;
1301 if let Some(ref args) = segment.args {
1302 self.visit_segment_args(path.res, depth, args);
1305 let scope = self.scope;
1306 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1307 // Add lifetime scope information to path segment. Note we cannot call `visit_path_segment`
1308 // here because that call would yield to resolution problems due to `walk_path_segment`
1309 // being called, which processes the path segments generic args, which we have already
1310 // processed using `visit_segment_args`.
1311 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1312 if let Some(hir_id) = segment.hir_id {
1313 let map = scope_for_path.entry(hir_id.owner).or_default();
1314 map.insert(hir_id.local_id, lifetime_scope);
1320 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'tcx hir::PathSegment<'tcx>) {
1321 let scope = self.scope;
1322 if let Some(scope_for_path) = self.map.scope_for_path.as_mut() {
1323 let lifetime_scope = get_lifetime_scopes_for_path(scope);
1324 if let Some(hir_id) = path_segment.hir_id {
1325 let map = scope_for_path.entry(hir_id.owner).or_default();
1326 map.insert(hir_id.local_id, lifetime_scope);
1330 intravisit::walk_path_segment(self, path_span, path_segment);
1333 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
1334 let output = match fd.output {
1335 hir::FnRetTy::DefaultReturn(_) => None,
1336 hir::FnRetTy::Return(ref ty) => Some(&**ty),
1338 self.visit_fn_like_elision(&fd.inputs, output);
1341 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1342 if !self.trait_definition_only {
1343 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
1345 let scope = Scope::TraitRefBoundary { s: self.scope };
1346 self.with(scope, |_, this| {
1347 for param in generics.params {
1349 GenericParamKind::Lifetime { .. } => {}
1350 GenericParamKind::Type { ref default, .. } => {
1351 walk_list!(this, visit_param_bound, param.bounds);
1352 if let Some(ref ty) = default {
1356 GenericParamKind::Const { ref ty, .. } => {
1357 let was_in_const_generic = this.is_in_const_generic;
1358 this.is_in_const_generic = true;
1359 walk_list!(this, visit_param_bound, param.bounds);
1361 this.is_in_const_generic = was_in_const_generic;
1365 for predicate in generics.where_clause.predicates {
1367 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1370 ref bound_generic_params,
1373 let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
1374 bound_generic_params
1376 .filter_map(|param| match param.kind {
1377 GenericParamKind::Lifetime { .. } => Some(param),
1381 .map(|(late_bound_idx, param)| {
1383 Region::late(late_bound_idx as u32, &this.tcx.hir(), param);
1384 let r = late_region_as_bound_region(this.tcx, &pair.1);
1388 this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
1389 let next_early_index = this.next_early_index();
1390 // Even if there are no lifetimes defined here, we still wrap it in a binder
1391 // scope. If there happens to be a nested poly trait ref (an error), that
1392 // will be `Concatenating` anyways, so we don't have to worry about the depth
1394 let scope = Scope::Binder {
1395 hir_id: bounded_ty.hir_id,
1399 track_lifetime_uses: true,
1400 opaque_type_parent: false,
1401 scope_type: BinderScopeType::Normal,
1403 this.with(scope, |old_scope, this| {
1404 this.check_lifetime_params(old_scope, &bound_generic_params);
1405 this.visit_ty(&bounded_ty);
1406 walk_list!(this, visit_param_bound, bounds);
1409 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1414 this.visit_lifetime(lifetime);
1415 walk_list!(this, visit_param_bound, bounds);
1417 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1422 this.visit_ty(lhs_ty);
1423 this.visit_ty(rhs_ty);
1430 fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
1432 hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
1433 // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
1434 // through the regular poly trait ref code, so we don't get another
1435 // chance to introduce a binder. For now, I'm keeping the existing logic
1436 // of "if there isn't a Binder scope above us, add one", but I
1437 // imagine there's a better way to go about this.
1438 let (binders, scope_type) = self.poly_trait_ref_binder_info();
1440 self.map.late_bound_vars.insert(*hir_id, binders);
1441 let scope = Scope::Binder {
1443 lifetimes: FxIndexMap::default(),
1445 next_early_index: self.next_early_index(),
1446 track_lifetime_uses: true,
1447 opaque_type_parent: false,
1450 self.with(scope, |_, this| {
1451 intravisit::walk_param_bound(this, bound);
1454 _ => intravisit::walk_param_bound(self, bound),
1458 fn visit_poly_trait_ref(
1460 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
1461 _modifier: hir::TraitBoundModifier,
1463 debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
1465 let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
1467 let next_early_index = self.next_early_index();
1468 let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
1470 let initial_bound_vars = binders.len() as u32;
1471 let mut lifetimes: FxIndexMap<hir::ParamName, Region> = FxIndexMap::default();
1472 let binders_iter = trait_ref
1473 .bound_generic_params
1475 .filter_map(|param| match param.kind {
1476 GenericParamKind::Lifetime { .. } => Some(param),
1480 .map(|(late_bound_idx, param)| {
1481 let pair = Region::late(
1482 initial_bound_vars + late_bound_idx as u32,
1486 let r = late_region_as_bound_region(self.tcx, &pair.1);
1487 lifetimes.insert(pair.0, pair.1);
1490 binders.extend(binders_iter);
1493 self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
1495 // Always introduce a scope here, even if this is in a where clause and
1496 // we introduced the binders around the bounded Ty. In that case, we
1497 // just reuse the concatenation functionality also present in nested trait
1499 let scope = Scope::Binder {
1500 hir_id: trait_ref.trait_ref.hir_ref_id,
1504 track_lifetime_uses: true,
1505 opaque_type_parent: false,
1508 self.with(scope, |old_scope, this| {
1509 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1510 walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
1511 this.visit_trait_ref(&trait_ref.trait_ref);
1514 if should_pop_missing_lt {
1515 self.missing_named_lifetime_spots.pop();
1520 #[derive(Copy, Clone, PartialEq)]
1534 fn original_label(span: Span) -> Original {
1535 Original { kind: ShadowKind::Label, span }
1537 fn shadower_label(span: Span) -> Shadower {
1538 Shadower { kind: ShadowKind::Label, span }
1540 fn original_lifetime(span: Span) -> Original {
1541 Original { kind: ShadowKind::Lifetime, span }
1543 fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
1544 Shadower { kind: ShadowKind::Lifetime, span: param.span }
1548 fn desc(&self) -> &'static str {
1550 ShadowKind::Label => "label",
1551 ShadowKind::Lifetime => "lifetime",
1556 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
1557 let lifetime_params: Vec<_> = params
1559 .filter_map(|param| match param.kind {
1560 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1564 let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1565 let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1567 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1572 "cannot mix in-band and explicit lifetime definitions"
1574 .span_label(*in_band_span, "in-band lifetime definition here")
1575 .span_label(*explicit_span, "explicit lifetime definition here")
1580 fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
1581 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1582 // lifetime/lifetime shadowing is an error
1587 "{} name `{}` shadows a \
1588 {} name that is already in scope",
1589 shadower.kind.desc(),
1594 // shadowing involving a label is only a warning, due to issues with
1595 // labels and lifetimes not being macro-hygienic.
1596 tcx.sess.struct_span_warn(
1599 "{} name `{}` shadows a \
1600 {} name that is already in scope",
1601 shadower.kind.desc(),
1607 err.span_label(orig.span, "first declared here");
1608 err.span_label(shadower.span, format!("{} `{}` already in scope", orig.kind.desc(), name));
1612 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1613 // if one of the label shadows a lifetime or another label.
1614 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
1615 struct GatherLabels<'a, 'tcx> {
1617 scope: ScopeRef<'a>,
1618 labels_in_fn: &'a mut Vec<Ident>,
1622 GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
1623 gather.visit_body(body);
1625 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1626 type Map = intravisit::ErasedMap<'v>;
1628 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1629 NestedVisitorMap::None
1632 fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
1633 if let Some(label) = expression_label(ex) {
1634 for prior_label in &self.labels_in_fn[..] {
1635 // FIXME (#24278): non-hygienic comparison
1636 if label.name == prior_label.name {
1637 signal_shadowing_problem(
1640 original_label(prior_label.span),
1641 shadower_label(label.span),
1646 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1648 self.labels_in_fn.push(label);
1650 intravisit::walk_expr(self, ex)
1654 fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
1655 if let hir::ExprKind::Loop(_, Some(label), ..) = ex.kind { Some(label.ident) } else { None }
1658 fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
1661 Scope::Body { s, .. }
1662 | Scope::Elision { s, .. }
1663 | Scope::ObjectLifetimeDefault { s, .. }
1664 | Scope::Supertrait { s, .. }
1665 | Scope::TraitRefBoundary { s, .. } => {
1673 Scope::Binder { ref lifetimes, s, .. } => {
1674 // FIXME (#24278): non-hygienic comparison
1676 lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
1679 tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
1681 signal_shadowing_problem(
1684 original_lifetime(tcx.hir().span(hir_id)),
1685 shadower_label(label.span),
1696 fn compute_object_lifetime_defaults(
1698 item: &hir::Item<'_>,
1699 ) -> Option<Vec<ObjectLifetimeDefault>> {
1701 hir::ItemKind::Struct(_, ref generics)
1702 | hir::ItemKind::Union(_, ref generics)
1703 | hir::ItemKind::Enum(_, ref generics)
1704 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, impl_trait_fn: None, .. })
1705 | hir::ItemKind::TyAlias(_, ref generics)
1706 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1707 let result = object_lifetime_defaults_for_item(tcx, generics);
1710 let attrs = tcx.hir().attrs(item.hir_id());
1711 if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
1712 let object_lifetime_default_reprs: String = result
1714 .map(|set| match *set {
1715 Set1::Empty => "BaseDefault".into(),
1716 Set1::One(Region::Static) => "'static".into(),
1717 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1720 .find_map(|param| match param.kind {
1721 GenericParamKind::Lifetime { .. } => {
1723 return Some(param.name.ident().to_string().into());
1731 Set1::One(_) => bug!(),
1732 Set1::Many => "Ambiguous".into(),
1734 .collect::<Vec<Cow<'static, str>>>()
1736 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1745 /// Scan the bounds and where-clauses on parameters to extract bounds
1746 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1747 /// for each type parameter.
1748 fn object_lifetime_defaults_for_item(
1750 generics: &hir::Generics<'_>,
1751 ) -> Vec<ObjectLifetimeDefault> {
1752 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
1753 for bound in bounds {
1754 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1755 set.insert(lifetime.name.normalize_to_macros_2_0());
1763 .filter_map(|param| match param.kind {
1764 GenericParamKind::Lifetime { .. } => None,
1765 GenericParamKind::Type { .. } => {
1766 let mut set = Set1::Empty;
1768 add_bounds(&mut set, ¶m.bounds);
1770 let param_def_id = tcx.hir().local_def_id(param.hir_id);
1771 for predicate in generics.where_clause.predicates {
1772 // Look for `type: ...` where clauses.
1773 let data = match *predicate {
1774 hir::WherePredicate::BoundPredicate(ref data) => data,
1778 // Ignore `for<'a> type: ...` as they can change what
1779 // lifetimes mean (although we could "just" handle it).
1780 if !data.bound_generic_params.is_empty() {
1784 let res = match data.bounded_ty.kind {
1785 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
1789 if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
1790 add_bounds(&mut set, &data.bounds);
1795 Set1::Empty => Set1::Empty,
1796 Set1::One(name) => {
1797 if name == hir::LifetimeName::Static {
1798 Set1::One(Region::Static)
1803 .filter_map(|param| match param.kind {
1804 GenericParamKind::Lifetime { .. } => Some((
1806 hir::LifetimeName::Param(param.name),
1807 LifetimeDefOrigin::from_param(param),
1812 .find(|&(_, (_, lt_name, _))| lt_name == name)
1813 .map_or(Set1::Many, |(i, (id, _, origin))| {
1814 let def_id = tcx.hir().local_def_id(id);
1815 Set1::One(Region::EarlyBound(
1823 Set1::Many => Set1::Many,
1826 GenericParamKind::Const { .. } => {
1827 // Generic consts don't impose any constraints.
1829 // We still store a dummy value here to allow generic parameters
1830 // in an arbitrary order.
1837 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1838 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1840 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1842 let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
1843 let labels_in_fn = take(&mut self.labels_in_fn);
1844 let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
1845 let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
1846 let mut this = LifetimeContext {
1850 is_in_fn_syntax: self.is_in_fn_syntax,
1851 is_in_const_generic: self.is_in_const_generic,
1852 trait_definition_only: self.trait_definition_only,
1854 xcrate_object_lifetime_defaults,
1856 missing_named_lifetime_spots,
1858 let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
1860 let _enter = span.enter();
1861 f(self.scope, &mut this);
1862 if !self.trait_definition_only {
1863 this.check_uses_for_lifetimes_defined_by_scope();
1866 self.labels_in_fn = this.labels_in_fn;
1867 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1868 self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
1871 /// helper method to determine the span to remove when suggesting the
1872 /// deletion of a lifetime
1873 fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
1874 generics.params.iter().enumerate().find_map(|(i, param)| {
1875 if param.name.ident() == name {
1876 let in_band = matches!(
1878 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::InBand }
1882 } else if generics.params.len() == 1 {
1883 // if sole lifetime, remove the entire `<>` brackets
1886 // if removing within `<>` brackets, we also want to
1887 // delete a leading or trailing comma as appropriate
1888 if i >= generics.params.len() - 1 {
1889 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1891 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1900 // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
1901 // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
1902 fn suggest_eliding_single_use_lifetime(
1904 err: &mut DiagnosticBuilder<'_>,
1906 lifetime: &hir::Lifetime,
1908 let name = lifetime.name.ident();
1909 let remove_decl = self
1912 .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id))
1913 .and_then(|generics| self.lifetime_deletion_span(name, generics));
1915 let mut remove_use = None;
1916 let mut elide_use = None;
1917 let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
1918 for input in inputs {
1920 hir::TyKind::Rptr(lt, _) => {
1921 if lt.name.ident() == name {
1922 // include the trailing whitespace between the lifetime and type names
1923 let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
1928 .span_until_non_whitespace(lt_through_ty_span),
1933 hir::TyKind::Path(ref qpath) => {
1934 if let QPath::Resolved(_, path) = qpath {
1935 let last_segment = &path.segments[path.segments.len() - 1];
1936 let generics = last_segment.args();
1937 for arg in generics.args.iter() {
1938 if let GenericArg::Lifetime(lt) = arg {
1939 if lt.name.ident() == name {
1940 elide_use = Some(lt.span);
1952 if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
1953 if let Some(parent) =
1954 self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
1957 Node::Item(item) => {
1958 if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
1959 find_arg_use_span(sig.decl.inputs);
1962 Node::ImplItem(impl_item) => {
1963 if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
1964 find_arg_use_span(sig.decl.inputs);
1972 let msg = "elide the single-use lifetime";
1973 match (remove_decl, remove_use, elide_use) {
1974 (Some(decl_span), Some(use_span), None) => {
1975 // if both declaration and use deletion spans start at the same
1976 // place ("start at" because the latter includes trailing
1977 // whitespace), then this is an in-band lifetime
1978 if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
1979 err.span_suggestion(
1983 Applicability::MachineApplicable,
1986 err.multipart_suggestion(
1988 vec![(decl_span, String::new()), (use_span, String::new())],
1989 Applicability::MachineApplicable,
1993 (Some(decl_span), None, Some(use_span)) => {
1994 err.multipart_suggestion(
1996 vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
1997 Applicability::MachineApplicable,
2004 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
2005 let defined_by = match self.scope {
2006 Scope::Binder { lifetimes, .. } => lifetimes,
2008 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
2013 let mut def_ids: Vec<_> = defined_by
2015 .flat_map(|region| match region {
2016 Region::EarlyBound(_, def_id, _)
2017 | Region::LateBound(_, _, def_id, _)
2018 | Region::Free(_, def_id) => Some(*def_id),
2020 Region::LateBoundAnon(..) | Region::Static => None,
2024 // ensure that we issue lints in a repeatable order
2025 def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
2027 'lifetimes: for def_id in def_ids {
2028 debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
2030 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
2033 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
2037 match lifetimeuseset {
2038 Some(LifetimeUseSet::One(lifetime)) => {
2039 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2040 debug!("hir id first={:?}", hir_id);
2041 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
2042 Node::Lifetime(hir_lifetime) => Some((
2043 hir_lifetime.hir_id,
2045 hir_lifetime.name.ident(),
2047 Node::GenericParam(param) => {
2048 Some((param.hir_id, param.span, param.name.ident()))
2052 debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
2053 if name.name == kw::UnderscoreLifetime {
2057 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2058 if let Some(def_id) = parent_def_id.as_local() {
2059 let parent_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2060 // lifetimes in `derive` expansions don't count (Issue #53738)
2064 .attrs(parent_hir_id)
2066 .any(|attr| attr.has_name(sym::automatically_derived))
2071 // opaque types generated when desugaring an async function can have a single
2072 // use lifetime even if it is explicitly denied (Issue #77175)
2073 if let hir::Node::Item(hir::Item {
2074 kind: hir::ItemKind::OpaqueTy(ref opaque),
2076 }) = self.tcx.hir().get(parent_hir_id)
2078 if opaque.origin != hir::OpaqueTyOrigin::AsyncFn {
2079 continue 'lifetimes;
2081 // We want to do this only if the liftime identifier is already defined
2082 // in the async function that generated this. Otherwise it could be
2083 // an opaque type defined by the developer and we still want this
2084 // lint to fail compilation
2085 for p in opaque.generics.params {
2086 if defined_by.contains_key(&p.name) {
2087 continue 'lifetimes;
2094 self.tcx.struct_span_lint_hir(
2095 lint::builtin::SINGLE_USE_LIFETIMES,
2099 let mut err = lint.build(&format!(
2100 "lifetime parameter `{}` only used once",
2103 if span == lifetime.span {
2104 // spans are the same for in-band lifetime declarations
2105 err.span_label(span, "this lifetime is only used here");
2107 err.span_label(span, "this lifetime...");
2108 err.span_label(lifetime.span, "...is used only here");
2110 self.suggest_eliding_single_use_lifetime(
2111 &mut err, def_id, lifetime,
2118 Some(LifetimeUseSet::Many) => {
2119 debug!("not one use lifetime");
2122 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2123 if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
2124 Node::Lifetime(hir_lifetime) => Some((
2125 hir_lifetime.hir_id,
2127 hir_lifetime.name.ident(),
2129 Node::GenericParam(param) => {
2130 Some((param.hir_id, param.span, param.name.ident()))
2134 debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
2135 self.tcx.struct_span_lint_hir(
2136 lint::builtin::UNUSED_LIFETIMES,
2141 .build(&format!("lifetime parameter `{}` never used", name));
2142 if let Some(parent_def_id) = self.tcx.parent(def_id) {
2143 if let Some(generics) =
2144 self.tcx.hir().get_generics(parent_def_id)
2146 let unused_lt_span =
2147 self.lifetime_deletion_span(name, generics);
2148 if let Some(span) = unused_lt_span {
2149 err.span_suggestion(
2151 "elide the unused lifetime",
2153 Applicability::MachineApplicable,
2167 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
2169 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
2170 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
2171 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
2175 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
2177 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
2178 /// lifetimes may be interspersed together.
2180 /// If early bound lifetimes are present, we separate them into their own list (and likewise
2181 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
2182 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
2183 /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
2184 /// ordering is not important there.
2185 fn visit_early_late<F>(
2187 parent_id: Option<hir::HirId>,
2189 decl: &'tcx hir::FnDecl<'tcx>,
2190 generics: &'tcx hir::Generics<'tcx>,
2193 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
2195 insert_late_bound_lifetimes(self.map, decl, generics);
2197 // Find the start of nested early scopes, e.g., in methods.
2198 let mut next_early_index = 0;
2199 if let Some(parent_id) = parent_id {
2200 let parent = self.tcx.hir().expect_item(parent_id);
2201 if sub_items_have_self_param(&parent.kind) {
2202 next_early_index += 1; // Self comes before lifetimes
2205 hir::ItemKind::Trait(_, _, ref generics, ..)
2206 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
2207 next_early_index += generics.params.len() as u32;
2213 let mut non_lifetime_count = 0;
2214 let mut named_late_bound_vars = 0;
2215 let lifetimes: FxIndexMap<hir::ParamName, Region> = generics
2218 .filter_map(|param| match param.kind {
2219 GenericParamKind::Lifetime { .. } => {
2220 if self.map.late_bound.contains(¶m.hir_id) {
2221 let late_bound_idx = named_late_bound_vars;
2222 named_late_bound_vars += 1;
2223 Some(Region::late(late_bound_idx, &self.tcx.hir(), param))
2225 Some(Region::early(&self.tcx.hir(), &mut next_early_index, param))
2228 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
2229 non_lifetime_count += 1;
2234 let next_early_index = next_early_index + non_lifetime_count;
2236 let binders: Vec<_> = generics
2239 .filter_map(|param| match param.kind {
2240 GenericParamKind::Lifetime { .. }
2241 if self.map.late_bound.contains(¶m.hir_id) =>
2248 .map(|(late_bound_idx, param)| {
2249 let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
2250 let r = late_region_as_bound_region(self.tcx, &pair.1);
2254 self.map.late_bound_vars.insert(hir_id, binders);
2255 let scope = Scope::Binder {
2260 opaque_type_parent: true,
2261 track_lifetime_uses: false,
2262 scope_type: BinderScopeType::Normal,
2264 self.with(scope, move |old_scope, this| {
2265 this.check_lifetime_params(old_scope, &generics.params);
2270 fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
2271 let mut scope = self.scope;
2274 Scope::Root => return 0,
2276 Scope::Binder { next_early_index, opaque_type_parent, .. }
2277 if (!only_opaque_type_parent || opaque_type_parent) =>
2279 return next_early_index;
2282 Scope::Binder { s, .. }
2283 | Scope::Body { s, .. }
2284 | Scope::Elision { s, .. }
2285 | Scope::ObjectLifetimeDefault { s, .. }
2286 | Scope::Supertrait { s, .. }
2287 | Scope::TraitRefBoundary { s, .. } => scope = s,
2292 /// Returns the next index one would use for an early-bound-region
2293 /// if extending the current scope.
2294 fn next_early_index(&self) -> u32 {
2295 self.next_early_index_helper(true)
2298 /// Returns the next index one would use for an `impl Trait` that
2299 /// is being converted into an opaque type alias `impl Trait`. This will be the
2300 /// next early index from the enclosing item, for the most
2301 /// part. See the `opaque_type_parent` field for more info.
2302 fn next_early_index_for_opaque_type(&self) -> u32 {
2303 self.next_early_index_helper(false)
2306 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2307 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
2309 // If we've already reported an error, just ignore `lifetime_ref`.
2310 if let LifetimeName::Error = lifetime_ref.name {
2314 // Walk up the scope chain, tracking the number of fn scopes
2315 // that we pass through, until we find a lifetime with the
2316 // given name or we run out of scopes.
2318 let mut late_depth = 0;
2319 let mut scope = self.scope;
2320 let mut outermost_body = None;
2323 Scope::Body { id, s } => {
2324 // Non-static lifetimes are prohibited in anonymous constants without
2325 // `generic_const_exprs`.
2326 self.maybe_emit_forbidden_non_static_lifetime_error(id, lifetime_ref);
2328 outermost_body = Some(id);
2336 Scope::Binder { ref lifetimes, scope_type, s, .. } => {
2337 match lifetime_ref.name {
2338 LifetimeName::Param(param_name) => {
2339 if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0())
2341 break Some(def.shifted(late_depth));
2344 _ => bug!("expected LifetimeName::Param"),
2347 BinderScopeType::Normal => late_depth += 1,
2348 BinderScopeType::Concatenating => {}
2353 Scope::Elision { s, .. }
2354 | Scope::ObjectLifetimeDefault { s, .. }
2355 | Scope::Supertrait { s, .. }
2356 | Scope::TraitRefBoundary { s, .. } => {
2362 if let Some(mut def) = result {
2363 if let Region::EarlyBound(..) = def {
2364 // Do not free early-bound regions, only late-bound ones.
2365 } else if let Some(body_id) = outermost_body {
2366 let fn_id = self.tcx.hir().body_owner(body_id);
2367 match self.tcx.hir().get(fn_id) {
2368 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
2369 | Node::TraitItem(&hir::TraitItem {
2370 kind: hir::TraitItemKind::Fn(..), ..
2372 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
2373 let scope = self.tcx.hir().local_def_id(fn_id);
2374 def = Region::Free(scope.to_def_id(), def.id().unwrap());
2380 // Check for fn-syntax conflicts with in-band lifetime definitions
2381 if !self.trait_definition_only && self.is_in_fn_syntax {
2383 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
2384 | Region::LateBound(_, _, _, LifetimeDefOrigin::InBand) => {
2389 "lifetimes used in `fn` or `Fn` syntax must be \
2390 explicitly declared using `<...>` binders"
2392 .span_label(lifetime_ref.span, "in-band lifetime definition")
2397 | Region::EarlyBound(
2400 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2402 | Region::LateBound(
2406 LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
2408 | Region::LateBoundAnon(..)
2409 | Region::Free(..) => {}
2413 self.insert_lifetime(lifetime_ref, def);
2415 self.emit_undeclared_lifetime_error(lifetime_ref);
2419 fn visit_segment_args(
2423 generic_args: &'tcx hir::GenericArgs<'tcx>,
2426 "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
2427 res, depth, generic_args,
2430 if generic_args.parenthesized {
2431 let was_in_fn_syntax = self.is_in_fn_syntax;
2432 self.is_in_fn_syntax = true;
2433 self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
2434 self.is_in_fn_syntax = was_in_fn_syntax;
2438 let mut elide_lifetimes = true;
2439 let lifetimes: Vec<_> = generic_args
2442 .filter_map(|arg| match arg {
2443 hir::GenericArg::Lifetime(lt) => {
2444 if !lt.is_elided() {
2445 elide_lifetimes = false;
2452 // We short-circuit here if all are elided in order to pluralize
2454 if elide_lifetimes {
2455 self.resolve_elided_lifetimes(&lifetimes);
2457 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
2460 // Figure out if this is a type/trait segment,
2461 // which requires object lifetime defaults.
2462 let parent_def_id = |this: &mut Self, def_id: DefId| {
2463 let def_key = this.tcx.def_key(def_id);
2464 DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
2466 let type_def_id = match res {
2467 Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
2468 Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
2476 ) if depth == 0 => Some(def_id),
2480 debug!("visit_segment_args: type_def_id={:?}", type_def_id);
2482 // Compute a vector of defaults, one for each type parameter,
2483 // per the rules given in RFCs 599 and 1156. Example:
2486 // struct Foo<'a, T: 'a, U> { }
2489 // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
2490 // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
2491 // and `dyn Baz` to `dyn Baz + 'static` (because there is no
2494 // Therefore, we would compute `object_lifetime_defaults` to a
2495 // vector like `['x, 'static]`. Note that the vector only
2496 // includes type parameters.
2497 let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
2499 let mut scope = self.scope;
2502 Scope::Root => break false,
2504 Scope::Body { .. } => break true,
2506 Scope::Binder { s, .. }
2507 | Scope::Elision { s, .. }
2508 | Scope::ObjectLifetimeDefault { s, .. }
2509 | Scope::Supertrait { s, .. }
2510 | Scope::TraitRefBoundary { s, .. } => {
2517 let map = &self.map;
2518 let set_to_region = |set: &ObjectLifetimeDefault| match *set {
2523 Some(Region::Static)
2527 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
2528 GenericArg::Lifetime(lt) => Some(lt),
2531 r.subst(lifetimes, map)
2535 if let Some(def_id) = def_id.as_local() {
2536 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2537 self.tcx.object_lifetime_defaults(id).unwrap().iter().map(set_to_region).collect()
2540 self.xcrate_object_lifetime_defaults
2542 .or_insert_with(|| {
2543 tcx.generics_of(def_id)
2546 .filter_map(|param| match param.kind {
2547 GenericParamDefKind::Type { object_lifetime_default, .. } => {
2548 Some(object_lifetime_default)
2550 GenericParamDefKind::Lifetime
2551 | GenericParamDefKind::Const { .. } => None,
2561 debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
2564 for arg in generic_args.args {
2566 GenericArg::Lifetime(_) => {}
2567 GenericArg::Type(ty) => {
2568 if let Some(<) = object_lifetime_defaults.get(i) {
2569 let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
2570 self.with(scope, |_, this| this.visit_ty(ty));
2576 GenericArg::Const(ct) => {
2577 self.visit_anon_const(&ct.value);
2579 GenericArg::Infer(inf) => {
2580 self.visit_id(inf.hir_id);
2581 if inf.kind.is_type() {
2588 // Hack: when resolving the type `XX` in binding like `dyn
2589 // Foo<'b, Item = XX>`, the current object-lifetime default
2590 // would be to examine the trait `Foo` to check whether it has
2591 // a lifetime bound declared on `Item`. e.g., if `Foo` is
2592 // declared like so, then the default object lifetime bound in
2593 // `XX` should be `'b`:
2601 // but if we just have `type Item;`, then it would be
2602 // `'static`. However, we don't get all of this logic correct.
2604 // Instead, we do something hacky: if there are no lifetime parameters
2605 // to the trait, then we simply use a default object lifetime
2606 // bound of `'static`, because there is no other possibility. On the other hand,
2607 // if there ARE lifetime parameters, then we require the user to give an
2608 // explicit bound for now.
2610 // This is intended to leave room for us to implement the
2611 // correct behavior in the future.
2612 let has_lifetime_parameter =
2613 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
2615 // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
2616 // in the trait ref `YY<...>` in `Item: YY<...>`.
2617 for binding in generic_args.bindings {
2618 let scope = Scope::ObjectLifetimeDefault {
2619 lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
2622 if let Some(type_def_id) = type_def_id {
2623 let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
2628 self.with(scope, |_, this| {
2629 let scope = Scope::Supertrait {
2630 lifetimes: lifetimes.unwrap_or_default(),
2633 this.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2636 self.with(scope, |_, this| this.visit_assoc_type_binding(binding));
2641 /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2642 /// associated type name and starting trait.
2643 /// For example, imagine we have
2645 /// trait Foo<'a, 'b> {
2648 /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2649 /// trait Bar: for<'b> Bar<'b> {}
2651 /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2652 /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2653 fn supertrait_hrtb_lifetimes(
2657 ) -> Option<Vec<ty::BoundVariableKind>> {
2658 let trait_defines_associated_type_named = |trait_def_id: DefId| {
2659 tcx.associated_items(trait_def_id)
2660 .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
2664 use smallvec::{smallvec, SmallVec};
2665 let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
2666 smallvec![(def_id, smallvec![])];
2667 let mut visited: FxHashSet<DefId> = FxHashSet::default();
2669 let (def_id, bound_vars) = match stack.pop() {
2673 // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
2674 // there being no supertrait HRTBs.
2675 match tcx.def_kind(def_id) {
2676 DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
2680 if trait_defines_associated_type_named(def_id) {
2681 break Some(bound_vars.into_iter().collect());
2684 tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
2685 let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
2686 let bound_predicate = pred.kind();
2687 match bound_predicate.skip_binder() {
2688 ty::PredicateKind::Trait(data) => {
2689 // The order here needs to match what we would get from `subst_supertrait`
2690 let pred_bound_vars = bound_predicate.bound_vars();
2691 let mut all_bound_vars = bound_vars.clone();
2692 all_bound_vars.extend(pred_bound_vars.iter());
2693 let super_def_id = data.trait_ref.def_id;
2694 Some((super_def_id, all_bound_vars))
2700 let obligations = obligations.filter(|o| visited.insert(o.0));
2701 stack.extend(obligations);
2705 #[tracing::instrument(level = "debug", skip(self))]
2706 fn visit_fn_like_elision(
2708 inputs: &'tcx [hir::Ty<'tcx>],
2709 output: Option<&'tcx hir::Ty<'tcx>>,
2711 debug!("visit_fn_like_elision: enter");
2712 let mut scope = &*self.scope;
2715 Scope::Binder { hir_id, .. } => {
2718 Scope::ObjectLifetimeDefault { ref s, .. }
2719 | Scope::Elision { ref s, .. }
2720 | Scope::Supertrait { ref s, .. }
2721 | Scope::TraitRefBoundary { ref s, .. } => {
2724 Scope::Root | Scope::Body { .. } => {
2725 // See issues #83907 and #83693. Just bail out from looking inside.
2726 self.tcx.sess.delay_span_bug(
2727 rustc_span::DUMMY_SP,
2728 "In fn_like_elision without appropriate scope above",
2734 // While not strictly necessary, we gather anon lifetimes *before* actually
2735 // visiting the argument types.
2736 let mut gather = GatherAnonLifetimes { anon_count: 0 };
2737 for input in inputs {
2738 gather.visit_ty(input);
2740 let late_bound_vars = self.map.late_bound_vars.entry(hir_id).or_default();
2741 let named_late_bound_vars = late_bound_vars.len() as u32;
2742 late_bound_vars.extend(
2743 (0..gather.anon_count).map(|var| ty::BoundVariableKind::Region(ty::BrAnon(var))),
2745 let arg_scope = Scope::Elision {
2746 elide: Elide::FreshLateAnon(named_late_bound_vars, Cell::new(0)),
2749 self.with(arg_scope, |_, this| {
2750 for input in inputs {
2751 this.visit_ty(input);
2755 let output = match output {
2760 debug!("determine output");
2762 // Figure out if there's a body we can get argument names from,
2763 // and whether there's a `self` argument (treated specially).
2764 let mut assoc_item_kind = None;
2765 let mut impl_self = None;
2766 let parent = self.tcx.hir().get_parent_node(output.hir_id);
2767 let body = match self.tcx.hir().get(parent) {
2768 // `fn` definitions and methods.
2769 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
2771 Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
2772 if let hir::ItemKind::Trait(.., ref trait_items) =
2773 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2776 trait_items.iter().find(|ti| ti.id.hir_id() == parent).map(|ti| ti.kind);
2779 hir::TraitFn::Required(_) => None,
2780 hir::TraitFn::Provided(body) => Some(body),
2784 Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
2785 if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) =
2786 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
2788 impl_self = Some(self_ty);
2790 items.iter().find(|ii| ii.id.hir_id() == parent).map(|ii| ii.kind);
2795 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2796 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2797 // Everything else (only closures?) doesn't
2798 // actually enjoy elision in return types.
2800 self.visit_ty(output);
2805 let has_self = match assoc_item_kind {
2806 Some(hir::AssocItemKind::Fn { has_self }) => has_self,
2810 // In accordance with the rules for lifetime elision, we can determine
2811 // what region to use for elision in the output type in two ways.
2812 // First (determined here), if `self` is by-reference, then the
2813 // implied output region is the region of the self parameter.
2815 struct SelfVisitor<'a> {
2816 map: &'a NamedRegionMap,
2817 impl_self: Option<&'a hir::TyKind<'a>>,
2818 lifetime: Set1<Region>,
2821 impl SelfVisitor<'_> {
2822 // Look for `self: &'a Self` - also desugared from `&'a self`,
2823 // and if that matches, use it for elision and return early.
2824 fn is_self_ty(&self, res: Res) -> bool {
2825 if let Res::SelfTy(..) = res {
2829 // Can't always rely on literal (or implied) `Self` due
2830 // to the way elision rules were originally specified.
2831 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
2835 // Permit the types that unambiguously always
2836 // result in the same type constructor being used
2837 // (it can't differ between `Self` and `self`).
2838 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
2839 | Res::PrimTy(_) => return res == path.res,
2848 impl<'a> Visitor<'a> for SelfVisitor<'a> {
2849 type Map = intravisit::ErasedMap<'a>;
2851 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2852 NestedVisitorMap::None
2855 fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
2856 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
2857 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
2859 if self.is_self_ty(path.res) {
2860 if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
2861 self.lifetime.insert(*lifetime);
2866 intravisit::walk_ty(self, ty)
2870 let mut visitor = SelfVisitor {
2872 impl_self: impl_self.map(|ty| &ty.kind),
2873 lifetime: Set1::Empty,
2875 visitor.visit_ty(&inputs[0]);
2876 if let Set1::One(lifetime) = visitor.lifetime {
2877 let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
2878 self.with(scope, |_, this| this.visit_ty(output));
2883 // Second, if there was exactly one lifetime (either a substitution or a
2884 // reference) in the arguments, then any anonymous regions in the output
2885 // have that lifetime.
2886 let mut possible_implied_output_region = None;
2887 let mut lifetime_count = 0;
2888 let arg_lifetimes = inputs
2891 .skip(has_self as usize)
2893 let mut gather = GatherLifetimes {
2895 outer_index: ty::INNERMOST,
2896 have_bound_regions: false,
2897 lifetimes: Default::default(),
2899 gather.visit_ty(input);
2901 lifetime_count += gather.lifetimes.len();
2903 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2904 // there's a chance that the unique lifetime of this
2905 // iteration will be the appropriate lifetime for output
2906 // parameters, so lets store it.
2907 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2910 ElisionFailureInfo {
2913 lifetime_count: gather.lifetimes.len(),
2914 have_bound_regions: gather.have_bound_regions,
2920 let elide = if lifetime_count == 1 {
2921 Elide::Exact(possible_implied_output_region.unwrap())
2923 Elide::Error(arg_lifetimes)
2928 let scope = Scope::Elision { elide, s: self.scope };
2929 self.with(scope, |_, this| this.visit_ty(output));
2931 struct GatherLifetimes<'a> {
2932 map: &'a NamedRegionMap,
2933 outer_index: ty::DebruijnIndex,
2934 have_bound_regions: bool,
2935 lifetimes: FxHashSet<Region>,
2938 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2939 type Map = intravisit::ErasedMap<'v>;
2941 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2942 NestedVisitorMap::None
2945 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2946 if let hir::TyKind::BareFn(_) = ty.kind {
2947 self.outer_index.shift_in(1);
2950 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2951 for bound in bounds {
2952 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2955 // Stay on the safe side and don't include the object
2956 // lifetime default (which may not end up being used).
2957 if !lifetime.is_elided() {
2958 self.visit_lifetime(lifetime);
2962 intravisit::walk_ty(self, ty);
2965 if let hir::TyKind::BareFn(_) = ty.kind {
2966 self.outer_index.shift_out(1);
2970 fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
2971 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2972 // FIXME(eddyb) Do we want this? It only makes a difference
2973 // if this `for<'a>` lifetime parameter is never used.
2974 self.have_bound_regions = true;
2977 intravisit::walk_generic_param(self, param);
2980 fn visit_poly_trait_ref(
2982 trait_ref: &hir::PolyTraitRef<'_>,
2983 modifier: hir::TraitBoundModifier,
2985 self.outer_index.shift_in(1);
2986 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2987 self.outer_index.shift_out(1);
2990 fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
2991 if let hir::GenericBound::LangItemTrait { .. } = bound {
2992 self.outer_index.shift_in(1);
2993 intravisit::walk_param_bound(self, bound);
2994 self.outer_index.shift_out(1);
2996 intravisit::walk_param_bound(self, bound);
3000 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
3001 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
3003 Region::LateBound(debruijn, _, _, _)
3004 | Region::LateBoundAnon(debruijn, _, _)
3005 if debruijn < self.outer_index =>
3007 self.have_bound_regions = true;
3010 // FIXME(jackh726): nested trait refs?
3011 self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
3018 struct GatherAnonLifetimes {
3021 impl<'v> Visitor<'v> for GatherAnonLifetimes {
3022 type Map = intravisit::ErasedMap<'v>;
3024 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3025 NestedVisitorMap::None
3028 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
3029 // If we enter a `BareFn`, then we enter a *new* binding scope
3030 if let hir::TyKind::BareFn(_) = ty.kind {
3033 intravisit::walk_ty(self, ty);
3036 fn visit_generic_args(
3039 generic_args: &'v hir::GenericArgs<'v>,
3041 // parenthesized args enter a new elison scope
3042 if generic_args.parenthesized {
3045 intravisit::walk_generic_args(self, path_span, generic_args)
3048 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
3049 if lifetime_ref.is_elided() {
3050 self.anon_count += 1;
3056 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[&'tcx hir::Lifetime]) {
3057 debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
3059 if lifetime_refs.is_empty() {
3063 let mut late_depth = 0;
3064 let mut scope = self.scope;
3065 let mut lifetime_names = FxHashSet::default();
3066 let mut lifetime_spans = vec![];
3069 // Do not assign any resolution, it will be inferred.
3070 Scope::Body { .. } => return,
3072 Scope::Root => break None,
3074 Scope::Binder { s, ref lifetimes, scope_type, .. } => {
3075 // collect named lifetimes for suggestions
3076 for name in lifetimes.keys() {
3077 if let hir::ParamName::Plain(name) = name {
3078 lifetime_names.insert(name.name);
3079 lifetime_spans.push(name.span);
3083 BinderScopeType::Normal => late_depth += 1,
3084 BinderScopeType::Concatenating => {}
3089 Scope::Elision { ref elide, ref s, .. } => {
3090 let lifetime = match *elide {
3091 Elide::FreshLateAnon(named_late_bound_vars, ref counter) => {
3092 for lifetime_ref in lifetime_refs {
3093 let lifetime = Region::late_anon(named_late_bound_vars, counter)
3094 .shifted(late_depth);
3096 self.insert_lifetime(lifetime_ref, lifetime);
3100 Elide::Exact(l) => l.shifted(late_depth),
3101 Elide::Error(ref e) => {
3105 Scope::Binder { ref lifetimes, s, .. } => {
3106 // Collect named lifetimes for suggestions.
3107 for name in lifetimes.keys() {
3108 if let hir::ParamName::Plain(name) = name {
3109 lifetime_names.insert(name.name);
3110 lifetime_spans.push(name.span);
3115 Scope::ObjectLifetimeDefault { ref s, .. }
3116 | Scope::Elision { ref s, .. }
3117 | Scope::TraitRefBoundary { ref s, .. } => {
3125 Elide::Forbid => break None,
3127 for lifetime_ref in lifetime_refs {
3128 self.insert_lifetime(lifetime_ref, lifetime);
3133 Scope::ObjectLifetimeDefault { s, .. }
3134 | Scope::Supertrait { s, .. }
3135 | Scope::TraitRefBoundary { s, .. } => {
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 report_elision_failure(
3181 db: &mut DiagnosticBuilder<'_>,
3182 params: &[ElisionFailureInfo],
3183 ) -> bool /* add `'static` lifetime to lifetime list */ {
3184 let mut m = String::new();
3185 let len = params.len();
3187 let elided_params: Vec<_> =
3188 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
3190 let elided_len = elided_params.len();
3192 for (i, info) in elided_params.into_iter().enumerate() {
3193 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
3196 db.span_label(span, "");
3197 let help_name = if let Some(ident) =
3198 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
3200 format!("`{}`", ident)
3202 format!("argument {}", index + 1)
3210 "one of {}'s {} {}lifetimes",
3213 if have_bound_regions { "free " } else { "" }
3218 if elided_len == 2 && i == 0 {
3220 } else if i + 2 == elided_len {
3221 m.push_str(", or ");
3222 } else if i != elided_len - 1 {
3229 "this function's return type contains a borrowed value, \
3230 but there is no value for it to be borrowed from",
3233 } else if elided_len == 0 {
3235 "this function's return type contains a borrowed value with \
3236 an elided lifetime, but the lifetime cannot be derived from \
3240 } else if elided_len == 1 {
3242 "this function's return type contains a borrowed value, \
3243 but the signature does not say which {} it is borrowed from",
3249 "this function's return type contains a borrowed value, \
3250 but the signature does not say whether it is borrowed from {}",
3257 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
3258 debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
3259 let mut late_depth = 0;
3260 let mut scope = self.scope;
3261 let lifetime = loop {
3263 Scope::Binder { s, scope_type, .. } => {
3265 BinderScopeType::Normal => late_depth += 1,
3266 BinderScopeType::Concatenating => {}
3271 Scope::Root | Scope::Elision { .. } => break Region::Static,
3273 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
3275 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
3277 Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
3282 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
3285 fn check_lifetime_params(
3287 old_scope: ScopeRef<'_>,
3288 params: &'tcx [hir::GenericParam<'tcx>],
3290 let lifetimes: Vec<_> = params
3292 .filter_map(|param| match param.kind {
3293 GenericParamKind::Lifetime { .. } => {
3294 Some((param, param.name.normalize_to_macros_2_0()))
3299 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
3300 if let hir::ParamName::Plain(_) = lifetime_i_name {
3301 let name = lifetime_i_name.ident().name;
3302 if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
3303 let mut err = struct_span_err!(
3307 "invalid lifetime parameter name: `{}`",
3308 lifetime_i.name.ident(),
3312 format!("{} is a reserved lifetime name", name),
3318 // It is a hard error to shadow a lifetime within the same scope.
3319 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
3320 if lifetime_i_name == lifetime_j_name {
3325 "lifetime name `{}` declared twice in the same scope",
3326 lifetime_j.name.ident()
3328 .span_label(lifetime_j.span, "declared twice")
3329 .span_label(lifetime_i.span, "previous declaration here")
3334 // It is a soft error to shadow a lifetime within a parent scope.
3335 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
3337 for bound in lifetime_i.bounds {
3339 hir::GenericBound::Outlives(ref lt) => match lt.name {
3340 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
3342 "use of `'_` in illegal place, but not caught by lowering",
3344 hir::LifetimeName::Static => {
3345 self.insert_lifetime(lt, Region::Static);
3349 lifetime_i.span.to(lt.span),
3351 "unnecessary lifetime parameter `{}`",
3352 lifetime_i.name.ident(),
3356 "you can use the `'static` lifetime directly, in place of `{}`",
3357 lifetime_i.name.ident(),
3361 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
3362 self.resolve_lifetime_ref(lt);
3364 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
3365 self.tcx.sess.delay_span_bug(
3367 "lowering generated `ImplicitObjectLifetimeDefault` \
3368 outside of an object type",
3371 hir::LifetimeName::Error => {
3372 // No need to do anything, error already reported.
3381 fn check_lifetime_param_for_shadowing(
3383 mut old_scope: ScopeRef<'_>,
3384 param: &'tcx hir::GenericParam<'tcx>,
3386 for label in &self.labels_in_fn {
3387 // FIXME (#24278): non-hygienic comparison
3388 if param.name.ident().name == label.name {
3389 signal_shadowing_problem(
3392 original_label(label.span),
3393 shadower_lifetime(¶m),
3401 Scope::Body { s, .. }
3402 | Scope::Elision { s, .. }
3403 | Scope::ObjectLifetimeDefault { s, .. }
3404 | Scope::Supertrait { s, .. }
3405 | Scope::TraitRefBoundary { s, .. } => {
3413 Scope::Binder { ref lifetimes, s, .. } => {
3414 if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) {
3416 self.tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
3418 signal_shadowing_problem(
3420 param.name.ident().name,
3421 original_lifetime(self.tcx.hir().span(hir_id)),
3422 shadower_lifetime(¶m),
3433 /// Returns `true` if, in the current scope, replacing `'_` would be
3434 /// equivalent to a single-use lifetime.
3435 fn track_lifetime_uses(&self) -> bool {
3436 let mut scope = self.scope;
3439 Scope::Root => break false,
3441 // Inside of items, it depends on the kind of item.
3442 Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
3444 // Inside a body, `'_` will use an inference variable,
3446 Scope::Body { .. } => break true,
3448 // A lifetime only used in a fn argument could as well
3449 // be replaced with `'_`, as that would generate a
3451 Scope::Elision { elide: Elide::FreshLateAnon(..), .. } => break true,
3453 // In the return type or other such place, `'_` is not
3454 // going to make a fresh name, so we cannot
3455 // necessarily replace a single-use lifetime with
3458 elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
3461 Scope::ObjectLifetimeDefault { s, .. }
3462 | Scope::Supertrait { s, .. }
3463 | Scope::TraitRefBoundary { s, .. } => scope = s,
3468 #[tracing::instrument(level = "debug", skip(self))]
3469 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
3471 node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
3472 span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
3474 self.map.defs.insert(lifetime_ref.hir_id, def);
3477 Region::LateBoundAnon(..) | Region::Static => {
3478 // These are anonymous lifetimes or lifetimes that are not declared.
3481 Region::Free(_, def_id)
3482 | Region::LateBound(_, _, def_id, _)
3483 | Region::EarlyBound(_, def_id, _) => {
3484 // A lifetime declared by the user.
3485 let track_lifetime_uses = self.track_lifetime_uses();
3486 debug!(?track_lifetime_uses);
3487 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
3488 debug!("first use of {:?}", def_id);
3489 self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
3491 debug!("many uses of {:?}", def_id);
3492 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
3498 /// Sometimes we resolve a lifetime, but later find that it is an
3499 /// error (esp. around impl trait). In that case, we remove the
3500 /// entry into `map.defs` so as not to confuse later code.
3501 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
3502 let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
3503 assert_eq!(old_value, Some(bad_def));
3507 /// Detects late-bound lifetimes and inserts them into
3508 /// `map.late_bound`.
3510 /// A region declared on a fn is **late-bound** if:
3511 /// - it is constrained by an argument type;
3512 /// - it does not appear in a where-clause.
3514 /// "Constrained" basically means that it appears in any type but
3515 /// not amongst the inputs to a projection. In other words, `<&'a
3516 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
3517 #[tracing::instrument(level = "debug", skip(map))]
3518 fn insert_late_bound_lifetimes(
3519 map: &mut NamedRegionMap,
3520 decl: &hir::FnDecl<'_>,
3521 generics: &hir::Generics<'_>,
3523 let mut constrained_by_input = ConstrainedCollector::default();
3524 for arg_ty in decl.inputs {
3525 constrained_by_input.visit_ty(arg_ty);
3528 let mut appears_in_output = AllCollector::default();
3529 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
3531 debug!(?constrained_by_input.regions);
3533 // Walk the lifetimes that appear in where clauses.
3535 // Subtle point: because we disallow nested bindings, we can just
3536 // ignore binders here and scrape up all names we see.
3537 let mut appears_in_where_clause = AllCollector::default();
3538 appears_in_where_clause.visit_generics(generics);
3540 for param in generics.params {
3541 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
3542 if !param.bounds.is_empty() {
3543 // `'a: 'b` means both `'a` and `'b` are referenced
3544 appears_in_where_clause
3546 .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
3551 debug!(?appears_in_where_clause.regions);
3553 // Late bound regions are those that:
3554 // - appear in the inputs
3555 // - do not appear in the where-clauses
3556 // - are not implicitly captured by `impl Trait`
3557 for param in generics.params {
3559 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
3561 // Neither types nor consts are late-bound.
3562 hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
3565 let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
3566 // appears in the where clauses? early-bound.
3567 if appears_in_where_clause.regions.contains(<_name) {
3571 // does not appear in the inputs, but appears in the return type? early-bound.
3572 if !constrained_by_input.regions.contains(<_name)
3573 && appears_in_output.regions.contains(<_name)
3578 debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
3580 let inserted = map.late_bound.insert(param.hir_id);
3581 assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
3587 struct ConstrainedCollector {
3588 regions: FxHashSet<hir::LifetimeName>,
3591 impl<'v> Visitor<'v> for ConstrainedCollector {
3592 type Map = intravisit::ErasedMap<'v>;
3594 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3595 NestedVisitorMap::None
3598 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3601 hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
3603 // ignore lifetimes appearing in associated type
3604 // projections, as they are not *constrained*
3608 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
3609 // consider only the lifetimes on the final
3610 // segment; I am not sure it's even currently
3611 // valid to have them elsewhere, but even if it
3612 // is, those would be potentially inputs to
3614 if let Some(last_segment) = path.segments.last() {
3615 self.visit_path_segment(path.span, last_segment);
3620 intravisit::walk_ty(self, ty);
3625 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3626 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
3631 struct AllCollector {
3632 regions: FxHashSet<hir::LifetimeName>,
3635 impl<'v> Visitor<'v> for AllCollector {
3636 type Map = intravisit::ErasedMap<'v>;
3638 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3639 NestedVisitorMap::None
3642 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
3643 self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());