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 pub use self::DefRegion::*;
19 use self::ScopeChain::*;
22 use middle::def::{self, DefMap};
27 use std::mem::replace;
29 use syntax::codemap::Span;
30 use syntax::parse::token::special_idents;
31 use util::nodemap::NodeMap;
34 use rustc_front::print::pprust::lifetime_to_string;
35 use rustc_front::visit::{self, Visitor, FnKind};
37 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
40 DefEarlyBoundRegion(/* space */ subst::ParamSpace,
42 /* lifetime decl */ ast::NodeId),
43 DefLateBoundRegion(ty::DebruijnIndex,
44 /* lifetime decl */ ast::NodeId),
45 DefFreeRegion(/* block scope */ region::DestructionScopeData,
46 /* lifetime decl */ ast::NodeId),
49 // Maps the id of each lifetime reference to the lifetime decl
50 // that it corresponds to.
51 pub type NamedRegionMap = NodeMap<DefRegion>;
53 struct LifetimeContext<'a> {
55 named_region_map: &'a mut NamedRegionMap,
58 // Deep breath. Our representation for poly trait refs contains a single
59 // binder and thus we only allow a single level of quantification. However,
60 // the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
61 // and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
62 // correct when representing these constraints, we should only introduce one
63 // scope. However, we want to support both locations for the quantifier and
64 // during lifetime resolution we want precise information (so we can't
65 // desugar in an earlier phase).
67 // SO, if we encounter a quantifier at the outer scope, we set
68 // trait_ref_hack to true (and introduce a scope), and then if we encounter
69 // a quantifier at the inner scope, we error. If trait_ref_hack is false,
70 // then we introduce the scope at the inner quantifier.
75 // List of labels in the function/method currently under analysis.
76 labels_in_fn: Vec<(ast::Name, Span)>,
80 /// EarlyScope(i, ['a, 'b, ...], s) extends s with early-bound
81 /// lifetimes, assigning indexes 'a => i, 'b => i+1, ... etc.
82 EarlyScope(subst::ParamSpace, &'a Vec<hir::LifetimeDef>, Scope<'a>),
83 /// LateScope(['a, 'b, ...], s) extends s with late-bound
84 /// lifetimes introduced by the declaration binder_id.
85 LateScope(&'a Vec<hir::LifetimeDef>, Scope<'a>),
86 /// lifetimes introduced by items within a code block are scoped
88 BlockScope(region::DestructionScopeData, Scope<'a>),
92 type Scope<'a> = &'a ScopeChain<'a>;
94 static ROOT_SCOPE: ScopeChain<'static> = RootScope;
96 pub fn krate(sess: &Session, krate: &hir::Crate, def_map: &DefMap) -> NamedRegionMap {
97 let mut named_region_map = NodeMap();
98 visit::walk_crate(&mut LifetimeContext {
100 named_region_map: &mut named_region_map,
103 trait_ref_hack: false,
104 labels_in_fn: vec![],
106 sess.abort_if_errors();
110 impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> {
111 fn visit_item(&mut self, item: &hir::Item) {
112 // Items save/restore the set of labels. This way inner items
113 // can freely reuse names, be they loop labels or lifetimes.
114 let saved = replace(&mut self.labels_in_fn, vec![]);
116 // Items always introduce a new root scope
117 self.with(RootScope, |_, this| {
120 // Fn lifetimes get added in visit_fn below:
121 visit::walk_item(this, item);
123 hir::ItemExternCrate(_) |
126 hir::ItemDefaultImpl(..) |
127 hir::ItemForeignMod(..) |
128 hir::ItemStatic(..) |
129 hir::ItemConst(..) => {
130 // These sorts of items have no lifetime parameters at all.
131 visit::walk_item(this, item);
133 hir::ItemTy(_, ref generics) |
134 hir::ItemEnum(_, ref generics) |
135 hir::ItemStruct(_, ref generics) |
136 hir::ItemTrait(_, ref generics, _, _) |
137 hir::ItemImpl(_, _, ref generics, _, _, _) => {
138 // These kinds of items have only early bound lifetime parameters.
139 let lifetimes = &generics.lifetimes;
140 let early_scope = EarlyScope(subst::TypeSpace, lifetimes, &ROOT_SCOPE);
141 this.with(early_scope, |old_scope, this| {
142 this.check_lifetime_defs(old_scope, lifetimes);
143 visit::walk_item(this, item);
149 // Done traversing the item; restore saved set of labels.
150 replace(&mut self.labels_in_fn, saved);
153 fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
154 // Items save/restore the set of labels. This way inner items
155 // can freely reuse names, be they loop labels or lifetimes.
156 let saved = replace(&mut self.labels_in_fn, vec![]);
158 // Items always introduce a new root scope
159 self.with(RootScope, |_, this| {
161 hir::ForeignItemFn(_, ref generics) => {
162 this.visit_early_late(subst::FnSpace, generics, |this| {
163 visit::walk_foreign_item(this, item);
166 hir::ForeignItemStatic(..) => {
167 visit::walk_foreign_item(this, item);
172 // Done traversing the item; restore saved set of labels.
173 replace(&mut self.labels_in_fn, saved);
176 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
177 b: &'v hir::Block, s: Span, _: ast::NodeId) {
179 FnKind::ItemFn(_, generics, _, _, _, _) => {
180 self.visit_early_late(subst::FnSpace, generics, |this| {
181 this.walk_fn(fk, fd, b, s)
184 FnKind::Method(_, sig, _) => {
185 self.visit_early_late(subst::FnSpace, &sig.generics, |this| {
186 this.walk_fn(fk, fd, b, s)
189 FnKind::Closure(..) => {
190 self.walk_fn(fk, fd, b, s)
195 fn visit_ty(&mut self, ty: &hir::Ty) {
197 hir::TyBareFn(ref c) => {
198 visit::walk_lifetime_decls_helper(self, &c.lifetimes);
199 self.with(LateScope(&c.lifetimes, self.scope), |old_scope, this| {
200 // a bare fn has no bounds, so everything
201 // contained within is scoped within its binder.
202 this.check_lifetime_defs(old_scope, &c.lifetimes);
203 visit::walk_ty(this, ty);
206 hir::TyPath(None, ref path) => {
207 // if this path references a trait, then this will resolve to
208 // a trait ref, which introduces a binding scope.
209 match self.def_map.borrow().get(&ty.id).map(|d| (d.base_def, d.depth)) {
210 Some((def::DefTrait(..), 0)) => {
211 self.with(LateScope(&Vec::new(), self.scope), |_, this| {
212 this.visit_path(path, ty.id);
216 visit::walk_ty(self, ty);
221 visit::walk_ty(self, ty)
226 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
227 // We reset the labels on every trait item, so that different
228 // methods in an impl can reuse label names.
229 let saved = replace(&mut self.labels_in_fn, vec![]);
231 if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
232 self.visit_early_late(
233 subst::FnSpace, &sig.generics,
234 |this| visit::walk_trait_item(this, trait_item))
236 visit::walk_trait_item(self, trait_item);
239 replace(&mut self.labels_in_fn, saved);
242 fn visit_block(&mut self, b: &hir::Block) {
243 self.with(BlockScope(region::DestructionScopeData::new(b.id),
245 |_, this| visit::walk_block(this, b));
248 fn visit_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
249 if lifetime_ref.name == special_idents::static_lifetime.name {
250 self.insert_lifetime(lifetime_ref, DefStaticRegion);
253 self.resolve_lifetime_ref(lifetime_ref);
256 fn visit_generics(&mut self, generics: &hir::Generics) {
257 for ty_param in generics.ty_params.iter() {
258 visit::walk_ty_param_bounds_helper(self, &ty_param.bounds);
259 match ty_param.default {
260 Some(ref ty) => self.visit_ty(&**ty),
264 for predicate in &generics.where_clause.predicates {
266 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
270 if !bound_lifetimes.is_empty() {
271 self.trait_ref_hack = true;
272 let result = self.with(LateScope(bound_lifetimes, self.scope),
274 this.check_lifetime_defs(old_scope, bound_lifetimes);
275 this.visit_ty(&**bounded_ty);
276 visit::walk_ty_param_bounds_helper(this, bounds);
278 self.trait_ref_hack = false;
281 self.visit_ty(&**bounded_ty);
282 visit::walk_ty_param_bounds_helper(self, bounds);
285 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
289 self.visit_lifetime_ref(lifetime);
290 for bound in bounds {
291 self.visit_lifetime_ref(bound);
294 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ id,
298 self.visit_path(path, id);
299 self.visit_ty(&**ty);
305 fn visit_poly_trait_ref(&mut self,
306 trait_ref: &hir::PolyTraitRef,
307 _modifier: &hir::TraitBoundModifier) {
308 debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
310 if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
311 if self.trait_ref_hack {
312 println!("{:?}", trait_ref.span);
313 span_err!(self.sess, trait_ref.span, E0316,
314 "nested quantification of lifetimes");
316 self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| {
317 this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
318 for lifetime in &trait_ref.bound_lifetimes {
319 this.visit_lifetime_def(lifetime);
321 visit::walk_path(this, &trait_ref.trait_ref.path)
324 self.visit_trait_ref(&trait_ref.trait_ref)
329 #[derive(Copy, Clone, PartialEq)]
330 enum ShadowKind { Label, Lifetime }
331 struct Original { kind: ShadowKind, span: Span }
332 struct Shadower { kind: ShadowKind, span: Span }
334 fn original_label(span: Span) -> Original {
335 Original { kind: ShadowKind::Label, span: span }
337 fn shadower_label(span: Span) -> Shadower {
338 Shadower { kind: ShadowKind::Label, span: span }
340 fn original_lifetime(l: &hir::Lifetime) -> Original {
341 Original { kind: ShadowKind::Lifetime, span: l.span }
343 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
344 Shadower { kind: ShadowKind::Lifetime, span: l.span }
348 fn desc(&self) -> &'static str {
350 ShadowKind::Label => "label",
351 ShadowKind::Lifetime => "lifetime",
356 fn signal_shadowing_problem(
357 sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) {
358 if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
359 // lifetime/lifetime shadowing is an error
360 span_err!(sess, shadower.span, E0496,
361 "{} name `{}` shadows a \
362 {} name that is already in scope",
363 shadower.kind.desc(), name, orig.kind.desc());
365 // shadowing involving a label is only a warning, due to issues with
366 // labels and lifetimes not being macro-hygienic.
367 sess.span_warn(shadower.span,
368 &format!("{} name `{}` shadows a \
369 {} name that is already in scope",
370 shadower.kind.desc(), name, orig.kind.desc()));
372 sess.span_note(orig.span,
373 &format!("shadowed {} `{}` declared here",
374 orig.kind.desc(), name));
377 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
378 // if one of the label shadows a lifetime or another label.
379 fn extract_labels<'v, 'a>(ctxt: &mut LifetimeContext<'a>, b: &'v hir::Block) {
381 struct GatherLabels<'a> {
384 labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
387 let mut gather = GatherLabels {
390 labels_in_fn: &mut ctxt.labels_in_fn,
392 gather.visit_block(b);
395 impl<'v, 'a> Visitor<'v> for GatherLabels<'a> {
396 fn visit_expr(&mut self, ex: &'v hir::Expr) {
397 // do not recurse into closures defined in the block
398 // since they are treated as separate fns from the POV of
400 if let hir::ExprClosure(..) = ex.node {
403 if let Some(label) = expression_label(ex) {
404 for &(prior, prior_span) in &self.labels_in_fn[..] {
405 // FIXME (#24278): non-hygienic comparison
407 signal_shadowing_problem(self.sess,
409 original_label(prior_span),
410 shadower_label(ex.span));
414 check_if_label_shadows_lifetime(self.sess,
419 self.labels_in_fn.push((label, ex.span));
421 visit::walk_expr(self, ex)
424 fn visit_item(&mut self, _: &hir::Item) {
425 // do not recurse into items defined in the block
429 fn expression_label(ex: &hir::Expr) -> Option<ast::Name> {
431 hir::ExprWhile(_, _, Some(label)) |
432 hir::ExprLoop(_, Some(label)) => Some(label.name),
437 fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
438 mut scope: Scope<'a>,
443 BlockScope(_, s) => { scope = s; }
444 RootScope => { return; }
446 EarlyScope(_, lifetimes, s) |
447 LateScope(lifetimes, s) => {
448 for lifetime_def in lifetimes {
449 // FIXME (#24278): non-hygienic comparison
450 if label == lifetime_def.lifetime.name {
451 signal_shadowing_problem(
454 original_lifetime(&lifetime_def.lifetime),
455 shadower_label(label_span));
466 impl<'a> LifetimeContext<'a> {
467 // This is just like visit::walk_fn, except that it extracts the
468 // labels of the function body and swaps them in before visiting
469 // the function body itself.
470 fn walk_fn<'b>(&mut self,
476 FnKind::ItemFn(_, generics, _, _, _, _) => {
477 visit::walk_fn_decl(self, fd);
478 self.visit_generics(generics);
480 FnKind::Method(_, sig, _) => {
481 visit::walk_fn_decl(self, fd);
482 self.visit_generics(&sig.generics);
483 self.visit_explicit_self(&sig.explicit_self);
485 FnKind::Closure(..) => {
486 visit::walk_fn_decl(self, fd);
490 // After inpsecting the decl, add all labels from the body to
491 // `self.labels_in_fn`.
492 extract_labels(self, fb);
494 self.visit_block(fb);
497 fn with<F>(&mut self, wrap_scope: ScopeChain, f: F) where
498 F: FnOnce(Scope, &mut LifetimeContext),
500 let LifetimeContext {sess, ref mut named_region_map, ..} = *self;
501 let mut this = LifetimeContext {
503 named_region_map: *named_region_map,
505 def_map: self.def_map,
506 trait_ref_hack: self.trait_ref_hack,
507 labels_in_fn: self.labels_in_fn.clone(),
509 debug!("entering scope {:?}", this.scope);
510 f(self.scope, &mut this);
511 debug!("exiting scope {:?}", this.scope);
514 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
516 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
517 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
518 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
522 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
524 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
525 /// lifetimes may be interspersed together.
527 /// If early bound lifetimes are present, we separate them into their own list (and likewise
528 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
529 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
530 /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
531 /// ordering is not important there.
532 fn visit_early_late<F>(&mut self,
533 early_space: subst::ParamSpace,
534 generics: &hir::Generics,
536 F: FnOnce(&mut LifetimeContext),
538 let referenced_idents = early_bound_lifetime_names(generics);
540 debug!("visit_early_late: referenced_idents={:?}",
543 let (early, late): (Vec<_>, _) = generics.lifetimes.iter().cloned().partition(
544 |l| referenced_idents.iter().any(|&i| i == l.lifetime.name));
546 self.with(EarlyScope(early_space, &early, self.scope), move |old_scope, this| {
547 this.with(LateScope(&late, this.scope), move |_, this| {
548 this.check_lifetime_defs(old_scope, &generics.lifetimes);
554 fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
555 // Walk up the scope chain, tracking the number of fn scopes
556 // that we pass through, until we find a lifetime with the
557 // given name or we run out of scopes. If we encounter a code
558 // block, then the lifetime is not bound but free, so switch
559 // over to `resolve_free_lifetime_ref()` to complete the
561 let mut late_depth = 0;
562 let mut scope = self.scope;
565 BlockScope(blk_scope, s) => {
566 return self.resolve_free_lifetime_ref(blk_scope, lifetime_ref, s);
573 EarlyScope(space, lifetimes, s) => {
574 match search_lifetimes(lifetimes, lifetime_ref) {
575 Some((index, lifetime_def)) => {
576 let decl_id = lifetime_def.id;
577 let def = DefEarlyBoundRegion(space, index, decl_id);
578 self.insert_lifetime(lifetime_ref, def);
587 LateScope(lifetimes, s) => {
588 match search_lifetimes(lifetimes, lifetime_ref) {
589 Some((_index, lifetime_def)) => {
590 let decl_id = lifetime_def.id;
591 let debruijn = ty::DebruijnIndex::new(late_depth + 1);
592 let def = DefLateBoundRegion(debruijn, decl_id);
593 self.insert_lifetime(lifetime_ref, def);
606 self.unresolved_lifetime_ref(lifetime_ref);
609 fn resolve_free_lifetime_ref(&mut self,
610 scope_data: region::DestructionScopeData,
611 lifetime_ref: &hir::Lifetime,
613 debug!("resolve_free_lifetime_ref \
614 scope_data: {:?} lifetime_ref: {:?} scope: {:?}",
615 scope_data, lifetime_ref, scope);
617 // Walk up the scope chain, tracking the outermost free scope,
618 // until we encounter a scope that contains the named lifetime
619 // or we run out of scopes.
620 let mut scope_data = scope_data;
621 let mut scope = scope;
622 let mut search_result = None;
624 debug!("resolve_free_lifetime_ref \
625 scope_data: {:?} scope: {:?} search_result: {:?}",
626 scope_data, scope, search_result);
628 BlockScope(blk_scope_data, s) => {
629 scope_data = blk_scope_data;
637 EarlyScope(_, lifetimes, s) |
638 LateScope(lifetimes, s) => {
639 search_result = search_lifetimes(lifetimes, lifetime_ref);
640 if search_result.is_some() {
648 match search_result {
649 Some((_depth, lifetime)) => {
650 let def = DefFreeRegion(scope_data, lifetime.id);
651 self.insert_lifetime(lifetime_ref, def);
655 self.unresolved_lifetime_ref(lifetime_ref);
661 fn unresolved_lifetime_ref(&self, lifetime_ref: &hir::Lifetime) {
662 span_err!(self.sess, lifetime_ref.span, E0261,
663 "use of undeclared lifetime name `{}`",
667 fn check_lifetime_defs(&mut self, old_scope: Scope, lifetimes: &Vec<hir::LifetimeDef>) {
668 for i in 0..lifetimes.len() {
669 let lifetime_i = &lifetimes[i];
671 let special_idents = [special_idents::static_lifetime];
672 for lifetime in lifetimes {
673 if special_idents.iter().any(|&i| i.name == lifetime.lifetime.name) {
674 span_err!(self.sess, lifetime.lifetime.span, E0262,
675 "invalid lifetime parameter name: `{}`", lifetime.lifetime.name);
679 // It is a hard error to shadow a lifetime within the same scope.
680 for j in i + 1..lifetimes.len() {
681 let lifetime_j = &lifetimes[j];
683 if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
684 span_err!(self.sess, lifetime_j.lifetime.span, E0263,
685 "lifetime name `{}` declared twice in \
687 lifetime_j.lifetime.name);
691 // It is a soft error to shadow a lifetime within a parent scope.
692 self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
694 for bound in &lifetime_i.bounds {
695 self.resolve_lifetime_ref(bound);
700 fn check_lifetime_def_for_shadowing(&self,
701 mut old_scope: Scope,
702 lifetime: &hir::Lifetime)
704 for &(label, label_span) in &self.labels_in_fn {
705 // FIXME (#24278): non-hygienic comparison
706 if lifetime.name == label {
707 signal_shadowing_problem(self.sess,
709 original_label(label_span),
710 shadower_lifetime(&lifetime));
717 BlockScope(_, s) => {
725 EarlyScope(_, lifetimes, s) |
726 LateScope(lifetimes, s) => {
727 if let Some((_, lifetime_def)) = search_lifetimes(lifetimes, lifetime) {
728 signal_shadowing_problem(
731 original_lifetime(&lifetime_def),
732 shadower_lifetime(&lifetime));
742 fn insert_lifetime(&mut self,
743 lifetime_ref: &hir::Lifetime,
745 if lifetime_ref.id == ast::DUMMY_NODE_ID {
746 self.sess.span_bug(lifetime_ref.span,
747 "lifetime reference not renumbered, \
748 probably a bug in syntax::fold");
751 debug!("lifetime_ref={:?} id={:?} resolved to {:?}",
752 lifetime_to_string(lifetime_ref),
755 self.named_region_map.insert(lifetime_ref.id, def);
759 fn search_lifetimes<'a>(lifetimes: &'a Vec<hir::LifetimeDef>,
760 lifetime_ref: &hir::Lifetime)
761 -> Option<(u32, &'a hir::Lifetime)> {
762 for (i, lifetime_decl) in lifetimes.iter().enumerate() {
763 if lifetime_decl.lifetime.name == lifetime_ref.name {
764 return Some((i as u32, &lifetime_decl.lifetime));
770 ///////////////////////////////////////////////////////////////////////////
772 pub fn early_bound_lifetimes<'a>(generics: &'a hir::Generics) -> Vec<hir::LifetimeDef> {
773 let referenced_idents = early_bound_lifetime_names(generics);
774 if referenced_idents.is_empty() {
778 generics.lifetimes.iter()
779 .filter(|l| referenced_idents.iter().any(|&i| i == l.lifetime.name))
784 /// Given a set of generic declarations, returns a list of names containing all early bound
785 /// lifetime names for those generics. (In fact, this list may also contain other names.)
786 fn early_bound_lifetime_names(generics: &hir::Generics) -> Vec<ast::Name> {
787 // Create two lists, dividing the lifetimes into early/late bound.
788 // Initially, all of them are considered late, but we will move
789 // things from late into early as we go if we find references to
791 let mut early_bound = Vec::new();
792 let mut late_bound = generics.lifetimes.iter()
793 .map(|l| l.lifetime.name)
796 // Any lifetime that appears in a type bound is early.
799 FreeLifetimeCollector { early_bound: &mut early_bound,
800 late_bound: &mut late_bound };
801 for ty_param in generics.ty_params.iter() {
802 visit::walk_ty_param_bounds_helper(&mut collector, &ty_param.bounds);
804 for predicate in &generics.where_clause.predicates {
806 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bounds,
809 collector.visit_ty(&**bounded_ty);
810 visit::walk_ty_param_bounds_helper(&mut collector, bounds);
812 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
815 collector.visit_lifetime_ref(lifetime);
817 for bound in bounds {
818 collector.visit_lifetime_ref(bound);
821 &hir::WherePredicate::EqPredicate(_) => unimplemented!()
826 // Any lifetime that either has a bound or is referenced by a
828 for lifetime_def in &generics.lifetimes {
829 if !lifetime_def.bounds.is_empty() {
830 shuffle(&mut early_bound, &mut late_bound,
831 lifetime_def.lifetime.name);
832 for bound in &lifetime_def.bounds {
833 shuffle(&mut early_bound, &mut late_bound,
840 struct FreeLifetimeCollector<'a> {
841 early_bound: &'a mut Vec<ast::Name>,
842 late_bound: &'a mut Vec<ast::Name>,
845 impl<'a, 'v> Visitor<'v> for FreeLifetimeCollector<'a> {
846 fn visit_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
847 shuffle(self.early_bound, self.late_bound,
852 fn shuffle(early_bound: &mut Vec<ast::Name>,
853 late_bound: &mut Vec<ast::Name>,
855 match late_bound.iter().position(|n| *n == name) {
857 late_bound.swap_remove(index);
858 early_bound.push(name);
865 impl<'a> fmt::Debug for ScopeChain<'a> {
866 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
868 EarlyScope(space, defs, _) => write!(fmt, "EarlyScope({:?}, {:?})", space, defs),
869 LateScope(defs, _) => write!(fmt, "LateScope({:?})", defs),
870 BlockScope(id, _) => write!(fmt, "BlockScope({:?})", id),
871 RootScope => write!(fmt, "RootScope"),