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.
18 use dep_graph::DepNode;
22 use hir::def_id::DefId;
27 use std::mem::replace;
31 use syntax::symbol::keywords;
33 use errors::DiagnosticBuilder;
34 use util::nodemap::{NodeMap, NodeSet, FxHashSet, FxHashMap, DefIdMap};
35 use rustc_back::slice;
38 use hir::intravisit::{self, Visitor, NestedVisitorMap};
40 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
43 EarlyBound(/* index */ u32, /* lifetime decl */ ast::NodeId),
44 LateBound(ty::DebruijnIndex, /* lifetime decl */ ast::NodeId),
45 LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
46 Free(region::CallSiteScopeData, /* lifetime decl */ ast::NodeId),
50 fn early(index: &mut u32, def: &hir::LifetimeDef) -> (ast::Name, Region) {
53 (def.lifetime.name, Region::EarlyBound(i, def.lifetime.id))
56 fn late(def: &hir::LifetimeDef) -> (ast::Name, Region) {
57 let depth = ty::DebruijnIndex::new(1);
58 (def.lifetime.name, Region::LateBound(depth, def.lifetime.id))
61 fn late_anon(index: &Cell<u32>) -> Region {
64 let depth = ty::DebruijnIndex::new(1);
65 Region::LateBoundAnon(depth, i)
68 fn id(&self) -> Option<ast::NodeId> {
71 Region::LateBoundAnon(..) => None,
73 Region::EarlyBound(_, id) |
74 Region::LateBound(_, id) |
75 Region::Free(_, id) => Some(id)
79 fn shifted(self, amount: u32) -> Region {
81 Region::LateBound(depth, id) => {
82 Region::LateBound(depth.shifted(amount), id)
84 Region::LateBoundAnon(depth, index) => {
85 Region::LateBoundAnon(depth.shifted(amount), index)
91 fn from_depth(self, depth: u32) -> Region {
93 Region::LateBound(debruijn, id) => {
94 Region::LateBound(ty::DebruijnIndex {
95 depth: debruijn.depth - (depth - 1)
98 Region::LateBoundAnon(debruijn, index) => {
99 Region::LateBoundAnon(ty::DebruijnIndex {
100 depth: debruijn.depth - (depth - 1)
107 fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap)
109 if let Region::EarlyBound(index, _) = self {
110 params.get(index as usize).and_then(|lifetime| {
111 map.defs.get(&lifetime.id).cloned()
119 /// A set containing, at most, one known element.
120 /// If two distinct values are inserted into a set, then it
121 /// becomes `Many`, which can be used to detect ambiguities.
122 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
129 impl<T: PartialEq> Set1<T> {
130 pub fn insert(&mut self, value: T) {
131 if let Set1::Empty = *self {
132 *self = Set1::One(value);
135 if let Set1::One(ref old) = *self {
144 pub type ObjectLifetimeDefault = Set1<Region>;
146 // Maps the id of each lifetime reference to the lifetime decl
147 // that it corresponds to.
148 pub struct NamedRegionMap {
149 // maps from every use of a named (not anonymous) lifetime to a
150 // `Region` describing how that region is bound
151 pub defs: NodeMap<Region>,
153 // the set of lifetime def ids that are late-bound; a region can
154 // be late-bound if (a) it does NOT appear in a where-clause and
155 // (b) it DOES appear in the arguments.
156 pub late_bound: NodeSet,
158 // Contains the node-ids for lifetimes that were (incorrectly) categorized
159 // as late-bound, until #32330 was fixed.
160 pub issue_32330: NodeMap<ty::Issue32330>,
162 // For each type and trait definition, maps type parameters
163 // to the trait object lifetime defaults computed from them.
164 pub object_lifetime_defaults: NodeMap<Vec<ObjectLifetimeDefault>>,
167 struct LifetimeContext<'a, 'tcx: 'a> {
169 hir_map: &'a Map<'tcx>,
170 map: &'a mut NamedRegionMap,
172 // Deep breath. Our representation for poly trait refs contains a single
173 // binder and thus we only allow a single level of quantification. However,
174 // the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
175 // and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
176 // correct when representing these constraints, we should only introduce one
177 // scope. However, we want to support both locations for the quantifier and
178 // during lifetime resolution we want precise information (so we can't
179 // desugar in an earlier phase).
181 // SO, if we encounter a quantifier at the outer scope, we set
182 // trait_ref_hack to true (and introduce a scope), and then if we encounter
183 // a quantifier at the inner scope, we error. If trait_ref_hack is false,
184 // then we introduce the scope at the inner quantifier.
187 trait_ref_hack: bool,
189 // List of labels in the function/method currently under analysis.
190 labels_in_fn: Vec<(ast::Name, Span)>,
192 // Cache for cross-crate per-definition object lifetime defaults.
193 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
198 /// Declares lifetimes, and each can be early-bound or late-bound.
199 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
200 /// it should be shifted by the number of `Binder`s in between the
201 /// declaration `Binder` and the location it's referenced from.
203 lifetimes: FxHashMap<ast::Name, Region>,
207 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
208 /// if this is a fn body, otherwise the original definitions are used.
209 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
210 /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
216 /// A scope which either determines unspecified lifetimes or errors
217 /// on them (e.g. due to ambiguity). For more details, see `Elide`.
223 /// Use a specific lifetime (if `Some`) or leave it unset (to be
224 /// inferred in a function body or potentially error outside one),
225 /// for the default choice of lifetime in a trait object type.
226 ObjectLifetimeDefault {
227 lifetime: Option<Region>,
234 #[derive(Clone, Debug)]
236 /// Use a fresh anonymous late-bound lifetime each time, by
237 /// incrementing the counter to generate sequential indices.
238 FreshLateAnon(Cell<u32>),
239 /// Always use this one lifetime.
241 /// Less or more than one lifetime were found, error on unspecified.
242 Error(Vec<ElisionFailureInfo>)
245 #[derive(Clone, Debug)]
246 struct ElisionFailureInfo {
247 /// Where we can find the argument pattern.
248 parent: Option<hir::BodyId>,
249 /// The index of the argument in the original definition.
251 lifetime_count: usize,
252 have_bound_regions: bool
255 type ScopeRef<'a> = &'a Scope<'a>;
257 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
259 pub fn krate(sess: &Session,
261 -> Result<NamedRegionMap, usize> {
262 let _task = hir_map.dep_graph.in_task(DepNode::ResolveLifetimes);
263 let krate = hir_map.krate();
264 let mut map = NamedRegionMap {
266 late_bound: NodeSet(),
267 issue_32330: NodeMap(),
268 object_lifetime_defaults: compute_object_lifetime_defaults(sess, hir_map),
270 sess.track_errors(|| {
271 let mut visitor = LifetimeContext {
276 trait_ref_hack: false,
277 labels_in_fn: vec![],
278 xcrate_object_lifetime_defaults: DefIdMap(),
280 for (_, item) in &krate.items {
281 visitor.visit_item(item);
287 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
288 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
289 NestedVisitorMap::All(self.hir_map)
292 // We want to nest trait/impl items in their parent, but nothing else.
293 fn visit_nested_item(&mut self, _: hir::ItemId) {}
295 fn visit_nested_body(&mut self, body: hir::BodyId) {
296 // Each body has their own set of labels, save labels.
297 let saved = replace(&mut self.labels_in_fn, vec![]);
298 let body = self.hir_map.body(body);
299 extract_labels(self, body);
300 self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
301 this.visit_body(body);
303 replace(&mut self.labels_in_fn, saved);
306 fn visit_item(&mut self, item: &'tcx hir::Item) {
308 hir::ItemFn(ref decl, _, _, _, ref generics, _) => {
309 self.visit_early_late(item.id, None, decl, generics, |this| {
310 intravisit::walk_item(this, item);
313 hir::ItemExternCrate(_) |
316 hir::ItemDefaultImpl(..) |
317 hir::ItemForeignMod(..) => {
318 // These sorts of items have no lifetime parameters at all.
319 intravisit::walk_item(self, item);
321 hir::ItemStatic(..) |
322 hir::ItemConst(..) => {
323 // No lifetime parameters, but implied 'static.
324 let scope = Scope::Elision {
325 elide: Elide::Exact(Region::Static),
328 self.with(scope, |_, this| intravisit::walk_item(this, item));
330 hir::ItemTy(_, ref generics) |
331 hir::ItemEnum(_, ref generics) |
332 hir::ItemStruct(_, ref generics) |
333 hir::ItemUnion(_, ref generics) |
334 hir::ItemTrait(_, ref generics, ..) |
335 hir::ItemImpl(_, _, ref generics, ..) => {
336 // These kinds of items have only early bound lifetime parameters.
337 let mut index = if let hir::ItemTrait(..) = item.node {
338 1 // Self comes before lifetimes
342 let lifetimes = generics.lifetimes.iter().map(|def| {
343 Region::early(&mut index, def)
345 let scope = Scope::Binder {
346 lifetimes: lifetimes,
349 self.with(scope, |old_scope, this| {
350 this.check_lifetime_defs(old_scope, &generics.lifetimes);
351 intravisit::walk_item(this, item);
357 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
359 hir::ForeignItemFn(ref decl, _, ref generics) => {
360 self.visit_early_late(item.id, None, decl, generics, |this| {
361 intravisit::walk_foreign_item(this, item);
364 hir::ForeignItemStatic(..) => {
365 intravisit::walk_foreign_item(self, item);
370 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
372 hir::TyBareFn(ref c) => {
373 let scope = Scope::Binder {
374 lifetimes: c.lifetimes.iter().map(Region::late).collect(),
377 self.with(scope, |old_scope, this| {
378 // a bare fn has no bounds, so everything
379 // contained within is scoped within its binder.
380 this.check_lifetime_defs(old_scope, &c.lifetimes);
381 intravisit::walk_ty(this, ty);
384 hir::TyTraitObject(ref bounds, ref lifetime) => {
385 for bound in bounds {
386 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
388 if lifetime.is_elided() {
389 self.resolve_object_lifetime_default(lifetime)
391 self.visit_lifetime(lifetime);
394 hir::TyRptr(ref lifetime_ref, ref mt) => {
395 self.visit_lifetime(lifetime_ref);
396 let scope = Scope::ObjectLifetimeDefault {
397 lifetime: self.map.defs.get(&lifetime_ref.id).cloned(),
400 self.with(scope, |_, this| this.visit_ty(&mt.ty));
403 intravisit::walk_ty(self, ty)
408 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
409 if let hir::TraitItemKind::Method(ref sig, _) = trait_item.node {
410 self.visit_early_late(
412 Some(self.hir_map.get_parent(trait_item.id)),
413 &sig.decl, &sig.generics,
414 |this| intravisit::walk_trait_item(this, trait_item))
416 intravisit::walk_trait_item(self, trait_item);
420 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
421 if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
422 self.visit_early_late(
424 Some(self.hir_map.get_parent(impl_item.id)),
425 &sig.decl, &sig.generics,
426 |this| intravisit::walk_impl_item(this, impl_item))
428 intravisit::walk_impl_item(self, impl_item);
432 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
433 if lifetime_ref.is_elided() {
434 self.resolve_elided_lifetimes(slice::ref_slice(lifetime_ref));
437 if lifetime_ref.is_static() {
438 self.insert_lifetime(lifetime_ref, Region::Static);
441 self.resolve_lifetime_ref(lifetime_ref);
444 fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) {
445 for (i, segment) in path.segments.iter().enumerate() {
446 let depth = path.segments.len() - i - 1;
447 self.visit_segment_parameters(path.def, depth, &segment.parameters);
451 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
452 let output = match fd.output {
453 hir::DefaultReturn(_) => None,
454 hir::Return(ref ty) => Some(ty)
456 self.visit_fn_like_elision(&fd.inputs, output);
459 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
460 for ty_param in generics.ty_params.iter() {
461 walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
462 if let Some(ref ty) = ty_param.default {
466 for predicate in &generics.where_clause.predicates {
468 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
472 if !bound_lifetimes.is_empty() {
473 self.trait_ref_hack = true;
474 let scope = Scope::Binder {
475 lifetimes: bound_lifetimes.iter().map(Region::late).collect(),
478 let result = self.with(scope, |old_scope, this| {
479 this.check_lifetime_defs(old_scope, bound_lifetimes);
480 this.visit_ty(&bounded_ty);
481 walk_list!(this, visit_ty_param_bound, bounds);
483 self.trait_ref_hack = false;
486 self.visit_ty(&bounded_ty);
487 walk_list!(self, visit_ty_param_bound, bounds);
490 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
494 self.visit_lifetime(lifetime);
495 for bound in bounds {
496 self.visit_lifetime(bound);
499 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
502 self.visit_ty(lhs_ty);
503 self.visit_ty(rhs_ty);
509 fn visit_poly_trait_ref(&mut self,
510 trait_ref: &'tcx hir::PolyTraitRef,
511 _modifier: hir::TraitBoundModifier) {
512 debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
514 if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
515 if self.trait_ref_hack {
516 span_err!(self.sess, trait_ref.span, E0316,
517 "nested quantification of lifetimes");
519 let scope = Scope::Binder {
520 lifetimes: trait_ref.bound_lifetimes.iter().map(Region::late).collect(),
523 self.with(scope, |old_scope, this| {
524 this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
525 for lifetime in &trait_ref.bound_lifetimes {
526 this.visit_lifetime_def(lifetime);
528 this.visit_trait_ref(&trait_ref.trait_ref)
531 self.visit_trait_ref(&trait_ref.trait_ref)
536 #[derive(Copy, Clone, PartialEq)]
537 enum ShadowKind { Label, Lifetime }
538 struct Original { kind: ShadowKind, span: Span }
539 struct Shadower { kind: ShadowKind, span: Span }
541 fn original_label(span: Span) -> Original {
542 Original { kind: ShadowKind::Label, span: span }
544 fn shadower_label(span: Span) -> Shadower {
545 Shadower { kind: ShadowKind::Label, span: span }
547 fn original_lifetime(span: Span) -> Original {
548 Original { kind: ShadowKind::Lifetime, span: span }
550 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
551 Shadower { kind: ShadowKind::Lifetime, span: l.span }
555 fn desc(&self) -> &'static str {
557 ShadowKind::Label => "label",
558 ShadowKind::Lifetime => "lifetime",
563 fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) {
564 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
565 // lifetime/lifetime shadowing is an error
566 struct_span_err!(sess, shadower.span, E0496,
567 "{} name `{}` shadows a \
568 {} name that is already in scope",
569 shadower.kind.desc(), name, orig.kind.desc())
571 // shadowing involving a label is only a warning, due to issues with
572 // labels and lifetimes not being macro-hygienic.
573 sess.struct_span_warn(shadower.span,
574 &format!("{} name `{}` shadows a \
575 {} name that is already in scope",
576 shadower.kind.desc(), name, orig.kind.desc()))
578 err.span_label(orig.span, &"first declared here");
579 err.span_label(shadower.span,
580 &format!("lifetime {} already in scope", name));
584 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
585 // if one of the label shadows a lifetime or another label.
586 fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) {
587 struct GatherLabels<'a, 'tcx: 'a> {
589 hir_map: &'a Map<'tcx>,
591 labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
594 let mut gather = GatherLabels {
596 hir_map: ctxt.hir_map,
598 labels_in_fn: &mut ctxt.labels_in_fn,
600 gather.visit_body(body);
602 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
603 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
604 NestedVisitorMap::None
607 fn visit_expr(&mut self, ex: &hir::Expr) {
608 if let Some((label, label_span)) = expression_label(ex) {
609 for &(prior, prior_span) in &self.labels_in_fn[..] {
610 // FIXME (#24278): non-hygienic comparison
612 signal_shadowing_problem(self.sess,
614 original_label(prior_span),
615 shadower_label(label_span));
619 check_if_label_shadows_lifetime(self.sess,
625 self.labels_in_fn.push((label, label_span));
627 intravisit::walk_expr(self, ex)
631 fn expression_label(ex: &hir::Expr) -> Option<(ast::Name, Span)> {
633 hir::ExprWhile(.., Some(label)) |
634 hir::ExprLoop(_, Some(label), _) => Some((label.node, label.span)),
639 fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
641 mut scope: ScopeRef<'a>,
646 Scope::Body { s, .. } |
647 Scope::Elision { s, .. } |
648 Scope::ObjectLifetimeDefault { s, .. } => { scope = s; }
650 Scope::Root => { return; }
652 Scope::Binder { ref lifetimes, s } => {
653 // FIXME (#24278): non-hygienic comparison
654 if let Some(def) = lifetimes.get(&label) {
655 signal_shadowing_problem(
658 original_lifetime(hir_map.span(def.id().unwrap())),
659 shadower_label(label_span));
669 fn compute_object_lifetime_defaults(sess: &Session, hir_map: &Map)
670 -> NodeMap<Vec<ObjectLifetimeDefault>> {
671 let mut map = NodeMap();
672 for item in hir_map.krate().items.values() {
674 hir::ItemStruct(_, ref generics) |
675 hir::ItemUnion(_, ref generics) |
676 hir::ItemEnum(_, ref generics) |
677 hir::ItemTy(_, ref generics) |
678 hir::ItemTrait(_, ref generics, ..) => {
679 let result = object_lifetime_defaults_for_item(hir_map, generics);
682 if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") {
683 let object_lifetime_default_reprs: String =
684 result.iter().map(|set| {
686 Set1::Empty => "BaseDefault".to_string(),
687 Set1::One(Region::Static) => "'static".to_string(),
688 Set1::One(Region::EarlyBound(i, _)) => {
689 generics.lifetimes[i as usize].lifetime.name.to_string()
691 Set1::One(_) => bug!(),
692 Set1::Many => "Ambiguous".to_string(),
694 }).collect::<Vec<String>>().join(",");
695 sess.span_err(item.span, &object_lifetime_default_reprs);
698 map.insert(item.id, result);
706 /// Scan the bounds and where-clauses on parameters to extract bounds
707 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
708 /// for each type parameter.
709 fn object_lifetime_defaults_for_item(hir_map: &Map, generics: &hir::Generics)
710 -> Vec<ObjectLifetimeDefault> {
711 fn add_bounds(set: &mut Set1<ast::Name>, bounds: &[hir::TyParamBound]) {
712 for bound in bounds {
713 if let hir::RegionTyParamBound(ref lifetime) = *bound {
714 set.insert(lifetime.name);
719 generics.ty_params.iter().map(|param| {
720 let mut set = Set1::Empty;
722 add_bounds(&mut set, ¶m.bounds);
724 let param_def_id = hir_map.local_def_id(param.id);
725 for predicate in &generics.where_clause.predicates {
726 // Look for `type: ...` where clauses.
727 let data = match *predicate {
728 hir::WherePredicate::BoundPredicate(ref data) => data,
732 // Ignore `for<'a> type: ...` as they can change what
733 // lifetimes mean (although we could "just" handle it).
734 if !data.bound_lifetimes.is_empty() {
738 let def = match data.bounded_ty.node {
739 hir::TyPath(hir::QPath::Resolved(None, ref path)) => path.def,
743 if def == Def::TyParam(param_def_id) {
744 add_bounds(&mut set, &data.bounds);
749 Set1::Empty => Set1::Empty,
751 if name == keywords::StaticLifetime.name() {
752 Set1::One(Region::Static)
754 generics.lifetimes.iter().enumerate().find(|&(_, def)| {
755 def.lifetime.name == name
756 }).map_or(Set1::Many, |(i, def)| {
757 Set1::One(Region::EarlyBound(i as u32, def.lifetime.id))
761 Set1::Many => Set1::Many
766 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
767 // FIXME(#37666) this works around a limitation in the region inferencer
768 fn hack<F>(&mut self, f: F) where
769 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
774 fn with<F>(&mut self, wrap_scope: Scope, f: F) where
775 F: for<'b> FnOnce(ScopeRef, &mut LifetimeContext<'b, 'tcx>),
777 let LifetimeContext {sess, hir_map, ref mut map, ..} = *self;
778 let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
779 let xcrate_object_lifetime_defaults =
780 replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap());
781 let mut this = LifetimeContext {
786 trait_ref_hack: self.trait_ref_hack,
787 labels_in_fn: labels_in_fn,
788 xcrate_object_lifetime_defaults: xcrate_object_lifetime_defaults,
790 debug!("entering scope {:?}", this.scope);
791 f(self.scope, &mut this);
792 debug!("exiting scope {:?}", this.scope);
793 self.labels_in_fn = this.labels_in_fn;
794 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
797 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
799 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
800 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
801 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
805 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
807 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
808 /// lifetimes may be interspersed together.
810 /// If early bound lifetimes are present, we separate them into their own list (and likewise
811 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
812 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
813 /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
814 /// ordering is not important there.
815 fn visit_early_late<F>(&mut self,
817 parent_id: Option<ast::NodeId>,
818 decl: &'tcx hir::FnDecl,
819 generics: &'tcx hir::Generics,
821 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
823 let fn_def_id = self.hir_map.local_def_id(fn_id);
824 insert_late_bound_lifetimes(self.map,
829 // Find the start of nested early scopes, e.g. in methods.
831 if let Some(parent_id) = parent_id {
832 let parent = self.hir_map.expect_item(parent_id);
833 if let hir::ItemTrait(..) = parent.node {
834 index += 1; // Self comes first.
837 hir::ItemTrait(_, ref generics, ..) |
838 hir::ItemImpl(_, _, ref generics, ..) => {
839 index += (generics.lifetimes.len() + generics.ty_params.len()) as u32;
845 let lifetimes = generics.lifetimes.iter().map(|def| {
846 if self.map.late_bound.contains(&def.lifetime.id) {
849 Region::early(&mut index, def)
853 let scope = Scope::Binder {
854 lifetimes: lifetimes,
857 self.with(scope, move |old_scope, this| {
858 this.check_lifetime_defs(old_scope, &generics.lifetimes);
859 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
863 fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
864 // Walk up the scope chain, tracking the number of fn scopes
865 // that we pass through, until we find a lifetime with the
866 // given name or we run out of scopes.
868 let mut late_depth = 0;
869 let mut scope = self.scope;
870 let mut outermost_body = None;
873 Scope::Body { id, s } => {
874 outermost_body = Some(id);
882 Scope::Binder { ref lifetimes, s } => {
883 if let Some(&def) = lifetimes.get(&lifetime_ref.name) {
884 break Some(def.shifted(late_depth));
891 Scope::Elision { s, .. } |
892 Scope::ObjectLifetimeDefault { s, .. } => {
898 if let Some(mut def) = result {
899 if let Some(body_id) = outermost_body {
900 let fn_id = self.hir_map.body_owner(body_id);
901 let scope_data = region::CallSiteScopeData {
902 fn_id: fn_id, body_id: body_id.node_id
904 match self.hir_map.get(fn_id) {
905 hir::map::NodeItem(&hir::Item {
906 node: hir::ItemFn(..), ..
908 hir::map::NodeTraitItem(&hir::TraitItem {
909 node: hir::TraitItemKind::Method(..), ..
911 hir::map::NodeImplItem(&hir::ImplItem {
912 node: hir::ImplItemKind::Method(..), ..
914 def = Region::Free(scope_data, def.id().unwrap());
919 self.insert_lifetime(lifetime_ref, def);
921 struct_span_err!(self.sess, lifetime_ref.span, E0261,
922 "use of undeclared lifetime name `{}`", lifetime_ref.name)
923 .span_label(lifetime_ref.span, &format!("undeclared lifetime"))
928 fn visit_segment_parameters(&mut self,
931 params: &'tcx hir::PathParameters) {
932 let data = match *params {
933 hir::ParenthesizedParameters(ref data) => {
934 self.visit_fn_like_elision(&data.inputs, data.output.as_ref());
937 hir::AngleBracketedParameters(ref data) => data
940 if data.lifetimes.iter().all(|l| l.is_elided()) {
941 self.resolve_elided_lifetimes(&data.lifetimes);
943 for l in &data.lifetimes { self.visit_lifetime(l); }
946 // Figure out if this is a type/trait segment,
947 // which requires object lifetime defaults.
948 let parent_def_id = |this: &mut Self, def_id: DefId| {
949 let def_key = if def_id.is_local() {
950 this.hir_map.def_key(def_id)
952 this.sess.cstore.def_key(def_id)
956 index: def_key.parent.expect("missing parent")
959 let type_def_id = match def {
960 Def::AssociatedTy(def_id) if depth == 1 => {
961 Some(parent_def_id(self, def_id))
963 Def::Variant(def_id) if depth == 0 => {
964 Some(parent_def_id(self, def_id))
966 Def::Struct(def_id) |
969 Def::TyAlias(def_id) |
970 Def::Trait(def_id) if depth == 0 => Some(def_id),
974 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
976 let mut scope = self.scope;
979 Scope::Root => break false,
981 Scope::Body { .. } => break true,
983 Scope::Binder { s, .. } |
984 Scope::Elision { s, .. } |
985 Scope::ObjectLifetimeDefault { s, .. } => {
993 let unsubst = if let Some(id) = self.hir_map.as_local_node_id(def_id) {
994 &map.object_lifetime_defaults[&id]
996 let cstore = &self.sess.cstore;
997 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
998 cstore.item_generics_cloned(def_id).types.into_iter().map(|def| {
999 def.object_lifetime_default
1003 unsubst.iter().map(|set| {
1009 Some(Region::Static)
1012 Set1::One(r) => r.subst(&data.lifetimes, map),
1018 for (i, ty) in data.types.iter().enumerate() {
1019 if let Some(<) = object_lifetime_defaults.get(i) {
1020 let scope = Scope::ObjectLifetimeDefault {
1024 self.with(scope, |_, this| this.visit_ty(ty));
1030 for b in &data.bindings { self.visit_assoc_type_binding(b); }
1033 fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
1034 output: Option<&'tcx P<hir::Ty>>) {
1035 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
1036 let arg_scope = Scope::Elision {
1037 elide: arg_elide.clone(),
1040 self.with(arg_scope, |_, this| {
1041 for input in inputs {
1042 this.visit_ty(input);
1045 Scope::Elision { ref elide, .. } => {
1046 arg_elide = elide.clone();
1052 let output = match output {
1057 // Figure out if there's a body we can get argument names from,
1058 // and whether there's a `self` argument (treated specially).
1059 let mut assoc_item_kind = None;
1060 let mut impl_self = None;
1061 let parent = self.hir_map.get_parent_node(output.id);
1062 let body = match self.hir_map.get(parent) {
1063 // `fn` definitions and methods.
1064 hir::map::NodeItem(&hir::Item {
1065 node: hir::ItemFn(.., body), ..
1068 hir::map::NodeTraitItem(&hir::TraitItem {
1069 node: hir::TraitItemKind::Method(_, ref m), ..
1071 match self.hir_map.expect_item(self.hir_map.get_parent(parent)).node {
1072 hir::ItemTrait(.., ref trait_items) => {
1073 assoc_item_kind = trait_items.iter().find(|ti| ti.id.node_id == parent)
1079 hir::TraitMethod::Required(_) => None,
1080 hir::TraitMethod::Provided(body) => Some(body),
1084 hir::map::NodeImplItem(&hir::ImplItem {
1085 node: hir::ImplItemKind::Method(_, body), ..
1087 match self.hir_map.expect_item(self.hir_map.get_parent(parent)).node {
1088 hir::ItemImpl(.., ref self_ty, ref impl_items) => {
1089 impl_self = Some(self_ty);
1090 assoc_item_kind = impl_items.iter().find(|ii| ii.id.node_id == parent)
1098 // `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
1099 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => None,
1101 // Foreign `fn` decls are terrible because we messed up,
1102 // and their return types get argument type elision.
1103 // And now too much code out there is abusing this rule.
1104 hir::map::NodeForeignItem(_) => {
1105 let arg_scope = Scope::Elision {
1109 self.with(arg_scope, |_, this| this.visit_ty(output));
1113 // Everything else (only closures?) doesn't
1114 // actually enjoy elision in return types.
1116 self.visit_ty(output);
1121 let has_self = match assoc_item_kind {
1122 Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
1126 // In accordance with the rules for lifetime elision, we can determine
1127 // what region to use for elision in the output type in two ways.
1128 // First (determined here), if `self` is by-reference, then the
1129 // implied output region is the region of the self parameter.
1131 // Look for `self: &'a Self` - also desugared from `&'a self`,
1132 // and if that matches, use it for elision and return early.
1133 let is_self_ty = |def: Def| {
1134 if let Def::SelfTy(..) = def {
1138 // Can't always rely on literal (or implied) `Self` due
1139 // to the way elision rules were originally specified.
1140 let impl_self = impl_self.map(|ty| &ty.node);
1141 if let Some(&hir::TyPath(hir::QPath::Resolved(None, ref path))) = impl_self {
1143 // Whitelist the types that unambiguously always
1144 // result in the same type constructor being used
1145 // (it can't differ between `Self` and `self`).
1149 Def::PrimTy(_) => return def == path.def,
1157 if let hir::TyRptr(lifetime_ref, ref mt) = inputs[0].node {
1158 if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
1159 if is_self_ty(path.def) {
1160 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
1161 let scope = Scope::Elision {
1162 elide: Elide::Exact(lifetime),
1165 self.with(scope, |_, this| this.visit_ty(output));
1173 // Second, if there was exactly one lifetime (either a substitution or a
1174 // reference) in the arguments, then any anonymous regions in the output
1175 // have that lifetime.
1176 let mut possible_implied_output_region = None;
1177 let mut lifetime_count = 0;
1178 let arg_lifetimes = inputs.iter().enumerate().skip(has_self as usize).map(|(i, input)| {
1179 let mut gather = GatherLifetimes {
1182 have_bound_regions: false,
1183 lifetimes: FxHashSet()
1185 gather.visit_ty(input);
1187 lifetime_count += gather.lifetimes.len();
1189 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
1190 // there's a chance that the unique lifetime of this
1191 // iteration will be the appropriate lifetime for output
1192 // parameters, so lets store it.
1193 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
1196 ElisionFailureInfo {
1199 lifetime_count: gather.lifetimes.len(),
1200 have_bound_regions: gather.have_bound_regions
1204 let elide = if lifetime_count == 1 {
1205 Elide::Exact(possible_implied_output_region.unwrap())
1207 Elide::Error(arg_lifetimes)
1210 let scope = Scope::Elision {
1214 self.with(scope, |_, this| this.visit_ty(output));
1216 struct GatherLifetimes<'a> {
1217 map: &'a NamedRegionMap,
1219 have_bound_regions: bool,
1220 lifetimes: FxHashSet<Region>,
1223 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
1224 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1225 NestedVisitorMap::None
1228 fn visit_ty(&mut self, ty: &hir::Ty) {
1229 if let hir::TyBareFn(_) = ty.node {
1230 self.binder_depth += 1;
1232 if let hir::TyTraitObject(ref bounds, ref lifetime) = ty.node {
1233 for bound in bounds {
1234 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
1237 // Stay on the safe side and don't include the object
1238 // lifetime default (which may not end up being used).
1239 if !lifetime.is_elided() {
1240 self.visit_lifetime(lifetime);
1243 intravisit::walk_ty(self, ty);
1245 if let hir::TyBareFn(_) = ty.node {
1246 self.binder_depth -= 1;
1250 fn visit_poly_trait_ref(&mut self,
1251 trait_ref: &hir::PolyTraitRef,
1252 modifier: hir::TraitBoundModifier) {
1253 self.binder_depth += 1;
1254 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1255 self.binder_depth -= 1;
1258 fn visit_lifetime_def(&mut self, lifetime_def: &hir::LifetimeDef) {
1259 for l in &lifetime_def.bounds { self.visit_lifetime(l); }
1262 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
1263 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
1265 Region::LateBound(debruijn, _) |
1266 Region::LateBoundAnon(debruijn, _)
1267 if debruijn.depth < self.binder_depth => {
1268 self.have_bound_regions = true;
1271 self.lifetimes.insert(lifetime.from_depth(self.binder_depth));
1280 fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[hir::Lifetime]) {
1281 if lifetime_refs.is_empty() {
1285 let span = lifetime_refs[0].span;
1286 let mut late_depth = 0;
1287 let mut scope = self.scope;
1290 // Do not assign any resolution, it will be inferred.
1291 Scope::Body { .. } => return,
1293 Scope::Root => break None,
1295 Scope::Binder { s, .. } => {
1300 Scope::Elision { ref elide, .. } => {
1301 let lifetime = match *elide {
1302 Elide::FreshLateAnon(ref counter) => {
1303 for lifetime_ref in lifetime_refs {
1304 let lifetime = Region::late_anon(counter).shifted(late_depth);
1305 self.insert_lifetime(lifetime_ref, lifetime);
1309 Elide::Exact(l) => l.shifted(late_depth),
1310 Elide::Error(ref e) => break Some(e)
1312 for lifetime_ref in lifetime_refs {
1313 self.insert_lifetime(lifetime_ref, lifetime);
1318 Scope::ObjectLifetimeDefault { s, .. } => {
1324 let mut err = struct_span_err!(self.sess, span, E0106,
1325 "missing lifetime specifier{}",
1326 if lifetime_refs.len() > 1 { "s" } else { "" });
1327 let msg = if lifetime_refs.len() > 1 {
1328 format!("expected {} lifetime parameters", lifetime_refs.len())
1330 format!("expected lifetime parameter")
1332 err.span_label(span, &msg);
1334 if let Some(params) = error {
1335 if lifetime_refs.len() == 1 {
1336 self.report_elision_failure(&mut err, params);
1342 fn report_elision_failure(&mut self,
1343 db: &mut DiagnosticBuilder,
1344 params: &[ElisionFailureInfo]) {
1345 let mut m = String::new();
1346 let len = params.len();
1348 let elided_params: Vec<_> = params.iter().cloned()
1349 .filter(|info| info.lifetime_count > 0)
1352 let elided_len = elided_params.len();
1354 for (i, info) in elided_params.into_iter().enumerate() {
1355 let ElisionFailureInfo {
1356 parent, index, lifetime_count: n, have_bound_regions
1359 let help_name = if let Some(body) = parent {
1360 let arg = &self.hir_map.body(body).arguments[index];
1361 format!("`{}`", self.hir_map.node_to_pretty_string(arg.pat.id))
1363 format!("argument {}", index + 1)
1366 m.push_str(&(if n == 1 {
1369 format!("one of {}'s {} elided {}lifetimes", help_name, n,
1370 if have_bound_regions { "free " } else { "" } )
1373 if elided_len == 2 && i == 0 {
1375 } else if i + 2 == elided_len {
1376 m.push_str(", or ");
1377 } else if i != elided_len - 1 {
1385 "this function's return type contains a borrowed value, but \
1386 there is no value for it to be borrowed from");
1388 "consider giving it a 'static lifetime");
1389 } else if elided_len == 0 {
1391 "this function's return type contains a borrowed value with \
1392 an elided lifetime, but the lifetime cannot be derived from \
1395 "consider giving it an explicit bounded or 'static \
1397 } else if elided_len == 1 {
1399 "this function's return type contains a borrowed value, but \
1400 the signature does not say which {} it is borrowed from",
1404 "this function's return type contains a borrowed value, but \
1405 the signature does not say whether it is borrowed from {}",
1410 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &hir::Lifetime) {
1411 let mut late_depth = 0;
1412 let mut scope = self.scope;
1413 let lifetime = loop {
1415 Scope::Binder { s, .. } => {
1421 Scope::Elision { .. } => break Region::Static,
1423 Scope::Body { .. } |
1424 Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
1426 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l
1429 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
1432 fn check_lifetime_defs(&mut self, old_scope: ScopeRef, lifetimes: &[hir::LifetimeDef]) {
1433 for i in 0..lifetimes.len() {
1434 let lifetime_i = &lifetimes[i];
1436 for lifetime in lifetimes {
1437 if lifetime.lifetime.is_static() {
1438 let lifetime = lifetime.lifetime;
1439 let mut err = struct_span_err!(self.sess, lifetime.span, E0262,
1440 "invalid lifetime parameter name: `{}`", lifetime.name);
1441 err.span_label(lifetime.span,
1442 &format!("{} is a reserved lifetime name", lifetime.name));
1447 // It is a hard error to shadow a lifetime within the same scope.
1448 for j in i + 1..lifetimes.len() {
1449 let lifetime_j = &lifetimes[j];
1451 if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
1452 struct_span_err!(self.sess, lifetime_j.lifetime.span, E0263,
1453 "lifetime name `{}` declared twice in the same scope",
1454 lifetime_j.lifetime.name)
1455 .span_label(lifetime_j.lifetime.span,
1456 &format!("declared twice"))
1457 .span_label(lifetime_i.lifetime.span,
1458 &format!("previous declaration here"))
1463 // It is a soft error to shadow a lifetime within a parent scope.
1464 self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
1466 for bound in &lifetime_i.bounds {
1467 if !bound.is_static() {
1468 self.resolve_lifetime_ref(bound);
1470 self.insert_lifetime(bound, Region::Static);
1471 self.sess.struct_span_warn(lifetime_i.lifetime.span.to(bound.span),
1472 &format!("unnecessary lifetime parameter `{}`", lifetime_i.lifetime.name))
1473 .help(&format!("you can use the `'static` lifetime directly, in place \
1474 of `{}`", lifetime_i.lifetime.name))
1481 fn check_lifetime_def_for_shadowing(&self,
1482 mut old_scope: ScopeRef,
1483 lifetime: &hir::Lifetime)
1485 for &(label, label_span) in &self.labels_in_fn {
1486 // FIXME (#24278): non-hygienic comparison
1487 if lifetime.name == label {
1488 signal_shadowing_problem(self.sess,
1490 original_label(label_span),
1491 shadower_lifetime(&lifetime));
1498 Scope::Body { s, .. } |
1499 Scope::Elision { s, .. } |
1500 Scope::ObjectLifetimeDefault { s, .. } => {
1508 Scope::Binder { ref lifetimes, s } => {
1509 if let Some(&def) = lifetimes.get(&lifetime.name) {
1510 signal_shadowing_problem(
1513 original_lifetime(self.hir_map.span(def.id().unwrap())),
1514 shadower_lifetime(&lifetime));
1524 fn insert_lifetime(&mut self,
1525 lifetime_ref: &hir::Lifetime,
1527 if lifetime_ref.id == ast::DUMMY_NODE_ID {
1528 span_bug!(lifetime_ref.span,
1529 "lifetime reference not renumbered, \
1530 probably a bug in syntax::fold");
1533 debug!("{} resolved to {:?} span={:?}",
1534 self.hir_map.node_to_string(lifetime_ref.id),
1536 self.sess.codemap().span_to_string(lifetime_ref.span));
1537 self.map.defs.insert(lifetime_ref.id, def);
1541 ///////////////////////////////////////////////////////////////////////////
1543 /// Detects late-bound lifetimes and inserts them into
1544 /// `map.late_bound`.
1546 /// A region declared on a fn is **late-bound** if:
1547 /// - it is constrained by an argument type;
1548 /// - it does not appear in a where-clause.
1550 /// "Constrained" basically means that it appears in any type but
1551 /// not amongst the inputs to a projection. In other words, `<&'a
1552 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
1553 fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
1556 generics: &hir::Generics) {
1557 debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
1559 let mut constrained_by_input = ConstrainedCollector { regions: FxHashSet() };
1560 for arg_ty in &decl.inputs {
1561 constrained_by_input.visit_ty(arg_ty);
1564 let mut appears_in_output = AllCollector {
1565 regions: FxHashSet(),
1568 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
1570 debug!("insert_late_bound_lifetimes: constrained_by_input={:?}",
1571 constrained_by_input.regions);
1573 // Walk the lifetimes that appear in where clauses.
1575 // Subtle point: because we disallow nested bindings, we can just
1576 // ignore binders here and scrape up all names we see.
1577 let mut appears_in_where_clause = AllCollector {
1578 regions: FxHashSet(),
1581 for ty_param in generics.ty_params.iter() {
1582 walk_list!(&mut appears_in_where_clause,
1583 visit_ty_param_bound,
1586 walk_list!(&mut appears_in_where_clause,
1587 visit_where_predicate,
1588 &generics.where_clause.predicates);
1589 for lifetime_def in &generics.lifetimes {
1590 if !lifetime_def.bounds.is_empty() {
1591 // `'a: 'b` means both `'a` and `'b` are referenced
1592 appears_in_where_clause.visit_lifetime_def(lifetime_def);
1596 debug!("insert_late_bound_lifetimes: appears_in_where_clause={:?}",
1597 appears_in_where_clause.regions);
1599 // Late bound regions are those that:
1600 // - appear in the inputs
1601 // - do not appear in the where-clauses
1602 // - are not implicitly captured by `impl Trait`
1603 for lifetime in &generics.lifetimes {
1604 let name = lifetime.lifetime.name;
1606 // appears in the where clauses? early-bound.
1607 if appears_in_where_clause.regions.contains(&name) { continue; }
1609 // any `impl Trait` in the return type? early-bound.
1610 if appears_in_output.impl_trait { continue; }
1612 // does not appear in the inputs, but appears in the return
1613 // type? eventually this will be early-bound, but for now we
1614 // just mark it so we can issue warnings.
1615 let constrained_by_input = constrained_by_input.regions.contains(&name);
1616 let appears_in_output = appears_in_output.regions.contains(&name);
1617 if !constrained_by_input && appears_in_output {
1618 debug!("inserting issue_32330 entry for {:?}, {:?} on {:?}",
1619 lifetime.lifetime.id,
1622 map.issue_32330.insert(
1623 lifetime.lifetime.id,
1625 fn_def_id: fn_def_id,
1631 debug!("insert_late_bound_lifetimes: \
1632 lifetime {:?} with id {:?} is late-bound",
1633 lifetime.lifetime.name, lifetime.lifetime.id);
1635 let inserted = map.late_bound.insert(lifetime.lifetime.id);
1636 assert!(inserted, "visited lifetime {:?} twice", lifetime.lifetime.id);
1641 struct ConstrainedCollector {
1642 regions: FxHashSet<ast::Name>,
1645 impl<'v> Visitor<'v> for ConstrainedCollector {
1646 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1647 NestedVisitorMap::None
1650 fn visit_ty(&mut self, ty: &'v hir::Ty) {
1652 hir::TyPath(hir::QPath::Resolved(Some(_), _)) |
1653 hir::TyPath(hir::QPath::TypeRelative(..)) => {
1654 // ignore lifetimes appearing in associated type
1655 // projections, as they are not *constrained*
1659 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
1660 // consider only the lifetimes on the final
1661 // segment; I am not sure it's even currently
1662 // valid to have them elsewhere, but even if it
1663 // is, those would be potentially inputs to
1665 if let Some(last_segment) = path.segments.last() {
1666 self.visit_path_segment(path.span, last_segment);
1671 intravisit::walk_ty(self, ty);
1676 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
1677 self.regions.insert(lifetime_ref.name);
1681 struct AllCollector {
1682 regions: FxHashSet<ast::Name>,
1686 impl<'v> Visitor<'v> for AllCollector {
1687 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1688 NestedVisitorMap::None
1691 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
1692 self.regions.insert(lifetime_ref.name);
1695 fn visit_ty(&mut self, ty: &hir::Ty) {
1696 if let hir::TyImplTrait(_) = ty.node {
1697 self.impl_trait = true;
1699 intravisit::walk_ty(self, ty);