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.
20 use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
22 use ty::{self, TyCtxt};
25 use std::mem::replace;
31 use errors::DiagnosticBuilder;
32 use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet};
36 use hir::{self, GenericParamsExt};
37 use hir::intravisit::{self, NestedVisitorMap, Visitor};
39 /// The origin of a named lifetime definition.
41 /// This is used to prevent the usage of in-band lifetimes in `Fn`/`fn` syntax.
42 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
43 pub enum LifetimeDefOrigin {
44 // Explicit binders like `fn foo<'a>(x: &'a u8)`
46 // In-band declarations like `fn foo(x: &'a u8)`
50 impl LifetimeDefOrigin {
51 fn from_is_in_band(is_in_band: bool) -> Self {
53 LifetimeDefOrigin::InBand
55 LifetimeDefOrigin::Explicit
60 // This counts the no of times a lifetime is used
61 #[derive(Clone, Copy, Debug)]
62 pub enum LifetimeUseSet<'tcx> {
63 One(&'tcx hir::Lifetime),
67 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
72 /* lifetime decl */ DefId,
77 /* lifetime decl */ DefId,
80 LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
81 Free(DefId, /* lifetime decl */ DefId),
88 def: &hir::LifetimeDef,
89 ) -> (hir::LifetimeName, Region) {
92 let def_id = hir_map.local_def_id(def.lifetime.id);
93 let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
94 debug!("Region::early: index={} def_id={:?}", i, def_id);
95 (def.lifetime.name, Region::EarlyBound(i, def_id, origin))
98 fn late(hir_map: &Map, def: &hir::LifetimeDef) -> (hir::LifetimeName, Region) {
99 let depth = ty::DebruijnIndex::new(1);
100 let def_id = hir_map.local_def_id(def.lifetime.id);
101 let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
102 (def.lifetime.name, Region::LateBound(depth, def_id, origin))
105 fn late_anon(index: &Cell<u32>) -> Region {
108 let depth = ty::DebruijnIndex::new(1);
109 Region::LateBoundAnon(depth, i)
112 fn id(&self) -> Option<DefId> {
114 Region::Static | Region::LateBoundAnon(..) => None,
116 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
122 fn shifted(self, amount: u32) -> Region {
124 Region::LateBound(depth, id, origin) => {
125 Region::LateBound(depth.shifted(amount), id, origin)
127 Region::LateBoundAnon(depth, index) => {
128 Region::LateBoundAnon(depth.shifted(amount), index)
134 fn from_depth(self, depth: u32) -> Region {
136 Region::LateBound(debruijn, id, origin) => Region::LateBound(
138 depth: debruijn.depth - (depth - 1),
143 Region::LateBoundAnon(debruijn, index) => Region::LateBoundAnon(
145 depth: debruijn.depth - (depth - 1),
153 fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap) -> Option<Region> {
154 if let Region::EarlyBound(index, _, _) = self {
157 .and_then(|lifetime| map.defs.get(&lifetime.id).cloned())
164 /// A set containing, at most, one known element.
165 /// If two distinct values are inserted into a set, then it
166 /// becomes `Many`, which can be used to detect ambiguities.
167 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
174 impl<T: PartialEq> Set1<T> {
175 pub fn insert(&mut self, value: T) {
176 if let Set1::Empty = *self {
177 *self = Set1::One(value);
180 if let Set1::One(ref old) = *self {
189 pub type ObjectLifetimeDefault = Set1<Region>;
191 /// Maps the id of each lifetime reference to the lifetime decl
192 /// that it corresponds to.
194 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
195 /// actual use. It has the same data, but indexed by `DefIndex`. This
198 struct NamedRegionMap {
199 // maps from every use of a named (not anonymous) lifetime to a
200 // `Region` describing how that region is bound
201 pub defs: NodeMap<Region>,
203 // the set of lifetime def ids that are late-bound; a region can
204 // be late-bound if (a) it does NOT appear in a where-clause and
205 // (b) it DOES appear in the arguments.
206 pub late_bound: NodeSet,
208 // For each type and trait definition, maps type parameters
209 // to the trait object lifetime defaults computed from them.
210 pub object_lifetime_defaults: NodeMap<Vec<ObjectLifetimeDefault>>,
213 /// See `NamedRegionMap`.
214 pub struct ResolveLifetimes {
215 defs: FxHashMap<LocalDefId, Rc<FxHashMap<ItemLocalId, Region>>>,
216 late_bound: FxHashMap<LocalDefId, Rc<FxHashSet<ItemLocalId>>>,
217 object_lifetime_defaults:
218 FxHashMap<LocalDefId, Rc<FxHashMap<ItemLocalId, Rc<Vec<ObjectLifetimeDefault>>>>>,
221 impl_stable_hash_for!(struct ::middle::resolve_lifetime::ResolveLifetimes {
224 object_lifetime_defaults
227 struct LifetimeContext<'a, 'tcx: 'a> {
228 tcx: TyCtxt<'a, 'tcx, 'tcx>,
229 map: &'a mut NamedRegionMap,
231 // Deep breath. Our representation for poly trait refs contains a single
232 // binder and thus we only allow a single level of quantification. However,
233 // the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
234 // and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
235 // correct when representing these constraints, we should only introduce one
236 // scope. However, we want to support both locations for the quantifier and
237 // during lifetime resolution we want precise information (so we can't
238 // desugar in an earlier phase).
240 // SO, if we encounter a quantifier at the outer scope, we set
241 // trait_ref_hack to true (and introduce a scope), and then if we encounter
242 // a quantifier at the inner scope, we error. If trait_ref_hack is false,
243 // then we introduce the scope at the inner quantifier.
246 trait_ref_hack: bool,
248 // Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
249 is_in_fn_syntax: bool,
251 // List of labels in the function/method currently under analysis.
252 labels_in_fn: Vec<(ast::Name, Span)>,
254 // Cache for cross-crate per-definition object lifetime defaults.
255 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
257 lifetime_uses: DefIdMap<LifetimeUseSet<'tcx>>,
262 /// Declares lifetimes, and each can be early-bound or late-bound.
263 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
264 /// it should be shifted by the number of `Binder`s in between the
265 /// declaration `Binder` and the location it's referenced from.
267 lifetimes: FxHashMap<hir::LifetimeName, Region>,
269 /// if we extend this scope with another scope, what is the next index
270 /// we should use for an early-bound region?
271 next_early_index: u32,
273 /// Whether or not this binder would serve as the parent
274 /// binder for abstract types introduced within. For example:
276 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
278 /// Here, the abstract types we create for the `impl Trait`
279 /// and `impl Trait2` references will both have the `foo` item
280 /// as their parent. When we get to `impl Trait2`, we find
281 /// that it is nested within the `for<>` binder -- this flag
282 /// allows us to skip that when looking for the parent binder
283 /// of the resulting abstract type.
284 abstract_type_parent: bool,
289 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
290 /// if this is a fn body, otherwise the original definitions are used.
291 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
292 /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
298 /// A scope which either determines unspecified lifetimes or errors
299 /// on them (e.g. due to ambiguity). For more details, see `Elide`.
305 /// Use a specific lifetime (if `Some`) or leave it unset (to be
306 /// inferred in a function body or potentially error outside one),
307 /// for the default choice of lifetime in a trait object type.
308 ObjectLifetimeDefault {
309 lifetime: Option<Region>,
316 #[derive(Clone, Debug)]
318 /// Use a fresh anonymous late-bound lifetime each time, by
319 /// incrementing the counter to generate sequential indices.
320 FreshLateAnon(Cell<u32>),
321 /// Always use this one lifetime.
323 /// Less or more than one lifetime were found, error on unspecified.
324 Error(Vec<ElisionFailureInfo>),
327 #[derive(Clone, Debug)]
328 struct ElisionFailureInfo {
329 /// Where we can find the argument pattern.
330 parent: Option<hir::BodyId>,
331 /// The index of the argument in the original definition.
333 lifetime_count: usize,
334 have_bound_regions: bool,
337 type ScopeRef<'a> = &'a Scope<'a>;
339 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
341 pub fn provide(providers: &mut ty::maps::Providers) {
342 *providers = ty::maps::Providers {
345 named_region_map: |tcx, id| {
346 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
347 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id).cloned()
350 is_late_bound_map: |tcx, id| {
351 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
352 tcx.resolve_lifetimes(LOCAL_CRATE)
358 object_lifetime_defaults_map: |tcx, id| {
359 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
360 tcx.resolve_lifetimes(LOCAL_CRATE)
361 .object_lifetime_defaults
369 // (*) FIXME the query should be defined to take a LocalDefId
372 /// Computes the `ResolveLifetimes` map that contains data for the
373 /// entire crate. You should not read the result of this query
374 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
376 fn resolve_lifetimes<'tcx>(
377 tcx: TyCtxt<'_, 'tcx, 'tcx>,
379 ) -> Rc<ResolveLifetimes> {
380 assert_eq!(for_krate, LOCAL_CRATE);
382 let named_region_map = krate(tcx);
384 let mut defs = FxHashMap();
385 for (k, v) in named_region_map.defs {
386 let hir_id = tcx.hir.node_to_hir_id(k);
387 let map = defs.entry(hir_id.owner_local_def_id())
388 .or_insert_with(|| Rc::new(FxHashMap()));
389 Rc::get_mut(map).unwrap().insert(hir_id.local_id, v);
391 let mut late_bound = FxHashMap();
392 for k in named_region_map.late_bound {
393 let hir_id = tcx.hir.node_to_hir_id(k);
395 .entry(hir_id.owner_local_def_id())
396 .or_insert_with(|| Rc::new(FxHashSet()));
397 Rc::get_mut(map).unwrap().insert(hir_id.local_id);
399 let mut object_lifetime_defaults = FxHashMap();
400 for (k, v) in named_region_map.object_lifetime_defaults {
401 let hir_id = tcx.hir.node_to_hir_id(k);
402 let map = object_lifetime_defaults
403 .entry(hir_id.owner_local_def_id())
404 .or_insert_with(|| Rc::new(FxHashMap()));
407 .insert(hir_id.local_id, Rc::new(v));
410 Rc::new(ResolveLifetimes {
413 object_lifetime_defaults,
417 fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> NamedRegionMap {
418 let krate = tcx.hir.krate();
419 let mut map = NamedRegionMap {
421 late_bound: NodeSet(),
422 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
425 let mut visitor = LifetimeContext {
429 trait_ref_hack: false,
430 is_in_fn_syntax: false,
431 labels_in_fn: vec![],
432 xcrate_object_lifetime_defaults: DefIdMap(),
433 lifetime_uses: DefIdMap(),
435 for (_, item) in &krate.items {
436 visitor.visit_item(item);
442 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
443 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
444 NestedVisitorMap::All(&self.tcx.hir)
447 // We want to nest trait/impl items in their parent, but nothing else.
448 fn visit_nested_item(&mut self, _: hir::ItemId) {}
450 fn visit_nested_body(&mut self, body: hir::BodyId) {
451 // Each body has their own set of labels, save labels.
452 let saved = replace(&mut self.labels_in_fn, vec![]);
453 let body = self.tcx.hir.body(body);
454 extract_labels(self, body);
461 this.visit_body(body);
464 replace(&mut self.labels_in_fn, saved);
467 fn visit_item(&mut self, item: &'tcx hir::Item) {
469 hir::ItemFn(ref decl, _, _, _, ref generics, _) => {
470 self.visit_early_late(None,
474 intravisit::walk_item(this, item);
478 hir::ItemExternCrate(_)
481 | hir::ItemForeignMod(..)
482 | hir::ItemGlobalAsm(..) => {
483 // These sorts of items have no lifetime parameters at all.
484 intravisit::walk_item(self, item);
486 hir::ItemStatic(..) | hir::ItemConst(..) => {
487 // No lifetime parameters, but implied 'static.
488 let scope = Scope::Elision {
489 elide: Elide::Exact(Region::Static),
492 self.with(scope, |_, this| intravisit::walk_item(this, item));
494 hir::ItemTy(_, ref generics)
495 | hir::ItemEnum(_, ref generics)
496 | hir::ItemStruct(_, ref generics)
497 | hir::ItemUnion(_, ref generics)
498 | hir::ItemTrait(_, _, ref generics, ..)
499 | hir::ItemTraitAlias(ref generics, ..)
500 | hir::ItemImpl(_, _, _, ref generics, ..) => {
501 // These kinds of items have only early bound lifetime parameters.
502 let mut index = if let hir::ItemTrait(..) = item.node {
503 1 // Self comes before lifetimes
507 let lifetimes = generics.lifetimes()
508 .map(|def| Region::early(&self.tcx.hir, &mut index, def))
510 let next_early_index = index + generics.ty_params().count() as u32;
511 let scope = Scope::Binder {
514 abstract_type_parent: true,
517 self.with(scope, |old_scope, this| {
518 this.check_lifetime_params(old_scope, &generics.params);
519 intravisit::walk_item(this, item);
525 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
527 hir::ForeignItemFn(ref decl, _, ref generics) => {
528 self.visit_early_late(None,
532 intravisit::walk_foreign_item(this, item);
535 hir::ForeignItemStatic(..) => {
536 intravisit::walk_foreign_item(self, item);
538 hir::ForeignItemType => {
539 intravisit::walk_foreign_item(self, item);
544 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
545 debug!("visit_ty: ty={:?}", ty);
547 hir::TyBareFn(ref c) => {
548 let next_early_index = self.next_early_index();
549 let was_in_fn_syntax = self.is_in_fn_syntax;
550 self.is_in_fn_syntax = true;
551 let scope = Scope::Binder {
552 lifetimes: c.generic_params
554 .map(|def| Region::late(&self.tcx.hir, def))
558 abstract_type_parent: false,
560 self.with(scope, |old_scope, this| {
561 // a bare fn has no bounds, so everything
562 // contained within is scoped within its binder.
563 this.check_lifetime_params(old_scope, &c.generic_params);
564 intravisit::walk_ty(this, ty);
566 self.is_in_fn_syntax = was_in_fn_syntax;
568 hir::TyTraitObject(ref bounds, ref lifetime) => {
569 for bound in bounds {
570 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
572 if lifetime.is_elided() {
573 self.resolve_object_lifetime_default(lifetime)
575 self.visit_lifetime(lifetime);
578 hir::TyRptr(ref lifetime_ref, ref mt) => {
579 self.visit_lifetime(lifetime_ref);
580 let scope = Scope::ObjectLifetimeDefault {
581 lifetime: self.map.defs.get(&lifetime_ref.id).cloned(),
584 self.with(scope, |_, this| this.visit_ty(&mt.ty));
586 hir::TyImplTraitExistential(ref exist_ty, ref lifetimes) => {
587 // Resolve the lifetimes that are applied to the existential type.
588 // These are resolved in the current scope.
589 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
590 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
591 // ^ ^this gets resolved in the current scope
592 for lifetime in lifetimes {
593 self.visit_lifetime(lifetime);
595 // Check for predicates like `impl for<'a> SomeTrait<impl OtherTrait<'a>>`
596 // and ban them. Type variables instantiated inside binders aren't
597 // well-supported at the moment, so this doesn't work.
598 // In the future, this should be fixed and this error should be removed.
599 let def = self.map.defs.get(&lifetime.id);
600 if let Some(&Region::LateBound(_, def_id, _)) = def {
601 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
602 // Ensure that the parent of the def is an item, not HRTB
603 let parent_id = self.tcx.hir.get_parent_node(node_id);
604 let parent_impl_id = hir::ImplItemId { node_id: parent_id };
605 let parent_trait_id = hir::TraitItemId { node_id: parent_id };
606 let krate = self.tcx.hir.forest.krate();
607 if !(krate.items.contains_key(&parent_id)
608 || krate.impl_items.contains_key(&parent_impl_id)
609 || krate.trait_items.contains_key(&parent_trait_id))
615 "`impl Trait` can only capture lifetimes \
616 bound at the fn or impl level"
623 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
624 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
625 // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
626 // ^ ^ this gets resolved in the scope of
627 // the exist_ty generics
633 // We want to start our early-bound indices at the end of the parent scope,
634 // not including any parent `impl Trait`s.
635 let mut index = self.next_early_index_for_abstract_type();
636 debug!("visit_ty: index = {}", index);
638 let mut elision = None;
639 let mut lifetimes = FxHashMap();
640 for lt_def in generics.lifetimes() {
641 let (lt_name, region) = Region::early(&self.tcx.hir, &mut index, <_def);
642 if let hir::LifetimeName::Underscore = lt_name {
643 // Pick the elided lifetime "definition" if one exists and use it to make an
645 elision = Some(region);
647 lifetimes.insert(lt_name, region);
651 let next_early_index = index + generics.ty_params().count() as u32;
653 if let Some(elision_region) = elision {
654 let scope = Scope::Elision {
655 elide: Elide::Exact(elision_region),
658 self.with(scope, |_old_scope, this| {
659 let scope = Scope::Binder {
663 abstract_type_parent: false,
665 this.with(scope, |_old_scope, this| {
666 this.visit_generics(generics);
667 for bound in bounds {
668 this.visit_ty_param_bound(bound);
673 let scope = Scope::Binder {
677 abstract_type_parent: false,
679 self.with(scope, |_old_scope, this| {
680 this.visit_generics(generics);
681 for bound in bounds {
682 this.visit_ty_param_bound(bound);
687 _ => intravisit::walk_ty(self, ty),
691 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
692 use self::hir::TraitItemKind::*;
693 match trait_item.node {
694 Method(ref sig, _) => {
696 self.visit_early_late(
697 Some(tcx.hir.get_parent(trait_item.id)),
699 &trait_item.generics,
700 |this| intravisit::walk_trait_item(this, trait_item),
703 Type(ref bounds, ref ty) => {
704 let generics = &trait_item.generics;
705 let mut index = self.next_early_index();
706 debug!("visit_ty: index = {}", index);
707 let lifetimes = generics.lifetimes()
708 .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def))
711 let next_early_index = index + generics.ty_params().count() as u32;
712 let scope = Scope::Binder {
716 abstract_type_parent: true,
718 self.with(scope, |_old_scope, this| {
719 this.visit_generics(generics);
720 for bound in bounds {
721 this.visit_ty_param_bound(bound);
723 if let Some(ty) = ty {
729 // Only methods and types support generics.
730 assert!(trait_item.generics.params.is_empty());
731 intravisit::walk_trait_item(self, trait_item);
736 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
737 use self::hir::ImplItemKind::*;
738 match impl_item.node {
739 Method(ref sig, _) => {
741 self.visit_early_late(
742 Some(tcx.hir.get_parent(impl_item.id)),
745 |this| intravisit::walk_impl_item(this, impl_item),
749 let generics = &impl_item.generics;
750 let mut index = self.next_early_index();
751 debug!("visit_ty: index = {}", index);
752 let lifetimes = generics.lifetimes()
753 .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def))
756 let next_early_index = index + generics.ty_params().count() as u32;
757 let scope = Scope::Binder {
761 abstract_type_parent: true,
763 self.with(scope, |_old_scope, this| {
764 this.visit_generics(generics);
769 // Only methods and types support generics.
770 assert!(impl_item.generics.params.is_empty());
771 intravisit::walk_impl_item(self, impl_item);
776 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
777 if lifetime_ref.is_elided() {
778 self.resolve_elided_lifetimes(slice::from_ref(lifetime_ref), false);
781 if lifetime_ref.is_static() {
782 self.insert_lifetime(lifetime_ref, Region::Static);
785 self.resolve_lifetime_ref(lifetime_ref);
788 fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) {
789 for (i, segment) in path.segments.iter().enumerate() {
790 let depth = path.segments.len() - i - 1;
791 if let Some(ref parameters) = segment.parameters {
792 self.visit_segment_parameters(path.def, depth, parameters);
797 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
798 let output = match fd.output {
799 hir::DefaultReturn(_) => None,
800 hir::Return(ref ty) => Some(ty),
802 self.visit_fn_like_elision(&fd.inputs, output);
805 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
806 check_mixed_explicit_and_in_band_defs(
808 &generics.lifetimes().cloned().collect::<Vec<_>>()
810 for ty_param in generics.ty_params() {
811 walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
812 if let Some(ref ty) = ty_param.default {
816 for predicate in &generics.where_clause.predicates {
818 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
821 ref bound_generic_params,
824 if bound_generic_params.iter().any(|p| p.is_lifetime_param()) {
825 self.trait_ref_hack = true;
826 let next_early_index = self.next_early_index();
827 let scope = Scope::Binder {
828 lifetimes: bound_generic_params.lifetimes()
829 .map(|def| Region::late(&self.tcx.hir, def))
833 abstract_type_parent: false,
835 let result = self.with(scope, |old_scope, this| {
836 this.check_lifetime_params(old_scope, &bound_generic_params);
837 this.visit_ty(&bounded_ty);
838 walk_list!(this, visit_ty_param_bound, bounds);
840 self.trait_ref_hack = false;
843 self.visit_ty(&bounded_ty);
844 walk_list!(self, visit_ty_param_bound, bounds);
847 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
852 self.visit_lifetime(lifetime);
853 for bound in bounds {
854 self.visit_lifetime(bound);
857 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
862 self.visit_ty(lhs_ty);
863 self.visit_ty(rhs_ty);
869 fn visit_poly_trait_ref(
871 trait_ref: &'tcx hir::PolyTraitRef,
872 _modifier: hir::TraitBoundModifier,
874 debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
876 if !self.trait_ref_hack ||
877 trait_ref.bound_generic_params.iter().any(|p| p.is_lifetime_param())
879 if self.trait_ref_hack {
884 "nested quantification of lifetimes"
887 let next_early_index = self.next_early_index();
888 let scope = Scope::Binder {
889 lifetimes: trait_ref.bound_generic_params
891 .map(|def| Region::late(&self.tcx.hir, def))
895 abstract_type_parent: false,
897 self.with(scope, |old_scope, this| {
898 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
899 walk_list!(this, visit_generic_param, &trait_ref.bound_generic_params);
900 this.visit_trait_ref(&trait_ref.trait_ref)
903 self.visit_trait_ref(&trait_ref.trait_ref)
908 #[derive(Copy, Clone, PartialEq)]
922 fn original_label(span: Span) -> Original {
924 kind: ShadowKind::Label,
928 fn shadower_label(span: Span) -> Shadower {
930 kind: ShadowKind::Label,
934 fn original_lifetime(span: Span) -> Original {
936 kind: ShadowKind::Lifetime,
940 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
942 kind: ShadowKind::Lifetime,
948 fn desc(&self) -> &'static str {
950 ShadowKind::Label => "label",
951 ShadowKind::Lifetime => "lifetime",
956 fn check_mixed_explicit_and_in_band_defs(
957 tcx: TyCtxt<'_, '_, '_>,
958 lifetime_defs: &[hir::LifetimeDef],
960 let oob_def = lifetime_defs.iter().find(|lt| !lt.in_band);
961 let in_band_def = lifetime_defs.iter().find(|lt| lt.in_band);
963 if let (Some(oob_def), Some(in_band_def)) = (oob_def, in_band_def) {
966 in_band_def.lifetime.span,
968 "cannot mix in-band and explicit lifetime definitions"
970 in_band_def.lifetime.span,
971 "in-band lifetime definition here",
973 .span_label(oob_def.lifetime.span, "explicit lifetime definition here")
978 fn signal_shadowing_problem(
979 tcx: TyCtxt<'_, '_, '_>,
984 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
985 // lifetime/lifetime shadowing is an error
990 "{} name `{}` shadows a \
991 {} name that is already in scope",
992 shadower.kind.desc(),
997 // shadowing involving a label is only a warning, due to issues with
998 // labels and lifetimes not being macro-hygienic.
999 tcx.sess.struct_span_warn(
1002 "{} name `{}` shadows a \
1003 {} name that is already in scope",
1004 shadower.kind.desc(),
1010 err.span_label(orig.span, "first declared here");
1011 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1015 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1016 // if one of the label shadows a lifetime or another label.
1017 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
1018 struct GatherLabels<'a, 'tcx: 'a> {
1019 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1020 scope: ScopeRef<'a>,
1021 labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
1024 let mut gather = GatherLabels {
1027 labels_in_fn: &mut ctxt.labels_in_fn,
1029 gather.visit_body(body);
1031 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1032 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1033 NestedVisitorMap::None
1036 fn visit_expr(&mut self, ex: &hir::Expr) {
1037 if let Some((label, label_span)) = expression_label(ex) {
1038 for &(prior, prior_span) in &self.labels_in_fn[..] {
1039 // FIXME (#24278): non-hygienic comparison
1041 signal_shadowing_problem(
1044 original_label(prior_span),
1045 shadower_label(label_span),
1050 check_if_label_shadows_lifetime(self.tcx, self.scope, label, label_span);
1052 self.labels_in_fn.push((label, label_span));
1054 intravisit::walk_expr(self, ex)
1058 fn expression_label(ex: &hir::Expr) -> Option<(ast::Name, Span)> {
1060 hir::ExprWhile(.., Some(label)) | hir::ExprLoop(_, Some(label), _) => {
1061 Some((label.name, label.span))
1067 fn check_if_label_shadows_lifetime(
1068 tcx: TyCtxt<'_, '_, '_>,
1069 mut scope: ScopeRef<'_>,
1075 Scope::Body { s, .. }
1076 | Scope::Elision { s, .. }
1077 | Scope::ObjectLifetimeDefault { s, .. } => {
1088 next_early_index: _,
1089 abstract_type_parent: _,
1091 // FIXME (#24278): non-hygienic comparison
1092 if let Some(def) = lifetimes.get(&hir::LifetimeName::Name(label)) {
1093 let node_id = tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
1095 signal_shadowing_problem(
1098 original_lifetime(tcx.hir.span(node_id)),
1099 shadower_label(label_span),
1110 fn compute_object_lifetime_defaults(
1111 tcx: TyCtxt<'_, '_, '_>,
1112 ) -> NodeMap<Vec<ObjectLifetimeDefault>> {
1113 let mut map = NodeMap();
1114 for item in tcx.hir.krate().items.values() {
1116 hir::ItemStruct(_, ref generics)
1117 | hir::ItemUnion(_, ref generics)
1118 | hir::ItemEnum(_, ref generics)
1119 | hir::ItemTy(_, ref generics)
1120 | hir::ItemTrait(_, _, ref generics, ..) => {
1121 let result = object_lifetime_defaults_for_item(tcx, generics);
1124 if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") {
1125 let object_lifetime_default_reprs: String = result
1127 .map(|set| match *set {
1128 Set1::Empty => "BaseDefault".to_string(),
1129 Set1::One(Region::Static) => "'static".to_string(),
1130 Set1::One(Region::EarlyBound(i, _, _)) => generics.lifetimes()
1137 Set1::One(_) => bug!(),
1138 Set1::Many => "Ambiguous".to_string(),
1140 .collect::<Vec<String>>()
1142 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1145 map.insert(item.id, result);
1153 /// Scan the bounds and where-clauses on parameters to extract bounds
1154 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1155 /// for each type parameter.
1156 fn object_lifetime_defaults_for_item(
1157 tcx: TyCtxt<'_, '_, '_>,
1158 generics: &hir::Generics,
1159 ) -> Vec<ObjectLifetimeDefault> {
1160 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::TyParamBound]) {
1161 for bound in bounds {
1162 if let hir::RegionTyParamBound(ref lifetime) = *bound {
1163 set.insert(lifetime.name);
1168 generics.ty_params()
1170 let mut set = Set1::Empty;
1172 add_bounds(&mut set, ¶m.bounds);
1174 let param_def_id = tcx.hir.local_def_id(param.id);
1175 for predicate in &generics.where_clause.predicates {
1176 // Look for `type: ...` where clauses.
1177 let data = match *predicate {
1178 hir::WherePredicate::BoundPredicate(ref data) => data,
1182 // Ignore `for<'a> type: ...` as they can change what
1183 // lifetimes mean (although we could "just" handle it).
1184 if !data.bound_generic_params.is_empty() {
1188 let def = match data.bounded_ty.node {
1189 hir::TyPath(hir::QPath::Resolved(None, ref path)) => path.def,
1193 if def == Def::TyParam(param_def_id) {
1194 add_bounds(&mut set, &data.bounds);
1199 Set1::Empty => Set1::Empty,
1200 Set1::One(name) => {
1201 if name == hir::LifetimeName::Static {
1202 Set1::One(Region::Static)
1207 .find(|&(_, def)| def.lifetime.name == name)
1208 .map_or(Set1::Many, |(i, def)| {
1209 let def_id = tcx.hir.local_def_id(def.lifetime.id);
1210 let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
1211 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1215 Set1::Many => Set1::Many,
1221 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1222 // FIXME(#37666) this works around a limitation in the region inferencer
1223 fn hack<F>(&mut self, f: F)
1225 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1230 fn with<F>(&mut self, wrap_scope: Scope, f: F)
1232 F: for<'b> FnOnce(ScopeRef, &mut LifetimeContext<'b, 'tcx>),
1234 let LifetimeContext {
1235 tcx, ref mut map, ..
1237 let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
1238 let xcrate_object_lifetime_defaults =
1239 replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap());
1240 let mut this = LifetimeContext {
1244 trait_ref_hack: self.trait_ref_hack,
1245 is_in_fn_syntax: self.is_in_fn_syntax,
1247 xcrate_object_lifetime_defaults,
1248 lifetime_uses: DefIdMap(),
1250 debug!("entering scope {:?}", this.scope);
1251 f(self.scope, &mut this);
1252 debug!("exiting scope {:?}", this.scope);
1253 self.labels_in_fn = this.labels_in_fn;
1254 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1256 for (def_id, lifetimeuseset) in &this.lifetime_uses {
1257 match lifetimeuseset {
1258 &LifetimeUseSet::One(_) => {
1259 let node_id = this.tcx.hir.as_local_node_id(*def_id).unwrap();
1260 debug!("node id first={:?}", node_id);
1261 if let hir::map::NodeLifetime(hir_lifetime) = this.tcx.hir.get(node_id) {
1262 let span = hir_lifetime.span;
1263 let id = hir_lifetime.id;
1264 debug!("id ={:?} span = {:?} hir_lifetime = {:?}",
1270 .struct_span_lint_node(lint::builtin::SINGLE_USE_LIFETIME,
1273 &format!("lifetime name `{}` only used once",
1274 hir_lifetime.name.name()))
1279 debug!("Not one use lifetime");
1285 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1287 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1288 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1289 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1293 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1295 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1296 /// lifetimes may be interspersed together.
1298 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1299 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1300 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1301 /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
1302 /// ordering is not important there.
1303 fn visit_early_late<F>(
1305 parent_id: Option<ast::NodeId>,
1306 decl: &'tcx hir::FnDecl,
1307 generics: &'tcx hir::Generics,
1310 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1312 insert_late_bound_lifetimes(self.map, decl, generics);
1314 // Find the start of nested early scopes, e.g. in methods.
1316 if let Some(parent_id) = parent_id {
1317 let parent = self.tcx.hir.expect_item(parent_id);
1318 if let hir::ItemTrait(..) = parent.node {
1319 index += 1; // Self comes first.
1322 hir::ItemTrait(_, _, ref generics, ..)
1323 | hir::ItemImpl(_, _, _, ref generics, ..) => {
1324 index += generics.params.len() as u32;
1330 let lifetimes = generics
1333 if self.map.late_bound.contains(&def.lifetime.id) {
1334 Region::late(&self.tcx.hir, def)
1336 Region::early(&self.tcx.hir, &mut index, def)
1341 let next_early_index = index + generics.ty_params().count() as u32;
1343 let scope = Scope::Binder {
1347 abstract_type_parent: true,
1349 self.with(scope, move |old_scope, this| {
1350 this.check_lifetime_params(old_scope, &generics.params);
1351 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1355 fn next_early_index_helper(&self, only_abstract_type_parent: bool) -> u32 {
1356 let mut scope = self.scope;
1359 Scope::Root => return 0,
1363 abstract_type_parent,
1365 } if (!only_abstract_type_parent || abstract_type_parent)
1366 => return next_early_index,
1368 Scope::Binder { s, .. }
1369 | Scope::Body { s, .. }
1370 | Scope::Elision { s, .. }
1371 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1376 /// Returns the next index one would use for an early-bound-region
1377 /// if extending the current scope.
1378 fn next_early_index(&self) -> u32 {
1379 self.next_early_index_helper(true)
1382 /// Returns the next index one would use for an `impl Trait` that
1383 /// is being converted into an `abstract type`. This will be the
1384 /// next early index from the enclosing item, for the most
1385 /// part. See the `abstract_type_parent` field for more info.
1386 fn next_early_index_for_abstract_type(&self) -> u32 {
1387 self.next_early_index_helper(false)
1390 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1391 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1392 // Walk up the scope chain, tracking the number of fn scopes
1393 // that we pass through, until we find a lifetime with the
1394 // given name or we run out of scopes.
1396 let mut late_depth = 0;
1397 let mut scope = self.scope;
1398 let mut outermost_body = None;
1401 Scope::Body { id, s } => {
1402 outermost_body = Some(id);
1413 next_early_index: _,
1414 abstract_type_parent: _,
1416 if let Some(&def) = lifetimes.get(&lifetime_ref.name) {
1417 break Some(def.shifted(late_depth));
1424 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1430 if let Some(mut def) = result {
1431 if let Region::EarlyBound(..) = def {
1432 // Do not free early-bound regions, only late-bound ones.
1433 } else if let Some(body_id) = outermost_body {
1434 let fn_id = self.tcx.hir.body_owner(body_id);
1435 match self.tcx.hir.get(fn_id) {
1436 hir::map::NodeItem(&hir::Item {
1437 node: hir::ItemFn(..),
1440 | hir::map::NodeTraitItem(&hir::TraitItem {
1441 node: hir::TraitItemKind::Method(..),
1444 | hir::map::NodeImplItem(&hir::ImplItem {
1445 node: hir::ImplItemKind::Method(..),
1448 let scope = self.tcx.hir.local_def_id(fn_id);
1449 def = Region::Free(scope, def.id().unwrap());
1455 // Check for fn-syntax conflicts with in-band lifetime definitions
1456 if self.is_in_fn_syntax {
1458 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1459 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1464 "lifetimes used in `fn` or `Fn` syntax must be \
1465 explicitly declared using `<...>` binders"
1466 ).span_label(lifetime_ref.span, "in-band lifetime definition")
1471 | Region::EarlyBound(_, _, LifetimeDefOrigin::Explicit)
1472 | Region::LateBound(_, _, LifetimeDefOrigin::Explicit)
1473 | Region::LateBoundAnon(..)
1474 | Region::Free(..) => {}
1478 self.insert_lifetime(lifetime_ref, def);
1484 "use of undeclared lifetime name `{}`",
1485 lifetime_ref.name.name()
1486 ).span_label(lifetime_ref.span, "undeclared lifetime")
1491 fn visit_segment_parameters(
1495 params: &'tcx hir::PathParameters,
1497 if params.parenthesized {
1498 let was_in_fn_syntax = self.is_in_fn_syntax;
1499 self.is_in_fn_syntax = true;
1500 self.visit_fn_like_elision(params.inputs(), Some(¶ms.bindings[0].ty));
1501 self.is_in_fn_syntax = was_in_fn_syntax;
1505 if params.lifetimes.iter().all(|l| l.is_elided()) {
1506 self.resolve_elided_lifetimes(¶ms.lifetimes, true);
1508 for l in ¶ms.lifetimes {
1509 self.visit_lifetime(l);
1513 // Figure out if this is a type/trait segment,
1514 // which requires object lifetime defaults.
1515 let parent_def_id = |this: &mut Self, def_id: DefId| {
1516 let def_key = this.tcx.def_key(def_id);
1518 krate: def_id.krate,
1519 index: def_key.parent.expect("missing parent"),
1522 let type_def_id = match def {
1523 Def::AssociatedTy(def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1524 Def::Variant(def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1526 | Def::Union(def_id)
1528 | Def::TyAlias(def_id)
1529 | Def::Trait(def_id) if depth == 0 =>
1536 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1538 let mut scope = self.scope;
1541 Scope::Root => break false,
1543 Scope::Body { .. } => break true,
1545 Scope::Binder { s, .. }
1546 | Scope::Elision { s, .. }
1547 | Scope::ObjectLifetimeDefault { s, .. } => {
1554 let map = &self.map;
1555 let unsubst = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1556 &map.object_lifetime_defaults[&id]
1559 self.xcrate_object_lifetime_defaults
1561 .or_insert_with(|| {
1562 tcx.generics_of(def_id)
1565 .map(|def| def.object_lifetime_default)
1571 .map(|set| match *set {
1572 Set1::Empty => if in_body {
1575 Some(Region::Static)
1577 Set1::One(r) => r.subst(¶ms.lifetimes, map),
1583 for (i, ty) in params.types.iter().enumerate() {
1584 if let Some(<) = object_lifetime_defaults.get(i) {
1585 let scope = Scope::ObjectLifetimeDefault {
1589 self.with(scope, |_, this| this.visit_ty(ty));
1595 for b in ¶ms.bindings {
1596 self.visit_assoc_type_binding(b);
1600 fn visit_fn_like_elision(
1602 inputs: &'tcx [P<hir::Ty>],
1603 output: Option<&'tcx P<hir::Ty>>,
1605 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
1606 let arg_scope = Scope::Elision {
1607 elide: arg_elide.clone(),
1610 self.with(arg_scope, |_, this| {
1611 for input in inputs {
1612 this.visit_ty(input);
1615 Scope::Elision { ref elide, .. } => {
1616 arg_elide = elide.clone();
1622 let output = match output {
1627 // Figure out if there's a body we can get argument names from,
1628 // and whether there's a `self` argument (treated specially).
1629 let mut assoc_item_kind = None;
1630 let mut impl_self = None;
1631 let parent = self.tcx.hir.get_parent_node(output.id);
1632 let body = match self.tcx.hir.get(parent) {
1633 // `fn` definitions and methods.
1634 hir::map::NodeItem(&hir::Item {
1635 node: hir::ItemFn(.., body),
1639 hir::map::NodeTraitItem(&hir::TraitItem {
1640 node: hir::TraitItemKind::Method(_, ref m),
1645 .expect_item(self.tcx.hir.get_parent(parent))
1648 hir::ItemTrait(.., ref trait_items) => {
1649 assoc_item_kind = trait_items
1651 .find(|ti| ti.id.node_id == parent)
1657 hir::TraitMethod::Required(_) => None,
1658 hir::TraitMethod::Provided(body) => Some(body),
1662 hir::map::NodeImplItem(&hir::ImplItem {
1663 node: hir::ImplItemKind::Method(_, body),
1668 .expect_item(self.tcx.hir.get_parent(parent))
1671 hir::ItemImpl(.., ref self_ty, ref impl_items) => {
1672 impl_self = Some(self_ty);
1673 assoc_item_kind = impl_items
1675 .find(|ii| ii.id.node_id == parent)
1683 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
1684 hir::map::NodeForeignItem(_) | hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) =>
1686 // Everything else (only closures?) doesn't
1687 // actually enjoy elision in return types.
1689 self.visit_ty(output);
1694 let has_self = match assoc_item_kind {
1695 Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
1699 // In accordance with the rules for lifetime elision, we can determine
1700 // what region to use for elision in the output type in two ways.
1701 // First (determined here), if `self` is by-reference, then the
1702 // implied output region is the region of the self parameter.
1704 // Look for `self: &'a Self` - also desugared from `&'a self`,
1705 // and if that matches, use it for elision and return early.
1706 let is_self_ty = |def: Def| {
1707 if let Def::SelfTy(..) = def {
1711 // Can't always rely on literal (or implied) `Self` due
1712 // to the way elision rules were originally specified.
1713 let impl_self = impl_self.map(|ty| &ty.node);
1714 if let Some(&hir::TyPath(hir::QPath::Resolved(None, ref path))) = impl_self {
1716 // Whitelist the types that unambiguously always
1717 // result in the same type constructor being used
1718 // (it can't differ between `Self` and `self`).
1719 Def::Struct(_) | Def::Union(_) | Def::Enum(_) | Def::PrimTy(_) => {
1720 return def == path.def
1729 if let hir::TyRptr(lifetime_ref, ref mt) = inputs[0].node {
1730 if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
1731 if is_self_ty(path.def) {
1732 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
1733 let scope = Scope::Elision {
1734 elide: Elide::Exact(lifetime),
1737 self.with(scope, |_, this| this.visit_ty(output));
1745 // Second, if there was exactly one lifetime (either a substitution or a
1746 // reference) in the arguments, then any anonymous regions in the output
1747 // have that lifetime.
1748 let mut possible_implied_output_region = None;
1749 let mut lifetime_count = 0;
1750 let arg_lifetimes = inputs
1753 .skip(has_self as usize)
1755 let mut gather = GatherLifetimes {
1758 have_bound_regions: false,
1759 lifetimes: FxHashSet(),
1761 gather.visit_ty(input);
1763 lifetime_count += gather.lifetimes.len();
1765 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
1766 // there's a chance that the unique lifetime of this
1767 // iteration will be the appropriate lifetime for output
1768 // parameters, so lets store it.
1769 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
1772 ElisionFailureInfo {
1775 lifetime_count: gather.lifetimes.len(),
1776 have_bound_regions: gather.have_bound_regions,
1781 let elide = if lifetime_count == 1 {
1782 Elide::Exact(possible_implied_output_region.unwrap())
1784 Elide::Error(arg_lifetimes)
1787 let scope = Scope::Elision {
1791 self.with(scope, |_, this| this.visit_ty(output));
1793 struct GatherLifetimes<'a> {
1794 map: &'a NamedRegionMap,
1796 have_bound_regions: bool,
1797 lifetimes: FxHashSet<Region>,
1800 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
1801 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1802 NestedVisitorMap::None
1805 fn visit_ty(&mut self, ty: &hir::Ty) {
1806 if let hir::TyBareFn(_) = ty.node {
1807 self.binder_depth += 1;
1809 if let hir::TyTraitObject(ref bounds, ref lifetime) = ty.node {
1810 for bound in bounds {
1811 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
1814 // Stay on the safe side and don't include the object
1815 // lifetime default (which may not end up being used).
1816 if !lifetime.is_elided() {
1817 self.visit_lifetime(lifetime);
1820 intravisit::walk_ty(self, ty);
1822 if let hir::TyBareFn(_) = ty.node {
1823 self.binder_depth -= 1;
1827 fn visit_generic_param(&mut self, param: &hir::GenericParam) {
1828 if let hir::GenericParam::Lifetime(ref lifetime_def) = *param {
1829 for l in &lifetime_def.bounds {
1830 self.visit_lifetime(l);
1834 intravisit::walk_generic_param(self, param);
1837 fn visit_poly_trait_ref(
1839 trait_ref: &hir::PolyTraitRef,
1840 modifier: hir::TraitBoundModifier,
1842 self.binder_depth += 1;
1843 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1844 self.binder_depth -= 1;
1847 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
1848 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
1850 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
1851 if debruijn.depth < self.binder_depth =>
1853 self.have_bound_regions = true;
1857 .insert(lifetime.from_depth(self.binder_depth));
1865 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &'tcx [hir::Lifetime], deprecated: bool) {
1866 if lifetime_refs.is_empty() {
1870 let span = lifetime_refs[0].span;
1871 let id = lifetime_refs[0].id;
1872 let mut late_depth = 0;
1873 let mut scope = self.scope;
1876 .struct_span_lint_node(
1877 lint::builtin::ELIDED_LIFETIME_IN_PATH,
1880 &format!("hidden lifetime parameters are deprecated, try `Foo<'_>`"))
1885 // Do not assign any resolution, it will be inferred.
1886 Scope::Body { .. } => return,
1888 Scope::Root => break None,
1890 Scope::Binder { s, .. } => {
1895 Scope::Elision { ref elide, .. } => {
1896 let lifetime = match *elide {
1897 Elide::FreshLateAnon(ref counter) => {
1898 for lifetime_ref in lifetime_refs {
1899 let lifetime = Region::late_anon(counter).shifted(late_depth);
1900 self.insert_lifetime(lifetime_ref, lifetime);
1904 Elide::Exact(l) => l.shifted(late_depth),
1905 Elide::Error(ref e) => break Some(e),
1907 for lifetime_ref in lifetime_refs {
1908 self.insert_lifetime(lifetime_ref, lifetime);
1913 Scope::ObjectLifetimeDefault { s, .. } => {
1919 let mut err = struct_span_err!(
1923 "missing lifetime specifier{}",
1924 if lifetime_refs.len() > 1 { "s" } else { "" }
1926 let msg = if lifetime_refs.len() > 1 {
1927 format!("expected {} lifetime parameters", lifetime_refs.len())
1929 format!("expected lifetime parameter")
1931 err.span_label(span, msg);
1933 if let Some(params) = error {
1934 if lifetime_refs.len() == 1 {
1935 self.report_elision_failure(&mut err, params);
1941 fn report_elision_failure(
1943 db: &mut DiagnosticBuilder,
1944 params: &[ElisionFailureInfo],
1946 let mut m = String::new();
1947 let len = params.len();
1949 let elided_params: Vec<_> = params
1952 .filter(|info| info.lifetime_count > 0)
1955 let elided_len = elided_params.len();
1957 for (i, info) in elided_params.into_iter().enumerate() {
1958 let ElisionFailureInfo {
1965 let help_name = if let Some(body) = parent {
1966 let arg = &self.tcx.hir.body(body).arguments[index];
1967 format!("`{}`", self.tcx.hir.node_to_pretty_string(arg.pat.id))
1969 format!("argument {}", index + 1)
1977 "one of {}'s {} {}lifetimes",
1980 if have_bound_regions { "free " } else { "" }
1985 if elided_len == 2 && i == 0 {
1987 } else if i + 2 == elided_len {
1988 m.push_str(", or ");
1989 } else if i != elided_len - 1 {
1997 "this function's return type contains a borrowed value, but \
1998 there is no value for it to be borrowed from"
2000 help!(db, "consider giving it a 'static lifetime");
2001 } else if elided_len == 0 {
2004 "this function's return type contains a borrowed value with \
2005 an elided lifetime, but the lifetime cannot be derived from \
2010 "consider giving it an explicit bounded or 'static \
2013 } else if elided_len == 1 {
2016 "this function's return type contains a borrowed value, but \
2017 the signature does not say which {} it is borrowed from",
2023 "this function's return type contains a borrowed value, but \
2024 the signature does not say whether it is borrowed from {}",
2030 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2031 let mut late_depth = 0;
2032 let mut scope = self.scope;
2033 let lifetime = loop {
2035 Scope::Binder { s, .. } => {
2040 Scope::Root | Scope::Elision { .. } => break Region::Static,
2042 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2044 Scope::ObjectLifetimeDefault {
2045 lifetime: Some(l), ..
2049 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2052 fn check_lifetime_params(&mut self, old_scope: ScopeRef, params: &'tcx [hir::GenericParam]) {
2053 for (i, lifetime_i) in params.lifetimes().enumerate() {
2054 for lifetime in params.lifetimes() {
2055 match lifetime.lifetime.name {
2056 hir::LifetimeName::Static | hir::LifetimeName::Underscore => {
2057 let lifetime = lifetime.lifetime;
2058 let name = lifetime.name.name();
2059 let mut err = struct_span_err!(
2063 "invalid lifetime parameter name: `{}`",
2068 format!("{} is a reserved lifetime name", name),
2072 hir::LifetimeName::Implicit | hir::LifetimeName::Name(_) => {}
2076 // It is a hard error to shadow a lifetime within the same scope.
2077 for lifetime_j in params.lifetimes().skip(i + 1) {
2078 if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
2081 lifetime_j.lifetime.span,
2083 "lifetime name `{}` declared twice in the same scope",
2084 lifetime_j.lifetime.name.name()
2085 ).span_label(lifetime_j.lifetime.span, "declared twice")
2086 .span_label(lifetime_i.lifetime.span, "previous declaration here")
2091 // It is a soft error to shadow a lifetime within a parent scope.
2092 self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
2094 for bound in &lifetime_i.bounds {
2096 hir::LifetimeName::Underscore => {
2097 let mut err = struct_span_err!(
2101 "invalid lifetime bound name: `'_`"
2103 err.span_label(bound.span, "`'_` is a reserved lifetime name");
2106 hir::LifetimeName::Static => {
2107 self.insert_lifetime(bound, Region::Static);
2111 lifetime_i.lifetime.span.to(bound.span),
2113 "unnecessary lifetime parameter `{}`",
2114 lifetime_i.lifetime.name.name()
2118 "you can use the `'static` lifetime directly, in place \
2120 lifetime_i.lifetime.name.name()
2124 hir::LifetimeName::Implicit | hir::LifetimeName::Name(_) => {
2125 self.resolve_lifetime_ref(bound);
2132 fn check_lifetime_def_for_shadowing(&self,
2133 mut old_scope: ScopeRef,
2134 lifetime: &'tcx hir::Lifetime) {
2135 for &(label, label_span) in &self.labels_in_fn {
2136 // FIXME (#24278): non-hygienic comparison
2137 if lifetime.name.name() == label {
2138 signal_shadowing_problem(
2141 original_label(label_span),
2142 shadower_lifetime(&lifetime),
2150 Scope::Body { s, .. }
2151 | Scope::Elision { s, .. }
2152 | Scope::ObjectLifetimeDefault { s, .. } => {
2163 next_early_index: _,
2164 abstract_type_parent: _,
2166 if let Some(&def) = lifetimes.get(&lifetime.name) {
2167 let node_id = self.tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
2169 signal_shadowing_problem(
2171 lifetime.name.name(),
2172 original_lifetime(self.tcx.hir.span(node_id)),
2173 shadower_lifetime(&lifetime),
2184 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2185 if lifetime_ref.id == ast::DUMMY_NODE_ID {
2188 "lifetime reference not renumbered, \
2189 probably a bug in syntax::fold"
2194 "insert_lifetime: {} resolved to {:?} span={:?}",
2195 self.tcx.hir.node_to_string(lifetime_ref.id),
2197 self.tcx.sess.codemap().span_to_string(lifetime_ref.span)
2199 self.map.defs.insert(lifetime_ref.id, def);
2202 Region::LateBoundAnon(..) |
2204 // These are anonymous lifetimes or lifetimes that are not declared.
2207 Region::Free(_, def_id) |
2208 Region::LateBound(_, def_id, _) |
2209 Region::EarlyBound(_, def_id, _) => {
2210 // A lifetime declared by the user.
2211 if !self.lifetime_uses.contains_key(&def_id) {
2213 .insert(def_id, LifetimeUseSet::One(lifetime_ref));
2215 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2222 ///////////////////////////////////////////////////////////////////////////
2224 /// Detects late-bound lifetimes and inserts them into
2225 /// `map.late_bound`.
2227 /// A region declared on a fn is **late-bound** if:
2228 /// - it is constrained by an argument type;
2229 /// - it does not appear in a where-clause.
2231 /// "Constrained" basically means that it appears in any type but
2232 /// not amongst the inputs to a projection. In other words, `<&'a
2233 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2234 fn insert_late_bound_lifetimes(
2235 map: &mut NamedRegionMap,
2237 generics: &hir::Generics,
2240 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2245 let mut constrained_by_input = ConstrainedCollector {
2246 regions: FxHashSet(),
2248 for arg_ty in &decl.inputs {
2249 constrained_by_input.visit_ty(arg_ty);
2252 let mut appears_in_output = AllCollector {
2253 regions: FxHashSet(),
2255 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2258 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2259 constrained_by_input.regions
2262 // Walk the lifetimes that appear in where clauses.
2264 // Subtle point: because we disallow nested bindings, we can just
2265 // ignore binders here and scrape up all names we see.
2266 let mut appears_in_where_clause = AllCollector {
2267 regions: FxHashSet(),
2270 for param in &generics.params {
2272 hir::GenericParam::Lifetime(ref lifetime_def) => {
2273 if !lifetime_def.bounds.is_empty() {
2274 // `'a: 'b` means both `'a` and `'b` are referenced
2275 appears_in_where_clause.visit_generic_param(param);
2278 hir::GenericParam::Type(ref ty_param) => {
2280 &mut appears_in_where_clause,
2281 visit_ty_param_bound,
2289 &mut appears_in_where_clause,
2290 visit_where_predicate,
2291 &generics.where_clause.predicates
2295 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2296 appears_in_where_clause.regions
2299 // Late bound regions are those that:
2300 // - appear in the inputs
2301 // - do not appear in the where-clauses
2302 // - are not implicitly captured by `impl Trait`
2303 for lifetime in generics.lifetimes() {
2304 let name = lifetime.lifetime.name;
2306 // appears in the where clauses? early-bound.
2307 if appears_in_where_clause.regions.contains(&name) {
2311 // does not appear in the inputs, but appears in the return type? early-bound.
2312 if !constrained_by_input.regions.contains(&name)
2313 && appears_in_output.regions.contains(&name)
2319 "insert_late_bound_lifetimes: \
2320 lifetime {:?} with id {:?} is late-bound",
2321 lifetime.lifetime.name,
2322 lifetime.lifetime.id
2325 let inserted = map.late_bound.insert(lifetime.lifetime.id);
2328 "visited lifetime {:?} twice",
2329 lifetime.lifetime.id
2335 struct ConstrainedCollector {
2336 regions: FxHashSet<hir::LifetimeName>,
2339 impl<'v> Visitor<'v> for ConstrainedCollector {
2340 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2341 NestedVisitorMap::None
2344 fn visit_ty(&mut self, ty: &'v hir::Ty) {
2346 hir::TyPath(hir::QPath::Resolved(Some(_), _))
2347 | hir::TyPath(hir::QPath::TypeRelative(..)) => {
2348 // ignore lifetimes appearing in associated type
2349 // projections, as they are not *constrained*
2353 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
2354 // consider only the lifetimes on the final
2355 // segment; I am not sure it's even currently
2356 // valid to have them elsewhere, but even if it
2357 // is, those would be potentially inputs to
2359 if let Some(last_segment) = path.segments.last() {
2360 self.visit_path_segment(path.span, last_segment);
2365 intravisit::walk_ty(self, ty);
2370 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2371 self.regions.insert(lifetime_ref.name);
2375 struct AllCollector {
2376 regions: FxHashSet<hir::LifetimeName>,
2379 impl<'v> Visitor<'v> for AllCollector {
2380 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2381 NestedVisitorMap::None
2384 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2385 self.regions.insert(lifetime_ref.name);