1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Name resolution for lifetimes.
13 //! Name resolution for lifetimes follows MUCH simpler rules than the
14 //! full resolve. For example, lifetime names are never exported or
15 //! used between functions, and they operate in a purely top-down
16 //! way. Therefore we break lifetime name resolution into a separate pass.
19 use hir
::def_id
::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}
;
21 use hir
::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName}
;
22 use ty
::{self, DefIdTree, GenericParamDefKind, TyCtxt}
;
24 use errors
::{Applicability, DiagnosticBuilder}
;
26 use rustc_data_structures
::sync
::Lrc
;
30 use std
::mem
::replace
;
34 use syntax
::symbol
::keywords
;
36 use util
::nodemap
::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet}
;
38 use hir
::intravisit
::{self, NestedVisitorMap, Visitor}
;
39 use hir
::{self, GenericParamKind, LifetimeParamKind}
;
41 /// The origin of a named lifetime definition.
43 /// This is used to prevent the usage of in-band lifetimes in `Fn`/`fn` syntax.
44 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
45 pub enum LifetimeDefOrigin
{
46 // Explicit binders like `fn foo<'a>(x: &'a u8)` or elided like `impl Foo<&u32>`
48 // In-band declarations like `fn foo(x: &'a u8)`
50 // Some kind of erroneous origin
54 impl LifetimeDefOrigin
{
55 fn from_param(param
: &GenericParam
) -> Self {
57 GenericParamKind
::Lifetime { kind }
=> match kind
{
58 LifetimeParamKind
::InBand
=> LifetimeDefOrigin
::InBand
,
59 LifetimeParamKind
::Explicit
=> LifetimeDefOrigin
::ExplicitOrElided
,
60 LifetimeParamKind
::Elided
=> LifetimeDefOrigin
::ExplicitOrElided
,
61 LifetimeParamKind
::Error
=> LifetimeDefOrigin
::Error
,
63 _
=> bug
!("expected a lifetime param"),
68 // This counts the no of times a lifetime is used
69 #[derive(Clone, Copy, Debug)]
70 pub enum LifetimeUseSet
<'tcx
> {
71 One(&'tcx hir
::Lifetime
),
75 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
80 /* lifetime decl */ DefId
,
85 /* lifetime decl */ DefId
,
88 LateBoundAnon(ty
::DebruijnIndex
, /* anon index */ u32),
89 Free(DefId
, /* lifetime decl */ DefId
),
93 fn early(hir_map
: &Map
<'_
>, index
: &mut u32, param
: &GenericParam
) -> (ParamName
, Region
) {
96 let def_id
= hir_map
.local_def_id(param
.id
);
97 let origin
= LifetimeDefOrigin
::from_param(param
);
98 debug
!("Region::early: index={} def_id={:?}", i
, def_id
);
99 (param
.name
.modern(), Region
::EarlyBound(i
, def_id
, origin
))
102 fn late(hir_map
: &Map
<'_
>, param
: &GenericParam
) -> (ParamName
, Region
) {
103 let depth
= ty
::INNERMOST
;
104 let def_id
= hir_map
.local_def_id(param
.id
);
105 let origin
= LifetimeDefOrigin
::from_param(param
);
107 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
108 param
, depth
, def_id
, origin
,
112 Region
::LateBound(depth
, def_id
, origin
),
116 fn late_anon(index
: &Cell
<u32>) -> Region
{
119 let depth
= ty
::INNERMOST
;
120 Region
::LateBoundAnon(depth
, i
)
123 fn id(&self) -> Option
<DefId
> {
125 Region
::Static
| Region
::LateBoundAnon(..) => None
,
127 Region
::EarlyBound(_
, id
, _
) | Region
::LateBound(_
, id
, _
) | Region
::Free(_
, id
) => {
133 fn shifted(self, amount
: u32) -> Region
{
135 Region
::LateBound(debruijn
, id
, origin
) => {
136 Region
::LateBound(debruijn
.shifted_in(amount
), id
, origin
)
138 Region
::LateBoundAnon(debruijn
, index
) => {
139 Region
::LateBoundAnon(debruijn
.shifted_in(amount
), index
)
145 fn shifted_out_to_binder(self, binder
: ty
::DebruijnIndex
) -> Region
{
147 Region
::LateBound(debruijn
, id
, origin
) => {
148 Region
::LateBound(debruijn
.shifted_out_to_binder(binder
), id
, origin
)
150 Region
::LateBoundAnon(debruijn
, index
) => {
151 Region
::LateBoundAnon(debruijn
.shifted_out_to_binder(binder
), index
)
157 fn subst
<'a
, L
>(self, mut params
: L
, map
: &NamedRegionMap
) -> Option
<Region
>
159 L
: Iterator
<Item
= &'a hir
::Lifetime
>,
161 if let Region
::EarlyBound(index
, _
, _
) = self {
164 .and_then(|lifetime
| map
.defs
.get(&lifetime
.id
).cloned())
171 /// A set containing, at most, one known element.
172 /// If two distinct values are inserted into a set, then it
173 /// becomes `Many`, which can be used to detect ambiguities.
174 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
181 impl<T
: PartialEq
> Set1
<T
> {
182 pub fn insert(&mut self, value
: T
) {
183 if let Set1
::Empty
= *self {
184 *self = Set1
::One(value
);
187 if let Set1
::One(ref old
) = *self {
196 pub type ObjectLifetimeDefault
= Set1
<Region
>;
198 /// Maps the id of each lifetime reference to the lifetime decl
199 /// that it corresponds to.
201 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
202 /// actual use. It has the same data, but indexed by `DefIndex`. This
205 struct NamedRegionMap
{
206 // maps from every use of a named (not anonymous) lifetime to a
207 // `Region` describing how that region is bound
208 pub defs
: NodeMap
<Region
>,
210 // the set of lifetime def ids that are late-bound; a region can
211 // be late-bound if (a) it does NOT appear in a where-clause and
212 // (b) it DOES appear in the arguments.
213 pub late_bound
: NodeSet
,
215 // For each type and trait definition, maps type parameters
216 // to the trait object lifetime defaults computed from them.
217 pub object_lifetime_defaults
: NodeMap
<Vec
<ObjectLifetimeDefault
>>,
220 /// See `NamedRegionMap`.
222 pub struct ResolveLifetimes
{
223 defs
: FxHashMap
<LocalDefId
, Lrc
<FxHashMap
<ItemLocalId
, Region
>>>,
224 late_bound
: FxHashMap
<LocalDefId
, Lrc
<FxHashSet
<ItemLocalId
>>>,
225 object_lifetime_defaults
:
226 FxHashMap
<LocalDefId
, Lrc
<FxHashMap
<ItemLocalId
, Lrc
<Vec
<ObjectLifetimeDefault
>>>>>,
229 impl_stable_hash_for
!(struct ::middle
::resolve_lifetime
::ResolveLifetimes
{
232 object_lifetime_defaults
235 struct LifetimeContext
<'a
, 'tcx
: 'a
> {
236 tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
237 map
: &'a
mut NamedRegionMap
,
240 /// Deep breath. Our representation for poly trait refs contains a single
241 /// binder and thus we only allow a single level of quantification. However,
242 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
243 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
244 /// correct when representing these constraints, we should only introduce one
245 /// scope. However, we want to support both locations for the quantifier and
246 /// during lifetime resolution we want precise information (so we can't
247 /// desugar in an earlier phase).
249 /// SO, if we encounter a quantifier at the outer scope, we set
250 /// trait_ref_hack to true (and introduce a scope), and then if we encounter
251 /// a quantifier at the inner scope, we error. If trait_ref_hack is false,
252 /// then we introduce the scope at the inner quantifier.
255 trait_ref_hack
: bool
,
257 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
258 is_in_fn_syntax
: bool
,
260 /// List of labels in the function/method currently under analysis.
261 labels_in_fn
: Vec
<ast
::Ident
>,
263 /// Cache for cross-crate per-definition object lifetime defaults.
264 xcrate_object_lifetime_defaults
: DefIdMap
<Vec
<ObjectLifetimeDefault
>>,
266 lifetime_uses
: &'a
mut DefIdMap
<LifetimeUseSet
<'tcx
>>,
271 /// Declares lifetimes, and each can be early-bound or late-bound.
272 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
273 /// it should be shifted by the number of `Binder`s in between the
274 /// declaration `Binder` and the location it's referenced from.
276 lifetimes
: FxHashMap
<hir
::ParamName
, Region
>,
278 /// if we extend this scope with another scope, what is the next index
279 /// we should use for an early-bound region?
280 next_early_index
: u32,
282 /// Flag is set to true if, in this binder, `'_` would be
283 /// equivalent to a "single-use region". This is true on
284 /// impls, but not other kinds of items.
285 track_lifetime_uses
: bool
,
287 /// Whether or not this binder would serve as the parent
288 /// binder for abstract types introduced within. For example:
290 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
292 /// Here, the abstract types we create for the `impl Trait`
293 /// and `impl Trait2` references will both have the `foo` item
294 /// as their parent. When we get to `impl Trait2`, we find
295 /// that it is nested within the `for<>` binder -- this flag
296 /// allows us to skip that when looking for the parent binder
297 /// of the resulting abstract type.
298 abstract_type_parent
: bool
,
303 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
304 /// if this is a fn body, otherwise the original definitions are used.
305 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
306 /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
312 /// A scope which either determines unspecified lifetimes or errors
313 /// on them (e.g. due to ambiguity). For more details, see `Elide`.
319 /// Use a specific lifetime (if `Some`) or leave it unset (to be
320 /// inferred in a function body or potentially error outside one),
321 /// for the default choice of lifetime in a trait object type.
322 ObjectLifetimeDefault
{
323 lifetime
: Option
<Region
>,
330 #[derive(Clone, Debug)]
332 /// Use a fresh anonymous late-bound lifetime each time, by
333 /// incrementing the counter to generate sequential indices.
334 FreshLateAnon(Cell
<u32>),
335 /// Always use this one lifetime.
337 /// Less or more than one lifetime were found, error on unspecified.
338 Error(Vec
<ElisionFailureInfo
>),
341 #[derive(Clone, Debug)]
342 struct ElisionFailureInfo
{
343 /// Where we can find the argument pattern.
344 parent
: Option
<hir
::BodyId
>,
345 /// The index of the argument in the original definition.
347 lifetime_count
: usize,
348 have_bound_regions
: bool
,
351 type ScopeRef
<'a
> = &'a Scope
<'a
>;
353 const ROOT_SCOPE
: ScopeRef
<'
static> = &Scope
::Root
;
355 pub fn provide(providers
: &mut ty
::query
::Providers
<'_
>) {
356 *providers
= ty
::query
::Providers
{
359 named_region_map
: |tcx
, id
| {
360 let id
= LocalDefId
::from_def_id(DefId
::local(id
)); // (*)
361 tcx
.resolve_lifetimes(LOCAL_CRATE
).defs
.get(&id
).cloned()
364 is_late_bound_map
: |tcx
, id
| {
365 let id
= LocalDefId
::from_def_id(DefId
::local(id
)); // (*)
366 tcx
.resolve_lifetimes(LOCAL_CRATE
)
372 object_lifetime_defaults_map
: |tcx
, id
| {
373 let id
= LocalDefId
::from_def_id(DefId
::local(id
)); // (*)
374 tcx
.resolve_lifetimes(LOCAL_CRATE
)
375 .object_lifetime_defaults
383 // (*) FIXME the query should be defined to take a LocalDefId
386 /// Computes the `ResolveLifetimes` map that contains data for the
387 /// entire crate. You should not read the result of this query
388 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
390 fn resolve_lifetimes
<'tcx
>(
391 tcx
: TyCtxt
<'_
, 'tcx
, 'tcx
>,
393 ) -> Lrc
<ResolveLifetimes
> {
394 assert_eq
!(for_krate
, LOCAL_CRATE
);
396 let named_region_map
= krate(tcx
);
398 let mut rl
= ResolveLifetimes
::default();
400 for (k
, v
) in named_region_map
.defs
{
401 let hir_id
= tcx
.hir
.node_to_hir_id(k
);
402 let map
= rl
.defs
.entry(hir_id
.owner_local_def_id()).or_default();
403 Lrc
::get_mut(map
).unwrap().insert(hir_id
.local_id
, v
);
405 for k
in named_region_map
.late_bound
{
406 let hir_id
= tcx
.hir
.node_to_hir_id(k
);
407 let map
= rl
.late_bound
408 .entry(hir_id
.owner_local_def_id())
410 Lrc
::get_mut(map
).unwrap().insert(hir_id
.local_id
);
412 for (k
, v
) in named_region_map
.object_lifetime_defaults
{
413 let hir_id
= tcx
.hir
.node_to_hir_id(k
);
414 let map
= rl
.object_lifetime_defaults
415 .entry(hir_id
.owner_local_def_id())
419 .insert(hir_id
.local_id
, Lrc
::new(v
));
425 fn krate
<'tcx
>(tcx
: TyCtxt
<'_
, 'tcx
, 'tcx
>) -> NamedRegionMap
{
426 let krate
= tcx
.hir
.krate();
427 let mut map
= NamedRegionMap
{
429 late_bound
: NodeSet(),
430 object_lifetime_defaults
: compute_object_lifetime_defaults(tcx
),
433 let mut visitor
= LifetimeContext
{
437 trait_ref_hack
: false,
438 is_in_fn_syntax
: false,
439 labels_in_fn
: vec
![],
440 xcrate_object_lifetime_defaults
: DefIdMap(),
441 lifetime_uses
: &mut DefIdMap(),
443 for (_
, item
) in &krate
.items
{
444 visitor
.visit_item(item
);
450 impl<'a
, 'tcx
> Visitor
<'tcx
> for LifetimeContext
<'a
, 'tcx
> {
451 fn nested_visit_map
<'this
>(&'this
mut self) -> NestedVisitorMap
<'this
, 'tcx
> {
452 NestedVisitorMap
::All(&self.tcx
.hir
)
455 // We want to nest trait/impl items in their parent, but nothing else.
456 fn visit_nested_item(&mut self, _
: hir
::ItemId
) {}
458 fn visit_nested_body(&mut self, body
: hir
::BodyId
) {
459 // Each body has their own set of labels, save labels.
460 let saved
= replace(&mut self.labels_in_fn
, vec
![]);
461 let body
= self.tcx
.hir
.body(body
);
462 extract_labels(self, body
);
469 this
.visit_body(body
);
472 replace(&mut self.labels_in_fn
, saved
);
475 fn visit_item(&mut self, item
: &'tcx hir
::Item
) {
477 hir
::ItemKind
::Fn(ref decl
, _
, ref generics
, _
) => {
478 self.visit_early_late(None
, decl
, generics
, |this
| {
479 intravisit
::walk_item(this
, item
);
483 hir
::ItemKind
::ExternCrate(_
)
484 | hir
::ItemKind
::Use(..)
485 | hir
::ItemKind
::Mod(..)
486 | hir
::ItemKind
::ForeignMod(..)
487 | hir
::ItemKind
::GlobalAsm(..) => {
488 // These sorts of items have no lifetime parameters at all.
489 intravisit
::walk_item(self, item
);
491 hir
::ItemKind
::Static(..) | hir
::ItemKind
::Const(..) => {
492 // No lifetime parameters, but implied 'static.
493 let scope
= Scope
::Elision
{
494 elide
: Elide
::Exact(Region
::Static
),
497 self.with(scope
, |_
, this
| intravisit
::walk_item(this
, item
));
499 hir
::ItemKind
::Existential(hir
::ExistTy
{
500 impl_trait_fn
: Some(_
),
503 // currently existential type declarations are just generated from impl Trait
504 // items. doing anything on this node is irrelevant, as we currently don't need
507 hir
::ItemKind
::Ty(_
, ref generics
)
508 | hir
::ItemKind
::Existential(hir
::ExistTy
{
513 | hir
::ItemKind
::Enum(_
, ref generics
)
514 | hir
::ItemKind
::Struct(_
, ref generics
)
515 | hir
::ItemKind
::Union(_
, ref generics
)
516 | hir
::ItemKind
::Trait(_
, _
, ref generics
, ..)
517 | hir
::ItemKind
::TraitAlias(ref generics
, ..)
518 | hir
::ItemKind
::Impl(_
, _
, _
, ref generics
, ..) => {
519 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
520 // This is not true for other kinds of items.x
521 let track_lifetime_uses
= match item
.node
{
522 hir
::ItemKind
::Impl(..) => true,
525 // These kinds of items have only early bound lifetime parameters.
526 let mut index
= if let hir
::ItemKind
::Trait(..) = item
.node
{
527 1 // Self comes before lifetimes
531 let mut type_count
= 0;
532 let lifetimes
= generics
535 .filter_map(|param
| match param
.kind
{
536 GenericParamKind
::Lifetime { .. }
=> {
537 Some(Region
::early(&self.tcx
.hir
, &mut index
, param
))
539 GenericParamKind
::Type { .. }
=> {
545 let scope
= Scope
::Binder
{
547 next_early_index
: index
+ type_count
,
548 abstract_type_parent
: true,
552 self.with(scope
, |old_scope
, this
| {
553 this
.check_lifetime_params(old_scope
, &generics
.params
);
554 intravisit
::walk_item(this
, item
);
560 fn visit_foreign_item(&mut self, item
: &'tcx hir
::ForeignItem
) {
562 hir
::ForeignItemKind
::Fn(ref decl
, _
, ref generics
) => {
563 self.visit_early_late(None
, decl
, generics
, |this
| {
564 intravisit
::walk_foreign_item(this
, item
);
567 hir
::ForeignItemKind
::Static(..) => {
568 intravisit
::walk_foreign_item(self, item
);
570 hir
::ForeignItemKind
::Type
=> {
571 intravisit
::walk_foreign_item(self, item
);
576 fn visit_ty(&mut self, ty
: &'tcx hir
::Ty
) {
577 debug
!("visit_ty: id={:?} ty={:?}", ty
.id
, ty
);
579 hir
::TyKind
::BareFn(ref c
) => {
580 let next_early_index
= self.next_early_index();
581 let was_in_fn_syntax
= self.is_in_fn_syntax
;
582 self.is_in_fn_syntax
= true;
583 let scope
= Scope
::Binder
{
584 lifetimes
: c
.generic_params
586 .filter_map(|param
| match param
.kind
{
587 GenericParamKind
::Lifetime { .. }
=> {
588 Some(Region
::late(&self.tcx
.hir
, param
))
595 track_lifetime_uses
: true,
596 abstract_type_parent
: false,
598 self.with(scope
, |old_scope
, this
| {
599 // a bare fn has no bounds, so everything
600 // contained within is scoped within its binder.
601 this
.check_lifetime_params(old_scope
, &c
.generic_params
);
602 intravisit
::walk_ty(this
, ty
);
604 self.is_in_fn_syntax
= was_in_fn_syntax
;
606 hir
::TyKind
::TraitObject(ref bounds
, ref lifetime
) => {
607 for bound
in bounds
{
608 self.visit_poly_trait_ref(bound
, hir
::TraitBoundModifier
::None
);
610 match lifetime
.name
{
611 LifetimeName
::Implicit
=> {
612 // If the user does not write *anything*, we
613 // use the object lifetime defaulting
614 // rules. So e.g. `Box<dyn Debug>` becomes
615 // `Box<dyn Debug + 'static>`.
616 self.resolve_object_lifetime_default(lifetime
)
618 LifetimeName
::Underscore
=> {
619 // If the user writes `'_`, we use the *ordinary* elision
620 // rules. So the `'_` in e.g. `Box<dyn Debug + '_>` will be
621 // resolved the same as the `'_` in `&'_ Foo`.
624 self.resolve_elided_lifetimes(vec
![lifetime
])
626 LifetimeName
::Param(_
) | LifetimeName
::Static
=> {
627 // If the user wrote an explicit name, use that.
628 self.visit_lifetime(lifetime
);
630 LifetimeName
::Error
=> {}
633 hir
::TyKind
::Rptr(ref lifetime_ref
, ref mt
) => {
634 self.visit_lifetime(lifetime_ref
);
635 let scope
= Scope
::ObjectLifetimeDefault
{
636 lifetime
: self.map
.defs
.get(&lifetime_ref
.id
).cloned(),
639 self.with(scope
, |_
, this
| this
.visit_ty(&mt
.ty
));
641 hir
::TyKind
::Def(item_id
, ref lifetimes
) => {
642 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
643 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
644 // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
645 // ^ ^ this gets resolved in the scope of
646 // the exist_ty generics
647 let (generics
, bounds
) = match self.tcx
.hir
.expect_item(item_id
.id
).node
{
648 // named existential types are reached via TyKind::Path
649 // this arm is for `impl Trait` in the types of statics, constants and locals
650 hir
::ItemKind
::Existential(hir
::ExistTy
{
654 intravisit
::walk_ty(self, ty
);
657 // RPIT (return position impl trait)
658 hir
::ItemKind
::Existential(hir
::ExistTy
{
662 }) => (generics
, bounds
),
663 ref i
=> bug
!("impl Trait pointed to non-existential type?? {:#?}", i
),
666 // Resolve the lifetimes that are applied to the existential type.
667 // These are resolved in the current scope.
668 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
669 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
670 // ^ ^this gets resolved in the current scope
671 for lifetime
in lifetimes
{
672 if let hir
::GenericArg
::Lifetime(lifetime
) = lifetime
{
673 self.visit_lifetime(lifetime
);
675 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
676 // and ban them. Type variables instantiated inside binders aren't
677 // well-supported at the moment, so this doesn't work.
678 // In the future, this should be fixed and this error should be removed.
679 let def
= self.map
.defs
.get(&lifetime
.id
).cloned();
680 if let Some(Region
::LateBound(_
, def_id
, _
)) = def
{
681 if let Some(node_id
) = self.tcx
.hir
.as_local_node_id(def_id
) {
682 // Ensure that the parent of the def is an item, not HRTB
683 let parent_id
= self.tcx
.hir
.get_parent_node(node_id
);
684 let parent_impl_id
= hir
::ImplItemId { node_id: parent_id }
;
685 let parent_trait_id
= hir
::TraitItemId { node_id: parent_id }
;
686 let krate
= self.tcx
.hir
.forest
.krate();
687 if !(krate
.items
.contains_key(&parent_id
)
688 || krate
.impl_items
.contains_key(&parent_impl_id
)
689 || krate
.trait_items
.contains_key(&parent_trait_id
))
695 "`impl Trait` can only capture lifetimes \
696 bound at the fn or impl level"
698 self.uninsert_lifetime_on_error(lifetime
, def
.unwrap());
705 // We want to start our early-bound indices at the end of the parent scope,
706 // not including any parent `impl Trait`s.
707 let mut index
= self.next_early_index_for_abstract_type();
708 debug
!("visit_ty: index = {}", index
);
710 let mut elision
= None
;
711 let mut lifetimes
= FxHashMap
::default();
712 let mut type_count
= 0;
713 for param
in &generics
.params
{
715 GenericParamKind
::Lifetime { .. }
=> {
716 let (name
, reg
) = Region
::early(&self.tcx
.hir
, &mut index
, ¶m
);
717 if let hir
::ParamName
::Plain(param_name
) = name
{
718 if param_name
.name
== keywords
::UnderscoreLifetime
.name() {
719 // Pick the elided lifetime "definition" if one exists
720 // and use it to make an elision scope.
723 lifetimes
.insert(name
, reg
);
726 lifetimes
.insert(name
, reg
);
729 GenericParamKind
::Type { .. }
=> {
734 let next_early_index
= index
+ type_count
;
736 if let Some(elision_region
) = elision
{
737 let scope
= Scope
::Elision
{
738 elide
: Elide
::Exact(elision_region
),
741 self.with(scope
, |_old_scope
, this
| {
742 let scope
= Scope
::Binder
{
746 track_lifetime_uses
: true,
747 abstract_type_parent
: false,
749 this
.with(scope
, |_old_scope
, this
| {
750 this
.visit_generics(generics
);
751 for bound
in bounds
{
752 this
.visit_param_bound(bound
);
757 let scope
= Scope
::Binder
{
761 track_lifetime_uses
: true,
762 abstract_type_parent
: false,
764 self.with(scope
, |_old_scope
, this
| {
765 this
.visit_generics(generics
);
766 for bound
in bounds
{
767 this
.visit_param_bound(bound
);
772 _
=> intravisit
::walk_ty(self, ty
),
776 fn visit_trait_item(&mut self, trait_item
: &'tcx hir
::TraitItem
) {
777 use self::hir
::TraitItemKind
::*;
778 match trait_item
.node
{
779 Method(ref sig
, _
) => {
781 self.visit_early_late(
782 Some(tcx
.hir
.get_parent(trait_item
.id
)),
784 &trait_item
.generics
,
785 |this
| intravisit
::walk_trait_item(this
, trait_item
),
788 Type(ref bounds
, ref ty
) => {
789 let generics
= &trait_item
.generics
;
790 let mut index
= self.next_early_index();
791 debug
!("visit_ty: index = {}", index
);
792 let mut type_count
= 0;
793 let lifetimes
= generics
796 .filter_map(|param
| match param
.kind
{
797 GenericParamKind
::Lifetime { .. }
=> {
798 Some(Region
::early(&self.tcx
.hir
, &mut index
, param
))
800 GenericParamKind
::Type { .. }
=> {
806 let scope
= Scope
::Binder
{
808 next_early_index
: index
+ type_count
,
810 track_lifetime_uses
: true,
811 abstract_type_parent
: true,
813 self.with(scope
, |_old_scope
, this
| {
814 this
.visit_generics(generics
);
815 for bound
in bounds
{
816 this
.visit_param_bound(bound
);
818 if let Some(ty
) = ty
{
824 // Only methods and types support generics.
825 assert
!(trait_item
.generics
.params
.is_empty());
826 intravisit
::walk_trait_item(self, trait_item
);
831 fn visit_impl_item(&mut self, impl_item
: &'tcx hir
::ImplItem
) {
832 use self::hir
::ImplItemKind
::*;
833 match impl_item
.node
{
834 Method(ref sig
, _
) => {
836 self.visit_early_late(
837 Some(tcx
.hir
.get_parent(impl_item
.id
)),
840 |this
| intravisit
::walk_impl_item(this
, impl_item
),
844 let generics
= &impl_item
.generics
;
845 let mut index
= self.next_early_index();
846 let mut next_early_index
= index
;
847 debug
!("visit_ty: index = {}", index
);
848 let lifetimes
= generics
851 .filter_map(|param
| match param
.kind
{
852 GenericParamKind
::Lifetime { .. }
=> {
853 Some(Region
::early(&self.tcx
.hir
, &mut index
, param
))
855 GenericParamKind
::Type { .. }
=> {
856 next_early_index
+= 1;
861 let scope
= Scope
::Binder
{
865 track_lifetime_uses
: true,
866 abstract_type_parent
: true,
868 self.with(scope
, |_old_scope
, this
| {
869 this
.visit_generics(generics
);
873 Existential(ref bounds
) => {
874 let generics
= &impl_item
.generics
;
875 let mut index
= self.next_early_index();
876 let mut next_early_index
= index
;
877 debug
!("visit_ty: index = {}", index
);
878 let lifetimes
= generics
881 .filter_map(|param
| match param
.kind
{
882 GenericParamKind
::Lifetime { .. }
=> {
883 Some(Region
::early(&self.tcx
.hir
, &mut index
, param
))
885 GenericParamKind
::Type { .. }
=> {
886 next_early_index
+= 1;
892 let scope
= Scope
::Binder
{
896 track_lifetime_uses
: true,
897 abstract_type_parent
: true,
899 self.with(scope
, |_old_scope
, this
| {
900 this
.visit_generics(generics
);
901 for bound
in bounds
{
902 this
.visit_param_bound(bound
);
907 // Only methods and types support generics.
908 assert
!(impl_item
.generics
.params
.is_empty());
909 intravisit
::walk_impl_item(self, impl_item
);
914 fn visit_lifetime(&mut self, lifetime_ref
: &'tcx hir
::Lifetime
) {
915 if lifetime_ref
.is_elided() {
916 self.resolve_elided_lifetimes(vec
![lifetime_ref
]);
919 if lifetime_ref
.is_static() {
920 self.insert_lifetime(lifetime_ref
, Region
::Static
);
923 self.resolve_lifetime_ref(lifetime_ref
);
926 fn visit_path(&mut self, path
: &'tcx hir
::Path
, _
: hir
::HirId
) {
927 for (i
, segment
) in path
.segments
.iter().enumerate() {
928 let depth
= path
.segments
.len() - i
- 1;
929 if let Some(ref args
) = segment
.args
{
930 self.visit_segment_args(path
.def
, depth
, args
);
935 fn visit_fn_decl(&mut self, fd
: &'tcx hir
::FnDecl
) {
936 let output
= match fd
.output
{
937 hir
::DefaultReturn(_
) => None
,
938 hir
::Return(ref ty
) => Some(ty
),
940 self.visit_fn_like_elision(&fd
.inputs
, output
);
943 fn visit_generics(&mut self, generics
: &'tcx hir
::Generics
) {
944 check_mixed_explicit_and_in_band_defs(self.tcx
, &generics
.params
);
945 for param
in &generics
.params
{
947 GenericParamKind
::Lifetime { .. }
=> {}
948 GenericParamKind
::Type { ref default, .. }
=> {
949 walk_list
!(self, visit_param_bound
, ¶m
.bounds
);
950 if let Some(ref ty
) = default {
956 for predicate
in &generics
.where_clause
.predicates
{
958 &hir
::WherePredicate
::BoundPredicate(hir
::WhereBoundPredicate
{
961 ref bound_generic_params
,
964 let lifetimes
: FxHashMap
<_
, _
> = bound_generic_params
966 .filter_map(|param
| match param
.kind
{
967 GenericParamKind
::Lifetime { .. }
=> {
968 Some(Region
::late(&self.tcx
.hir
, param
))
973 if !lifetimes
.is_empty() {
974 self.trait_ref_hack
= true;
975 let next_early_index
= self.next_early_index();
976 let scope
= Scope
::Binder
{
980 track_lifetime_uses
: true,
981 abstract_type_parent
: false,
983 let result
= self.with(scope
, |old_scope
, this
| {
984 this
.check_lifetime_params(old_scope
, &bound_generic_params
);
985 this
.visit_ty(&bounded_ty
);
986 walk_list
!(this
, visit_param_bound
, bounds
);
988 self.trait_ref_hack
= false;
991 self.visit_ty(&bounded_ty
);
992 walk_list
!(self, visit_param_bound
, bounds
);
995 &hir
::WherePredicate
::RegionPredicate(hir
::WhereRegionPredicate
{
1000 self.visit_lifetime(lifetime
);
1001 walk_list
!(self, visit_param_bound
, bounds
);
1003 &hir
::WherePredicate
::EqPredicate(hir
::WhereEqPredicate
{
1008 self.visit_ty(lhs_ty
);
1009 self.visit_ty(rhs_ty
);
1015 fn visit_poly_trait_ref(
1017 trait_ref
: &'tcx hir
::PolyTraitRef
,
1018 _modifier
: hir
::TraitBoundModifier
,
1020 debug
!("visit_poly_trait_ref trait_ref={:?}", trait_ref
);
1022 if !self.trait_ref_hack
|| trait_ref
.bound_generic_params
.iter().any(|param
| {
1024 GenericParamKind
::Lifetime { .. }
=> true,
1028 if self.trait_ref_hack
{
1033 "nested quantification of lifetimes"
1036 let next_early_index
= self.next_early_index();
1037 let scope
= Scope
::Binder
{
1038 lifetimes
: trait_ref
1039 .bound_generic_params
1041 .filter_map(|param
| match param
.kind
{
1042 GenericParamKind
::Lifetime { .. }
=> {
1043 Some(Region
::late(&self.tcx
.hir
, param
))
1050 track_lifetime_uses
: true,
1051 abstract_type_parent
: false,
1053 self.with(scope
, |old_scope
, this
| {
1054 this
.check_lifetime_params(old_scope
, &trait_ref
.bound_generic_params
);
1055 walk_list
!(this
, visit_generic_param
, &trait_ref
.bound_generic_params
);
1056 this
.visit_trait_ref(&trait_ref
.trait_ref
)
1059 self.visit_trait_ref(&trait_ref
.trait_ref
)
1064 #[derive(Copy, Clone, PartialEq)]
1078 fn original_label(span
: Span
) -> Original
{
1080 kind
: ShadowKind
::Label
,
1084 fn shadower_label(span
: Span
) -> Shadower
{
1086 kind
: ShadowKind
::Label
,
1090 fn original_lifetime(span
: Span
) -> Original
{
1092 kind
: ShadowKind
::Lifetime
,
1096 fn shadower_lifetime(param
: &hir
::GenericParam
) -> Shadower
{
1098 kind
: ShadowKind
::Lifetime
,
1104 fn desc(&self) -> &'
static str {
1106 ShadowKind
::Label
=> "label",
1107 ShadowKind
::Lifetime
=> "lifetime",
1112 fn check_mixed_explicit_and_in_band_defs(tcx
: TyCtxt
<'_
, '_
, '_
>, params
: &P
<[hir
::GenericParam
]>) {
1113 let lifetime_params
: Vec
<_
> = params
1115 .filter_map(|param
| match param
.kind
{
1116 GenericParamKind
::Lifetime { kind, .. }
=> Some((kind
, param
.span
)),
1120 let explicit
= lifetime_params
1122 .find(|(kind
, _
)| *kind
== LifetimeParamKind
::Explicit
);
1123 let in_band
= lifetime_params
1125 .find(|(kind
, _
)| *kind
== LifetimeParamKind
::InBand
);
1127 if let (Some((_
, explicit_span
)), Some((_
, in_band_span
))) = (explicit
, in_band
) {
1132 "cannot mix in-band and explicit lifetime definitions"
1133 ).span_label(*in_band_span
, "in-band lifetime definition here")
1134 .span_label(*explicit_span
, "explicit lifetime definition here")
1139 fn signal_shadowing_problem(
1140 tcx
: TyCtxt
<'_
, '_
, '_
>,
1145 let mut err
= if let (ShadowKind
::Lifetime
, ShadowKind
::Lifetime
) = (orig
.kind
, shadower
.kind
) {
1146 // lifetime/lifetime shadowing is an error
1151 "{} name `{}` shadows a \
1152 {} name that is already in scope",
1153 shadower
.kind
.desc(),
1158 // shadowing involving a label is only a warning, due to issues with
1159 // labels and lifetimes not being macro-hygienic.
1160 tcx
.sess
.struct_span_warn(
1163 "{} name `{}` shadows a \
1164 {} name that is already in scope",
1165 shadower
.kind
.desc(),
1171 err
.span_label(orig
.span
, "first declared here");
1172 err
.span_label(shadower
.span
, format
!("lifetime {} already in scope", name
));
1176 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1177 // if one of the label shadows a lifetime or another label.
1178 fn extract_labels(ctxt
: &mut LifetimeContext
<'_
, '_
>, body
: &hir
::Body
) {
1179 struct GatherLabels
<'a
, 'tcx
: 'a
> {
1180 tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
1181 scope
: ScopeRef
<'a
>,
1182 labels_in_fn
: &'a
mut Vec
<ast
::Ident
>,
1185 let mut gather
= GatherLabels
{
1188 labels_in_fn
: &mut ctxt
.labels_in_fn
,
1190 gather
.visit_body(body
);
1192 impl<'v
, 'a
, 'tcx
> Visitor
<'v
> for GatherLabels
<'a
, 'tcx
> {
1193 fn nested_visit_map
<'this
>(&'this
mut self) -> NestedVisitorMap
<'this
, 'v
> {
1194 NestedVisitorMap
::None
1197 fn visit_expr(&mut self, ex
: &hir
::Expr
) {
1198 if let Some(label
) = expression_label(ex
) {
1199 for prior_label
in &self.labels_in_fn
[..] {
1200 // FIXME (#24278): non-hygienic comparison
1201 if label
.name
== prior_label
.name
{
1202 signal_shadowing_problem(
1205 original_label(prior_label
.span
),
1206 shadower_label(label
.span
),
1211 check_if_label_shadows_lifetime(self.tcx
, self.scope
, label
);
1213 self.labels_in_fn
.push(label
);
1215 intravisit
::walk_expr(self, ex
)
1219 fn expression_label(ex
: &hir
::Expr
) -> Option
<ast
::Ident
> {
1221 hir
::ExprKind
::While(.., Some(label
)) | hir
::ExprKind
::Loop(_
, Some(label
), _
) => {
1228 fn check_if_label_shadows_lifetime(
1229 tcx
: TyCtxt
<'_
, '_
, '_
>,
1230 mut scope
: ScopeRef
<'_
>,
1235 Scope
::Body { s, .. }
1236 | Scope
::Elision { s, .. }
1237 | Scope
::ObjectLifetimeDefault { s, .. }
=> {
1246 ref lifetimes
, s
, ..
1248 // FIXME (#24278): non-hygienic comparison
1249 if let Some(def
) = lifetimes
.get(&hir
::ParamName
::Plain(label
.modern())) {
1250 let node_id
= tcx
.hir
.as_local_node_id(def
.id().unwrap()).unwrap();
1252 signal_shadowing_problem(
1255 original_lifetime(tcx
.hir
.span(node_id
)),
1256 shadower_label(label
.span
),
1267 fn compute_object_lifetime_defaults(
1268 tcx
: TyCtxt
<'_
, '_
, '_
>,
1269 ) -> NodeMap
<Vec
<ObjectLifetimeDefault
>> {
1270 let mut map
= NodeMap();
1271 for item
in tcx
.hir
.krate().items
.values() {
1273 hir
::ItemKind
::Struct(_
, ref generics
)
1274 | hir
::ItemKind
::Union(_
, ref generics
)
1275 | hir
::ItemKind
::Enum(_
, ref generics
)
1276 | hir
::ItemKind
::Existential(hir
::ExistTy
{
1278 impl_trait_fn
: None
,
1281 | hir
::ItemKind
::Ty(_
, ref generics
)
1282 | hir
::ItemKind
::Trait(_
, _
, ref generics
, ..) => {
1283 let result
= object_lifetime_defaults_for_item(tcx
, generics
);
1286 if attr
::contains_name(&item
.attrs
, "rustc_object_lifetime_default") {
1287 let object_lifetime_default_reprs
: String
= result
1289 .map(|set
| match *set
{
1290 Set1
::Empty
=> "BaseDefault".into(),
1291 Set1
::One(Region
::Static
) => "'static".into(),
1292 Set1
::One(Region
::EarlyBound(mut i
, _
, _
)) => generics
1295 .find_map(|param
| match param
.kind
{
1296 GenericParamKind
::Lifetime { .. }
=> {
1298 return Some(param
.name
.ident().to_string().into());
1306 Set1
::One(_
) => bug
!(),
1307 Set1
::Many
=> "Ambiguous".into(),
1309 .collect
::<Vec
<Cow
<'
static, str>>>()
1311 tcx
.sess
.span_err(item
.span
, &object_lifetime_default_reprs
);
1314 map
.insert(item
.id
, result
);
1322 /// Scan the bounds and where-clauses on parameters to extract bounds
1323 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1324 /// for each type parameter.
1325 fn object_lifetime_defaults_for_item(
1326 tcx
: TyCtxt
<'_
, '_
, '_
>,
1327 generics
: &hir
::Generics
,
1328 ) -> Vec
<ObjectLifetimeDefault
> {
1329 fn add_bounds(set
: &mut Set1
<hir
::LifetimeName
>, bounds
: &[hir
::GenericBound
]) {
1330 for bound
in bounds
{
1331 if let hir
::GenericBound
::Outlives(ref lifetime
) = *bound
{
1332 set
.insert(lifetime
.name
.modern());
1340 .filter_map(|param
| match param
.kind
{
1341 GenericParamKind
::Lifetime { .. }
=> None
,
1342 GenericParamKind
::Type { .. }
=> {
1343 let mut set
= Set1
::Empty
;
1345 add_bounds(&mut set
, ¶m
.bounds
);
1347 let param_def_id
= tcx
.hir
.local_def_id(param
.id
);
1348 for predicate
in &generics
.where_clause
.predicates
{
1349 // Look for `type: ...` where clauses.
1350 let data
= match *predicate
{
1351 hir
::WherePredicate
::BoundPredicate(ref data
) => data
,
1355 // Ignore `for<'a> type: ...` as they can change what
1356 // lifetimes mean (although we could "just" handle it).
1357 if !data
.bound_generic_params
.is_empty() {
1361 let def
= match data
.bounded_ty
.node
{
1362 hir
::TyKind
::Path(hir
::QPath
::Resolved(None
, ref path
)) => path
.def
,
1366 if def
== Def
::TyParam(param_def_id
) {
1367 add_bounds(&mut set
, &data
.bounds
);
1372 Set1
::Empty
=> Set1
::Empty
,
1373 Set1
::One(name
) => {
1374 if name
== hir
::LifetimeName
::Static
{
1375 Set1
::One(Region
::Static
)
1380 .filter_map(|param
| match param
.kind
{
1381 GenericParamKind
::Lifetime { .. }
=> Some((
1383 hir
::LifetimeName
::Param(param
.name
),
1384 LifetimeDefOrigin
::from_param(param
),
1389 .find(|&(_
, (_
, lt_name
, _
))| lt_name
== name
)
1390 .map_or(Set1
::Many
, |(i
, (id
, _
, origin
))| {
1391 let def_id
= tcx
.hir
.local_def_id(id
);
1392 Set1
::One(Region
::EarlyBound(i
as u32, def_id
, origin
))
1396 Set1
::Many
=> Set1
::Many
,
1403 impl<'a
, 'tcx
> LifetimeContext
<'a
, 'tcx
> {
1404 // FIXME(#37666) this works around a limitation in the region inferencer
1405 fn hack
<F
>(&mut self, f
: F
)
1407 F
: for<'b
> FnOnce(&mut LifetimeContext
<'b
, 'tcx
>),
1412 fn with
<F
>(&mut self, wrap_scope
: Scope
<'_
>, f
: F
)
1414 F
: for<'b
> FnOnce(ScopeRef
<'_
>, &mut LifetimeContext
<'b
, 'tcx
>),
1416 let LifetimeContext
{
1422 let labels_in_fn
= replace(&mut self.labels_in_fn
, vec
![]);
1423 let xcrate_object_lifetime_defaults
=
1424 replace(&mut self.xcrate_object_lifetime_defaults
, DefIdMap());
1425 let mut this
= LifetimeContext
{
1429 trait_ref_hack
: self.trait_ref_hack
,
1430 is_in_fn_syntax
: self.is_in_fn_syntax
,
1432 xcrate_object_lifetime_defaults
,
1433 lifetime_uses
: lifetime_uses
,
1435 debug
!("entering scope {:?}", this
.scope
);
1436 f(self.scope
, &mut this
);
1437 this
.check_uses_for_lifetimes_defined_by_scope();
1438 debug
!("exiting scope {:?}", this
.scope
);
1439 self.labels_in_fn
= this
.labels_in_fn
;
1440 self.xcrate_object_lifetime_defaults
= this
.xcrate_object_lifetime_defaults
;
1443 /// helper method to determine the span to remove when suggesting the
1444 /// deletion of a lifetime
1445 fn lifetime_deletion_span(&self, name
: ast
::Ident
, generics
: &hir
::Generics
) -> Option
<Span
> {
1446 if generics
.params
.len() == 1 {
1447 // if sole lifetime, remove the `<>` brackets
1450 generics
.params
.iter().enumerate().find_map(|(i
, param
)| {
1451 if param
.name
.ident() == name
{
1452 // We also want to delete a leading or trailing comma
1454 if i
>= generics
.params
.len() - 1 {
1455 Some(generics
.params
[i
- 1].span
.shrink_to_hi().to(param
.span
))
1457 Some(param
.span
.to(generics
.params
[i
+ 1].span
.shrink_to_lo()))
1466 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1467 let defined_by
= match self.scope
{
1468 Scope
::Binder { lifetimes, .. }
=> lifetimes
,
1470 debug
!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1475 let mut def_ids
: Vec
<_
> = defined_by
1477 .flat_map(|region
| match region
{
1478 Region
::EarlyBound(_
, def_id
, _
)
1479 | Region
::LateBound(_
, def_id
, _
)
1480 | Region
::Free(_
, def_id
) => Some(*def_id
),
1482 Region
::LateBoundAnon(..) | Region
::Static
=> None
,
1486 // ensure that we issue lints in a repeatable order
1487 def_ids
.sort_by_key(|&def_id
| self.tcx
.def_path_hash(def_id
));
1489 for def_id
in def_ids
{
1491 "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
1495 let lifetimeuseset
= self.lifetime_uses
.remove(&def_id
);
1498 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1502 match lifetimeuseset
{
1503 Some(LifetimeUseSet
::One(lifetime
)) => {
1504 let node_id
= self.tcx
.hir
.as_local_node_id(def_id
).unwrap();
1505 debug
!("node id first={:?}", node_id
);
1506 if let Some((id
, span
, name
)) = match self.tcx
.hir
.get(node_id
) {
1507 Node
::Lifetime(hir_lifetime
) => Some((
1510 hir_lifetime
.name
.ident(),
1512 Node
::GenericParam(param
) => {
1513 Some((param
.id
, param
.span
, param
.name
.ident()))
1517 debug
!("id = {:?} span = {:?} name = {:?}", node_id
, span
, name
);
1518 let mut err
= self.tcx
.struct_span_lint_node(
1519 lint
::builtin
::SINGLE_USE_LIFETIMES
,
1522 &format
!("lifetime parameter `{}` only used once", name
),
1524 err
.span_label(span
, "this lifetime...");
1525 err
.span_label(lifetime
.span
, "...is used only here");
1529 Some(LifetimeUseSet
::Many
) => {
1530 debug
!("Not one use lifetime");
1533 let node_id
= self.tcx
.hir
.as_local_node_id(def_id
).unwrap();
1534 if let Some((id
, span
, name
)) = match self.tcx
.hir
.get(node_id
) {
1535 Node
::Lifetime(hir_lifetime
) => Some((
1538 hir_lifetime
.name
.ident(),
1540 Node
::GenericParam(param
) => {
1541 Some((param
.id
, param
.span
, param
.name
.ident()))
1545 debug
!("id ={:?} span = {:?} name = {:?}", node_id
, span
, name
);
1546 let mut err
= self.tcx
.struct_span_lint_node(
1547 lint
::builtin
::UNUSED_LIFETIMES
,
1550 &format
!("lifetime parameter `{}` never used", name
),
1552 if let Some(parent_def_id
) = self.tcx
.parent(def_id
) {
1553 if let Some(generics
) = self.tcx
.hir
.get_generics(parent_def_id
) {
1554 let unused_lt_span
= self.lifetime_deletion_span(name
, generics
);
1555 if let Some(span
) = unused_lt_span
{
1556 err
.span_suggestion_with_applicability(
1560 Applicability
::MachineApplicable
,
1572 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1574 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1575 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1576 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1580 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1582 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1583 /// lifetimes may be interspersed together.
1585 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1586 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1587 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1588 /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
1589 /// ordering is not important there.
1590 fn visit_early_late
<F
>(
1592 parent_id
: Option
<ast
::NodeId
>,
1593 decl
: &'tcx hir
::FnDecl
,
1594 generics
: &'tcx hir
::Generics
,
1597 F
: for<'b
, 'c
> FnOnce(&'b
mut LifetimeContext
<'c
, 'tcx
>),
1599 insert_late_bound_lifetimes(self.map
, decl
, generics
);
1601 // Find the start of nested early scopes, e.g. in methods.
1603 if let Some(parent_id
) = parent_id
{
1604 let parent
= self.tcx
.hir
.expect_item(parent_id
);
1605 if let hir
::ItemKind
::Trait(..) = parent
.node
{
1606 index
+= 1; // Self comes first.
1609 hir
::ItemKind
::Trait(_
, _
, ref generics
, ..)
1610 | hir
::ItemKind
::Impl(_
, _
, _
, ref generics
, ..) => {
1611 index
+= generics
.params
.len() as u32;
1617 let mut type_count
= 0;
1618 let lifetimes
= generics
1621 .filter_map(|param
| match param
.kind
{
1622 GenericParamKind
::Lifetime { .. }
=> {
1623 if self.map
.late_bound
.contains(¶m
.id
) {
1624 Some(Region
::late(&self.tcx
.hir
, param
))
1626 Some(Region
::early(&self.tcx
.hir
, &mut index
, param
))
1629 GenericParamKind
::Type { .. }
=> {
1635 let next_early_index
= index
+ type_count
;
1637 let scope
= Scope
::Binder
{
1641 abstract_type_parent
: true,
1642 track_lifetime_uses
: false,
1644 self.with(scope
, move |old_scope
, this
| {
1645 this
.check_lifetime_params(old_scope
, &generics
.params
);
1646 this
.hack(walk
); // FIXME(#37666) workaround in place of `walk(this)`
1650 fn next_early_index_helper(&self, only_abstract_type_parent
: bool
) -> u32 {
1651 let mut scope
= self.scope
;
1654 Scope
::Root
=> return 0,
1658 abstract_type_parent
,
1660 } if (!only_abstract_type_parent
|| abstract_type_parent
) =>
1662 return next_early_index
1665 Scope
::Binder { s, .. }
1666 | Scope
::Body { s, .. }
1667 | Scope
::Elision { s, .. }
1668 | Scope
::ObjectLifetimeDefault { s, .. }
=> scope
= s
,
1673 /// Returns the next index one would use for an early-bound-region
1674 /// if extending the current scope.
1675 fn next_early_index(&self) -> u32 {
1676 self.next_early_index_helper(true)
1679 /// Returns the next index one would use for an `impl Trait` that
1680 /// is being converted into an `abstract type`. This will be the
1681 /// next early index from the enclosing item, for the most
1682 /// part. See the `abstract_type_parent` field for more info.
1683 fn next_early_index_for_abstract_type(&self) -> u32 {
1684 self.next_early_index_helper(false)
1687 fn resolve_lifetime_ref(&mut self, lifetime_ref
: &'tcx hir
::Lifetime
) {
1688 debug
!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref
);
1690 // If we've already reported an error, just ignore `lifetime_ref`.
1691 if let LifetimeName
::Error
= lifetime_ref
.name
{
1695 // Walk up the scope chain, tracking the number of fn scopes
1696 // that we pass through, until we find a lifetime with the
1697 // given name or we run out of scopes.
1699 let mut late_depth
= 0;
1700 let mut scope
= self.scope
;
1701 let mut outermost_body
= None
;
1704 Scope
::Body { id, s }
=> {
1705 outermost_body
= Some(id
);
1714 ref lifetimes
, s
, ..
1716 match lifetime_ref
.name
{
1717 LifetimeName
::Param(param_name
) => {
1718 if let Some(&def
) = lifetimes
.get(¶m_name
.modern()) {
1719 break Some(def
.shifted(late_depth
));
1722 _
=> bug
!("expected LifetimeName::Param"),
1729 Scope
::Elision { s, .. }
| Scope
::ObjectLifetimeDefault { s, .. }
=> {
1735 if let Some(mut def
) = result
{
1736 if let Region
::EarlyBound(..) = def
{
1737 // Do not free early-bound regions, only late-bound ones.
1738 } else if let Some(body_id
) = outermost_body
{
1739 let fn_id
= self.tcx
.hir
.body_owner(body_id
);
1740 match self.tcx
.hir
.get(fn_id
) {
1741 Node
::Item(&hir
::Item
{
1742 node
: hir
::ItemKind
::Fn(..),
1745 | Node
::TraitItem(&hir
::TraitItem
{
1746 node
: hir
::TraitItemKind
::Method(..),
1749 | Node
::ImplItem(&hir
::ImplItem
{
1750 node
: hir
::ImplItemKind
::Method(..),
1753 let scope
= self.tcx
.hir
.local_def_id(fn_id
);
1754 def
= Region
::Free(scope
, def
.id().unwrap());
1760 // Check for fn-syntax conflicts with in-band lifetime definitions
1761 if self.is_in_fn_syntax
{
1763 Region
::EarlyBound(_
, _
, LifetimeDefOrigin
::InBand
)
1764 | Region
::LateBound(_
, _
, LifetimeDefOrigin
::InBand
) => {
1769 "lifetimes used in `fn` or `Fn` syntax must be \
1770 explicitly declared using `<...>` binders"
1771 ).span_label(lifetime_ref
.span
, "in-band lifetime definition")
1776 | Region
::EarlyBound(_
, _
, LifetimeDefOrigin
::ExplicitOrElided
)
1777 | Region
::LateBound(_
, _
, LifetimeDefOrigin
::ExplicitOrElided
)
1778 | Region
::EarlyBound(_
, _
, LifetimeDefOrigin
::Error
)
1779 | Region
::LateBound(_
, _
, LifetimeDefOrigin
::Error
)
1780 | Region
::LateBoundAnon(..)
1781 | Region
::Free(..) => {}
1785 self.insert_lifetime(lifetime_ref
, def
);
1791 "use of undeclared lifetime name `{}`",
1793 ).span_label(lifetime_ref
.span
, "undeclared lifetime")
1798 fn visit_segment_args(&mut self, def
: Def
, depth
: usize, generic_args
: &'tcx hir
::GenericArgs
) {
1799 if generic_args
.parenthesized
{
1800 let was_in_fn_syntax
= self.is_in_fn_syntax
;
1801 self.is_in_fn_syntax
= true;
1802 self.visit_fn_like_elision(generic_args
.inputs(), Some(&generic_args
.bindings
[0].ty
));
1803 self.is_in_fn_syntax
= was_in_fn_syntax
;
1807 let mut elide_lifetimes
= true;
1808 let lifetimes
= generic_args
1811 .filter_map(|arg
| match arg
{
1812 hir
::GenericArg
::Lifetime(lt
) => {
1813 if !lt
.is_elided() {
1814 elide_lifetimes
= false;
1821 if elide_lifetimes
{
1822 self.resolve_elided_lifetimes(lifetimes
);
1824 lifetimes
.iter().for_each(|lt
| self.visit_lifetime(lt
));
1827 // Figure out if this is a type/trait segment,
1828 // which requires object lifetime defaults.
1829 let parent_def_id
= |this
: &mut Self, def_id
: DefId
| {
1830 let def_key
= this
.tcx
.def_key(def_id
);
1832 krate
: def_id
.krate
,
1833 index
: def_key
.parent
.expect("missing parent"),
1836 let type_def_id
= match def
{
1837 Def
::AssociatedTy(def_id
) if depth
== 1 => Some(parent_def_id(self, def_id
)),
1838 Def
::Variant(def_id
) if depth
== 0 => Some(parent_def_id(self, def_id
)),
1840 | Def
::Union(def_id
)
1842 | Def
::TyAlias(def_id
)
1843 | Def
::Trait(def_id
) if depth
== 0 =>
1850 let object_lifetime_defaults
= type_def_id
.map_or(vec
![], |def_id
| {
1852 let mut scope
= self.scope
;
1855 Scope
::Root
=> break false,
1857 Scope
::Body { .. }
=> break true,
1859 Scope
::Binder { s, .. }
1860 | Scope
::Elision { s, .. }
1861 | Scope
::ObjectLifetimeDefault { s, .. }
=> {
1868 let map
= &self.map
;
1869 let unsubst
= if let Some(id
) = self.tcx
.hir
.as_local_node_id(def_id
) {
1870 &map
.object_lifetime_defaults
[&id
]
1873 self.xcrate_object_lifetime_defaults
1875 .or_insert_with(|| {
1876 tcx
.generics_of(def_id
)
1879 .filter_map(|param
| match param
.kind
{
1880 GenericParamDefKind
::Type
{
1881 object_lifetime_default
,
1883 } => Some(object_lifetime_default
),
1884 GenericParamDefKind
::Lifetime
=> None
,
1891 .map(|set
| match *set
{
1892 Set1
::Empty
=> if in_body
{
1895 Some(Region
::Static
)
1898 let lifetimes
= generic_args
.args
.iter().filter_map(|arg
| match arg
{
1899 GenericArg
::Lifetime(lt
) => Some(lt
),
1902 r
.subst(lifetimes
, map
)
1910 for arg
in &generic_args
.args
{
1912 GenericArg
::Lifetime(_
) => {}
1913 GenericArg
::Type(ty
) => {
1914 if let Some(<
) = object_lifetime_defaults
.get(i
) {
1915 let scope
= Scope
::ObjectLifetimeDefault
{
1919 self.with(scope
, |_
, this
| this
.visit_ty(ty
));
1928 for b
in &generic_args
.bindings
{
1929 self.visit_assoc_type_binding(b
);
1933 fn visit_fn_like_elision(&mut self, inputs
: &'tcx
[hir
::Ty
], output
: Option
<&'tcx P
<hir
::Ty
>>) {
1934 debug
!("visit_fn_like_elision: enter");
1935 let mut arg_elide
= Elide
::FreshLateAnon(Cell
::new(0));
1936 let arg_scope
= Scope
::Elision
{
1937 elide
: arg_elide
.clone(),
1940 self.with(arg_scope
, |_
, this
| {
1941 for input
in inputs
{
1942 this
.visit_ty(input
);
1945 Scope
::Elision { ref elide, .. }
=> {
1946 arg_elide
= elide
.clone();
1952 let output
= match output
{
1957 debug
!("visit_fn_like_elision: determine output");
1959 // Figure out if there's a body we can get argument names from,
1960 // and whether there's a `self` argument (treated specially).
1961 let mut assoc_item_kind
= None
;
1962 let mut impl_self
= None
;
1963 let parent
= self.tcx
.hir
.get_parent_node(output
.id
);
1964 let body
= match self.tcx
.hir
.get(parent
) {
1965 // `fn` definitions and methods.
1966 Node
::Item(&hir
::Item
{
1967 node
: hir
::ItemKind
::Fn(.., body
),
1971 Node
::TraitItem(&hir
::TraitItem
{
1972 node
: hir
::TraitItemKind
::Method(_
, ref m
),
1975 if let hir
::ItemKind
::Trait(.., ref trait_items
) = self.tcx
1977 .expect_item(self.tcx
.hir
.get_parent(parent
))
1980 assoc_item_kind
= trait_items
1982 .find(|ti
| ti
.id
.node_id
== parent
)
1986 hir
::TraitMethod
::Required(_
) => None
,
1987 hir
::TraitMethod
::Provided(body
) => Some(body
),
1991 Node
::ImplItem(&hir
::ImplItem
{
1992 node
: hir
::ImplItemKind
::Method(_
, body
),
1995 if let hir
::ItemKind
::Impl(.., ref self_ty
, ref impl_items
) = self.tcx
1997 .expect_item(self.tcx
.hir
.get_parent(parent
))
2000 impl_self
= Some(self_ty
);
2001 assoc_item_kind
= impl_items
2003 .find(|ii
| ii
.id
.node_id
== parent
)
2009 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2010 Node
::ForeignItem(_
) | Node
::Ty(_
) | Node
::TraitRef(_
) => None
,
2011 // Everything else (only closures?) doesn't
2012 // actually enjoy elision in return types.
2014 self.visit_ty(output
);
2019 let has_self
= match assoc_item_kind
{
2020 Some(hir
::AssociatedItemKind
::Method { has_self }
) => has_self
,
2024 // In accordance with the rules for lifetime elision, we can determine
2025 // what region to use for elision in the output type in two ways.
2026 // First (determined here), if `self` is by-reference, then the
2027 // implied output region is the region of the self parameter.
2029 // Look for `self: &'a Self` - also desugared from `&'a self`,
2030 // and if that matches, use it for elision and return early.
2031 let is_self_ty
= |def
: Def
| {
2032 if let Def
::SelfTy(..) = def
{
2036 // Can't always rely on literal (or implied) `Self` due
2037 // to the way elision rules were originally specified.
2038 let impl_self
= impl_self
.map(|ty
| &ty
.node
);
2039 if let Some(&hir
::TyKind
::Path(hir
::QPath
::Resolved(None
, ref path
))) = impl_self
{
2041 // Whitelist the types that unambiguously always
2042 // result in the same type constructor being used
2043 // (it can't differ between `Self` and `self`).
2044 Def
::Struct(_
) | Def
::Union(_
) | Def
::Enum(_
) | Def
::PrimTy(_
) => {
2045 return def
== path
.def
2054 if let hir
::TyKind
::Rptr(lifetime_ref
, ref mt
) = inputs
[0].node
{
2055 if let hir
::TyKind
::Path(hir
::QPath
::Resolved(None
, ref path
)) = mt
.ty
.node
{
2056 if is_self_ty(path
.def
) {
2057 if let Some(&lifetime
) = self.map
.defs
.get(&lifetime_ref
.id
) {
2058 let scope
= Scope
::Elision
{
2059 elide
: Elide
::Exact(lifetime
),
2062 self.with(scope
, |_
, this
| this
.visit_ty(output
));
2070 // Second, if there was exactly one lifetime (either a substitution or a
2071 // reference) in the arguments, then any anonymous regions in the output
2072 // have that lifetime.
2073 let mut possible_implied_output_region
= None
;
2074 let mut lifetime_count
= 0;
2075 let arg_lifetimes
= inputs
2078 .skip(has_self
as usize)
2080 let mut gather
= GatherLifetimes
{
2082 outer_index
: ty
::INNERMOST
,
2083 have_bound_regions
: false,
2084 lifetimes
: Default
::default(),
2086 gather
.visit_ty(input
);
2088 lifetime_count
+= gather
.lifetimes
.len();
2090 if lifetime_count
== 1 && gather
.lifetimes
.len() == 1 {
2091 // there's a chance that the unique lifetime of this
2092 // iteration will be the appropriate lifetime for output
2093 // parameters, so lets store it.
2094 possible_implied_output_region
= gather
.lifetimes
.iter().cloned().next();
2097 ElisionFailureInfo
{
2100 lifetime_count
: gather
.lifetimes
.len(),
2101 have_bound_regions
: gather
.have_bound_regions
,
2106 let elide
= if lifetime_count
== 1 {
2107 Elide
::Exact(possible_implied_output_region
.unwrap())
2109 Elide
::Error(arg_lifetimes
)
2112 debug
!("visit_fn_like_elision: elide={:?}", elide
);
2114 let scope
= Scope
::Elision
{
2118 self.with(scope
, |_
, this
| this
.visit_ty(output
));
2119 debug
!("visit_fn_like_elision: exit");
2121 struct GatherLifetimes
<'a
> {
2122 map
: &'a NamedRegionMap
,
2123 outer_index
: ty
::DebruijnIndex
,
2124 have_bound_regions
: bool
,
2125 lifetimes
: FxHashSet
<Region
>,
2128 impl<'v
, 'a
> Visitor
<'v
> for GatherLifetimes
<'a
> {
2129 fn nested_visit_map
<'this
>(&'this
mut self) -> NestedVisitorMap
<'this
, 'v
> {
2130 NestedVisitorMap
::None
2133 fn visit_ty(&mut self, ty
: &hir
::Ty
) {
2134 if let hir
::TyKind
::BareFn(_
) = ty
.node
{
2135 self.outer_index
.shift_in(1);
2137 if let hir
::TyKind
::TraitObject(ref bounds
, ref lifetime
) = ty
.node
{
2138 for bound
in bounds
{
2139 self.visit_poly_trait_ref(bound
, hir
::TraitBoundModifier
::None
);
2142 // Stay on the safe side and don't include the object
2143 // lifetime default (which may not end up being used).
2144 if !lifetime
.is_elided() {
2145 self.visit_lifetime(lifetime
);
2148 intravisit
::walk_ty(self, ty
);
2150 if let hir
::TyKind
::BareFn(_
) = ty
.node
{
2151 self.outer_index
.shift_out(1);
2155 fn visit_generic_param(&mut self, param
: &hir
::GenericParam
) {
2156 if let hir
::GenericParamKind
::Lifetime { .. }
= param
.kind
{
2157 // FIXME(eddyb) Do we want this? It only makes a difference
2158 // if this `for<'a>` lifetime parameter is never used.
2159 self.have_bound_regions
= true;
2162 intravisit
::walk_generic_param(self, param
);
2165 fn visit_poly_trait_ref(
2167 trait_ref
: &hir
::PolyTraitRef
,
2168 modifier
: hir
::TraitBoundModifier
,
2170 self.outer_index
.shift_in(1);
2171 intravisit
::walk_poly_trait_ref(self, trait_ref
, modifier
);
2172 self.outer_index
.shift_out(1);
2175 fn visit_lifetime(&mut self, lifetime_ref
: &hir
::Lifetime
) {
2176 if let Some(&lifetime
) = self.map
.defs
.get(&lifetime_ref
.id
) {
2178 Region
::LateBound(debruijn
, _
, _
) | Region
::LateBoundAnon(debruijn
, _
)
2179 if debruijn
< self.outer_index
=>
2181 self.have_bound_regions
= true;
2185 .insert(lifetime
.shifted_out_to_binder(self.outer_index
));
2193 fn resolve_elided_lifetimes(&mut self, lifetime_refs
: Vec
<&'tcx hir
::Lifetime
>) {
2194 if lifetime_refs
.is_empty() {
2198 let span
= lifetime_refs
[0].span
;
2199 let mut late_depth
= 0;
2200 let mut scope
= self.scope
;
2203 // Do not assign any resolution, it will be inferred.
2204 Scope
::Body { .. }
=> return,
2206 Scope
::Root
=> break None
,
2208 Scope
::Binder { s, .. }
=> {
2213 Scope
::Elision { ref elide, .. }
=> {
2214 let lifetime
= match *elide
{
2215 Elide
::FreshLateAnon(ref counter
) => {
2216 for lifetime_ref
in lifetime_refs
{
2217 let lifetime
= Region
::late_anon(counter
).shifted(late_depth
);
2218 self.insert_lifetime(lifetime_ref
, lifetime
);
2222 Elide
::Exact(l
) => l
.shifted(late_depth
),
2223 Elide
::Error(ref e
) => break Some(e
),
2225 for lifetime_ref
in lifetime_refs
{
2226 self.insert_lifetime(lifetime_ref
, lifetime
);
2231 Scope
::ObjectLifetimeDefault { s, .. }
=> {
2237 let mut err
= report_missing_lifetime_specifiers(self.tcx
.sess
, span
, lifetime_refs
.len());
2238 let mut add_label
= true;
2240 if let Some(params
) = error
{
2241 if lifetime_refs
.len() == 1 {
2242 add_label
= add_label
&& self.report_elision_failure(&mut err
, params
, span
);
2246 add_missing_lifetime_specifiers_label(&mut err
, span
, lifetime_refs
.len());
2252 fn suggest_lifetime(&self, db
: &mut DiagnosticBuilder
<'_
>, span
: Span
, msg
: &str) -> bool
{
2253 match self.tcx
.sess
.source_map().span_to_snippet(span
) {
2254 Ok(ref snippet
) => {
2255 let (sugg
, applicability
) = if snippet
== "&" {
2256 ("&'static ".to_owned(), Applicability
::MachineApplicable
)
2257 } else if snippet
== "'_" {
2258 ("'static".to_owned(), Applicability
::MachineApplicable
)
2260 (format
!("{} + 'static", snippet
), Applicability
::MaybeIncorrect
)
2262 db
.span_suggestion_with_applicability(span
, msg
, sugg
, applicability
);
2272 fn report_elision_failure(
2274 db
: &mut DiagnosticBuilder
<'_
>,
2275 params
: &[ElisionFailureInfo
],
2278 let mut m
= String
::new();
2279 let len
= params
.len();
2281 let elided_params
: Vec
<_
> = params
2284 .filter(|info
| info
.lifetime_count
> 0)
2287 let elided_len
= elided_params
.len();
2289 for (i
, info
) in elided_params
.into_iter().enumerate() {
2290 let ElisionFailureInfo
{
2297 let help_name
= if let Some(body
) = parent
{
2298 let arg
= &self.tcx
.hir
.body(body
).arguments
[index
];
2299 format
!("`{}`", self.tcx
.hir
.node_to_pretty_string(arg
.pat
.id
))
2301 format
!("argument {}", index
+ 1)
2309 "one of {}'s {} {}lifetimes",
2312 if have_bound_regions { "free " }
else { "" }
2317 if elided_len
== 2 && i
== 0 {
2319 } else if i
+ 2 == elided_len
{
2320 m
.push_str(", or ");
2321 } else if i
!= elided_len
- 1 {
2329 "this function's return type contains a borrowed value, but \
2330 there is no value for it to be borrowed from"
2332 self.suggest_lifetime(db
, span
, "consider giving it a 'static lifetime")
2333 } else if elided_len
== 0 {
2336 "this function's return type contains a borrowed value with \
2337 an elided lifetime, but the lifetime cannot be derived from \
2340 let msg
= "consider giving it an explicit bounded or 'static lifetime";
2341 self.suggest_lifetime(db
, span
, msg
)
2342 } else if elided_len
== 1 {
2345 "this function's return type contains a borrowed value, but \
2346 the signature does not say which {} it is borrowed from",
2353 "this function's return type contains a borrowed value, but \
2354 the signature does not say whether it is borrowed from {}",
2361 fn resolve_object_lifetime_default(&mut self, lifetime_ref
: &'tcx hir
::Lifetime
) {
2362 let mut late_depth
= 0;
2363 let mut scope
= self.scope
;
2364 let lifetime
= loop {
2366 Scope
::Binder { s, .. }
=> {
2371 Scope
::Root
| Scope
::Elision { .. }
=> break Region
::Static
,
2373 Scope
::Body { .. }
| Scope
::ObjectLifetimeDefault { lifetime: None, .. }
=> return,
2375 Scope
::ObjectLifetimeDefault
{
2376 lifetime
: Some(l
), ..
2380 self.insert_lifetime(lifetime_ref
, lifetime
.shifted(late_depth
));
2383 fn check_lifetime_params(
2385 old_scope
: ScopeRef
<'_
>,
2386 params
: &'tcx
[hir
::GenericParam
],
2388 let lifetimes
: Vec
<_
> = params
2390 .filter_map(|param
| match param
.kind
{
2391 GenericParamKind
::Lifetime { .. }
=> Some((param
, param
.name
)),
2395 for (i
, (lifetime_i
, lifetime_i_name
)) in lifetimes
.iter().enumerate() {
2396 if let hir
::ParamName
::Plain(_
) = lifetime_i_name
{
2397 let name
= lifetime_i_name
.ident().name
;
2398 if name
== keywords
::UnderscoreLifetime
.name()
2399 || name
== keywords
::StaticLifetime
.name()
2401 let mut err
= struct_span_err
!(
2405 "invalid lifetime parameter name: `{}`",
2406 lifetime_i
.name
.ident(),
2410 format
!("{} is a reserved lifetime name", name
),
2416 // It is a hard error to shadow a lifetime within the same scope.
2417 for (lifetime_j
, lifetime_j_name
) in lifetimes
.iter().skip(i
+ 1) {
2418 if lifetime_i_name
== lifetime_j_name
{
2423 "lifetime name `{}` declared twice in the same scope",
2424 lifetime_j
.name
.ident()
2425 ).span_label(lifetime_j
.span
, "declared twice")
2426 .span_label(lifetime_i
.span
, "previous declaration here")
2431 // It is a soft error to shadow a lifetime within a parent scope.
2432 self.check_lifetime_param_for_shadowing(old_scope
, &lifetime_i
);
2434 for bound
in &lifetime_i
.bounds
{
2436 hir
::GenericBound
::Outlives(lt
) => match lt
.name
{
2437 hir
::LifetimeName
::Underscore
=> self.tcx
.sess
.delay_span_bug(
2439 "use of `'_` in illegal place, but not caught by lowering",
2441 hir
::LifetimeName
::Static
=> {
2442 self.insert_lifetime(lt
, Region
::Static
);
2446 lifetime_i
.span
.to(lt
.span
),
2448 "unnecessary lifetime parameter `{}`",
2449 lifetime_i
.name
.ident(),
2453 "you can use the `'static` lifetime directly, in place of `{}`",
2454 lifetime_i
.name
.ident(),
2458 hir
::LifetimeName
::Param(_
) | hir
::LifetimeName
::Implicit
=> {
2459 self.resolve_lifetime_ref(lt
);
2461 hir
::LifetimeName
::Error
=> {
2462 // No need to do anything, error already reported.
2471 fn check_lifetime_param_for_shadowing(
2473 mut old_scope
: ScopeRef
<'_
>,
2474 param
: &'tcx hir
::GenericParam
,
2476 for label
in &self.labels_in_fn
{
2477 // FIXME (#24278): non-hygienic comparison
2478 if param
.name
.ident().name
== label
.name
{
2479 signal_shadowing_problem(
2482 original_label(label
.span
),
2483 shadower_lifetime(¶m
),
2491 Scope
::Body { s, .. }
2492 | Scope
::Elision { s, .. }
2493 | Scope
::ObjectLifetimeDefault { s, .. }
=> {
2502 ref lifetimes
, s
, ..
2504 if let Some(&def
) = lifetimes
.get(¶m
.name
.modern()) {
2505 let node_id
= self.tcx
.hir
.as_local_node_id(def
.id().unwrap()).unwrap();
2507 signal_shadowing_problem(
2509 param
.name
.ident().name
,
2510 original_lifetime(self.tcx
.hir
.span(node_id
)),
2511 shadower_lifetime(¶m
),
2522 /// Returns true if, in the current scope, replacing `'_` would be
2523 /// equivalent to a single-use lifetime.
2524 fn track_lifetime_uses(&self) -> bool
{
2525 let mut scope
= self.scope
;
2528 Scope
::Root
=> break false,
2530 // Inside of items, it depends on the kind of item.
2532 track_lifetime_uses
,
2534 } => break track_lifetime_uses
,
2536 // Inside a body, `'_` will use an inference variable,
2538 Scope
::Body { .. }
=> break true,
2540 // A lifetime only used in a fn argument could as well
2541 // be replaced with `'_`, as that would generate a
2544 elide
: Elide
::FreshLateAnon(_
),
2548 // In the return type or other such place, `'_` is not
2549 // going to make a fresh name, so we cannot
2550 // necessarily replace a single-use lifetime with
2553 elide
: Elide
::Exact(_
),
2557 elide
: Elide
::Error(_
),
2561 Scope
::ObjectLifetimeDefault { s, .. }
=> scope
= s
,
2566 fn insert_lifetime(&mut self, lifetime_ref
: &'tcx hir
::Lifetime
, def
: Region
) {
2567 if lifetime_ref
.id
== ast
::DUMMY_NODE_ID
{
2570 "lifetime reference not renumbered, \
2571 probably a bug in syntax::fold"
2576 "insert_lifetime: {} resolved to {:?} span={:?}",
2577 self.tcx
.hir
.node_to_string(lifetime_ref
.id
),
2579 self.tcx
.sess
.source_map().span_to_string(lifetime_ref
.span
)
2581 self.map
.defs
.insert(lifetime_ref
.id
, def
);
2584 Region
::LateBoundAnon(..) | Region
::Static
=> {
2585 // These are anonymous lifetimes or lifetimes that are not declared.
2588 Region
::Free(_
, def_id
)
2589 | Region
::LateBound(_
, def_id
, _
)
2590 | Region
::EarlyBound(_
, def_id
, _
) => {
2591 // A lifetime declared by the user.
2592 let track_lifetime_uses
= self.track_lifetime_uses();
2594 "insert_lifetime: track_lifetime_uses={}",
2597 if track_lifetime_uses
&& !self.lifetime_uses
.contains_key(&def_id
) {
2598 debug
!("insert_lifetime: first use of {:?}", def_id
);
2600 .insert(def_id
, LifetimeUseSet
::One(lifetime_ref
));
2602 debug
!("insert_lifetime: many uses of {:?}", def_id
);
2603 self.lifetime_uses
.insert(def_id
, LifetimeUseSet
::Many
);
2609 /// Sometimes we resolve a lifetime, but later find that it is an
2610 /// error (esp. around impl trait). In that case, we remove the
2611 /// entry into `map.defs` so as not to confuse later code.
2612 fn uninsert_lifetime_on_error(&mut self, lifetime_ref
: &'tcx hir
::Lifetime
, bad_def
: Region
) {
2613 let old_value
= self.map
.defs
.remove(&lifetime_ref
.id
);
2614 assert_eq
!(old_value
, Some(bad_def
));
2618 /// Detects late-bound lifetimes and inserts them into
2619 /// `map.late_bound`.
2621 /// A region declared on a fn is **late-bound** if:
2622 /// - it is constrained by an argument type;
2623 /// - it does not appear in a where-clause.
2625 /// "Constrained" basically means that it appears in any type but
2626 /// not amongst the inputs to a projection. In other words, `<&'a
2627 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2628 fn insert_late_bound_lifetimes(
2629 map
: &mut NamedRegionMap
,
2631 generics
: &hir
::Generics
,
2634 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2638 let mut constrained_by_input
= ConstrainedCollector
::default();
2639 for arg_ty
in &decl
.inputs
{
2640 constrained_by_input
.visit_ty(arg_ty
);
2643 let mut appears_in_output
= AllCollector
{
2644 regions
: Default
::default(),
2646 intravisit
::walk_fn_ret_ty(&mut appears_in_output
, &decl
.output
);
2649 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2650 constrained_by_input
.regions
2653 // Walk the lifetimes that appear in where clauses.
2655 // Subtle point: because we disallow nested bindings, we can just
2656 // ignore binders here and scrape up all names we see.
2657 let mut appears_in_where_clause
= AllCollector
{
2658 regions
: Default
::default(),
2660 appears_in_where_clause
.visit_generics(generics
);
2662 for param
in &generics
.params
{
2663 if let hir
::GenericParamKind
::Lifetime { .. }
= param
.kind
{
2664 if !param
.bounds
.is_empty() {
2665 // `'a: 'b` means both `'a` and `'b` are referenced
2666 appears_in_where_clause
2668 .insert(hir
::LifetimeName
::Param(param
.name
.modern()));
2674 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2675 appears_in_where_clause
.regions
2678 // Late bound regions are those that:
2679 // - appear in the inputs
2680 // - do not appear in the where-clauses
2681 // - are not implicitly captured by `impl Trait`
2682 for param
in &generics
.params
{
2684 hir
::GenericParamKind
::Lifetime { .. }
=> { /* fall through */ }
2686 // Types are not late-bound.
2687 hir
::GenericParamKind
::Type { .. }
=> continue,
2690 let lt_name
= hir
::LifetimeName
::Param(param
.name
.modern());
2691 // appears in the where clauses? early-bound.
2692 if appears_in_where_clause
.regions
.contains(<_name
) {
2696 // does not appear in the inputs, but appears in the return type? early-bound.
2697 if !constrained_by_input
.regions
.contains(<_name
)
2698 && appears_in_output
.regions
.contains(<_name
)
2704 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2709 let inserted
= map
.late_bound
.insert(param
.id
);
2710 assert
!(inserted
, "visited lifetime {:?} twice", param
.id
);
2716 struct ConstrainedCollector
{
2717 regions
: FxHashSet
<hir
::LifetimeName
>,
2720 impl<'v
> Visitor
<'v
> for ConstrainedCollector
{
2721 fn nested_visit_map
<'this
>(&'this
mut self) -> NestedVisitorMap
<'this
, 'v
> {
2722 NestedVisitorMap
::None
2725 fn visit_ty(&mut self, ty
: &'v hir
::Ty
) {
2727 hir
::TyKind
::Path(hir
::QPath
::Resolved(Some(_
), _
))
2728 | hir
::TyKind
::Path(hir
::QPath
::TypeRelative(..)) => {
2729 // ignore lifetimes appearing in associated type
2730 // projections, as they are not *constrained*
2734 hir
::TyKind
::Path(hir
::QPath
::Resolved(None
, ref path
)) => {
2735 // consider only the lifetimes on the final
2736 // segment; I am not sure it's even currently
2737 // valid to have them elsewhere, but even if it
2738 // is, those would be potentially inputs to
2740 if let Some(last_segment
) = path
.segments
.last() {
2741 self.visit_path_segment(path
.span
, last_segment
);
2746 intravisit
::walk_ty(self, ty
);
2751 fn visit_lifetime(&mut self, lifetime_ref
: &'v hir
::Lifetime
) {
2752 self.regions
.insert(lifetime_ref
.name
.modern());
2756 struct AllCollector
{
2757 regions
: FxHashSet
<hir
::LifetimeName
>,
2760 impl<'v
> Visitor
<'v
> for AllCollector
{
2761 fn nested_visit_map
<'this
>(&'this
mut self) -> NestedVisitorMap
<'this
, 'v
> {
2762 NestedVisitorMap
::None
2765 fn visit_lifetime(&mut self, lifetime_ref
: &'v hir
::Lifetime
) {
2766 self.regions
.insert(lifetime_ref
.name
.modern());
2771 fn report_missing_lifetime_specifiers(
2775 ) -> DiagnosticBuilder
<'_
> {
2780 "missing lifetime specifier{}",
2781 if count
> 1 { "s" }
else { "" }
2785 fn add_missing_lifetime_specifiers_label(
2786 err
: &mut DiagnosticBuilder
<'_
>,
2791 err
.span_label(span
, format
!("expected {} lifetime parameters", count
));
2793 err
.span_label(span
, "expected lifetime parameter");